@adhdev/daemon-standalone 0.9.8 → 0.9.10

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,76 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-Bv6gUGuY.js","assets/vendor-BRZ4K-AC.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
- var El=Object.defineProperty;var $l=(e,s,r)=>s in e?El(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var Ve=(e,s,r)=>$l(e,typeof s!="symbol"?s+"":s,r);import{r as o,j as t,M as ia,a as ca,b as ai,c as oi,u as Ms,R as St,d as Vs,t as Bl,e as Kl,D as Ol,f as Hn,g as Fn,h as la,i as Wl,k as Hl,B as Fl,l as Ul,m as Yt,N as Un,n as zl}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 Vl(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 js=Vl();function to(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 Gl(e,s){return typeof e=="string"&&e.trim().length>0&&e!==s}function ql(e,s){return Object.prototype.hasOwnProperty.call(e,s)}function ii(e,s){if(!e)return s??null;if(!s)return e??null;const r=ql(e,"messages"),n=r?Array.isArray(e.messages)?e.messages:[]:s.messages,a=e.activeModal||(e.status==="waiting_approval"?s.activeModal:null),i={...s,...e,activeModal:a,inputContent:e.inputContent??s.inputContent};return r?{...i,messages:n}:i}function Ks(e,s){const r=Gl(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:ii(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 ci(e,s,r){if(!(s!=null&&s.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(s)?s:e;if(!(e!=null&&e.length))return s;const n=s.map(a=>{const i=e.find(c=>c.id===a.id);return i?Ks(a,i):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(s.map(i=>i.id));for(const i of e)a.has(i.id)||n.push(i)}return n}function so(e){return!!e&&typeof e=="object"&&"text"in e}function da(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:so(i)?String(i.text||""):"").join(r):so(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function qr(e){return da(e,{normalizeWhitespace:!0})}const li=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}),di=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function ro(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 ui(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 Yl(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 ln(e){if(!e||typeof e!="object")return"";const s=e,r=Yl(qr(s.content).slice(0,512));return[String(s.id||""),String(s._localId||""),String(s._turnKey||""),String(s.index??""),String(s.role||""),String(s.receivedAt??s.timestamp??""),r].join(":")}function Xl(e){if(!Array.isArray(e))return e;let s=2166136261;for(const r of e){const n=ln(r);for(let a=0;a<n.length;a+=1)s^=n.charCodeAt(a),s=Math.imul(s,16777619)>>>0}return{count:e.length,hash:s.toString(16).padStart(8,"0"),first:ln(e[0]),last:ln(e[e.length-1])}}function Jl(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function Os(e){return Array.isArray(e)?e.map(Os):!e||typeof e!="object"?e:Jl(e)?Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,r==="messages"?Xl(n):Os(n)])):Object.fromEntries(Object.entries(e).filter(([s])=>s!=="timestamp"&&s!=="_lastUpdate").sort(([s],[r])=>s.localeCompare(r)).map(([s,r])=>[s,Os(r)]))}function Ql(e,s){try{return JSON.stringify(Os(e))===JSON.stringify(Os(s))}catch{return!1}}function zn(e,s,r){return Ql(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function mi(e){var s;return e.daemonId||((s=e.id)==null?void 0:s.split(":")[0])||e.id}function Zl(e,s,r){s[r]!==void 0&&(e[r]=s[r])}function no(e,s,r,n){var l;const a=(l=s.chats)!=null&&l.length?s.chats:e.chats,i=ci(e.childSessions,s.childSessions,{preserveMissing:n}),c=ii(s.activeChat,e.activeChat);return ui(e,s,{...e,...s,chats:a,childSessions:i,activeChat:c,_lastUpdate:r})}function ed(e,s,r){var a,i;const n={};s.status&&s.status!==e.status&&(n.status=s.status),s.cdpConnected!==void 0&&(n.cdpConnected=s.cdpConnected),s.childSessions!==void 0&&(n.childSessions=ci(e.childSessions,s.childSessions,{preserveMissing:r})),(a=s.chats)!=null&&a.length&&!((i=e.chats)!=null&&i.length)&&(n.chats=s.chats);for(const c of["title","workspace","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion"])Zl(n,s,c);return s.machineNickname!==void 0&&s.machineNickname!==e.machineNickname&&(n.machineNickname=s.machineNickname),s.versionMismatch===!0&&(n.versionMismatch=!0),n}function td(e,s,r,n){const a=ed(e,s,n),i=Object.keys(a).length>0?ui(e,s,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return zn(e,i,r)}function sd(e){const s=new Set(e.map(a=>a.id)),r=new Set,n=new Set;for(const a of e){const i=mi(a);i&&r.add(i),i&&a.type!=="adhdev-daemon"&&n.add(i)}return{incomingIds:s,incomingDaemonIds:r,daemonIdsWithSessionEntries:n}}function rd(e,s,r,n,a,i){return!a.has(s)||!i.has(s)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function nd(e,s,r,n){return!!(r.has(s)&&e.transport&&!n.has(s))}function ad(e,s,r){var p,d;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return e.map(h=>({...h,_lastUpdate:n}));const i=new Map;for(const h of s)i.set(h.id,h);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:u}=sd(e);for(const h of e){const f=i.get(h.id);if(!f){i.set(h.id,{...h,_lastUpdate:n});continue}const v=ro(h),N=ro(f),m=mi(h),g=!a.has(m);if(v>N){const C=no(f,h,n,g);i.set(h.id,zn(f,C,n));continue}if(v<N){i.set(h.id,td(f,h,n,g));continue}const j=h.timestamp||n,b=f._lastUpdate||f.timestamp||0;if(j>=b){const C=no(f,h,n,g);i.set(h.id,zn(f,C,n));continue}(p=h.chats)!=null&&p.length&&!((d=f.chats)!=null&&d.length)&&i.set(h.id,{...f,chats:h.chats})}for(const[h,f]of i){const v=f.daemonId||h.split(":")[0];if(!l.has(v))continue;if(a.has(v)&&!c.has(h)){i.delete(h);continue}const N=n-(f._lastUpdate||f.timestamp||0);rd(f,v,N,c,a,u)&&i.delete(h)}for(const[h,f]of i){const v=f.daemonId||h.split(":")[0];if(nd(f,v,l,u))continue;n-(f._lastUpdate||f.timestamp||0)>3e5&&f.status!=="online"&&i.delete(h)}return Array.from(i.values())}function od(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 id({children:e,connectionOverrides:s}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[u,p]=o.useState(void 0),d=o.useRef(r);o.useEffect(()=>{d.current=r},[r]);const h=o.useCallback((j,b)=>{n(C=>{let A=!1;const w=C.map(M=>M.id!==j||M.chats===b?M:(A=!0,{...M,chats:b}));return A?w:C})},[]),f=o.useCallback((j,b)=>{n(C=>{const A=C.length===0?j:ad(j,C,b),w=!od(C,A);return w&&js.record({kind:"dashboard.entries_applied",payload:{incoming:to(j),next:to(A)}}),w?A:C})},[]),v=o.useCallback(()=>i(!0),[]),N=o.useMemo(()=>({injectEntries:f,markLoaded:v,getIdes:()=>d.current}),[f,v]),m=s,g=o.useMemo(()=>({ides:r,updateRouteChats:h,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,retryServerConnection:m==null?void 0:m.retryServerConnection,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:p}),[r,h,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.retryServerConnection,m==null?void 0:m.isP2PActive,m==null?void 0:m.p2pStates,m==null?void 0:m.userRole,u]);return t.jsx(di.Provider,{value:N,children:t.jsx(li.Provider,{value:g,children:e})})}function cs(){return o.useContext(li)}function Gs(){return o.useContext(di)}function fi(e){const{baseUrl:s,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${s}${l.startsWith("/")?"":"/"}${l}`}function i(l){const u=r==null?void 0:r(),p=a(l),d=l.startsWith("http")?new URL(p):new URL(p,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 p={"Content-Type":"application/json",...u.headers||{}},d=r==null?void 0:r();d&&(p.Authorization=`Bearer ${d}`);const h=a(l),f=new AbortController,v=setTimeout(()=>f.abort(),15e3);try{const N=await fetch(h,{...u,headers:p,signal:f.signal});if(N.status===401)throw n==null||n(),new Error("Unauthorized");if(!N.ok){const m=await N.json().catch(()=>({error:N.statusText}));throw new Error(m.error||`API Error: ${N.status}`)}return N.json()}finally{clearTimeout(v)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,u,p={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:u,payload:p})}),execTerminal:(l,u,p)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:p})}),sendAgentMessage:(l,u,p)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:p})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,u,p)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:u,action:p?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,u,p={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:p})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const cd=fi({baseUrl:"http://localhost:3847"}),ld=o.createContext(cd);function dd({client:e,children:s}){return t.jsx(ld.Provider,{value:e,children:s})}const ud={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},pi=o.createContext(ud);function md({value:e,children:s}){return t.jsx(pi.Provider,{value:e,children:s})}function jt(){return o.useContext(pi)}function fd(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 pd(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function hi(e){return e?fd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),pd(e.content)]):""}const _e={size:18};function xi({size:e=_e.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 ua({size:e=_e.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 ls({size:e=_e.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 bi({size:e=_e.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 hd({size:e=_e.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 xd({size:e=_e.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 gi({size:e=_e.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 bd({size:e=_e.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 Yr({size:e=_e.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 yi({size:e=_e.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 gd({size:e=_e.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 Ft({size:e=_e.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 Ct({size:e=_e.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 ma({size:e=_e.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 yd({size:e=_e.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 ks({size:e=_e.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 er({size:e=_e.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 qs({size:e=_e.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),t.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),t.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Ys({size:e=_e.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 vi({size:e=_e.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 wi({size:e=_e.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 ji({size:e=_e.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 vd({size:e=_e.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 fa({size:e=_e.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 wd({size:e=_e.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 pa({size:e=_e.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 ki({size:e=_e.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 wt({size:e=_e.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 jd({size:e=_e.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 kd({size:e=_e.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 Sd({size:e=_e.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 Nd({size:e=_e.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 Xr({size:e=_e.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 Cd({size:e=_e.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 Id({size:e=_e.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 Md({size:e=_e.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 Ad({size:e=_e.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 Td({size:e=_e.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 Ld({size:e=_e.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 Rd({size:e=_e.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 Pd({size:e=_e.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 _d({size:e=_e.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 Dd({size:e=_e.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 Ed({size:e=_e.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 $d({size:e=_e.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"})]})}const dn=new Map;function ao(e,s){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(s||""):!0}function Bd(e){if(!Array.isArray(e)||e.length===0)return"0:empty";const s=e[e.length-1];return`${e.length}:${hi(s)}`}function oo(e,s){const r=Math.max(0,e.scrollHeight-e.clientHeight-s.fromBottom);e.scrollTop=Number.isFinite(r)?r:s.top}function Si(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Kd(e,s,r){return Number(e.receivedAt||r[Kr(e,s)]||0)||0}function Ni(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Od(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function dr(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 un(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 io(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):Ni(e)?t.jsx(ia,{remarkPlugins:[ca,ai,oi],children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function ur({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:io(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const a=un(r);return a?t.jsx("img",{src:a,alt:dr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=un(r);return a?t.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=un(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:dr(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||dr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=dr(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}),io(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 Kr(e,s){const r=e,n=da(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 Wd=o.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(ia,{remarkPlugins:[ca],children:s.text}),t.jsx("span",{className:"action-time",children:Si(s.timestamp)})]})},(e,s)=>e.log===s.log),Hd=o.memo(function({message:s,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var M,S,k;const u=(s.role||"").toLowerCase(),p=u==="user"||u==="human",d=s.kind||(u==="tool"?"tool":"standard"),h=Od(s.content)?s.content:null,f=!!(h!=null&&h.some(x=>x.type!=="text")),v=da(s.content,{joiner:`
4
- `});if(d==="thought"){const x=typeof((M=s.meta)==null?void 0:M.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(Sd,{size:13}),t.jsx("span",{children:x})]}),t.jsx("div",{className:"chat-msg-body",children:v})]})}if(d==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),f&&h?t.jsx("div",{className:"tool-text w-full",children:t.jsx(ur,{parts:h,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:v})]});if(d==="terminal"){const x=(S=s.meta)!=null&&S.isRunning?"⏳":"✅",E=typeof((k=s.meta)==null?void 0:k.label)=="string"?s.meta.label:"Ran command";return t.jsxs("div",{className:"self-start chat-msg-terminal",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx("span",{children:x}),t.jsx("span",{children:E})]}),f&&h?t.jsx("div",{className:"chat-msg-body",children:t.jsx(ur,{parts:h,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:v})]})}if(d==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:f&&h?t.jsx(ur,{parts:h,renderAsPreformatted:!1}):v.slice(0,100)});const N=s.meta,g=(typeof(N==null?void 0:N.renderMode)=="string"?N.renderMode.trim():"")==="preformatted",j=v,b=!1,C=j,A=g,w=!A&&Ni(C);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${p?"self-end":"self-start"}`,children:(j||f||p)&&t.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${j||f?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:p?a||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:Si(r)})]}),(j||f)&&t.jsx("div",{className:"chat-markdown",children:f&&h?t.jsx(ur,{parts:h,renderAsPreformatted:A}):A?t.jsx("pre",{className:"chat-preformatted",children:C}):w?t.jsx(ia,{remarkPlugins:[ca,ai,oi],children:C}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:C})}),b]})})},(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),Fd=o.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:u={},emptyState:p,onLoadMore:d,isLoadingMore:h,hasMoreHistory:f,hiddenLiveCount:v=0,loadError:N,scrollToBottomRequestNonce:m},g){const j=o.useRef(null),b=o.useRef(null),C=o.useRef(null),A=o.useRef(0),w=o.useRef(""),M=o.useRef(!1),S=o.useRef(null),k=o.useRef(!1),x=o.useRef(null),E=o.useRef(!1),[R,I]=o.useState(new Set),P=o.useRef(!1),K=o.useRef(!1),z=()=>{const Q=j.current;return Q?Q.scrollHeight-Q.scrollTop-Q.clientHeight<200:!0},L=o.useCallback((Q="auto")=>{const fe=j.current;fe&&fe.scrollTo({top:fe.scrollHeight,behavior:Q})},[]),T=o.useCallback(()=>{var oe;const Q=j.current,fe=(oe=window.getSelection)==null?void 0:oe.call(window);if(!Q||!fe||fe.rangeCount===0||fe.isCollapsed){E.current=!1;return}const W=fe.anchorNode,q=fe.focusNode;E.current=!!(W&&q&&Q.contains(W)&&Q.contains(q))},[]),H=Bd(s),B=o.useCallback(()=>{const Q=j.current;!Q||!l||dn.set(l,{top:Q.scrollTop,fromBottom:Math.max(0,Q.scrollHeight-Q.scrollTop-Q.clientHeight),messageFingerprint:H})},[l,H]),D=o.useCallback((Q="auto")=>{S.current!=null&&cancelAnimationFrame(S.current),S.current=requestAnimationFrame(()=>{S.current=null,L(Q)})},[L]);o.useEffect(()=>{const Q=!M.current,fe=w.current!==l;if(w.current=l,Q||fe){if(M.current=!0,P.current=!1,k.current=!0,!E.current){const q=l?dn.get(l):null;q&&ao(q,H)?requestAnimationFrame(()=>{const oe=j.current;oe&&(oo(oe,q),K.current=!0)}):D("auto")}A.current=s.length;return}s.length>A.current?!P.current&&!E.current&&D("auto"):z()&&!P.current&&!E.current&&D("auto"),A.current=s.length},[H,l,c,s.length,D]),o.useEffect(()=>{m&&(P.current=!1,k.current=!0,K.current=!0,x.current!=null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{k.current=!1,x.current=null},180),E.current||D("auto"))},[D,m]),o.useEffect(()=>()=>{B(),S.current!=null&&cancelAnimationFrame(S.current),x.current!=null&&window.clearTimeout(x.current)},[B]),o.useEffect(()=>{const Q=b.current;if(!Q)return;const fe=()=>{x.current!=null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{k.current=!1,x.current=null},180)},W=new ResizeObserver(()=>{k.current&&(E.current||(D("auto"),fe()))});return W.observe(Q),()=>{W.disconnect(),x.current!=null&&(window.clearTimeout(x.current),x.current=null)}},[D,l]),o.useImperativeHandle(g,()=>({scrollToBottom:(Q="smooth")=>{L(Q)}}),[L]),o.useEffect(()=>{const Q=j.current;if(!Q)return;let fe;const W=()=>{clearTimeout(fe),fe=setTimeout(()=>{P.current=!z(),B()},50)};return Q.addEventListener("scroll",W,{passive:!0}),()=>{Q.removeEventListener("scroll",W),clearTimeout(fe)}},[B]),o.useEffect(()=>(document.addEventListener("selectionchange",T),()=>document.removeEventListener("selectionchange",T)),[T]);const G=o.useRef(0),J=o.useRef(!1);o.useEffect(()=>{const Q=j.current;if(!Q||!J.current||G.current===0)return;const fe=Q.scrollHeight-G.current;fe>0&&(Q.scrollTop=fe),B(),G.current=0,J.current=!1},[s.length,B]),o.useEffect(()=>{if(K.current||!l)return;const Q=dn.get(l),fe=j.current;if(!(!Q||!fe)){if(!ao(Q,H)){L("auto"),K.current=!0;return}oo(fe,Q),K.current=!0}},[l,H,s.length,L]);const xe=()=>{const Q=j.current;Q&&(G.current=Q.scrollHeight),J.current=!0,d==null||d()},re=o.useMemo(()=>{const Q=s.map((oe,he)=>({type:"message",data:oe,index:he,ts:Kd(oe,he,u)}));if(!r||r.length===0)return Q;const fe=[...r].sort((oe,he)=>oe.timestamp-he.timestamp).map((oe,he)=>({type:"action",data:oe,index:he,ts:oe.timestamp})),W=[];let q=0;for(const oe of Q){for(;q<fe.length&&oe.ts>0&&fe[q].ts<oe.ts;)W.push(fe[q++]);W.push(oe)}for(;q<fe.length;)W.push(fe[q++]);return W},[s,r,u]),ge=v>0||!!f,ye=v>0?`↑ Show ${Math.min(v,80)} earlier messages${v>80?` (${v} hidden)`:""}`:N?`↻ ${N}`:"↑ Load older messages";return t.jsx("div",{ref:j,"data-chat-scroll":!0,className:"chat-container",children:t.jsxs("div",{ref:b,className:"chat-container-content",children:[h&&t.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),ge&&!h&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{onClick:xe,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${N&&v===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:ye})}),re.length===0&&!ge&&(p||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),re.map(Q=>{if(Q.type==="action"){const ve=Q.data;return t.jsx(Wd,{log:ve},`action-${Q.index}`)}const fe=Q.data,W=Q.index,q=Kr(fe,W),oe=fe.receivedAt||u[q],he=`${l}-${q}`,le=R.has(he);return t.jsx(Hd,{message:fe,receivedAt:oe,agentName:n,userName:a,isCliMode:i,isTextExpanded:le,onToggleTextExpanded:()=>I(ve=>{const ne=new Set(ve);return le?ne.delete(he):ne.add(he),ne})},`msg-${q}`)}),c&&t.jsx("div",{className:"self-start chat-typing-wrapper",children:t.jsxs("div",{className:"typing-indicator",children:[t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),t.jsx("div",{className:"min-h-10",ref:C})]})})}),Ud=o.memo(Fd,(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),zd="modulepreload",Vd=function(e){return"/"+e},co={},Gd=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=Vd(u),u in co)return;co[u]=!0;const p=u.endsWith(".css"),d=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const h=document.createElement("link");if(h.rel=p?"stylesheet":zd,p||(h.as="script"),h.crossOrigin="",h.href=u,l&&h.setAttribute("nonce",l),document.head.appendChild(h),p)return new Promise((f,v)=>{h.addEventListener("load",f),h.addEventListener("error",()=>v(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 lo=!1;const Ci=o.forwardRef(({onInput:e,onViewportMetrics:s,fontSize:r=13,readOnly:n=!1,sizingMode:a="measured"},i)=>{const c=o.useRef(null),[l,u]=o.useState(null),p=o.useRef([]),d=o.useRef(!1),h=o.useRef(!1),f=o.useRef(!1),v=()=>{const N=c.current;if(N){d.current&&(N.clear(),d.current=!1);for(const m of p.current)N.write(m);p.current=[],h.current&&(N.fit(),h.current=!1),f.current&&(N.bumpResize(),f.current=!1)}};return o.useImperativeHandle(i,()=>({write:N=>{c.current?c.current.write(N):p.current.push(N)},clear:()=>{c.current?c.current.clear():(p.current=[],d.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(p.current=[],d.current=!0)},resize:(N,m)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(N,m)},fit:()=>{c.current?c.current.fit():h.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():f.current=!0}}),[]),o.useEffect(()=>{l&&v()},[l]),o.useEffect(()=>{let N=!1;return Gd(()=>import("./terminal-Bv6gUGuY.js"),__vite__mapDeps([0,1,2])).then(m=>{lo||(lo=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),N||u(()=>m.GhosttyTerminalView)}).catch(m=>{console.error("[CliTerminal] failed to load terminal renderer",m)}),()=>{N=!0}},[]),l?t.jsx(l,{ref:c,onInput:e,onViewportMetrics:s,fontSize:r,readOnly:n,sizingMode:a,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"}})});Ci.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 uo({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 qd({cursorPos:e,viewportRef:s,imgRef:r}){var b;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(b=s.current)==null?void 0:b.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,u=c/l,p=a.width/a.height;let d,h,f,v;u>p?(d=a.width,h=a.width/u,f=0,v=(a.height-h)/2):(h=a.height,d=a.height*u,f=(a.width-d)/2,v=0);const N=a.left-i.left+f+d*e.nx,m=a.top-i.top+v+h*e.ny,g=Math.max(8,Math.min(i.width-8,N)),j=Math.max(8,Math.min(i.height-8,m));return t.jsxs("div",{style:{position:"absolute",left:g-8,top:j-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 Yd({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:u,isConnActive:p,zoom:d,isMobile:h,mobileFillZoom:f,onZoomOut:v,onZoomReset:N,onZoomIn:m,transportType:g,screenshotUsage:j,lastActionStatus:b}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:C=>C.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[t.jsxs("div",{onClick:s,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[t.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),t.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),t.jsxs("div",{className:"relative",children:[t.jsx("div",{onClick:()=>{n(C=>!C),i(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&t.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:t.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:C=>C.stopPropagation(),onChange:C=>l(C.target.value),onKeyDown:C=>{u(C)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),t.jsx("div",{className:"relative",children:t.jsx("div",{onClick:()=>{i(C=>!C),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⚙️"})})}),t.jsx("div",{className:"w-px h-[18px] bg-white/10"}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:p?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[t.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:p?"#22c55e":"#eab308",boxShadow:p?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:p?"#22c55e":"#eab308"},children:p?"Connected":"WS"})]}),d>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),g==="direct"&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),g==="relay"&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),j&&j.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:j.budgetExhausted?"#ef4444":"#c4b5fd",background:j.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:j.budgetExhausted?"TURN blocked":`TURN ${j.dailyUsedMinutes}/${j.dailyBudgetMinutes}m`}),b&&t.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:b})]})]}),a&&t.jsxs("div",{onTouchStart:C=>C.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[t.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",d<=(h?f:1)+.01?h?"FILL":"FIT":`${Math.round(d*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:C=>{C.stopPropagation(),v()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),t.jsx("button",{onClick:C=>{C.stopPropagation(),N()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:h?"FILL":"FIT"}),t.jsx("button",{onClick:C=>{C.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 Xd({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 Jd(){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 mo(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 tr(e,s){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!Jd())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,mo(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,mo(s[c])]))}),r.current=s})}function Qd({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:u,setPanX:p,setPanY:d,setZoom:h,lastWheelTimeRef:f,onAction:v,setLastActionStatus:N,spawnRippleFromNormalized:m,clampPan:g,isMobile:j,mobileFillZoom:b}){const[C,A]=o.useState(null),w=o.useRef(null),M=o.useRef(null),S=o.useRef(null),k=o.useRef(!1),x=o.useRef(null),E=o.useRef(0),R=o.useRef(null),I=o.useRef(1),P=o.useRef({x:0,y:0}),K=o.useRef(!1),z=o.useRef(n),L=o.useRef(v),T=30,H=550,B=18,D=60,G=400,J=12,xe=()=>{if(w.current)return;const ye={nx:.5,ny:.5};w.current=ye,A(ye)};return o.useEffect(()=>{z.current=n,n==="mouse"&&xe()},[n]),o.useEffect(()=>{L.current=v},[v]),o.useEffect(()=>{const ye=e.current;if(!ye)return;const Q=le=>{if(!r.current)return null;const ve=r.current.getBoundingClientRect();return!ve.width||!ve.height?null:{nx:Math.max(0,Math.min(1,(le.clientX-ve.left)/ve.width)),ny:Math.max(0,Math.min(1,(le.clientY-ve.top)/ve.height))}},fe=(le,ve)=>{if(!r.current)return{dnx:0,dny:0};const ne=r.current,pe=ne.getBoundingClientRect(),ce=ne.naturalWidth||pe.width,de=ne.naturalHeight||pe.height,ae=ce/de,je=pe.width/pe.height;let U,se;return ae>je?(U=pe.width,se=pe.width/ae):(se=pe.height,U=pe.height*ae),{dnx:le/U,dny:ve/se}},W=(le,ve,ne)=>{if(ne<=1.05)return;const pe=-(le-.5)*100,ce=-(ve-.5)*100,de=g(pe,ce,ne);(Math.abs(de.x-l.current)>.1||Math.abs(de.y-u.current)>.1)&&(p(de.x),d(de.y),l.current=de.x,u.current=de.y)},q=le=>{const ve=s.current;if(ve&&le.target instanceof Node&&ve.contains(le.target))le.preventDefault();else return;if(le.touches.length===1){const ne=le.touches[0];M.current={x:ne.clientX,y:ne.clientY,time:Date.now()},S.current={x:ne.clientX,y:ne.clientY},K.current||(k.current=!1),x.current=setTimeout(()=>{if(!k.current&&!K.current)if(k.current=!0,z.current==="mouse"){const pe=w.current||{nx:.5,ny:.5};N("Right Click"),m(pe.nx,pe.ny,"right"),L.current("input_click",{...pe,button:"right"}).catch(()=>{})}else{const pe=Q(ne);pe&&(N("Right Click"),m(pe.nx,pe.ny,"right"),L.current("input_click",{...pe,button:"right"}).catch(()=>{}))}},500);return}if(le.touches.length===2){x.current&&clearTimeout(x.current),k.current=!0,K.current=!0;const ne=le.touches[1].clientX-le.touches[0].clientX,pe=le.touches[1].clientY-le.touches[0].clientY;R.current=Math.sqrt(ne*ne+pe*pe),I.current=c.current,P.current={x:(le.touches[0].clientX+le.touches[1].clientX)/2,y:(le.touches[0].clientY+le.touches[1].clientY)/2}}},oe=le=>{const ve=s.current;if(ve&&le.target instanceof Node&&ve.contains(le.target)&&le.preventDefault(),le.touches.length===1&&S.current){const ne=le.touches[0],pe=ne.clientX-S.current.x,ce=ne.clientY-S.current.y;if(!k.current&&M.current){const de=ne.clientX-M.current.x,ae=ne.clientY-M.current.y;Math.sqrt(de*de+ae*ae)>8&&(k.current=!0,x.current&&clearTimeout(x.current))}if(k.current)if(z.current==="mouse"){const de=fe(pe,ce),ae=w.current||{nx:.5,ny:.5},je=Math.max(0,Math.min(1,ae.nx+de.dnx)),U=Math.max(0,Math.min(1,ae.ny+de.dny));w.current={nx:je,ny:U},A({nx:je,ny:U}),N(`Cursor: ${Math.round(je*100)}%, ${Math.round(U*100)}%`),W(je,U,c.current);const se=Date.now();se-f.current>=30&&(f.current=se,L.current("input_mouseMoved",{nx:je,ny:U}).catch(()=>{}))}else if(c.current>1){const de=s.current;if(de){const ae=de.clientWidth,je=de.clientHeight,U=l.current+pe/ae*100,se=u.current+ce/je*100,y=g(U,se,c.current);p(y.x),d(y.y),l.current=y.x,u.current=y.y}}else{const de=Q(ne);if(de){const ae=Date.now();ae-f.current>=40&&(f.current=ae,N("Scroll"),L.current("input_wheel",{nx:de.nx,ny:de.ny,deltaX:Math.round(-pe*2.5),deltaY:Math.round(-ce*2.5)}).catch(()=>{}))}}S.current={x:ne.clientX,y:ne.clientY};return}if(le.touches.length===2&&R.current!==null){const ne=le.touches[1].clientX-le.touches[0].clientX,pe=le.touches[1].clientY-le.touches[0].clientY,de=Math.sqrt(ne*ne+pe*pe)/R.current,ae=(le.touches[0].clientX+le.touches[1].clientX)/2,je=(le.touches[0].clientY+le.touches[1].clientY)/2,U=ae-P.current.x,se=je-P.current.y,y=Math.abs(de-1)>.03;if(z.current==="mouse"){if(y){const X=Math.max(i,Math.min(5,I.current*de));h(X),c.current=X}else if(Math.abs(U)>2||Math.abs(se)>2){const X=w.current||{nx:.5,ny:.5},te=Date.now();te-f.current>=30&&(f.current=te,N("Scroll"),L.current("input_wheel",{nx:X.nx,ny:X.ny,deltaX:Math.round(-U*3),deltaY:Math.round(-se*3)}).catch(()=>{}))}}else{const X=Math.max(i,Math.min(5,I.current*de));h(X),c.current=X;const te=s.current;if(te&&X>1){const ue=te.clientWidth,we=te.clientHeight,Ne=l.current+U/ue*100,Be=u.current+se/we*100,Ke=g(Ne,Be,X);p(Ke.x),d(Ke.y),l.current=Ke.x,u.current=Ke.y}}P.current={x:ae,y:je}}},he=le=>{var ve;if(x.current&&clearTimeout(x.current),R.current=null,le.touches.length===1&&K.current){const ne=le.touches[0];M.current={x:ne.clientX,y:ne.clientY,time:Date.now()},S.current={x:ne.clientX,y:ne.clientY},k.current=!0;return}if(le.touches.length===0){if(K.current){K.current=!1,k.current=!1;return}if(le.changedTouches.length===1){const ne=le.changedTouches[0],pe=Date.now(),ce=pe-(((ve=M.current)==null?void 0:ve.time)||0),de=M.current?ne.clientX-M.current.x:0,ae=M.current?ne.clientY-M.current.y:0,je=Math.sqrt(de*de+ae*ae);if(z.current==="mouse"){if(ce<T||ce>H||je>B){k.current=!1;return}const U=w.current||Q(ne);U&&(N(`Click: ${Math.round(U.nx*100)}%, ${Math.round(U.ny*100)}%`),m(U.nx,U.ny,"left"),L.current("input_click",{...U}).catch(()=>{}))}else{if(k.current){k.current=!1;return}if(ce<D||ce>G||je>J){k.current=!1;return}const U=Q(ne);if(!U)return;pe-E.current<300?(N("Double tap"),m(U.nx,U.ny,"double"),L.current("input_click",{...U,clickCount:2}).catch(()=>{}),E.current=0):(N(`Tap: ${Math.round(U.nx*100)}%, ${Math.round(U.ny*100)}%`),m(U.nx,U.ny,"left"),L.current("input_click",{...U}).catch(()=>{}),E.current=pe)}}k.current=!1}};return ye.addEventListener("touchstart",q,{passive:!1}),ye.addEventListener("touchmove",oe,{passive:!1}),ye.addEventListener("touchend",he,{passive:!1}),()=>{ye.removeEventListener("touchstart",q),ye.removeEventListener("touchmove",oe),ye.removeEventListener("touchend",he),x.current&&clearTimeout(x.current)}},[e,s,r,i,c,l,u,p,d,h,f,N,m,g]),{cursorPos:C,cursorPosRef:w,handleToggleInputMode:()=>{a(ye=>{const Q=ye==="touch"?"mouse":"touch";return Q==="mouse"&&xe(),Q})},handleZoomReset:()=>{const ye=j?b:1;h(ye),c.current=ye,p(0),d(0),l.current=0,u.current=0}}}function Ii({onAction:e,addLog:s,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),u=o.useRef(null),[p,d]=o.useState(null),[h,f]=o.useState(""),[,v]=o.useState(!1),[N,m]=o.useState([]),g=o.useRef(0),[j,b]=o.useState(!1),[C,A]=o.useState(!1),w=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[M,S]=o.useState(w?"mouse":"touch"),[k,x]=o.useState(1),E=o.useRef(!1),[R,I]=o.useState(1),[P,K]=o.useState(0),[z,L]=o.useState(0);tr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:M,zoom:R,panX:P,panY:z,isMenuOpen:j,isImeOpen:C});const T=o.useRef(0),H=o.useRef(R),B=o.useRef(P),D=o.useRef(z);o.useEffect(()=>{H.current=R},[R]),o.useEffect(()=>{B.current=P},[P]),o.useEffect(()=>{D.current=z},[z]),o.useEffect(()=>{var ce;(ce=c.current)==null||ce.focus()},[]);const G=r==="connected",J=n,xe=G?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",re=G?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!w||E.current||!J)return;const ce=u.current,de=l.current;if(!ce||!de)return;const ae=()=>{const je=de.clientWidth,U=de.clientHeight,se=ce.naturalWidth,y=ce.naturalHeight;if(!se||!y||!je||!U)return;const X=Math.min(je/se,U/y),ue=Math.max(je/se,U/y)/X;ue>1.01&&(x(ue),I(ue),H.current=ue),E.current=!0};ce.complete&&ce.naturalWidth?ae():ce.addEventListener("load",ae,{once:!0})},[J,w]);const ge=.5;o.useEffect(()=>{R<=ge&&(K(0),L(0))},[R,ge]);const ye=(ce,de,ae)=>{if(ae<=ge)return{x:0,y:0};const je=(ae-1)/(2*ae)*100,U=(ae-1)/(2*ae)*100;return{x:Math.max(-je,Math.min(je,ce)),y:Math.max(-U,Math.min(U,de))}},Q=(ce,de)=>{if(!u.current)return null;const ae=u.current.getBoundingClientRect();return!ae.width||!ae.height?null:{nx:Math.max(0,Math.min(1,(ce-ae.left)/ae.width)),ny:Math.max(0,Math.min(1,(de-ae.top)/ae.height))}},fe=(ce,de,ae)=>{const je=l.current;if(!je)return;const U=je.getBoundingClientRect(),se=++g.current;m(y=>[...y,{id:se,x:ce-U.left,y:de-U.top,type:ae}]),setTimeout(()=>m(y=>y.filter(X=>X.id!==se)),600)},W=(ce,de,ae)=>{const je=u.current,U=l.current;if(!je||!U)return;const se=je.getBoundingClientRect(),y=U.getBoundingClientRect(),X=je.naturalWidth||se.width,te=je.naturalHeight||se.height,ue=X/te,we=se.width/se.height;let Ne,Be,Ke,Fe;ue>we?(Ne=se.width,Be=se.width/ue,Ke=0,Fe=(se.height-Be)/2):(Be=se.height,Ne=se.height*ue,Ke=(se.width-Ne)/2,Fe=0);const Ue=se.left-y.left+Ke+Ne*ce,ot=se.top-y.top+Fe+Be*de,rt=++g.current;m(dt=>[...dt,{id:rt,x:Ue,y:ot,type:ae}]),setTimeout(()=>m(dt=>dt.filter(yt=>yt.id!==rt)),600)},q=async ce=>{var ae;const de=Q(ce.clientX,ce.clientY);if(de){d(`Click: ${Math.round(de.nx*100)}%, ${Math.round(de.ny*100)}%`),fe(ce.clientX,ce.clientY,"left"),(ae=c.current)==null||ae.focus();try{const je=await e("input_click",{nx:de.nx,ny:de.ny});je!=null&&je.success||s(`❌ Click failed: ${je==null?void 0:je.error}`)}catch(je){s(`❌ Click error: ${je.message||je}`)}}},oe=async(ce,de,ae,je=0)=>{try{await e("input_key",{type:ae?"char":"keyDown",key:ce,code:de,text:ae?ce:void 0,unmodifiedText:ae?ce:void 0,modifiers:je})}catch(U){s(`❌ Key error: ${U.message||U}`)}},he=async ce=>{if(ce.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ce.key)&&ce.preventDefault();let ae=0;ce.altKey&&(ae|=1),ce.ctrlKey&&(ae|=2),ce.metaKey&&(ae|=4),ce.shiftKey&&(ae|=8),d(`Key: ${ce.key}`),await oe(ce.key,ce.code,ce.key.length===1,ae)},le=async ce=>{if(ce.key==="Enter"){if(ce.nativeEvent.isComposing)return;if(h){const de=h;f(""),d(`IME Sent: ${de}`);try{const ae=await e("input_type",{text:de});ae!=null&&ae.success||s(`❌ IME error: ${ae==null?void 0:ae.error}`)}catch(ae){s(`❌ IME error: ${ae.message}`)}}else d("Key: Enter"),await oe("Enter","Enter",!1)}};o.useEffect(()=>{const ce=c.current;if(!ce)return;const de=ae=>{var je;if((je=u.current)!=null&&je.contains(ae.target)){ae.preventDefault();const U=Date.now();if(U-T.current<40)return;T.current=U;const se=Q(ae.clientX,ae.clientY);if(!se)return;d(`Scroll: ${Math.round(ae.deltaY)}`),e("input_wheel",{nx:se.nx,ny:se.ny,deltaX:Math.round(ae.deltaX),deltaY:Math.round(ae.deltaY)}).catch(()=>{})}};return ce.addEventListener("wheel",de,{passive:!1}),()=>ce.removeEventListener("wheel",de)},[e]);const{cursorPos:ve,handleToggleInputMode:ne,handleZoomReset:pe}=Qd({containerRef:c,viewportRef:l,imgRef:u,inputMode:M,setInputMode:S,minZoom:ge,zoomRef:H,panXRef:B,panYRef:D,setPanX:K,setPanY:L,setZoom:I,lastWheelTimeRef:T,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:W,clampPan:ye,isMobile:w,mobileFillZoom:k});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:he,onContextMenu:ce=>ce.preventDefault(),onFocus:()=>v(!0),onBlur:()=>v(!1),tabIndex:0,children:[t.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[J?t.jsx("img",{ref:u,src:J,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${R}) translate(${P}%, ${z}%)`,transformOrigin:"center center",cursor:M==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:q,onContextMenu:ce=>ce.preventDefault(),onDragStart:ce=>ce.preventDefault()}):t.jsx(Xd,{waitingLabel:xe,waitingHint:re,transportType:i}),M==="mouse"&&J&&t.jsx(qd,{cursorPos:ve,viewportRef:l,imgRef:u}),N.map(ce=>{const ae={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ce.type];return t.jsxs("div",{style:{position:"absolute",left:ce.x,top:ce.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ae}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),t.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${ae}, 0.9)`,boxShadow:`0 0 12px rgba(${ae}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ce.id)})]}),t.jsx(Yd,{inputMode:M,onToggleInputMode:ne,isImeOpen:C,setIsImeOpen:A,isMenuOpen:j,setIsMenuOpen:b,imeText:h,setImeText:f,handleImeSubmit:le,isConnActive:G,zoom:R,isMobile:w,mobileFillZoom:k,onZoomOut:()=>I(ce=>Math.max(.5,ce-.25)),onZoomReset:pe,onZoomIn:()=>I(ce=>Math.min(5,ce+.25)),transportType:i,screenshotUsage:a,lastActionStatus:p}),t.jsx("style",{children:`
5
- @keyframes slideUp {
6
- from { opacity: 0; transform: translateY(6px); }
7
- to { opacity: 1; transform: translateY(0); }
8
- }
9
- @keyframes slideUpSidebar {
10
- from { opacity: 0; transform: translateY(6px); }
11
- to { opacity: 1; transform: translateY(0); }
12
- }
13
- @keyframes click-ripple-ring {
14
- 0% { transform: scale(0.3); opacity: 1; }
15
- 100% { transform: scale(2.2); opacity: 0; }
16
- }
17
- @keyframes click-ripple-dot {
18
- 0% { transform: scale(1); opacity: 0.9; }
19
- 50% { transform: scale(1.8); opacity: 0.6; }
20
- 100% { transform: scale(0.5); opacity: 0; }
21
- }
22
- @keyframes remote-float {
23
- 0% { transform: translateY(0px); }
24
- 50% { transform: translateY(-7px); }
25
- 100% { transform: translateY(0px); }
26
- }
27
- `})]})}function Jr(e,s={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=s,i=Date.now()-e,c=Math.floor(i/1e3);if(c<a)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const u=Math.floor(l/60);if(u<24)return`${u}h${r}`;const p=Math.floor(u/24);return p<7?`${p}d${r}`:new Date(e).toLocaleDateString()}const Mi=e=>Jr(e);function Zd(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 As(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 eu(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...Zd(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 Or(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 Qr(e,s,r){const n=Or(e,s),a=As(e),i=a.isReconnecting,c=a.isConnecting,l=a.isGenerating,u=a.isWaiting,p=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||u,d=n.inboxBucket==="working"||l,f=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:f,requiresAction:p,isWorking:d,isReconnecting:i,isConnecting:c,isGenerating:l,isWaiting:u,inboxBucket:p?"needs_attention":d?"working":f?"task_complete":"idle"}}function tu(e,s,r){return Qr(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Ai({activeConv:e,onModalButton:s}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!As(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(qs,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,u)=>{const p=c(l).toLowerCase(),d=/^(run|approve|accept|yes|allow|always)/.test(p),h=/^(reject|deny|delete|remove|abort)/.test(p),f=r===l,v=r!==null;return t.jsx("button",{onClick:()=>i(l),disabled:v,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${d?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${v&&!f?"opacity-40":"opacity-100"} ${v?"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)"}:h?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:f?"⏳ ...":c(l)},u)})})]})]})}const ha="adhdev_controls_bar_visible",Vn="adhdev:controlsbarvisibilitychange";function mn(e){if(!e)return!1;try{return e.getItem(ha)==="1"}catch{return!1}}function fo(e,s){if(s)try{s.setItem(ha,e?"1":"0")}catch{}}function po(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Vn,{detail:{visible:e}}))}function Ti(){const[e,s]=o.useState(()=>typeof window>"u"?!1:mn(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(mn(window.localStorage))},i=c=>{c.key===ha&&s(mn(window.localStorage))};return window.addEventListener(Vn,a),window.addEventListener("storage",i),()=>{window.removeEventListener(Vn,a),window.removeEventListener("storage",i)}},[]);const r=o.useCallback(a=>{s(a),typeof window<"u"&&fo(a,window.localStorage),po(a)},[]),n=o.useCallback(()=>{s(a=>{const i=!a;return typeof window<"u"&&fo(i,window.localStorage),po(i),i})},[]);return{isVisible:e,setVisibility:r,toggleVisibility:n}}var su=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function ru(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function bt(e,s){if(ru(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":su.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 Li(e){return bt(e)==="generating"}function et(e){return e?e.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" "):"IDE"}function nu(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 fn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Zr(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 au(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 ou(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function iu(e){return au(e.trim().replace(/\.local$/i,""))}function cu(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function Ri(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&&!ou(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 Tt(e,s={}){return cu(e)||Ri(e,s)}function Pi(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 _i(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 ds(e,s){return Pi(e).join(" · ")}function Xs(e){return e.transport==="pty"}function gs(e){return e.transport==="acp"}function lu(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:et(e)}function ho(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=et(r||"").trim().toLowerCase();return n===a||n===i||n===c}function du(e){return bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function uu(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=bt(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 mu(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 fu(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&&mu(s.receivedAt)||0}function pu(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Gn(e){return Math.max(pu(e),fu(e.activeChat))}function hu(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 xa(e,s){return hu(Gn(e),Gn(s),Tt(e,{fallbackId:e.id}),Tt(s,{fallbackId:s.id}),e.id,s.id)}const Di="adhdev_notification_prefs",xo={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function xu(){try{const e=localStorage.getItem(Di);if(e){const s=JSON.parse(e);return{...xo,...s}}}catch{}return{...xo}}function bu(e){try{localStorage.setItem(Di,JSON.stringify(e))}catch{}}let Wt=xu(),Ar=[];function gu(){Ar.forEach(e=>e())}function yu(e){Wt={...Wt,...e},bu(Wt),gu()}function vu(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Ar.push(r),()=>{Ar=Ar.filter(n=>n!==r)}},[]);const s=o.useCallback(r=>{yu(r)},[]);return[{...Wt},s]}function Ws(e){if(!Wt.globalEnabled)return!1;switch(e){case"disconnect":return Wt.disconnectAlert;case"completion":return Wt.completionAlert;case"approval":return Wt.approvalAlert;case"browser":return Wt.browserNotifications;default:return!0}}const wu={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Ei(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function $i(){return"Notification"in window&&Notification.permission==="granted"}let Xt=null;async function ju(){if(Xt!==null)return Xt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Xt=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Xt=!!await e.pushManager.getSubscription(),Xt):(Xt=!1,!1)}catch{return Xt=!1,!1}}function qn(e,s,r){if($i())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 ku(e,s={}){const r={...wu,...s},n=o.useRef(new Map),a=o.useRef(0),i=o.useRef(null);o.useEffect(()=>{ju().then(l=>{i.current=l})},[]);const c=o.useCallback((l,u,p)=>{const d=Date.now();d-a.current<r.throttleMs||(a.current=d,qn(l,u,p))},[r.throttleMs]);o.useEffect(()=>{var l;if(!(!r.enabled||!$i())&&Ws("browser")&&i.current!==!0){if(document.hasFocus()){for(const u of e)n.current.set(u.id,bt(u.status,{activeModal:u.activeModal}));return}for(const u of e){const p=n.current.get(u.id),d=bt(u.status,{activeModal:u.activeModal}),h=u.name||u.id;if(r.onApproval&&Ws("approval")&&d==="waiting_approval"&&p!=="waiting_approval"){const f=((l=u.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${h} — Approval needed`,f.slice(0,120),`approval-${u.id}`)}r.onComplete&&Ws("completion")&&Li(p)&&d==="idle"&&c(`✅ ${h} — Task complete`,"Agent has finished generating",`complete-${u.id}`),r.onError&&d==="error"&&p!=="error"&&c(`⚠️ ${h} — 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 Su=/^(run|approve|accept|yes|allow|always)/,Nu=/^(run|approve|accept|yes|allow|always|proceed|save)/,Cu=/^(reject|deny|delete|remove|abort|cancel|no)/;function ba(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Iu(e){const s=ba(e).toLowerCase();return Su.test(s)?"primary":Cu.test(s)?"danger":"default"}function Mu(e){return Nu.test(ba(e).toLowerCase())?"approve":"reject"}function Au(e){return e.map((s,r)=>({label:ba(s),variant:Iu(s),action:Mu(s),button:s,buttonIndex:r}))}function Tu(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Lu(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 Ru{constructor(){Ve(this,"dedupMap",new Map);Ve(this,"DEDUP_WINDOW_MS",5e3);Ve(this,"DEDUP_MAX_SIZE",50);Ve(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ve(this,"toastCallbacks",[]);Ve(this,"resolveActionFn",null);Ve(this,"viewRequestRespondFn",null);Ve(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.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})}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 N;const n=this.resolveConversationKey(s),a=Number.isFinite(s.timestamp)?Number(s.timestamp):Date.now(),i=n||s.daemonId||"",c=s.requestId||s.targetName||s.requesterName||s.modalMessage||String(a),l=`${i}:${s.event}:${c}`;if(this.isDuplicate(l))return;const u=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,p=(u==null?void 0:u.type)||"";let d=et(p);const h=this.resolveOwningDaemon(s);if(h){const m=Tt(h,{fallbackId:h.id});m&&(d=!p||p==="adhdev-daemon"?m:`${m}/${d}`)}let f="",v="info";if(s.event==="agent:generating_completed"){const m=s.duration?` (${s.duration}s)`:"";f=`✅ ${d} agent task completed${m}`,v="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(f=`⚡ ${d} approval needed`,v="warning",(N=s.modalButtons)!=null&&N.length&&this.resolveActionFn){const m=this.resolveActionRouteTarget(s);if(!m)return;const g=this.resolveActionFn,j=Au(s.modalButtons).map(A=>({label:A.label,variant:A.variant,onClick:()=>{g(m,"resolve_action",{action:A.action,button:A.button,buttonIndex:A.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),b=Tu(d,s.modalMessage,f),C=Date.now();this.emitToast({id:C,message:b,type:v,timestamp:C,targetKey:n||m,actions:j,duration:15e3}),f=""}}else if(s.event==="monitor:long_generating"){const m=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";f=`⚠️ ${d} agent is taking a long time${m}`,v="warning",Ws("browser")&&!document.hasFocus()&&qn(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${m.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const m=s.requesterName||"A team member",g=s.requestId,j=s.orgId;if(f=`👁️ ${m} wants to view your session`,v="warning",g&&j&&this.viewRequestRespondFn){const b=Date.now(),C=Lu(j,g,this.viewRequestRespondFn,(A,w)=>console.error(`[EventManager] ${A} view request failed:`,w));this.emitToast({id:b,message:f,type:v,timestamp:b,actions:C,duration:3e4}),f=""}Ws("browser")&&!document.hasFocus()&&qn("👁️ View Request",`${m} wants to view your session`,`view-request-${g}`)}else s.event==="team:view_request_approved"?(f="✅ View request approved",v="success"):s.event==="team:view_request_rejected"&&(f=`❌ ${s.targetName||"Team member"} declined your view request`,v="warning");if(f){const m=Date.now();this.emitToast({id:m,message:f,type:v,timestamp:m,targetKey:n||s.daemonId,duration:5e3})}}}const ct=new Ru,bo=new Map;function Ss(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ys(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Pu(e){return!Ss(e)||!Ss(e.controlResult)||!Array.isArray(e.controlResult.options)?null:e.controlResult}function fr(e){return!Ss(e)||!Ss(e.controlResult)||typeof e.controlResult.ok!="boolean"?null:e.controlResult}function Rs(e){if(!(!Ss(e)||typeof e.error!="string"||!e.error.trim()))return e.error}function pr(e){return Ss(e)&&e.success===!1}function _u(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";ct.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";ct.showToast(n.notification.body,a)}}}function Du(e,s){return e&&ys(e.currentValue)?e.currentValue:s}function Eu(e,s){return ys(s)?ys(e)?typeof e=="string"&&e.trim()==="":!0:!1}function $u(e,s){var i,c;if((s.now??Date.now())<s.localOverrideUntil){const l=s.localValues[e];if(ys(l))return l}const n=(i=s.controlValues)==null?void 0:i[e];if(ys(n))return n;const a=(c=s.defaultValues)==null?void 0:c[e];return ys(a)?a:void 0}function Tr(e,s){return e.options||s[e.id]||[]}const Bu={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 Ku(e,s,r){var n;return((n=Bu[s])==null?void 0:n.has(r.id))===!0}function ga(e,s){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Ku(s.hostIdeType,s.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function pn(e,s){return{value:s}}function Ou(e,s,r){var a;return r?((a=Tr(e,s).find(i=>i.value===r))==null?void 0:a.label)||r:""}const Wu={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Hu({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=jt(),u=`${e}:${s||n}`,p=Wu[n]||"#94a3b8",[d,h]=o.useState({}),f=o.useRef({}),v=o.useRef(c);f.current=d,v.current=c;const N=o.useRef(0),m={};for(const T of i||[])T.defaultValue!==void 0&&(m[T.id]=T.defaultValue);const g={...m,...c||{},...Date.now()<N.current?d:{}};o.useEffect(()=>{c&&Date.now()>N.current&&h({})},[c]);const[j,b]=o.useState(bo.get(u)||{}),[C,A]=o.useState(null),[w,M]=o.useState(null),S=o.useCallback(async(T,H={})=>{const B={...H,...s&&{targetSessionId:s}};return await l(e,T,B)},[e,s,l]),k=o.useCallback(async(T,H={})=>{const B=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await S("invoke_provider_script",{...B,scriptName:T,...H})},[S,n,r,s]),x=o.useCallback((T,H,B)=>{const D=Du(B,H);h(G=>({...G,[T.id]:D})),_u(B==null?void 0:B.effects)},[]),E=o.useCallback((T,H)=>{h(B=>{const D={...B};return H===void 0?delete D[T.id]:D[T.id]=H,D}),N.current=0},[]);if(!i||i.length===0)return null;const R=ga(i,{hostIdeType:r,providerType:n});if(R.length===0)return null;const I=async T=>{if(C===T.id){A(null);return}if(Tr(T,j).length>0){A(T.id);return}if(T.dynamic&&T.listScript){M(T.id);try{const B=await k(T.listScript,{}),D=Pu(B);if(!D){const xe=Rs(B);xe&&ct.showToast(xe,"warning");return}const G=D.options;b(xe=>{const re={...xe,[T.id]:G};return bo.set(u,re),re});const J=$u(T.id,{localOverrideUntil:N.current,localValues:f.current,controlValues:v.current,defaultValues:m});if(Eu(J,D.currentValue)){const xe=D.currentValue;h(re=>({...re,[T.id]:xe}))}A(T.id)}catch(B){const D=B instanceof Error?B.message:`Could not load ${T.label}`;ct.showToast(D,"warning")}finally{M(null)}}},P=async(T,H)=>{A(null);const B=(c==null?void 0:c[T.id])??m[T.id];h(D=>({...D,[T.id]:H})),N.current=Date.now()+5e3;try{if(!T.setScript)return;const D=await k(T.setScript,pn(T,H)),G=fr(D);if(G&&!G.ok||pr(D))throw new Error((G==null?void 0:G.error)||Rs(D)||`Could not update ${T.label}`);x(T,H,G)}catch(D){E(T,B);const G=D instanceof Error?D.message:`Could not update ${T.label}`;ct.showToast(G,"warning")}},K=async T=>{const H=Tr(T,j).map(re=>re.value);if(H.length===0)return;const B=String(g[T.id]||""),G=(H.indexOf(B)+1)%H.length,J=H[G];if(typeof J!="string")return;const xe=(c==null?void 0:c[T.id])??m[T.id];h(re=>({...re,[T.id]:J})),N.current=Date.now()+5e3;try{if(!T.setScript)return;const re=await k(T.setScript,pn(T,J)),ge=fr(re);if(ge&&!ge.ok||pr(re))throw new Error((ge==null?void 0:ge.error)||Rs(re)||`Could not update ${T.label}`);x(T,J,ge)}catch(re){E(T,xe);const ge=re instanceof Error?re.message:`Could not update ${T.label}`;ct.showToast(ge,"warning")}},z=async T=>{const B=!g[T.id],D=(c==null?void 0:c[T.id])??m[T.id];h(G=>({...G,[T.id]:B})),N.current=Date.now()+5e3;try{if(!T.setScript)return;const G=await k(T.setScript,pn(T,B)),J=fr(G);if(J&&!J.ok||pr(G))throw new Error((J==null?void 0:J.error)||Rs(G)||`Could not update ${T.label}`);x(T,B,J)}catch(G){E(T,D);const J=G instanceof Error?G.message:`Could not update ${T.label}`;ct.showToast(J,"warning")}},L=async T=>{if(!T.invokeScript)return;if(T.confirmMessage){const B=[T.confirmTitle,T.confirmMessage,T.confirmLabel].filter(G=>typeof G=="string"&&G.trim().length>0);if(!window.confirm(B.join(`
28
-
29
- `)))return}const H=(c==null?void 0:c[T.id])??m[T.id];try{const B=await k(T.invokeScript),D=fr(B);if(D&&!D.ok||pr(B))throw new Error((D==null?void 0:D.error)||Rs(B)||`Could not run ${T.label}`);D&&x(T,H??!0,D)}catch(B){E(T,H);const D=B instanceof Error?B.message:`Could not run ${T.label}`;ct.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:`${p}33`,background:`${p}12`,color:p},children:a}),R.map(T=>{const H=String(g[T.id]||""),B=Ou(T,j,H),D=C===T.id,G=w===T.id,J=Tr(T,j),xe="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(T.type){case"select":return t.jsxs("div",{className:"relative max-w-full",children:[t.jsxs("button",{type:"button",className:`${xe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:D?`${p}55`:"var(--border-default)",background:D?`${p}10`:"var(--surface-tertiary)",color:H?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void I(T),title:T.label,children:[T.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:G?"Loading…":B||T.label}),t.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),D&&J.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>A(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:T.label}),J.map(re=>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:re.value===H?`${p}14`:"transparent",color:re.value===H?"var(--text-primary)":"var(--text-secondary)",borderLeft:re.value===H?`2px solid ${p}`:"2px solid transparent"},title:re.description||re.label,onMouseEnter:ge=>{ge.currentTarget.style.background=`${p}10`},onMouseLeave:ge=>{ge.currentTarget.style.background=re.value===H?`${p}14`:"transparent"},onClick:()=>void P(T,re.value),children:[t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:re.label}),re.value===H&&t.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:p},children:"✓"})]},re.value))]})]})]},T.id);case"cycle":return t.jsxs("button",{type:"button",className:`${xe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:H?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void K(T),title:`Click to cycle: ${J.map(re=>re.label).join(" → ")}`,children:[T.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:B||T.label}),t.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},T.id);case"toggle":return t.jsxs("button",{type:"button",className:`${xe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:H?`${p}44`:"var(--border-default)",background:H?`${p}14`:"var(--surface-tertiary)",color:H?p:"var(--text-muted)"},onClick:()=>void z(T),"aria-pressed":!!H,children:[T.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),T.label]},T.id);case"action":return t.jsxs("button",{type:"button",className:`${xe} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void L(T),children:[T.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:T.resultDisplay==="inline"&&H?`${T.label}: ${H}`:T.label})]},T.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:H?"var(--text-primary)":"var(--text-muted)"},children:[T.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:H?`${T.label}: ${H}`:T.label})]},T.id);default:return null}})]})})}function Fu({isActive:e=!0,isCliTerminal:s=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:p}=Ti(),d=ga(l,{hostIdeType:a,providerType:i});return!e||s||d.length===0||!p?null:t.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:t.jsx(Hu,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:d,controlValues:u})})}function Uu({hasDraft:e,isBusy:s=!1}){return!e||s}const Bi=o.memo(function({contextKey:s,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:u=!1}){const p=o.useRef(null),[d,h]=o.useState(""),{isVisible:f,toggleVisibility:v}=Ti();o.useEffect(()=>{h("")},[s]),o.useEffect(()=>{var m;l&&((m=p.current)==null||m.focus())},[s,l]);const N=async()=>{const m=d.trim();if(!m||a)return;await c(m)!==!1&&h("")};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:v,"aria-label":f?"Hide controls":"Show controls","aria-pressed":f,title:f?"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:p,type:"text",placeholder:i||`Send message to ${r}...`,value:d,onChange:m=>h(m.target.value),onPaste:m=>{const g=m.clipboardData.getData("text");g&&h(j=>j+g),m.preventDefault()},onKeyDown:m=>{if(m.key==="Enter"){if(m.nativeEvent.isComposing){m.preventDefault();return}m.preventDefault(),N()}},onBlur:m=>{if(window.innerWidth<768){const g=m.relatedTarget;if((g==null?void 0:g.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:()=>{N()},disabled:Uu({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})]})}),Qe=e=>e.transport==="pty",Ts=(e,s)=>Qe(e)?e.mode||"terminal":"chat",Ki=(e,s)=>Qe(e)&&Ts(e)==="terminal",Ge=e=>e.transport==="acp";function zt(e){return e.streamSource!=="agent-stream"}function qt(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function Oi(e){return e.machineName||""}function sr(e){return qt(e)}function _t(e){return e.agentType||""}function Wr(e){return e.hostIdeType||""}function ya(e){return e.displayPrimary||e.agentName||"Agent"}function Wi(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function zu(e){return e.lastMessagePreview||e.displaySecondary||""}function Hi(e){return[e.displaySecondary,Oi(e)].filter(Boolean)}function Ns(e){return e.agentName||et(_t(e))}function Vu(e){var s,r;if(!zt(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return et(Wr(e)||_t(e))}function Fi(e){return zt(e)?e.sessionId:e.nativeSessionId}function go(e){return zt(e)?"native":e.tabKey}function Gu(e){return e.sessionId}function qu(e,s){if(s)return zt(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function Yu(e,s){const r=_t(e),n=zt(e),a=Qe(e)||Ge(e),i=n?a?Ns(e)||(s==null?void 0:s.cliName)||et(Wr(e)||r):s!=null&&s.type?et(s.type):et(Wr(e)||r):Ns(e);return{isNativeConversation:n,isCli:Qe(e),isAcp:Ge(e),isCliTerminal:Ki(e),providerType:r,displayLabel:i,targetEntry:qu(e,s)}}function gt(e){return(typeof e=="string"?e.trim():"")||void 0}function Ht(e,s){const r=gt(s);return r?`${e}:${r}`:void 0}function Ut(e,s,r){const n=Ht(s,r),a=gt(r);n&&e.push(n),a&&e.push(a)}function bs(e){const s=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),s.push(n));return s}function Ui(e){return gt(e.providerSessionId)||gt(e.sessionId)||gt(e.tabKey)||gt(e.routeId)}function va(e){return bs([gt(e.providerSessionId),gt(e.sessionId)])}function vs(e){const s=[];return Ut(s,"provider",e.providerSessionId),Ut(s,"session",e.sessionId),Ut(s,"tab",e.tabKey),Ut(s,"route",e.routeId),bs(s)}function Xu(e){const s=[];return gt(e.providerSessionId)?(Ut(s,"provider",e.providerSessionId),bs(s)):gt(e.sessionId)?(Ut(s,"session",e.sessionId),bs(s)):gt(e.tabKey)?(Ut(s,"tab",e.tabKey),bs(s)):gt(e.routeId)?(Ut(s,"route",e.routeId),bs(s)):[]}function wa(e){return Ht("provider",e.providerSessionId)||Ht("session",e.sessionId)||Ht("tab",e.tabKey)||Ht("route",e.routeId)||"unknown:"}function rr(e){return va(e)[0]}function Ju(e){const s=gt(e.providerSessionId),r=gt(e.sessionId),n=gt(e.tabKey),a=gt(e.routeId),i=[Ht("provider",s),Ht("session",r),Ht("tab",n),Ht("route",a)].filter(u=>typeof u=="string"),c=vs({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),l=wa({providerSessionId:s,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:s,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:Ui({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),historySessionId:rr({providerSessionId:s,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function Yn(e,s){const r=Ju(e);return Xu(s).some(n=>r.lookupKeys.includes(n))}function Qu(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 es(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||Qu(s==null?void 0:s.receivedAt)||0}function Xn(e,s=0){return es(e)||e.lastUpdated||s||0}function zi(e){return es(e)||e.lastUpdated||0}function Vi(e,s,r=zi){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 Jn(e){var r;const s=bt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function Zu(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!Jn(e)&&!e.title.trim()}function em(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(Jn(r))-Number(Jn(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:Vi(s,r)})[0]||null}function Dt(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=em(a);return n?i&&Zu(n)?i:n:i||r[0]||null}function Vt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function ja(e){return rr(e)||e.tabKey||e.routeId||null}function Gi(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=Dt(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?ja(a):null}function qi({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Ms(),c=qt(e),l=Oi(e),u=e.transport==="cdp-page"||e.transport==="cdp-webview",p=e.streamSource==="agent-stream"&&!!e.agentName,d=!p&&(e.transport==="pty"||e.transport==="acp"),h=Ns(e),f=Vu(e),v=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),N=o.useCallback(()=>{if(r){r();return}const m=ja(e);m&&i(Vt(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:N,title:f,children:[t.jsx(Ct,{size:12}),t.jsx("span",{children:f})]}):t.jsxs("span",{className:"conversation-meta-chip",title:f,children:[t.jsx(Ct,{size:12}),t.jsx("span",{children:f})]})),p&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[t.jsx(Ys,{size:12}),t.jsx("span",{children:h})]}),d&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[t.jsx(Ys,{size:12}),t.jsx("span",{children:h})]}),l&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:v,title:l,children:[t.jsx(ls,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(ls,{size:12}),t.jsx("span",{children:l})]}))]})}function hn(e,s){return`${e}:${s}`}function tm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function hr(e,s){tm()&&console.debug(`[subscription-manager] ${e}`,s)}class sm{constructor(){Ve(this,"active",new Map)}subscribe(s,r,n,a){var p;const i=hn(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),hr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((p=s.sendData)==null?void 0:p.call(s,r,n))??!1}const u=()=>{var f;const d=this.active.get(i);if(!d||(d.handlers.delete(a),d.handlers.size>0))return;this.active.delete(i);const h={type:"unsubscribe",topic:n.topic,key:n.key};hr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(f=s.sendData)==null||f.call(s,r,h)};return u.initialSendAccepted=l,u}publish(s){const r=hn(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,js.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),js.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=hn(s,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(s){var r;hr("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);hr("resubscribe_daemon",{daemonId:s,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(a=r.sendData)==null||a.call(r,i.daemonId,i.request)}}const Gt=new sm;function rm(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 nm(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 Hr(e,s){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=s,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:p,childrenByParent:d}=nm(u),h=rm(i,n),f=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,v=p.filter(g=>g.kind==="workspace"&&g.transport==="cdp-page"),N=p.filter(g=>g.kind==="agent"&&g.transport==="pty"),m=p.filter(g=>g.kind==="agent"&&g.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...f&&{machine:f,platform:f.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:v.some(g=>!!g.cdpConnected)});for(const g of v){const j=h.get(g.id),b=Ks(g,j),C=(d.get(g.id)||[]).map(A=>Ks(A,h.get(A.id)));r.push({id:`${n}:ide:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,status:b.cdpConnected?"online":"detected",daemonId:n,instanceId:g.id,workspace:b.workspace,terminals:0,childSessions:C,agents:C.map(A=>({id:A.id,name:A.providerName||A.providerType,type:A.providerType,status:A.status})),activeChat:b.activeChat,chats:[],cdpConnected:b.cdpConnected,...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l})}for(const g of N){const j=h.get(g.id),b=Ks(g,j);r.push({id:`${n}:cli:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:g.id,cliName:b.providerName||b.providerType,mode:b.mode||(j==null?void 0:j.mode)||"terminal",workspace:b.workspace||"",activeChat:b.activeChat,...b.resume!==void 0&&{resume:b.resume},...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l,_isCli:!0})}for(const g of m){const j=h.get(g.id),b=Ks(g,j);r.push({id:`${n}:acp:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:g.id,cliName:b.providerName||b.providerType,mode:"chat",workspace:b.workspace||"",activeChat:b.activeChat,...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const am=15e3,om=15e3,im=6e4,cm=1200,yo=12,lm=8e3,dm=4e3,xn=new Map,bn=new Map,xr=new Set,Hs=new Map;function um(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 vo(e,s){const r=Hs.get(e);!r||r.size===0||(Hs.delete(e),r.forEach(n=>n(s)))}function mm(e,s){return new Promise(r=>{const n=Hs.get(e)||new Set;Hs.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&Hs.delete(e),r(c)},i=setTimeout(()=>a(!1),s);n.add(a)})}function nr(){const{sendCommand:e,sendData:s}=jt(),{injectEntries:r,getIdes:n}=Gs();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??im,l=bn.get(a)||0;if(!(i!=null&&i.force)&&xr.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=xn.get(a);if(u)return u;const p=(async()=>{if(s&&!xr.has(a)){const m=Gt.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},g=>{const j=n(),b=j.find(A=>A.id===a),C=Hr(g.status,{daemonId:a,existingDaemon:b,existingEntries:j,timestamp:g.timestamp});C.length>0&&r(C),bn.set(a,Date.now()),vo(a,!0)});if(m.initialSendAccepted?xr.add(a):xr.delete(a),!(i!=null&&i.force)&&m.initialSendAccepted&&await mm(a,cm))return}const d=await e(a,"get_status_metadata"),h=um(d);if(!h)return;const f=n(),v=f.find(m=>m.id===a),N=Hr(h,{daemonId:a,existingDaemon:v,existingEntries:f,timestamp:h.timestamp||Date.now()});N.length>0&&r(N,{authoritativeDaemonIds:[a]}),bn.set(a,Date.now()),vo(a,!0)})().finally(()=>{xn.delete(a)});return xn.set(a,p),p},[n,r,e,s])}function fm(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function ws(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:Qe(e)||Ge(e)?{agentType:_t(e)}:e.streamSource==="agent-stream"?{agentType:_t(e)}:s}function Js(e){return e?sr(e):""}function Ps(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function ka(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function pm(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 hm=60,xm=1e3;function Yi(e={}){return e.isCliLike?xm:hm}function bm(e={}){return Yi(e)}const ar=60,gm=1e3,Sa=12e4,ym=new Set(["generating","waiting_approval","starting","streaming","working"]),wo=new Map;function Xi(e,s){return`${e}::${s}`}function Qn(e=ar){return{liveMessages:[],cursor:Qi([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Ji(e){return hi(e)}function Qi(e,s=ar){return{knownMessageCount:e.length,lastMessageSignature:Ji(e[e.length-1]),tailLimit:s}}function br(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 vm(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 wm{constructor(s){Ve(this,"manager");Ve(this,"sendData");Ve(this,"daemonId");Ve(this,"sessionId");Ve(this,"historySessionId");Ve(this,"subscriptionKey");Ve(this,"snapshot");Ve(this,"transportSubscription",null);Ve(this,"listeners",new Set);Ve(this,"retainCount",0);Ve(this,"loadHistoryPromise",null);Ve(this,"pendingDisconnectTimer",null);Ve(this,"pendingSubscribeRetryTimer",null);this.manager=s.manager||Gt,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.snapshot=Qn(Math.max(0,s.tailLimit??ar))}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=Qi(n,this.snapshot.cursor.tailLimit);br(this.snapshot.liveMessages)===br(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()},gm))}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=vm(this.snapshot.liveMessages,s),n={knownMessageCount:r.length,lastMessageSignature:typeof s.lastMessageSignature=="string"?s.lastMessageSignature:Ji(r[r.length-1]),tailLimit:this.snapshot.cursor.tailLimit};br(this.snapshot.liveMessages)===br(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 Zi(e){const s=Xi(e.daemonId,e.sessionId),r=wo.get(s);if(r)return r.updateOptions(e),r;const n=new wm(e);return wo.set(s,n),n}function jm(e,s){return{...e,loadHistoryPage:s}}function km(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function Sm(e,s={}){const r=String(e.status||"").trim().toLowerCase();if(ym.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??Sa)),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 Nm(e=Sa){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Cm(e,s={}){const r=new Set,n=[];for(const a of e){if(!Sm(a,s))continue;const i=sr(a),c=a.sessionId||"";if(!i||!c)continue;const l=Xi(i,c);if(r.has(l))continue;r.add(l);const u=rr(a);n.push({daemonId:i,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(km),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Im(e,s){const{sendData:r,sendCommand:n}=jt(),a=(s==null?void 0:s.enabled)!==!1,i=sr(e),c=e.sessionId||"",l=rr(e)||c,u=`daemon:${i}:session:${c}`,p=Math.max(0,(s==null?void 0:s.tailLimit)??ar),d=o.useMemo(()=>!a||!i||!c?null:Zi({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:p}),[i,a,l,r,c,u,p]),[h,f]=o.useState(()=>(d==null?void 0:d.getSnapshot())||Qn(p));o.useEffect(()=>{if(!d){f(Qn(p));return}d.retain(),f(d.getSnapshot());const N=d.subscribe(m=>{f(m)});return()=>{N(),d.release()}},[d,p]),o.useEffect(()=>{d&&(d.hydrateLiveMessages(e.messages),f(d.getSnapshot()))},[e.messages,d]);const v=o.useCallback(async()=>{!d||!i||!c||await d.loadHistoryPage(async()=>{const N=e.agentType,m=await n(i,"chat_history",{agentType:N,offset:d.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),g=m&&typeof m=="object"&&"result"in m?m.result||{}:m||{};return{messages:Array.isArray(g.messages)?g.messages:[],hasMore:g.hasMore===!0}})},[e.agentType,d,i,l,n,c]);return o.useMemo(()=>jm(h,v),[v,h])}function Mm(e,s){const{sendData:r}=jt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,(s==null?void 0:s.tailLimit)??ar),i=Math.max(0,Number((s==null?void 0:s.recentActivityMs)??Sa)),c=Nm(i),[l,u]=o.useState(0);o.useEffect(()=>{if(!n||e.length===0)return;const d=setInterval(()=>{u(h=>h+1)},c);return()=>{clearInterval(d)}},[e.length,n,c]);const p=o.useMemo(()=>Cm(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||p.descriptors.length===0)return;const d=p.descriptors.map(h=>Zi({...h,sendData:r,tailLimit:a}));return d.forEach(h=>h.retain()),()=>{d.forEach(h=>h.release())}},[p.signature,n,r,a])}function Am(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function Tm(e){return Am(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Lm=60;function Zn({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:p=!1,scrollToBottomRequestNonce:d,isInputActive:h=!0}){var ge,ye,Q,fe,W;const f=o.useRef(new Map),v=nr();tr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const N=St.useMemo(()=>As(e),[e.status,e.connectionState]),m=o.useMemo(()=>Yu(e,s),[e,s]),g=o.useMemo(()=>{var q;return ga((q=m.targetEntry)==null?void 0:q.providerControls,{hostIdeType:e.hostIdeType,providerType:m.providerType})},[e.hostIdeType,m.providerType,(ge=m.targetEntry)==null?void 0:ge.providerControls]),j=Yi({isCliLike:m.isCli||m.isAcp}),b=bm({isCliLike:m.isCli||m.isAcp}),C=Im(e,{enabled:!!e.sessionId,tailLimit:b}),[A,w]=o.useState(j),M=e.tabKey,S=C.historyMessages,k=C.hasMoreHistory,x=C.historyError,E=C.liveMessages.length>0?C.liveMessages:e.messages;o.useEffect(()=>{w(j)},[j,M]);const R=Math.max(0,E.length-A),I=ya(e),P=sr(e),K=Tm(e),z=ka(e),L=a||z,T=!!z,[H,B]=o.useState(!1);o.useEffect(()=>{const q=m.targetEntry;P&&(!q||q.providerControls===void 0||q.controlValues===void 0)&&v(P,{minFreshMs:3e4}).catch(()=>{})},[P,m.isAcp,(ye=m.targetEntry)==null?void 0:ye.providerControls,(Q=m.targetEntry)==null?void 0:Q.controlValues,v]);const D=o.useCallback(async()=>{if(!H){if(E.length>A){w(q=>Math.min(E.length,q+Lm));return}B(!0);try{await C.loadHistoryPage()}finally{B(!1)}}},[C,H,E.length,A]),{allMessages:G,receivedAtMap:J}=o.useMemo(()=>{const q=R>0?E.slice(-A):E,oe=S.length===0?q:[...S,...q],he={};return oe.forEach((le,ve)=>{const ne=`${e.tabKey}:${Kr(le,ve)}`;let pe=fm(le)||f.current.get(ne)||0;pe||(pe=Date.now(),f.current.set(ne,pe)),he[Kr(le,ve)]=pe}),{allMessages:oe,receivedAtMap:he}},[e.tabKey,R,S,E,A]),xe=o.useMemo(()=>l.filter(q=>q.routeId===e.tabKey).sort((q,oe)=>q.timestamp-oe.timestamp),[l,e.tabKey]),re=o.useMemo(()=>{if(E.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((N.isGenerating||e.status==="streaming")&&B(!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(Ys,{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(ks,{size:14})," Open ",I," 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(vi,{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(ks,{size:14})," Open ",I," 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"&&!H)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,H,E.length,I,N.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[p&&t.jsx(qi,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(Ud,{messages:G,actionLogs:xe,agentName:Ns(e)||I||"Agent",userName:u,isCliMode:m.isCli||m.isAcp,isWorking:N.isGenerating,contextKey:e.tabKey,receivedAtMap:J,onLoadMore:D,isLoadingMore:H,hasMoreHistory:k,hiddenLiveCount:R,loadError:x??void 0,emptyState:re,scrollToBottomRequestNonce:d}),t.jsx(Fu,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:m.providerType,displayLabel:m.displayLabel,controls:(fe=m.targetEntry)==null?void 0:fe.providerControls,controlValues:(W=m.targetEntry)==null?void 0:W.controlValues,isActive:h,isCliTerminal:m.isCliTerminal}),!m.isCliTerminal&&t.jsx(Bi,{contextKey:e.tabKey,panelLabel:I,isSending:n,isBusy:T,statusMessage:L,onSend:r,isActive:h,showControlsToggle:g.length>0})]})}let ec=cs;function tc(){return ec()}class Rm{constructor(){Ve(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 sc=new Rm;class Pm{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 Ye=new Pm;function _m(e){e.dashboardWS&&(sc=e.dashboardWS),e.connectionManager&&(Ye=e.connectionManager),e.useDaemonsHook&&(ec=e.useDaemonsHook)}const Dm=.5,Em=1.25;function st(e){return ya(e)}function us(e){return Hi(e).join(" · ")}function rc(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=qr(s==null?void 0:s.content);return r||(e.title?e.title:us(e)||"No messages yet")}function nc(e,s){const{isReconnecting:r,isConnecting:n}=As(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function $m(e,s){const r=["Chat",...Hi(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function ts(e){return nc(e)||us(e)}function Bm(e){return`${st(e)} · ${rc(e)}`}function Km(e){const s=Wr(e),r=s?et(s):Ns(e);return`${st(e)} — ${r||"Agent"}`}function Om(e){return Ns(e)||"CLI"}function ac(e){return Wi(e)}function oc(e){return e?`Remote · ${st(e)||e.workspaceName||"Session"}`:"Remote"}function Wm({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var je;cs();const{sendPtyInput:u}=jt(),[p,d]=o.useState(!1),[h,f]=o.useState(1),[v,N]=o.useState({width:0,height:0}),[m,g]=o.useState({width:0,height:0}),j=o.useRef(null),b=o.useRef(null),C=o.useRef(!1),A=o.useRef(!1),w=o.useRef(0),M=o.useRef(!1),S=o.useRef(""),k=o.useRef(null),x=o.useRef(!1),E=o.useRef(null),R=32*1024,I=()=>{var U,se,y,X;return((se=(U=j.current)==null?void 0:U.ownerDocument)==null?void 0:se.defaultView)||((X=(y=b.current)==null?void 0:y.ownerDocument)==null?void 0:X.defaultView)||window},P=U=>{const se=I();return{ownerWindow:se,frameId:se.requestAnimationFrame(U)}},K=()=>{const U=E.current;if(U){try{U.ownerWindow.cancelAnimationFrame(U.frameId)}catch{}E.current=null}},z=()=>{c&&E.current===null&&(E.current=P(()=>{ce()}))},L=e.tabKey,T=e.sessionId||"",H=e.daemonId||((je=e.routeId)==null?void 0:je.split(":")[0])||e.routeId||"",B=ka(e),D=p?i||B:"Runtime terminal unavailable",G=Dm,J=Em,xe=.05,re=Number.isFinite(h)&&h>0?h:1,ge=Number((13*h).toFixed(2)),ye=()=>{const U=m.width>0?Math.max(v.width,Math.round(m.width)):v.width,se=m.height>0?Math.max(v.height,Math.round(m.height)):v.height;if(!Number.isFinite(v.width)||v.width<=0||!Number.isFinite(v.height)||v.height<=0||!Number.isFinite(U)||U<=0||!Number.isFinite(se)||se<=0)return 1;const y=U/re,X=se/re;if(!Number.isFinite(y)||y<=0||!Number.isFinite(X)||X<=0)return 1;const te=v.width/y,ue=v.height/X;return Number(Math.min(J,Math.max(G,Math.min(te,ue))).toFixed(2))},Q=ye(),fe=C.current&&h>Q,W=m.width>v.width+1||m.height>v.height+1,q=m.width>0?Math.max(v.width,Math.round(m.width)):v.width,oe=m.height>0?Math.max(v.height,Math.round(m.height)):v.height,he=m.width>0?Math.round(m.width):q,le=m.height>0?Math.round(m.height):oe,ve=()=>{P(()=>{const U=b.current;U&&(U.scrollLeft=0,U.scrollTop=U.scrollHeight-U.clientHeight)})},ne=()=>{var U,se;w.current=0,M.current=!1,S.current="",k.current=null,x.current=!1,C.current||(A.current=!1,f(1)),E.current!==null&&K(),d(!1),(se=(U=r.current)==null?void 0:U.reset)==null||se.call(U)},pe=()=>{var U,se;w.current=0,M.current=!1,S.current="",k.current=null,x.current=!1,E.current!==null&&K(),d(!0),(se=(U=r.current)==null?void 0:U.reset)==null||se.call(U)},ce=()=>{var y;if(E.current=null,!c)return;const U=S.current;if(!U)return;const se=U.slice(0,R);S.current=U.slice(se.length),(y=r.current)==null||y.write(se),S.current.length>0&&z()},de=U=>{U&&(S.current+=U,z())},ae=(U,se=0,y,X)=>{var te,ue,we,Ne;se>0&&w.current>=se||se===0&&M.current||(w.current=se,d(!0),typeof y=="number"&&typeof X=="number"&&y>0&&X>0&&((ue=(te=r.current)==null?void 0:te.resize)==null||ue.call(te,y,X)),S.current="",(Ne=(we=r.current)==null?void 0:we.reset)==null||Ne.call(we),U&&de(U))};return o.useEffect(()=>{ne()},[T]),o.useEffect(()=>{var se;if(!T)return;const U=((se=Ye.onRuntimeEvent)==null?void 0:se.call(Ye,T,y=>{if(!(!y||y.sessionId!==T)){if(y.type==="runtime_snapshot"){if(!c){k.current={text:y.text||"",seq:y.seq||0,cols:y.cols,rows:y.rows};return}ae(y.text||"",y.seq||0,y.cols,y.rows);return}if(y.type==="session_output"){M.current=!0,typeof y.seq=="number"&&(w.current=Math.max(w.current,y.seq)),p||d(!0),typeof y.data=="string"&&de(y.data);return}if(y.type==="session_cleared"){if(!c){x.current=!0,S.current="",k.current=null;return}pe()}}}))||(()=>{});return()=>{U()}},[H,T,r,c,p]),o.useEffect(()=>{var se,y,X;if(!T)return;H&&((se=Ye.getState)==null?void 0:se.call(Ye,H))==="connected"&&(d(!0),(y=Ye.requestRuntimeSnapshot)==null||y.call(Ye,H,T).catch(()=>{}));const U=(X=Ye.onStateChange)==null?void 0:X.call(Ye,(te,ue)=>{var we;te!==H||ue!=="connected"||(d(!0),(we=Ye.requestRuntimeSnapshot)==null||we.call(Ye,H,T).catch(()=>{}))});return()=>{U==null||U()}},[H,T,r]),o.useEffect(()=>{s&&ne()},[s,L,r]),o.useEffect(()=>{var X,te;const U=j.current,se=(te=(X=U==null?void 0:U.ownerDocument)==null?void 0:X.defaultView)==null?void 0:te.ResizeObserver;if(!U||!se)return;const y=new se(ue=>{const we=ue[0];if(!we)return;const{width:Ne,height:Be}=we.contentRect;N(Ke=>{const Fe=Math.round(Ne),Ue=Math.round(Be);return Ke.width===Fe&&Ke.height===Ue?Ke:{width:Fe,height:Ue}})});return y.observe(U),()=>y.disconnect()},[]),o.useEffect(()=>{if(C.current)return;const U=ye();!Number.isFinite(U)||U<=0||f(se=>A.current?U<se-xe?U:se:(A.current=!0,U))},[m.height,m.width,v.height,v.width]),o.useEffect(()=>{!W&&!fe||ve()},[W,fe,oe,q]),o.useEffect(()=>{var se,y;if(!c)return;x.current&&(x.current=!1,pe());const U=k.current;U&&(k.current=null,ae(U.text,U.seq,U.cols,U.rows)),H&&T&&((se=Ye.getState)==null?void 0:se.call(Ye,H))==="connected"&&((y=Ye.requestRuntimeSnapshot)==null||y.call(Ye,H,T).catch(()=>{})),S.current&&E.current===null&&z(),P(()=>{var X;(X=r.current)==null||X.bumpResize()})},[H,c,T]),o.useEffect(()=>()=>{E.current!==null&&K()},[]),o.useEffect(()=>{const U=X=>{var ue;const te=X.detail;te!=null&&te.sessionId&&te.sessionId!==T||p&&((ue=r.current)==null||ue.bumpResize())},se=I(),y=se===window?[window]:[window,se];for(const X of y)X.addEventListener("adhdev:fit-cli-terminal",U);return()=>{for(const X of y)X.removeEventListener("adhdev:fit-cli-terminal",U)}},[p,T,r]),t.jsxs(t.Fragment,{children:[t.jsxs("div",{ref:j,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:()=>{C.current=!0,f(U=>{const se=Math.max(Q,Number((U-.1).toFixed(2)));return se>Q&&ve(),se})},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:()=>{C.current=!0,f(U=>{const se=Math.min(J,Number((U+.1).toFixed(2)));return se>Q&&ve(),se})},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{ref:b,className:W?"w-full h-full overflow-x-auto overflow-y-hidden rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",style:{display:"flex",justifyContent:"flex-start",alignItems:"flex-end"},children:t.jsx("div",{style:{width:he>0?`${he}px`:q>0?`${q}px`:"100%",height:le>0?`${le}px`:oe>0?`${oe}px`:"100%",minWidth:he>0?`${he}px`:"100%",minHeight:le>0?`${le}px`:"100%",position:"relative"},children:t.jsx("div",{style:{width:"100%",height:"100%",position:"absolute",left:0,bottom:0},children:t.jsx(Ci,{ref:r,readOnly:!p||!c,sizingMode:"measured",fontSize:ge,onViewportMetrics:g,onInput:U=>{!p||(u==null||u(H,T,U))}})})})}),!p&&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(Bi,{contextKey:e.tabKey,panelLabel:st(e),isSending:a,isBusy:!p||!!B,statusMessage:D,onSend:async U=>!p||B?!1:n(U),isActive:l&&c,showControlsToggle:!1})]})}function Hm({wsStatus:e,showReconnected:s,loginUrl:r,onReconnect:n}){const a=e==="disconnected"||e==="reconnecting"||e==="offline"||e==="auth_failed",i=e==="auth_failed"?"red":e==="offline"?"orange":"accent",c={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))"},l={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},u={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},p="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",d={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return t.jsxs(t.Fragment,{children:[a&&t.jsx("div",{className:p,style:d,children:t.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-4 py-3 text-[13px] font-semibold flex items-center gap-2.5 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:c[i],border:l[i],color:u[i]},children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",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}}),t.jsxs("span",{className:"min-w-0 text-center",children:[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.")]}),n&&e!=="auth_failed"&&t.jsx("button",{type:"button",className:"ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:n,disabled:e==="offline",children:"Reconnect now"})]})}),s&&e==="connected"&&t.jsx("div",{className:p,style:d,children:t.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 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-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function Fm({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 Na({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(fa,{size:n}):t.jsx(Ft,{size:n})})}const Bt="New session",ic="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 Um({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 jo({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function ko({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=Jr(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 zm({activeConv:e,wsStatus:s,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:u,onHideConversation:p,hiddenConversations:d=[],onShowConversation:h,onShowAllHidden:f,onResetPanelsToMain:v,inboxOpen:N,onInboxOpenChange:m,hiddenOpen:g,onHiddenOpenChange:j,onOpenNewSession:b,actionShortcuts:C,notifications:A,notificationUnreadCount:w,onOpenNotification:M,onMarkNotificationRead:S,onMarkNotificationUnread:k,onDeleteNotification:x}){const{ides:E,p2pStates:R={}}=cs(),I=!!e&&Qe(e)&&!Ge(e),P=!!e&&Ge(e),K=l||(e?Ki(e)?"terminal":"chat":null),[z,L]=o.useState(!1),T=o.useRef(null),H=o.useRef(null),B=E.filter(W=>W.type==="adhdev-daemon"),D=Um({wsStatus:s,isConnected:r,daemonCount:B.length,p2pStates:R}),G=D.subtitle,J=D.tone==="connected"?"#22c55e":D.tone==="limited"?"#eab308":"#ef4444",xe=D.tone==="connected"?"0 0 4px #22c55e80":D.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",re=o.useMemo(()=>A.filter(W=>!W.readAt),[A]),ge=o.useMemo(()=>A.filter(W=>!!W.readAt),[A]),ye=o.useMemo(()=>re.slice(0,9),[re]),Q=w;o.useEffect(()=>{if(!N)return;const W=q=>{var oe;(oe=T.current)!=null&&oe.contains(q.target)||m(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[N,m]),o.useEffect(()=>{if(!g)return;const W=q=>{var oe;(oe=H.current)!=null&&oe.contains(q.target)||j(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[g,j]),o.useEffect(()=>{if(!g&&!N)return;const W=q=>{if(!q.altKey)return;const oe=q.code.match(/^Digit([1-9])$/);if(!oe)return;const he=Number(oe[1])-1,le=g?d[he]:void 0,ve=N?ye[he]:void 0;if(!(!le&&!ve)){if(q.preventDefault(),q.stopPropagation(),le){h==null||h(le),j(!1);return}ve&&(M(ve),m(!1))}};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[d,g,N,ye,j,m,M,h]);const fe=W=>{if(!W)return;const q=n.find(oe=>oe.tabKey===W);q&&(p==null||p(q))};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(Ft,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?st(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:J,boxShadow:xe}})})]}),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:J,boxShadow:xe}}),G&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",G]}),b&&t.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:Bt,"aria-label":Bt,children:t.jsx(ki,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(I||P||!Ge(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:us(e)||st(e),children:st(e)}),(I||P)&&c&&t.jsxs(t.Fragment,{children:[I&&u&&K&&t.jsx(Na,{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(wt,{size:14})})]}),!Ge(e)&&t.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(ma,{size:14})}),!I&&!Ge(e)&&t.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(Ct,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:T,children:[t.jsxs("div",{className:`dashboard-header-hidden${z?" is-drop-target":""}`,ref:H,onDragEnter:W=>{W.dataTransfer.types.includes("text/tab-key")&&(W.preventDefault(),L(!0))},onDragOver:W=>{W.dataTransfer.types.includes("text/tab-key")&&(W.preventDefault(),W.dataTransfer.dropEffect="move",L(!0))},onDragLeave:W=>{W.currentTarget.contains(W.relatedTarget)||L(!1)},onDrop:W=>{const q=W.dataTransfer.getData("text/tab-key");W.preventDefault(),L(!1),fe(q)},children:[t.jsxs("button",{type:"button",onClick:()=>j(!g),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${C!=null&&C.toggleHiddenTabs?` (${C.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(wi,{size:16}),d.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:d.length})]}),g&&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(jo,{value:C==null?void 0:C.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[v&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:v,children:"Reset panels"}),d.length>0&&f&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),j(!1)},children:"Restore all"})]})]}),e&&p&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>p(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(jo,{value:C==null?void 0:C.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:st(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:()=>{h==null||h(W),j(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:st(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,us(W)]})]},W.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>m(!N),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(Xr,{size:16}),Q>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:Q})]}),N&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[re.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),re.map(W=>t.jsx(ko,{notification:W,shortcutIndex:ye.indexOf(W)>=0?ye.indexOf(W)+1:void 0,onOpen:()=>M(W),onMarkRead:()=>S(W.id),onMarkUnread:()=>k(W.id),onDelete:()=>x(W.id)},W.id))]}),ge.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),ge.map(W=>t.jsx(ko,{notification:W,onOpen:()=>M(W),onMarkRead:()=>S(W.id),onMarkUnread:()=>k(W.id),onDelete:()=>x(W.id)},W.id))]}),A.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function pt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Vm(e,s){return String(e||"")!==String(s||"")}function Gm(e,s={}){const r=String(s.textQuery||"").trim().toLowerCase(),n=String(s.workspaceQuery||"").trim().toLowerCase(),a=String(s.modelQuery||"").trim().toLowerCase(),i=!!s.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(u=>String(u||"").toLowerCase()).join(`
30
- `).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!Pi(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
31
- `).includes(a)))}function qm(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 cc(e,s={}){return qm(Gm(e,s),s.sortMode||"recent")}function Fr(e){return e?"Resume saved history":"Start fresh"}function Ca(e){return e?"Resuming saved history…":"Starting fresh…"}function Ym(){return"Start fresh"}function lc(e,s=!1){return e==="cli"?Fr(s):e==="ide"?"Start IDE":"Start ACP session"}function dc(e,s=!1){return e==="cli"?Ca(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Xm(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Jm(){return"Open saved history"}function Qm(){return"Saved History"}function Ia(){return"Use saved history when you want continuity in the same provider conversation."}function Zm(){return"No saved history found yet."}function ef(){return"Refresh saved history"}function tf(){return"Refreshing saved history…"}function ss(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function rs(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Cs(e){return e==="start-fresh"?"Start fresh":"Restart"}function Is(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Ma(e){return`Resume saved history with ${e}?`}function Aa(){return"Review or change the target workspace before resuming saved history."}function sf(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 Ta({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:p,onNewChat:d,onSwitchSession:h,onRefreshHistory:f,onResumeSavedSession:v}){var k;const N=s.find(x=>x.id===e.routeId),m=(N==null?void 0:N.chats)||[],g=(k=N==null?void 0:N.activeChat)==null?void 0:k.id,j=Qe(e)&&!Ge(e),[b,C]=o.useState(()=>pt()),A=l||b,w=x=>{if(u){u(x);return}C(x)},M=o.useMemo(()=>cc(a,{textQuery:A.textQuery,workspaceQuery:A.workspaceQuery,modelQuery:A.modelQuery,resumableOnly:A.resumableOnly,sortMode:A.sortMode}),[A.modelQuery,A.resumableOnly,A.sortMode,A.textQuery,A.workspaceQuery,a]),S=t.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[t.jsx("div",{onClick:p,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[t.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"m-0 text-lg font-extrabold",children:j?Qm():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Km(e)}),j&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Ia()})]}),t.jsx("button",{onClick:p,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:t.jsx(wt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!j&&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"}),j?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:A.textQuery,onChange:x=>w({...A,textQuery:x.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("input",{type:"text",value:A.workspaceQuery,onChange:x=>w({...A,workspaceQuery:x.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("input",{type:"text",value:A.modelQuery,onChange:x=>w({...A,modelQuery:x.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsxs("select",{value:A.sortMode,onChange:x=>w({...A,sortMode:x.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:A.resumableOnly,onChange:x=>w({...A,resumableOnly:x.target.checked})}),"Resume-ready only"]})]}),M.map(x=>{const E=e.providerSessionId===x.providerSessionId,R=E||!x.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{R||!v||v(x)},disabled:R,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${E?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${R?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:`font-bold text-sm mb-1 truncate ${E?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:x.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:x.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:sf(x.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:x.preview||"No saved preview yet"}),t.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[t.jsxs("div",{className:"truncate",children:[x.workspace||"Workspace unknown",ds(x.summaryMetadata)?` · ${ds(x.summaryMetadata)}`:"",x.messageCount>0?` · ${x.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:E?"ACTIVE":x.canResume?c===x.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},x.id)})]}):m.map(x=>t.jsxs("div",{onClick:()=>{h(e.routeId,x.id),p()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${g===x.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[t.jsx("div",{className:`font-bold text-sm mb-1 ${g===x.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:x.title||"Untitled Session"}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[x.id.substring(0,12),"..."]}),g===x.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},x.id)),(j&&!i&&M.length===0||!j&&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(Nd,{size:32})}),t.jsx("div",{className:"text-[13px]",children:j?a.length>0?"No saved history matches these filters.":Zm():"No recent chat sessions found."})]}),j&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:tf()})})]}),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:f,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(er,{size:13})," ",j?ef():"Refresh History"]})})})]})]});return typeof document>"u"?S:Vs.createPortal(S,document.body)}const So={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 uc({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=So[n.type]||So.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(wt,{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 rf=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function nf(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function af(e){return e.sessionId||e.instanceId||e.agentType}function gn(e,s){return e||s}function mc(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=Tt(r,{fallbackId:r.id}));return s}function fc(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 La(e,s={}){return of(e,fc(e,s))}function of(e,s={}){var d,h,f,v,N,m;const r=[],n=s.machineName,a=s.connectionState,i=nf(e),c=lu(e.type,{agentName:e.cliName}),l=Qe(e)||Ge(e)?c:et(e.type),u=Array.isArray(e.childSessions)?e.childSessions.map(g=>{var j,b;return{sessionId:g.id,instanceId:g.id,providerSessionId:g.providerSessionId,transport:g.transport,sessionCapabilities:g.capabilities,agentType:g.providerType,agentName:g.providerName||et(g.providerType),status:g.status,title:g.title,lastMessagePreview:g.lastMessagePreview,lastMessageRole:g.lastMessageRole,lastMessageAt:g.lastMessageAt,lastMessageHash:g.lastMessageHash,messages:((j=g.activeChat)==null?void 0:j.messages)||[],activeModal:((b=g.activeChat)==null?void 0:b.activeModal)||void 0,unread:g.unread,lastSeenAt:g.lastSeenAt,lastUpdated:g.lastUpdated,inboxBucket:g.inboxBucket,surfaceHidden:g.surfaceHidden}}):[],p=rf(e);if(p){const g=e.sessionId||e.instanceId,j=c,b=(d=e.activeChat)==null?void 0:d.activeModal,C=b&&Array.isArray(b.buttons)&&b.buttons.length>0,A=bt((h=e.activeChat)==null?void 0:h.status,{activeModal:(f=e.activeChat)==null?void 0:f.activeModal})||bt((N=(v=e.agents)==null?void 0:v[0])==null?void 0:N.status)||"idle",w=e.activeChat||{title:"",messages:[]};let M=w.title&&String(w.title).trim()?String(w.title).trim():"";const S=(m=e.activeChat)==null?void 0:m.id,k=e.chats;if(S&&Array.isArray(k)&&k.length>0){const I=k.find(P=>P.id===S||P.id&&String(P.id)===String(S));I!=null&&I.title&&String(I.title).trim()&&(M=String(I.title).trim())}const x=(Qe(e)||Ge(e),e.type),E=(Qe(e)||Ge(e))&&ho(M,j,x)?"":M,R=w.messages||[];r.push({routeId:e.id,sessionId:g,providerSessionId:e.providerSessionId,nativeSessionId:g,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:Qe(e)?e.mode||"terminal":"chat",agentName:j,agentType:x,status:A,title:E,messages:R,resume:e.resume,hostIdeType:!Qe(e)&&!Ge(e)?e.type:void 0,workspaceName:i,displayPrimary:E||i||(Qe(e)?e.mode==="chat"?j:"Terminal":j),displaySecondary:l,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:C?b.buttons:void 0,modalMessage:C?b.message:void 0,streamSource:"native",tabKey:gn(g,e.id),machineName:n,connectionState:a})}if(p&&(Qe(e)||Ge(e)))return r;for(const g of u){const j=g.activeModal&&Array.isArray(g.activeModal.buttons)&&g.activeModal.buttons.length>0,b=du(g),C=af(g),A=`${e.id}:${C}`,w=g.title&&String(g.title).trim()||"",M=ho(w,g.agentName,g.agentType)?"":w,S=g.messages||[];(g.transport==="cdp-webview"||g.sessionId||g.providerSessionId||S.length>0||j||M||!["idle","panel_hidden","disconnected","not_monitored"].includes(b))&&r.push({routeId:e.id,sessionId:g.sessionId||g.instanceId,providerSessionId:g.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:g.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:g.sessionCapabilities,mode:"chat",agentName:g.agentName,agentType:g.agentType,status:b,title:M,messages:S,hostIdeType:e.type,workspaceName:i,displayPrimary:M||i||g.agentName||l,displaySecondary:`${l} · ${g.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:g.lastMessagePreview,lastMessageRole:g.lastMessageRole,lastMessageAt:g.lastMessageAt,lastMessageHash:g.lastMessageHash,lastUpdated:g.lastUpdated||e.lastUpdated,modalButtons:j?g.activeModal.buttons:void 0,modalMessage:j?g.activeModal.message:void 0,streamSource:"agent-stream",tabKey:gn(g.sessionId||g.instanceId,A),machineName:n,connectionState:a})}return r.length===0&&r.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:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:i,displayPrimary:i||l,displaySecondary:l,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:gn(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function cf(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 pc(e,s){const r=cf(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const hc=[{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:"🏄"}],xc=[{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:"🧩"}],bc=[{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:"🟠"}],lf=hc,df=xc,uf=bc;function ms(...e){return Bl(Kl(e))}function mf({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:ms("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 gc({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(mf,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:ms("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const ea="adhdev:themechange";function ff(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function hs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function xs(e){return e==="system"?ff():e}function yc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Lr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(ea,{detail:{preference:e,theme:s}}))}function pf(){const e=hs(),s=xs(e);yc(s),Lr(e,s)}function Ra(){const[e,s]=o.useState(hs),[r,n]=o.useState(()=>xs(hs()));o.useEffect(()=>{yc(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const p=u.matches?"light":"dark";n(p),Lr("system",p)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const p=u.detail||{},d=p.preference,h=p.theme;s(d==="dark"||d==="light"||d==="system"?d:hs()),n(h==="dark"||h==="light"?h:xs(hs()))},l=u=>{if(u.key!=="theme")return;const p=hs(),d=xs(p);s(p),n(d)};return window.addEventListener(ea,c),window.addEventListener("storage",l),()=>{window.removeEventListener(ea,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=xs(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}Lr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=xs(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Lr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const No={dark:"Dark",light:"Light",system:"System"};function hf({collapsed:e}){const{preference:s,cycleTheme:r}=Ra(),n=s==="dark"?t.jsx(Id,{size:16}):s==="light"?t.jsx(Cd,{size:16}):t.jsx(Md,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${No[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:No[s]})]})}function yn(e,s){return e?typeof e=="function"?e(s):e:null}function xf({children:e,brand:s,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:i,footerActions:c,preMainContent:l,collapsedStorageKey:u="sidebar-collapsed"}){const[p,d]=o.useState(!1),[h,f]=o.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),v=()=>d(!0),N=()=>d(!1),m=()=>{f(C=>{const A=!C;try{localStorage.setItem(u,A?"1":"0")}catch{}return A})},g=o.useMemo(()=>({collapsed:h,mobileMenuOpen:p,openMobileMenu:v,closeMobileMenu:N,toggleCollapsed:m}),[h,p]),j=C=>`nav-item${C.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${C.className?` ${C.className}`:""}`,b=C=>t.jsxs("div",{className:j(C),id:`nav-${C.id}`,onClick:()=>{C.onSelect(),N()},title:h?C.title??(typeof C.label=="string"?C.label:void 0):C.title,children:[t.jsx("span",{className:"nav-icon",children:C.icon}),!h&&C.label]},C.id);return t.jsxs("div",{className:`app-layout${p?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[t.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:v,children:[t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"})]}),p&&t.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:N,onKeyDown:C=>C.key==="Escape"&&N()}),t.jsxs("aside",{className:`sidebar ${p?"sidebar-open":""}`,children:[t.jsxs("div",{className:"sidebar-header",children:[t.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:yn(s,g)}),t.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:N,children:t.jsx(wt,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:r.map(b)}),n.map(C=>t.jsxs("div",{className:C.className??"border-t border-border-subtle pt-2 mt-2",children:[!h&&C.title?t.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:C.title}):null,C.items.map(b)]},C.key)),t.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(b),yn(i,g),t.jsx(hf,{collapsed:h}),yn(c,g)]})]}),t.jsx("main",{className:"main-content relative",children:t.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function Nt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:ms("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 vc({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:ms("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 bf={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"},gf={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function gr({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:ms("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",bf[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:gf[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 yf={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"},vf={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function wf({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:ms("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",yf[e],r),children:[t.jsx("span",{className:ms("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",vf[e])}),n]})}function Qt({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 jf({onPrefChange:e}){const[s,r]=vu(),[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(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Xr,{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(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ct,{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:()=>{Ei().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(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ad,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:c=>i("completionAlert",c)}),t.jsx(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Td,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:c=>i("approvalAlert",c)}),t.jsx(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ys,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange: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 Ur(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function kf(e,s){const r=Ur(e),n=Ur(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 wc(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function Fs(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||kf(r,s)>=0)return!1;const n=Ur(r),a=Ur(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Sf(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function vn(e,s){return e instanceof Error?e.message:s}function Nf({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(vc,{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(If,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Co({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 Vs.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 Cf(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...lf,...df,...uf].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 If({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var K,z;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[p,d]=o.useState(null),[h,f]=o.useState("idle"),[v,N]=o.useState(""),m=e.version||null,g=((K=e.machine)==null?void 0:K.platform)||((z=e.system)==null?void 0:z.platform)||"",j=Tt(e,{fallbackId:e.id}),b=g==="win32"?"🪟":g==="darwin"?"🍎":"🐧",C=s.filter(L=>L.daemonId===e.id&&L.transport==="cdp-page"),A=s.filter(L=>L.daemonId===e.id&&L.transport==="pty"),w=s.filter(L=>L.daemonId===e.id&&L.transport==="acp"),M=e.p2p,S=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const L=Sf(await r(e.id,"daemon_upgrade",{}));L.alreadyLatest?(c("done"),u(`Already on v${L.version||"latest"}.`)):L.upgraded||L.success?(c("done"),u(`Upgrade to v${L.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(L.error||"Upgrade failed"))}catch(L){c("error"),u(vn(L,"Connection lost during upgrade"))}}},k=async()=>{if(d(null),!!n){f("loading");try{await n(e.id),f("done"),N("Machine disconnected.")}catch(L){f("error"),N(vn(L,"Failed to disconnect"))}}},x=async()=>{if(d(null),!!a){f("loading");try{await a(e.id),f("done"),N("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(L){f("error"),N(vn(L,"Failed to revoke token"))}}},E="0.9.8",R=wc(e,E),I=Fs(e,E),P=C.length+A.length+w.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:b}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:j}),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] ${R?"":"bg-bg-secondary"}`,style:R?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",m,!R&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&R&&t.jsx("button",{onClick:S,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${E}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${I?"↑ Update now":`↑ Update${` to v${E}`}`}`}),n&&t.jsx("button",{onClick:()=>d("disconnect"),disabled:h==="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:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(wf,{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:[M&&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 ${M.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${M.state==="connecting"||M.state==="new"?"animate-pulse":""}`,style:M.state==="connecting"||M.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",M.state==="connected"?"connected":M.state==="connecting"||M.state==="new"?"connecting...":M.state||"off"]}),M.peers!==void 0&&M.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",M.peers," peer",M.peers!==1?"s":"",")"]})]}),M&&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:[C.map(L=>{const T=Cf(L.type),H=L.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:T.icon}),t.jsx("span",{children:T.name}),H!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${H?"bg-green-400":"animate-pulse"}`,style:H?void 0:{background:"var(--status-warning)"},title:H?"CDP connected":"CDP connecting..."})]},L.id)}),A.map(L=>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:L.cliName||"CLI"})]},L.id)),w.map(L=>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:L.cliName||"ACP"})]},L.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||v)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||h==="error"?"text-red-400":i==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:v||l})]}),p==="disconnect"&&t.jsx(Co,{title:"🔌 Disconnect Machine",message:`Disconnect "${j}" from ADHDev?
32
-
33
- This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
34
-
35
- Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:k,onCancel:()=>d(null)}),p==="revoke"&&t.jsx(Co,{title:"⚠️ Remove Machine",message:`Remove "${j}" from your dashboard?
36
-
37
- This will:
38
- • Immediately disconnect the machine
39
- • Delete the machine registration
40
- • Require restarting ADHDev on that machine
41
-
42
- Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:x,onCancel:()=>d(null)})]})}const Mf=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Af(){const{preference:e,setPreference:s}=Ra();return t.jsx("div",{className:"flex gap-2",children:Mf.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 Tf(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 Lf(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 Io(e){const{r:s,g:r,b:n}=Lf(e);return .2126*wn(s)+.7152*wn(r)+.0722*wn(n)}function Mo(e,s){const r=Io(e),n=Io(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function jc(e){const s=Tf(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return Mo(s,r)>=Mo(s,n)?r:n}const ta={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},sa={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},Rf=[{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"}}}],kc="adhdev-chat-theme",Sc="adhdev-chat-theme-custom";function Rr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(kc)||"ember"}catch{return"ember"}}function Pt(e){try{const s=localStorage.getItem(Sc);if(s){const r=JSON.parse(s);return{...e==="dark"?ta:sa,...r[e]}}}catch{}return e==="dark"?ta:sa}function yr(e,s){try{localStorage.setItem(Sc,JSON.stringify({dark:e,light:s}))}catch{}}function Mt(e,s){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${s})`}function zr(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 Pf={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Us(e,s){var a;const r=(a=Pf[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",zr(r,24)),n.style.setProperty("--accent-on-primary",jc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${zr(r,18)})`),n.style.setProperty("--border-accent",Mt(r,.35)),n.style.setProperty("--nav-active-bg",Mt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Mt(r,.06)}`)}function ns(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Mt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Mt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Mt(e.borderSubtle,.25)),s.style.setProperty("--text-primary",e.textPrimary),s.style.setProperty("--text-secondary",e.textSecondary),s.style.setProperty("--text-muted",e.textMuted),s.style.setProperty("--border-subtle",Mt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Mt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",zr(e.accentColor,30)),s.style.setProperty("--accent-on-primary",jc(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${zr(e.accentColor,40)})`),s.style.setProperty("--border-accent",Mt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Mt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Mt(e.accentColor,.06)}`),s.style.setProperty("--chat-user-bg",e.userBubble),s.style.setProperty("--chat-user-color",e.userText),s.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),s.style.setProperty("--chat-assistant-bg",e.assistantBubble),s.style.setProperty("--chat-assistant-color",e.assistantText),s.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),s.style.setProperty("--chat-assistant-border",`1px solid ${Mt(e.accentColor,.12)}`),s.style.setProperty("--chat-container-bg",e.containerBg),s.style.setProperty("--dashboard-pane-bg",e.containerBg),s.style.setProperty("--chat-thought-accent",e.accentColor),s.style.setProperty("--chat-tool-accent",e.accentColor),s.style.setProperty("--chat-action-color",e.accentColor),s.style.setProperty("--chat-send-bg",e.sendButton),s.style.setProperty("--chat-input-border",e.inputBorder)}function Pa(){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 _f(e){try{localStorage.setItem(kc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=as()?"dark":"light";ns(Pt(s))}else Pa(),Us(e,as()?"dark":"light")}function Df(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Rr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=as()?"dark":"light";ns(Pt(s))}else Pa(),Us(e,as()?"dark":"light")}function as(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function xt({label:e,value:s,onChange:r}){return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[t.jsx("input",{type:"color",value:s,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),t.jsx("input",{type:"text",value:s,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function _s({title:e,children:s}){return t.jsxs("div",{style:{marginBottom:14},children:[t.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function Ef({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>Pt(r));o.useEffect(()=>{a(Pt(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const p={...u,[c]:l},h=Pt(r==="dark"?"light":"dark");return r==="dark"?yr(p,h):yr(h,p),ns(p),s(p),p})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",t.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(_s,{title:"App Background",children:[t.jsx(xt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(xt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(xt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs(_s,{title:"App Text",children:[t.jsx(xt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(xt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(xt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs(_s,{title:"Borders & Accent",children:[t.jsx(xt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(xt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(xt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs(_s,{title:"Chat Bubbles",children:[t.jsx(xt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(xt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(xt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(xt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs(_s,{title:"Chat Layout",children:[t.jsx(xt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(xt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(xt,{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?ta:sa,u=Pt(e?"light":"dark");e?yr(c,u):yr(u,c),a(c),ns(c),s(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function $f(){const[e,s]=o.useState(Rr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Pt("dark"));o.useEffect(()=>{n(as());const u=new MutationObserver(()=>{const h=as();n(h);const f=Rr();f==="custom"?ns(Pt(h?"dark":"light")):Us(f,h?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const h=as();n(h);const f=Rr();f==="custom"?ns(Pt(h?"dark":"light")):Us(f,h?"dark":"light")};return p.addEventListener("change",d),()=>{u.disconnect(),p.removeEventListener("change",d)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ns(Pt(r?"dark":"light")):(Pa(),Us(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Pt(r?"dark":"light"))},[r]);const c=u=>{s(u),_f(u)},l=[...Rf,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return t.jsxs("div",{children:[t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(u=>{const p=e===u.id,d=r?u.preview.dark:u.preview.light,h=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return t.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:p?"var(--bg-glass-hover)":"var(--bg-glass)",border:p?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:p?1:.75},children:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background: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:h},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:[p&&t.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?"🎨 Custom":u.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&t.jsx(Ef,{dark:r,onColorsChange:u=>i(u)})]})}const _a="adhdev_mobileDashboardMode_v1",ra="adhdev:mobile-dashboard-mode-change";function Da(){try{return localStorage.getItem(_a)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Bf(e){if(typeof window>"u")return()=>{};const s=a=>{e(a??Da())},r=a=>{const i=a.detail;s(i)},n=a=>{a.key&&a.key!==_a||s()};return window.addEventListener(ra,r),window.addEventListener("storage",n),()=>{window.removeEventListener(ra,r),window.removeEventListener("storage",n)}}function Kf(e){try{localStorage.setItem(_a,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ra,{detail:e}))}function Of(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(Da()==="chat")},[]),t.jsx(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ft,{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),Kf(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const jn=new Map,Ao=new Map;function Wf(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 Hf(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 Nc(){const{sendCommand:e}=jt(),{injectEntries:s,getIdes:r}=Gs();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??om,c=Ao.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=jn.get(n);if(l)return l;const u=(async()=>{const p=await e(n,"get_machine_runtime_stats"),d=Wf(p);if(!d)return;const h=r().find(v=>v.id===n),f=Hf(h,n,d.machine,d.timestamp||Date.now());s([f]),Ao.set(n,Date.now())})().finally(()=>{jn.delete(n)});return jn.set(n,u),u},[r,s,e])}function Ff(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 Uf(e,s){const{sendData:r}=jt(),{injectEntries:n,getIdes:a}=Gs(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(u=>Gt.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:s==null?void 0:s.intervalMs}},d=>{const h=a().find(v=>v.id===u),f=Ff(h,u,d);n([f])}));return()=>{l.forEach(u=>u())}},[i,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}function zf(e,s){const{sendData:r}=jt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const u=Gt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},p=>{l&&(clearTimeout(l),l=null),a(p.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},dm):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 Vf(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Cc(e){const{sendData:s}=jt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=Vf(e);if(!a||!e.sessionId||!s){n({});return}const i=Gt.subscribe({sendData:s},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),js.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 Ic="adhdev_hiddenTabs";function Gf(){try{const e=localStorage.getItem(Ic);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function fs(e){try{localStorage.setItem(Ic,JSON.stringify([...e]))}catch{}}function kn(e){return wa(e)}function Ea(e,s){return vs(s).some(r=>e.has(r))}function qf(){const[e,s]=o.useState(Gf),r=o.useCallback(p=>{const d=kn(p);s(h=>{const f=new Set(h);return f.has(d)?f.delete(d):f.add(d),fs(f),f})},[]),n=o.useCallback(p=>{const d=kn(p);s(h=>{if(h.has(d))return h;const f=new Set(h);return f.add(d),fs(f),f})},[]),a=o.useCallback(p=>{const d=kn(p);s(h=>{if(!h.has(d))return h;const f=new Set(h);return f.delete(d),fs(f),f})},[]),i=o.useCallback(()=>{s(p=>{if(p.size===0)return p;const d=new Set;return fs(d),d})},[]),c=o.useCallback((p,d)=>{s(h=>{const f=new Set(h);for(const v of d)f.add(v);return fs(f),f})},[]),l=o.useCallback((p,d)=>{s(h=>{const f=new Set(h);for(const v of d)f.delete(v);return fs(f),f})},[]),u=o.useCallback(p=>Ea(e,p),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function Mc(e){return e instanceof Error?e.message:String(e||"")}function $a(e){const s=Mc(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 Ba(e){const s=Mc(e);return s.includes("P2P command timeout")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function To(e,s){const r=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!r||e.transport!=="pty")return e;const n=s[r];return!n||e.mode===n?e:{...e,mode:n}}function Yf(e,s){if(!Array.isArray(e)||e.length===0||!s||Object.keys(s).length===0)return e;let r=!1;const n=e.map(a=>{const i=To(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>To(u,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Ac(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 Xf(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))Ac(s,a)===i&&(delete n[a],r=!0);return r?n:e}function Jf({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Ei()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:ac(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return ku(a),o.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),p={};for(const[d,h]of Object.entries(l))u-h<5e3&&(p[d]=h);return Object.keys(p).length===Object.keys(l).length?l:p})},5500);return()=>clearTimeout(c)},[s,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const u=l.filter(p=>p.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(i)},[n]),null}function Qf(e){const s=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of s){const a=r.get(n.id);if(!a){r.set(n.id,n);continue}const i=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function Sn(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==s[r])return!1;return!0}function Zf(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 Lo(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?Zf(qr(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 ep(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||""),Lo(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),Lo(r.activeChat)].join(":"))].join("|")}function tp(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 sp(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const i of vs({routeId:n.routeId}))r.set(i,a);for(const i of vs({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of vs({tabKey:n.tabKey}))r.set(i,n)}return r}function rp(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function np(e){const s=rp(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=qr(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function ap({ides:e,connectionStates:s,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>Qf(e),[e]),i=o.useMemo(()=>mc(e),[e]),c=o.useRef([]),l=o.useRef([]),u=o.useRef([]),p=o.useRef(new Map),d=o.useRef(new Map),h=o.useMemo(()=>{const A=new Map,w=[];for(const x of a){const{connectionState:E="new",machineName:R}=fc(x,{machineNames:i,connectionStates:s,defaultConnectionState:"new"}),I=ep(x),P=p.current.get(x.id);if(P&&P.ide===x&&P.sourceSignature===I&&P.connectionState===E&&P.machineName===R){A.set(x.id,P),w.push(...P.conversations);continue}const K=La(x,{machineNames:i,connectionStates:s,defaultConnectionState:"new"}),z={ide:x,sourceSignature:I,connectionState:E,machineName:R,conversations:K};A.set(x.id,z),w.push(...K)}p.current=A;const M=new Map,S=x=>{const E=np(x),R=d.current.get(x.tabKey);if(R&&R.signature===E)return M.set(x.tabKey,R),R.timestamp;const I={signature:E,timestamp:zi(x)||(R==null?void 0:R.timestamp)||0};return M.set(x.tabKey,I),I.timestamp},k=[...w].sort((x,E)=>Vi(x,E,S));return d.current=M,k},[a,s,i]),f=o.useMemo(()=>{const A=tp(h,r);return Sn(c.current,A)?c.current:(c.current=A,A)},[h,r]),v=o.useMemo(()=>{const A=new Map,w=Array.from(new Set(f.map(M=>M.routeId)));for(const M of w){const S=Dt(f,M);S&&A.set(M,S)}return A},[f]),N=o.useMemo(()=>{const A=new Map;for(const w of f){const M=v.get(w.routeId),S=w.streamSource==="native"&&M?M:w;for(const k of vs({providerSessionId:w.providerSessionId,sessionId:w.sessionId}))A.set(k,S)}return A},[f,v]),m=o.useMemo(()=>sp(f,v),[f,v]),g=o.useCallback(A=>{if(A)return N.get(A)},[N]),j=o.useCallback(A=>{if(A)return m.get(A)},[m]),b=o.useMemo(()=>{const A=f.filter(w=>!Ea(n,w));return Sn(l.current,A)?l.current:(l.current=A,A)},[f,n]),C=o.useMemo(()=>{const A=b.map(w=>w.tabKey);return Sn(u.current,A)?u.current:(u.current=A,A)},[b]);return{chatIdes:a,conversations:f,visibleConversations:b,visibleTabKeys:C,resolveConversationBySessionId:g,resolveConversationByTarget:j}}function op({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 ip({ides:e,sendDaemonCommand:s,setToasts:r,resolveConversationByTarget:n}){o.useEffect(()=>{ct.setIdes(e)},[e]),o.useEffect(()=>{ct.setResolveAction((a,i,c)=>{s(a,i,c).catch(()=>{})})},[s]),o.useEffect(()=>{const a=ct.onToast(i=>{r(l=>l.some(p=>p.message===i.message&&i.timestamp-p.timestamp<3e3)?l:[...l.slice(-4),{id:i.id,message:i.message,type:i.type,timestamp:i.timestamp,targetKey:i.targetKey,actions:i.actions}]);const c=i.duration||5e3;setTimeout(()=>r(l=>l.filter(u=>u.id!==i.id)),c)});return()=>{a()}},[r]),o.useEffect(()=>{const a=sc.on("status_event",i=>{ct.handleRawEvent(i,"ws")});return()=>{a()}},[]),o.useEffect(()=>{var i;const a=c=>{var m;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const u=l.targetSessionId||l.targetKey||l.daemonId,p=n(u),d=(p==null?void 0:p.routeId)||l.daemonId;if(!d)return;const h=Number(l.buttonIndex),f=l.button||((m=p==null?void 0:p.modalButtons)==null?void 0:m[h])||"Approve",v=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),N=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(v);s(d,"resolve_action",{action:N?"approve":"reject",button:f,...Number.isFinite(h)&&{buttonIndex:h},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(g=>console.error("[SW Action] approval failed:",g))};return(i=navigator.serviceWorker)==null||i.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,s])}const cp="adhdev_dashboardLayout_v1",lp="adhdev_dashboardDockview_v1",dp="adhdev_dashboardDockviewHiddenRestore_v1",Ds={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Ka(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function up(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Tc(e){return`${cp}:${e}`}function mp(e){const s=Tc(e);return Ka(s,null)}function fp(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=Tc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function Lc(e){return`${lp}:${e}`}function pp(e){const s=Lc(e);return Ka(s,null)}function hp(e,s){try{const r=Lc(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Rc(e){return`${dp}:${e}`}function xp(e){const s=Rc(e);return Ka(s,{})}function bp(e,s){try{const r=Rc(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function gp(){return{groupAssignments:[...Ds.groupAssignments],focusedGroup:Ds.focusedGroup,groupActiveTabIds:{...Ds.groupActiveTabIds},groupTabOrders:{...Ds.groupTabOrders},groupSizes:[...Ds.groupSizes]}}function yp(e,s){return e?e.length===s.length&&e.every((r,n)=>r===s[n]):s.length===0}function vp(){const[e]=o.useState(()=>up(typeof window<"u"?window.innerWidth:1280)),[s,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,u]=o.useState({}),[p,d]=o.useState([]),[h,f]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[v,N]=o.useState(!1),m=o.useCallback(()=>{if(v)return;const x=mp(e)??gp();r(new Map(x.groupAssignments)),a(x.focusedGroup),c(x.groupActiveTabIds),u(x.groupTabOrders),d(x.groupSizes),N(!0)},[v,e]);o.useEffect(()=>{v&&fp(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:p})},[v,e,s,n,i,l,p]),o.useEffect(()=>{const x=window.matchMedia("(max-width: 767px)"),E=R=>f(R.matches);return x.addEventListener("change",E),()=>x.removeEventListener("change",E)},[]);const g=o.useCallback(x=>{r(x)},[]),j=o.useCallback(x=>{a(x)},[]),b=o.useCallback(x=>{c(x)},[]),C=o.useCallback(x=>{u(x)},[]),A=o.useCallback(x=>{d(x)},[]),w=o.useCallback(x=>{j(x)},[j]),M=o.useCallback((x,E)=>{c(R=>(R[x]??null)===(E??null)?R:{...R,[x]:E})},[]),S=o.useCallback((x,E)=>{u(R=>{const I=R[x];return yp(I,E)?R:{...R,[x]:E}})},[]),k=o.useCallback((x,E)=>{const R=E.get(x)??0;return M(R,x),w(R),R},[w,M]);return{layoutProfile:e,groupAssignments:s,updateGroupAssignments:g,focusedGroup:n,updateFocusedGroup:j,focusGroup:w,groupActiveTabIds:i,updateGroupActiveTabIds:b,setGroupActiveTab:M,groupTabOrders:l,updateGroupTabOrders:C,setGroupTabOrder:S,groupSizes:p,updateGroupSizes:A,isMobile:h,hasHydratedStoredLayout:v,hydrateStoredLayout:m,focusConversationTab:k}}function wp(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=va(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function jp({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,focusConversationTab:c,setSearchParams:l,historyModalOpen:u,activeConv:p,isRefreshingHistory:d,ides:h,handleRefreshHistory:f}){const v=o.useRef(!1),N=o.useRef(!1),m=o.useRef(null),g=o.useRef(!1);o.useEffect(()=>{if(!e||v.current||s.length===0)return;if(!a){i();return}const j=r(e);j&&(c(j.tabKey,n),v.current=!0,N.current=!0,m.current!=null&&(window.clearTimeout(m.current),m.current=null),l(b=>{const C=new URLSearchParams(b);return C.delete("activeTab"),C},{replace:!0}))},[e,s,r,n,a,i,c,l]),o.useEffect(()=>{if(!(N.current||a)&&s.length!==0){if(!e){i(),N.current=!0;return}if(v.current){N.current=!0;return}if(m.current==null)return m.current=window.setTimeout(()=>{m.current=null,!(N.current||a)&&(i(),N.current=!0)},1500),()=>{m.current!=null&&(window.clearTimeout(m.current),m.current=null)}}},[e,s.length,a,i]),o.useEffect(()=>{if(!u){g.current=!1;return}if(!p||g.current||d)return;const j=h.find(b=>b.id===p.routeId);j&&(!j.chats||j.chats.length===0||wp(j.chats,p))&&(g.current=!0,f())},[u,p,d,h,f]),o.useEffect(()=>{if(!p)return;let j=null,b=0,C=-1,A=0;const w=()=>{j=null;const M=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(k=>k.offsetParent!==null);if(M.length===0){b<18&&(b+=1,j=requestAnimationFrame(w));return}let S=0;for(const k of M)k.scrollTop=k.scrollHeight,S+=k.scrollHeight;S===C?A+=1:(A=0,C=S),b+=1,!(A>=2||b>=18)&&(j=requestAnimationFrame(w))};return j=requestAnimationFrame(w),()=>{j!=null&&cancelAnimationFrame(j)}},[p==null?void 0:p.tabKey])}function Nn(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=va(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Pc({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:i}){const[c,l]=o.useState(!1),[u,p]=o.useState(!1),d=o.useCallback(async N=>{try{await e("standalone","launch_ide",{ideType:N,enableCdp:!0})}catch(m){console.error("Launch failed",m)}},[e]),h=o.useCallback(async(N,m)=>{try{const g=N||(s==null?void 0:s.daemonId)||"",j=await e(g,"switch_chat",{id:m,sessionId:m,...ws(s)}),b=j==null?void 0:j.result;if((j==null?void 0:j.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Ps(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Ps(a,`⚠️ Switch error: ${b}`):Ps(a,"⚠️ Session switch failed")}catch(g){console.error("Switch failed",g),Ps(a,`❌ Switch failed: ${g.message||"connection error"}`)}},[s,e,a]),f=o.useCallback(async()=>{if(!(!s||c)){l(!0);try{const N=Js(s);await e(N,"new_chat",{...ws(s)}),i(m=>({...m,[s.tabKey]:Date.now()}))}catch(N){console.error("New chat failed",N)}finally{l(!1)}}},[s,c,e,i]),v=o.useCallback(async()=>{var N,m;if(!(!s||u)){p(!0);try{const g=Js(s),j=async()=>e(g,"list_chats",{forceExpand:!0,...ws(s)});let b=await j(),C=(b==null?void 0:b.chats)||((N=b==null?void 0:b.result)==null?void 0:N.chats);Nn(C,s)&&(await new Promise(A=>setTimeout(A,450)),b=await j(),C=(b==null?void 0:b.chats)||((m=b==null?void 0:b.result)==null?void 0:m.chats)),b!=null&&b.success&&Array.isArray(C)&&(n(s.routeId,C),Nn(C,s)&&!Nn(r,s)&&Ps(a,"⚠️ History dialog did not fully open — try once more"))}catch(g){console.error("Refresh history failed",g)}finally{p(!1)}}},[s,r,u,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:h,handleNewChat:f,handleRefreshHistory:v}}function kp(e,s){if(e.size!==s.size)return!1;for(const[r,n]of e)if(s.get(r)!==n)return!1;return!0}function Sp(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function Ro(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 vr(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 Po(e,s){const r={};for(const[n,a]of Object.entries(e)){const i=s[Number(n)];typeof i=="number"&&(r[i]=a)}return r}function Np(e,s,r){if(s.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...s].reverse().find(a=>a<e)??s[0];return r[n]??0}function Cp(e,s,r){if(s.length<=1)return[];const n=s.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===s.length?n:Array(r).fill(100/r),i=a.reduce((c,l)=>c+l,0);return i>0?a.map(c=>c/i*100):Array(r).fill(100/r)}function _o(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 Do(e){return Array(e).fill(100/e)}function Ip({groupAssignments:e,updateGroupAssignments:s,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:i,updateGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:p}){const d=o.useRef(null),h=o.useMemo(()=>vr(e,p),[e,p]),f=h.assignments,v=o.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),N=v>1,m=o.useCallback((w,M)=>{s(S=>{const k=new Map(vr(S,p).assignments);return M===0?k.delete(w):k.set(w,M),k}),n(S=>({...S,[M]:w})),r(M)},[s,p,n,r]),g=o.useCallback(w=>{s(M=>{const S=vr(M,p).assignments,k=new Map;for(const[x,E]of S)E!==w&&(E>w?k.set(x,E-1):k.set(x,E));return k}),c(M=>{if(M.length<=1)return[];const S=[...M];S.splice(w,1);const k=S.reduce((x,E)=>x+E,0);return k>0?S.map(x=>x/k*100):[]}),r(0)},[s,p,c,r]),j=o.useCallback((w,M)=>{M.preventDefault();const S=d.current;if(!S)return;const k=M.clientX,x=S.offsetWidth,E=i.length===v?[...i]:Do(v),R=P=>{const z=(P.clientX-k)/x*100,L=[...E];L[w]=Math.max(15,E[w]+z),L[w+1]=Math.max(15,E[w+1]-z),c(L)},I=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",I),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",R),document.addEventListener("mouseup",I)},[i,v,c]),b=o.useCallback((w,M,S)=>{if(v>=4)return;const k=S==="left"?M:M+1;s(x=>{const E=vr(x,p).assignments,R=new Map;for(const I of u){const P=E.get(I.tabKey)??0,K=P>=k?P+1:P;K>0&&R.set(I.tabKey,K)}return k>0&&R.set(w,k),R}),c(x=>{const E=x.length===v?[...x]:Do(v),R=E[M]??100/v,I=Math.max(15,R/2),P=Math.max(15,R/2),K=[...E];K[M]=I,K.splice(k,0,P);const z=K.reduce((L,T)=>L+T,0);return K.map(L=>L/z*100)}),n(x=>{const E=_o(x,k);return E[k]=w,E}),a(x=>{const E=_o(x,k);return E[k]=[w],E}),r(k)},[v,s,p,u,c,n,a,r]);o.useEffect(()=>{kp(e,f)||s(f)},[e,f,s]),o.useEffect(()=>{const{mapping:w,usedGroups:M}=h;n(S=>{const k=Po(S,w);return Ro(S,k)?S:k}),a(S=>{const k=Po(S,w);return Ro(S,k)?S:k}),r(S=>{const k=l?0:Np(S,M,w);return S===k?S:k}),c(S=>{const k=l?[]:Cp(S,M,h.groupCount);return Sp(S,k)?S:k})},[h,l,n,a,r,c]);const C=o.useMemo(()=>{const w=Array.from({length:v},()=>[]);for(const M of u){const S=f.get(M.tabKey)??0,k=Math.min(S,v-1);w[k].push(M)}return w},[u,f,v]),A=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:d,normalizedGroupAssignments:f,numGroups:v,isSplitMode:N,groupedConvs:C,moveTabToGroup:m,closeGroup:g,handleResizeStart:j,splitTabRelative:b,clearAllSplits:A}}function Mp({ides:e,sendDaemonCommand:s}){const r="0.9.8",n=o.useMemo(()=>e.filter(d=>d.type!=="adhdev-daemon"?!1:wc(d,r)).sort((d,h)=>Number(Fs(h,r))-Number(Fs(d,r))),[r,e]),a=o.useMemo(()=>n.some(d=>Fs(d,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),p=o.useCallback(async d=>{var h,f;u(v=>({...v,[d]:"upgrading"}));try{const v=await s(d,"daemon_upgrade",{});(h=v==null?void 0:v.result)!=null&&h.upgraded||(f=v==null?void 0:v.result)!=null&&f.success?u(N=>({...N,[d]:"done"})):u(N=>({...N,[d]:"error"}))}catch{u(v=>({...v,[d]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:p}}const _c=80;function Pr(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function Ap(e){return{...e,createdAt:Pr(e.createdAt),updatedAt:Pr(e.updatedAt,e.createdAt),lastEventAt:Pr(e.lastEventAt,e.updatedAt||e.createdAt)}}function Tp(e){const s=wa(e);return s==="unknown:"?e.id:s}function Lp(e){return[e.type,Ui(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Rp(e,s=_c){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Tp(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 Pp(e,s){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?s.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=Qr(a,s),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const u=Pr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),p=Lp({type:l,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(i==null?void 0:i.lastUpdated)||a.lastUpdated});n.push(Ap({id:p,dedupKey:p,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Wi(a),preview:zu(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return Rp(n)}function _p(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function Dp(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=_c}=e,a=o.useMemo(()=>Pp(s,r).slice(0,Math.max(0,n)),[s,r,n]),i=o.useMemo(()=>_p(a),[a]);return{notifications:a,unreadCount:i}}function Ep({notifications:e,sendDaemonCommand:s}){const r=o.useCallback(i=>{const c=e.find(u=>u.id===i),l=Math.max(Date.now(),(c==null?void 0:c.updatedAt)||0);c!=null&&c.sessionId&&s(c.machineId||c.routeId,"mark_session_seen",{sessionId:c.sessionId,seenAt:l}).catch(()=>{})},[e,s]),n=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&s(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,s]),a=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&s(c.machineId||c.routeId,"delete_notification",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,s]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}function en(...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 $p(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 tn(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=$p(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 Bp(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 Kp(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function sn(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=Kp(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const i=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=i.includes("\\")?"\\":"/",l=(p,d)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${d}`:p==="/"||p==="\\"?`${c}${d}`:`${p.replace(/[\\/]+$/,"")}${c}${d}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:l(i,p.name)})).sort((p,d)=>p.name.localeCompare(d.name)):[];return{path:i,directories:u}}function Op(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Eo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Wp(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Hp({ides:e,conversations:s,onOpenSession:r}){const[n,a]=o.useState(null),i=o.useCallback(c=>{a(c)},[]);return o.useEffect(()=>{if(!n)return;const c=Eo(n.workspacePath),l=e.find(p=>{var N,m,g,j;if(!p||p.type==="adhdev-daemon"||Op(p.daemonId||p.id)!==n.machineId||(Xs(p)?"cli":gs(p)?"acp":"ide")!==n.kind||String(p.agentType||p.type||"")!==n.providerType)return!1;if(n.resumeSessionId)return String(p.providerSessionId||"")===n.resumeSessionId;if(c){const b=Eo(p.workspace||p.runtimeWorkspaceLabel);return b?b===c:!1}return Number(p.lastUpdated||p._lastUpdate||p.timestamp||((j=(g=(m=(N=p.activeChat)==null?void 0:N.messages)==null?void 0:m.at)==null?void 0:g.call(m,-1))==null?void 0:j.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const u=Gi({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:s});u&&(a(null),r(u))},[s,e,r,n]),o.useEffect(()=>{if(!n)return;const c=window.setTimeout(()=>{a(l=>!l||l.startedAt!==n.startedAt?l:null)},45e3);return()=>window.clearTimeout(c)},[n]),{trackPendingLaunch:i}}function Fp({sendDaemonCommand:e,trackPendingLaunch:s,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=o.useCallback(async(f,v)=>sn(e,f,v),[e]),l=o.useCallback(async(f,v)=>{if(!v.trim())return{ok:!1,error:"Choose a workspace path first."};try{const N=await e(f,"workspace_add",{path:v.trim()});return N!=null&&N.success?{ok:!0}:{ok:!1,error:(N==null?void 0:N.error)||"Could not save workspace"}}catch(N){return{ok:!1,error:N instanceof Error?N.message:"Could not save workspace"}}},[e]),u=o.useCallback(async(f,v,N)=>{var m;try{const g={ideType:v,enableCdp:!0};(m=N==null?void 0:N.workspacePath)!=null&&m.trim()&&(g.workspace=N.workspacePath.trim());const j=await e(f,"launch_ide",g);return!(j!=null&&j.success)&&(j==null?void 0:j.success)!==void 0?{ok:!1,error:(j==null?void 0:j.error)||"Could not launch IDE"}:(s({machineId:f,kind:"ide",providerType:v,workspacePath:(N==null?void 0:N.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(g){return{ok:!1,error:g instanceof Error?g.message:"Could not launch IDE"}}},[e,s]),p=o.useCallback(async(f,v,N,m)=>{var j,b,C;const g=Date.now();try{const A={cliType:N};(j=m==null?void 0:m.workspacePath)!=null&&j.trim()?A.dir=m.workspacePath.trim():m!=null&&m.workspaceId&&(A.workspaceId=m.workspaceId),(b=m==null?void 0:m.resumeSessionId)!=null&&b.trim()&&(A.resumeSessionId=m.resumeSessionId.trim()),Array.isArray(m==null?void 0:m.cliArgs)&&m.cliArgs.length>0&&(A.cliArgs=m.cliArgs),(C=m==null?void 0:m.initialModel)!=null&&C.trim()&&(A.initialModel=m.initialModel.trim());const w=await e(f,"launch_cli",A),M=(w==null?void 0:w.result)||w,S=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);return w!=null&&w.success&&S?(r(S),{ok:!0}):w!=null&&w.success?(s({machineId:f,kind:v,providerType:N,workspacePath:(m==null?void 0:m.workspacePath)||null,resumeSessionId:(m==null?void 0:m.resumeSessionId)||null,startedAt:g}),{ok:!0}):{ok:!1,error:(w==null?void 0:w.error)||(M==null?void 0:M.error)||`Could not launch ${v.toUpperCase()} session`}}catch(A){return Wp(A)?(s({machineId:f,kind:v,providerType:N,workspacePath:(m==null?void 0:m.workspacePath)||null,resumeSessionId:(m==null?void 0:m.resumeSessionId)||null,startedAt:g}),{ok:!0}):{ok:!1,error:A instanceof Error?A.message:`Could not launch ${v.toUpperCase()} session`}}},[r,e,s]),d=o.useCallback(async(f,v)=>{if(!f||!v)return[];try{const N=await e(f,"list_saved_sessions",{providerType:v,kind:"cli",limit:30}),m=(N==null?void 0:N.result)??N;return Array.isArray(m==null?void 0:m.sessions)?m.sessions:[]}catch(N){return console.error("List saved sessions failed",N),[]}},[e]),h=o.useCallback(async f=>{if(!n||!Qe(n)||Ge(n))return;const v=Ts(n);if(v===f)return;const N=n.sessionId;N&&i(m=>({...m,[N]:f}));try{await e(qt(n)||n.routeId,"set_cli_view_mode",{targetSessionId:n.sessionId,cliType:_t(n),mode:f})}catch(m){const g=Ba(m);N&&!g&&i(j=>{const b={...j};return v===Ac(a,N)?delete b[N]:b[N]=v,b}),$a(m)?console.warn(g?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",m instanceof Error?m.message:String(m)):console.error("Failed to switch CLI view mode:",m)}},[n,a,e,i]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:l,handleLaunchMachineIde:u,handleLaunchMachineProvider:p,handleListMachineSavedSessions:d,setActiveCliViewMode:h}}function Up(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 zp(e,s,r=Date.now()){return!e||!Up(s)?null:{tabKey:e,nonce:r}}function Vp({isMobile:e,conversations:s,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:i,setSearchParams:c}){const[l,u]=o.useState(null),[p,d]=o.useState(null),h=o.useMemo(()=>{var g,j;if(!e){if(l){const b=s.find(C=>C.tabKey===l);if(b)return b}return r[0]}const m=n[a];if(m){const b=s.find(C=>C.tabKey===m);if(b)return b}return((g=i[a])==null?void 0:g[0])||((j=i[0])==null?void 0:j[0])},[s,l,a,n,i,e,r]),f=o.useCallback(m=>{u(m)},[]),v=o.useCallback(m=>{u(m.tabKey),c(g=>{const j=new URLSearchParams(g),b=Gu(m);return b?j.set("activeTab",b):j.delete("activeTab"),j},{replace:!0})},[c]),N=o.useCallback((m,g)=>{const j=zp(m,g);j&&d(j)},[]);return{activeConv:h,openDesktopConversation:v,requestScrollToBottom:N,scrollToBottomRequest:p,setDesktopActiveTab:f}}function Gp({activeConv:e,remoteDialogConv:s,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:u}){var L;const[p,d]=o.useState(!1),[h,f]=o.useState([]),[v,N]=o.useState(()=>pt()),[m,g]=o.useState(!1),[j,b]=o.useState(null),C=o.useRef(null),A=o.useMemo(()=>r||s||e,[e,r,s]),w=!!A&&Qe(A)&&!Ge(A),M=o.useMemo(()=>{if(!A||!w)return null;const T=A.daemonId||A.routeId||"",H=_t(A);return`${T}:${H}`},[A,w]),{isCreatingChat:S,isRefreshingHistory:k,handleSwitchSession:x,handleNewChat:E,handleRefreshHistory:R}=Pc({sendDaemonCommand:a,activeConv:A,chats:(L=n.find(T=>T.id===(A==null?void 0:A.routeId)))==null?void 0:L.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),I=o.useCallback(()=>{d(!0)},[]),P=o.useCallback(()=>{d(!1)},[]),K=o.useCallback(async()=>{if(!(!A||!w||m)){g(!0);try{const T=A.daemonId||A.routeId,H=_t(A),B=await a(T,"list_saved_sessions",{agentType:H,providerType:H,kind:"cli",limit:50}),D=(B==null?void 0:B.result)??B;f(Array.isArray(D==null?void 0:D.sessions)?D.sessions:[])}catch(T){console.error("Refresh saved sessions failed",T),f([])}finally{g(!1)}}},[A,m,w,a]);o.useEffect(()=>{if(!p){C.current=null;return}if(!w){C.current=null,f([]),g(!1);return}!M||m||C.current!==M&&(C.current=M,K())},[K,p,m,w,M]);const z=o.useCallback(async T=>{if(!A||!w||!T.providerSessionId||!T.workspace)return;const H=A.daemonId||A.routeId,B=_t(A);try{b(T.providerSessionId);const D=await a(H,"launch_cli",{cliType:B,dir:T.workspace,resumeSessionId:T.providerSessionId,initialModel:_i(T.summaryMetadata,"model",{preferShortValue:!0})||void 0}),G=(D==null?void 0:D.result)??D,J=typeof(G==null?void 0:G.sessionId)=="string"?G.sessionId:typeof(G==null?void 0:G.id)=="string"?G.id:"";J&&u(xe=>{const re=new URLSearchParams(xe);return re.set("activeTab",J),re},{replace:!0}),P()}catch(D){console.error("Resume saved session failed",D)}finally{b(null)}},[P,A,w,a,u]);return{historyModalOpen:p,openHistoryModal:I,closeHistoryModal:P,historyTargetConv:A,isSavedSessionHistoryTarget:w,isHistoryCreatingChat:S,isHistoryRefreshingHistory:k,handleHistorySwitchSession:x,handleHistoryNewChat:E,handleHistoryRefresh:R,savedHistorySessions:h,savedHistoryFilters:v,setSavedHistoryFilters:N,isSavedHistoryLoading:m,resumingSavedHistorySessionId:j,handleRefreshSavedHistory:K,handleResumeSavedHistorySession:z}}function qp({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,p]=o.useState(null),[d,h]=o.useState(null),f=o.useMemo(()=>{if(e||!n)return null;const j=l(n);return j&&!Qe(j)&&!Ge(j)?j:null},[e,n,l]),v=o.useMemo(()=>{const j=u==null?void 0:u.routeId;if(!j)return null;const b=u!=null&&u.tabKey?i.find(C=>C.tabKey===u.tabKey):a?i.find(C=>C.tabKey===a):null;return(b==null?void 0:b.routeId)===j?b:Dt(i,j)},[i,u,a]),N=o.useMemo(()=>{if(v)return c.find(j=>j.id===v.routeId)},[c,v]);o.useEffect(()=>{f&&(p({routeId:f.routeId,tabKey:go(f)}),h(f),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,f]);const m=o.useCallback(j=>{j&&(p({routeId:j.routeId,tabKey:go(j)}),h(j))},[]),g=o.useCallback(()=>{p(null),h(null)},[]);return{remoteDialogConv:v,remoteDialogIdeEntry:N,remoteDialogActiveConv:d,setRemoteDialogActiveConv:h,openRemoteDialog:m,closeRemoteDialog:g}}function Yp({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l,activeConv:u,sendDaemonCommand:p}){const{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:f,setRemoteDialogActiveConv:v,openRemoteDialog:N,closeRemoteDialog:m}=qp({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[g,j]=o.useState(!1),[b,C]=o.useState(null),A=o.useCallback(async S=>{const k=S||u;!k||!Qe(k)&&!Ge(k)||(C(k),j(!0))},[u]),w=o.useCallback(()=>{j(!1),C(null)},[]),M=o.useCallback(async S=>{const k=b||u;if(!k||!Qe(k)&&!Ge(k)){w();return}j(!1);try{const x=_t(k),E=k.routeId||k.daemonId||"";await p(E,"stop_cli",{cliType:x,targetSessionId:k.sessionId,mode:S})}catch(x){console.error("Stop CLI failed:",x)}finally{C(null)}},[u,w,b,p]);return{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:f,setRemoteDialogActiveConv:v,openRemoteDialog:N,closeRemoteDialog:m,cliStopDialogOpen:g,cliStopTargetConv:b,requestCliStop:A,cancelCliStop:w,confirmCliStop:M}}function Dc(){return"select_session"}function Xp(){return"open_panel"}function Jp({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function Qp(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function $o(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function Bo(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Oa(e){return e instanceof Error?e.message:String(e||"")}function Ko(e){const s=Oa(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Oo(e,s){const r=Oa(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function rn({sendDaemonCommand:e,activeConv:s,setActionLogs:r,isStandalone:n}){const[a,i]=o.useState(!1),[c,l]=o.useState(!1),[u,p]=o.useState(null),d=o.useRef(!1),h=o.useRef(null);o.useEffect(()=>{p(null)},[s==null?void 0:s.tabKey]);const f=o.useCallback(async g=>{if(!s)return!1;const j=g.trim(),b=ka(s);if(Jp({hasMessage:!!j,blockedMessage:b,sendInFlight:d.current}))return b&&p(b),!1;const C=Date.now(),A={tabKey:s.tabKey,message:j,timestamp:C};if(Qp(h.current,A))return p(null),!0;d.current=!0,l(!0),p(null),h.current=A;try{const w=Js(s);if(!w)return h.current=$o(h.current,A),p("Unable to send message right now."),!1;const M=await e(w,"send_chat",{message:j,...ws(s)}),S=Bo(M);if(S!=null&&S.deduplicated)return p(null),!0;if((S==null?void 0:S.sent)===!1)throw new Error((S==null?void 0:S.error)||"Send failed");if((S==null?void 0:S.success)===!1)throw new Error((S==null?void 0:S.error)||"Send failed");return p(null),!0}catch(w){const M=Oa(w);return M.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",M):console.warn("Send blocked/failed",w),h.current=$o(h.current,A),p(pm(w)),!1}finally{d.current=!1,l(!1)}},[s,e]),v=o.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(g){console.error("Relaunch failed",g)}},[s,e]),N=o.useCallback(async g=>{if(s)try{const b=(s.modalButtons||[]).indexOf(g),C=g.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),A=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(C),w=Js(s);if(!w)return;const M=await e(w,"resolve_action",{button:g,action:A?"approve":"reject",...b>=0&&{buttonIndex:b},...ws(s)}),S=Bo(M);S.success||r(k=>[...k,{routeId:s.tabKey,text:Oo(g,S==null?void 0:S.error),timestamp:Date.now()}])}catch(j){Ko(j)||console.error("[ModalButton] Error:",j),r(b=>[...b,{routeId:s.tabKey,text:Ko(j)?Oo(g,j):`❌ **${g}** error`,timestamp:Date.now()}])}},[s,e,r]),m=o.useCallback(async()=>{if(!(!s||a)){i(!0);try{await e(s.routeId,Xp(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(g){console.error("Focus agent failed",g)}finally{i(!1)}}},[s,a,e]);return{isSendingChat:c,sendFeedbackMessage:u,isFocusingAgent:a,handleSendChat:f,handleRelaunch:v,handleModalButton:N,handleFocusAgent:m}}const Wa=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:d=null,handleFocusAgent:h,isFocusingAgent:f,actionLogs:v,userName:N,scrollToBottomRequestNonce:m,isInputActive:g=!0}){const j=Cc(s),b=j.status||j.modalMessage||j.modalButtons?{...s,...j.status?{status:j.status}:{},...j.modalMessage!==void 0?{modalMessage:j.modalMessage}:{},...j.modalButtons!==void 0?{modalButtons:j.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(Ai,{activeConv:b,onModalButton:c}),b.transport!=="pty"&&b.transport!=="acp"&&b.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(qs,{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,b.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(Wm,{activeConv:b,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:d,isVisible:n,isInputActive:g})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(Zn,{activeConv:b,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:f,actionLogs:v,userName:N,scrollToBottomRequestNonce:m,isInputActive:g})})]}):t.jsx(Zn,{activeConv:b,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:f,actionLogs:v,userName:N,scrollToBottomRequestNonce:m,isInputActive:g})]})},(e,s)=>e.activeConv===s.activeConv&&e.isCliTerminal===s.isCliTerminal&&e.ideEntry===s.ideEntry&&e.terminalRef===s.terminalRef&&e.handleModalButton===s.handleModalButton&&e.handleRelaunch===s.handleRelaunch&&e.handleSendChat===s.handleSendChat&&e.isSendingChat===s.isSendingChat&&e.sendFeedbackMessage===s.sendFeedbackMessage&&e.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive);function Zp({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:p,onOpenNativeConversation:d,onOpenMachine:h,onOpenHistory:f,onOpenRemote:v,onHideConversation:N,onStopCli:m,cliViewMode:g,onSetCliViewMode:j,handleSendChat:b,handleFocusAgent:C,handleModalButton:A,handleRelaunch:w}){const M=o.useRef(null),S=Qe(e)&&!s,k=S&&g==="terminal",x=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`flex items-center justify-between gap-3 ${x} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:t.jsx(ua,{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:st(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(qi,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>h(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S&&g&&t.jsx(Na,{mode:g,onChange:j,compact:!0}),S&&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(wt,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:t.jsx(ma,{size:14})}),!s&&!S&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e),type:"button",children:t.jsx(Ct,{size:14})}),N&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>N(e),type:"button",title:"Close chat",children:t.jsx(wt,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(Wa,{activeConv:e,clearToken:0,isCliTerminal:k,ideEntry:n,terminalRef:M,handleModalButton:A,handleRelaunch:w,handleSendChat:b,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:C,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const Cn={unix:{cmd:"curl -fsSL https://adhf.dev/install | sh",shell:"Terminal",prompt:"$ "},powershell:{cmd:"irm https://adhf.dev/install.ps1 | iex",shell:"PowerShell",prompt:"PS> "},cmd:{cmd:"curl -fsSL https://adhf.dev/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd",shell:"CMD",prompt:"> "}};function eh(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Ec(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(eh())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Cn[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return t.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>s("unix"),children:"🍎🐧 macOS / Linux"}),t.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>s("windows"),children:"🪟 Windows"})]}),e==="windows"&&t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),t.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),t.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[t.jsx("span",{className:"text-text-muted select-none",children:Cn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:Cn[c].cmd}),t.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),t.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",t.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function $c({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Ct},{key:"chats",label:"Chats",icon:Ft}];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 wr({title:e,className:s=""}){return t.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:t.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function ps({children:e,className:s=""}){return t.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${s}`,children:e})}function Es({icon:e,title:s,subtitle:r,children:n}){return t.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[t.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),t.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function jr({item:e,type:s,getAvatarText:r,onOpenConversation:n}){const a=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",l=s==="task_complete",{isReconnecting:u,isConnecting:p}=As(e.conversation),d=st(e.conversation),h=us(e.conversation),f=nc(e.conversation,{requiresAction:s==="needs_attention"}),v=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",N=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",g=c?"text-text-muted":"text-text-secondary",j=c?"text-text-secondary opacity-80":"text-text-muted",b=c?"text-text-muted opacity-80":"text-text-muted",C="text-[color:var(--status-warning)]";return t.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${v}`,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 ${N}`,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 ${b}`,children:Mi(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${g}`,children:[h,u?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${C} animate-pulse`,children:"Reconnecting…"})]}):p?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):f==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:C,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${j}`,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 Wo({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 th({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:p,onShowAllHidden:d,onOpenNewSession:h,onOpenMachine:f,onOpenSettings:v,onSectionChange:N,wsStatus:m="connected",isStandalone:g=!1}){const j=m==="disconnected"||m==="reconnecting"||m==="offline"||m==="auth_failed",b=c.length>0,C=s.length>0||r.length>0||n.length>0||a.length>0,A=e==="machines"?"Machines":"Chats",w=g?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",M=g?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return t.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[t.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${w}`,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:A}),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(Xr,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:v,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(Yr,{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] ${M}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:j?t.jsx(Es,{icon:t.jsx(Wo,{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(Es,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:g?"Waiting for your daemon":"Connect your machines",subtitle:g?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!g&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(Ec,{})})}):t.jsx(ps,{children:c.map((S,k)=>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] ${k>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(S.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(S.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:S.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:S.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[S.unread," new"]}):S.total>0?`${S.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:S.subtitle}),S.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[S.total," chat",S.total!==1?"s":"",S.unread>0?` · ${S.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},S.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(wr,{title:"Needs attention",className:"mb-0"}),t.jsx(ps,{children:s.map((S,k)=>t.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:t.jsx(jr,{item:S,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},S.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(wr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(ps,{children:r.map((S,k)=>t.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:t.jsx(jr,{item:S,type:"task_complete",getAvatarText:l,onOpenConversation:u})},S.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(wr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(ps,{children:n.map((S,k)=>t.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:t.jsx(jr,{item:S,type:"working",getAvatarText:l,onOpenConversation:u})},S.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(wr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(ps,{children:a.map((S,k)=>t.jsx("div",{className:k>0?"border-t border-border-subtle/70":"",children:t.jsx(jr,{item:S,type:"earlier",getAvatarText:l,onOpenConversation:u})},S.conversation.tabKey))}):C?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):j?t.jsx(Es,{icon:t.jsx(Wo,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):b?t.jsx(Es,{icon:t.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:t.jsx(Ft,{size:20})}),title:"No conversations yet",subtitle:ic,children:h&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":Bt,title:Bt,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:Bt})]})}):t.jsx(Es,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[t.jsx("span",{children:"Hidden"}),t.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:d,children:"Restore all"})]}),t.jsx(ps,{className:"bg-bg-secondary/25",children:i.map((S,k)=>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 ${k>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(S),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(st(S))}),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:st(S)}),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:us(S)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},S.tabKey))})]})]}),e==="chats"&&h&&C&&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:h,"aria-label":Bt,title:Bt,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($c,{section:e,onSectionChange:N})]})}function sh(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function Bc(e){const s=[e.workspace||"Workspace unknown"],r=ds(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=sh(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function nn({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:p}){const[d,h]=o.useState(r);o.useEffect(()=>{h(r)},[r]);const f=Bp(r),v=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(wt,{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:()=>{!f||a||u(f)},disabled:!f||a,children:[t.jsx(ua,{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:N=>h(N.target.value),onKeyDown:N=>{N.key!=="Enter"||!v||a||(N.preventDefault(),u(v))},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:()=>{!v||a||u(v)},disabled:!v||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(N=>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(N.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(ks,{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:N.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:N.path})]})]},N.path))})}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(v||r),disabled:!v&&!r||a,children:c})]})]})})}function Ha({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:p,argsValue:d,onArgsChange:h,showModelInput:f,modelValue:v,onModelChange:N,historyProviderNode:m,onConfirm:g,onCancel:j}){const b=n==null?void 0:n.find(C=>C.key===a);return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:t.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:j,"aria-label":"Close launch confirmation",children:t.jsx(wt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),t.jsx("select",{value:a||"",onChange:C=>i(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:n.map(C=>t.jsx("option",{value:C.key,children:C.label},C.key))}),(b==null?void 0:b.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:b.description})]}),m,r.map(C=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:C.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:C.value})]},`${C.label}:${C.value}`)),f&&N&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),t.jsx("input",{type:"text",value:v||"",onChange:C=>N(C.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),p&&h&&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:C=>h(C.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:j,disabled:u,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:g,disabled:u,children:[t.jsx(pa,{size:14}),u?l:c]})]})]})})}function Ho(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function os(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?"⭐ ":""}${Ho(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:Ho(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(p=>p.key===u))return{options:i,selectedKey:u}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function rh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function nh(e){return[rh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function ah(e){return e.lastLaunchedAt?Jr(e.lastLaunchedAt):""}function Kc(e){return{metaText:nh(e),updatedLabel:ah(e)}}function In(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function oh({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var yt,ut,Xe,nt;const c=nr(),[l,u]=o.useState(!1),p=(((yt=e.detectedIdes)==null?void 0:yt.length)||0)>0,d=o.useMemo(()=>(e.workspaces||[]).map(ke=>({id:ke.id,path:ke.path,label:ke.label})),[e]),h=e.defaultWorkspaceId||null,[f,v]=o.useState(h||((ut=d[0])==null?void 0:ut.id)||""),[N,m]=o.useState(""),[g,j]=o.useState(""),[b,C]=o.useState([]),[A,w]=o.useState(!1),[M,S]=o.useState(""),[k,x]=o.useState(!1),[E,R]=o.useState(In(p,s.length,r.length)),I=o.useRef(null),[P,K]=o.useState(null),z=o.useRef("__home__"),[L,T]=o.useState("__home__"),[H,B]=o.useState(""),[D,G]=o.useState(""),[J,xe]=o.useState(""),[re,ge]=o.useState([]),[ye,Q]=o.useState(()=>pt().textQuery),[fe,W]=o.useState(()=>pt().workspaceQuery),[q,oe]=o.useState(()=>pt().modelQuery),[he,le]=o.useState(()=>pt().resumableOnly),[ve,ne]=o.useState(()=>pt().sortMode),[pe,ce]=o.useState(!1),[de,ae]=o.useState(!1),je=o.useRef(null),U=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const se=f==="__custom__"?N.trim():((Xe=d.find(ke=>ke.id===f))==null?void 0:Xe.path)||"",y=f==="__custom__"&&!!se&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),X=f!=="__custom__"&&((nt=d.find(ke=>ke.id===f))==null?void 0:nt.path)||"",te=o.useMemo(()=>(e.recentLaunches||[]).map(ke=>ke.workspace),[e]),ue=o.useCallback(async ke=>{w(!0),S("");try{const De=await a(ke);j(De.path),m(De.path),C(De.directories)}catch(De){S(De instanceof Error?De.message:"Could not load folder")}finally{w(!1)}},[a]),we=o.useCallback(()=>{var De;v("__custom__"),x(!0);const ke=tn(e.platform,en(N.trim(),X,te,e.defaultWorkspacePath,(De=d.find($e=>$e.id===h))==null?void 0:De.path,d.map($e=>$e.path)));ue(ke)},[N,h,ue,te,X,e.platform,d]),Ne=o.useCallback(ke=>{if(ke!=null&&ke.workspaceId){v(ke.workspaceId),m("");return}if(ke!=null&&ke.workspacePath){v("__custom__"),m(ke.workspacePath);return}v(""),m("")},[]),Be=o.useCallback(ke=>{if(v(ke),ke==="__custom__"){we();return}m("")},[we]),Ke=o.useCallback(ke=>{v("__custom__"),m(ke)},[]),Fe=o.useCallback((ke,De)=>{I.current=De,z.current=ke.selectedWorkspaceKey||"__home__",T(ke.selectedWorkspaceKey||"__home__"),B(ke.initialArgs||""),G(ke.initialModel||""),xe(""),ge([]);const $e=ke.providerType?`${e.id}:${ke.providerType}`:null;if(Vm(U.current,$e)){const tt=pt();Q(tt.textQuery),W(tt.workspaceQuery),oe(tt.modelQuery),le(tt.resumableOnly),ne(tt.sortMode)}U.current=$e,K(ke),ke.providerType&&i&&(ce(!0),i(ke.providerType).then(tt=>ge(tt||[])).catch(tt=>console.warn("Failed to load saved sessions",tt)).finally(()=>ce(!1)))},[i,e.id]),Ue=o.useMemo(()=>cc(re,{textQuery:ye,workspaceQuery:fe,modelQuery:q,resumableOnly:he,sortMode:ve}),[q,he,re,ve,ye,fe]);o.useEffect(()=>{J&&(Ue.some(ke=>ke.providerSessionId===J)||xe(""))},[Ue,J]);const ot=o.useCallback(()=>{I.current&&(ae(!0),I.current().finally(()=>{I.current=null,ae(!1),K(null)}))},[]),rt=o.useCallback(()=>{I.current=null,K(null)},[]),dt=o.useCallback(ke=>{z.current=ke,T(ke)},[]);return o.useEffect(()=>{var ke;je.current!==e.id&&(je.current=e.id,v(h||((ke=d[0])==null?void 0:ke.id)||"__custom__"),m(""),j(""),C([]),S(""),x(!1),Q(pt().textQuery),W(pt().workspaceQuery),oe(pt().modelQuery),le(pt().resumableOnly),ne(pt().sortMode),U.current=null,R(In(p,s.length,r.length)))},[r.length,s.length,h,p,e.id,d]),o.useEffect(()=>{var ke;f!=="__custom__"&&(f&&d.some(De=>De.id===f)||v(h||((ke=d[0])==null?void 0:ke.id)||"__custom__"))},[h,f,d]),o.useEffect(()=>{E==="ide"&&p||E==="cli"&&s.length>0||E==="acp"&&r.length>0||R(In(p,s.length,r.length))},[E,r.length,s.length,p]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:d,defaultWorkspaceId:h,workspaceChoice:f,customWorkspacePath:N,browseCurrentPath:g,browseDirectories:b,browseBusy:A,browseError:M,browseDialogOpen:k,activeLauncherKind:E,launchConfirm:P,launchConfirmWorkspaceKeyRef:z,launchConfirmWorkspaceKey:L,launchConfirmArgs:H,launchConfirmModel:D,launchConfirmResumeId:J,launchConfirmSavedSessions:re,launchConfirmTextFilter:ye,launchConfirmWorkspaceFilter:fe,launchConfirmModelFilter:q,launchConfirmResumableOnly:he,launchConfirmSortMode:ve,filteredLaunchConfirmSavedSessions:Ue,launchConfirmSessionsLoading:pe,launchConfirmBusy:de,resolvedWorkspacePath:se,canCreateMissingWorkspace:y,openBrowseDialog:we,loadBrowsePath:ue,handleWorkspaceChoiceChange:Be,chooseCustomWorkspacePath:Ke,setCustomWorkspacePath:m,setBrowseDialogOpen:x,setActiveLauncherKind:R,openLaunchConfirm:Fe,handleConfirmLaunch:ot,closeLaunchConfirm:rt,setWorkspaceSelectionFromOption:Ne,setLaunchConfirmWorkspaceKeyAndSync:dt,setLaunchConfirmArgs:B,setLaunchConfirmModel:G,setLaunchConfirmResumeId:xe,setLaunchConfirmTextFilter:Q,setLaunchConfirmWorkspaceFilter:W,setLaunchConfirmModelFilter:oe,setLaunchConfirmResumableOnly:le,setLaunchConfirmSortMode:ne}}function ih({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:p,showBottomNav:d,onBack:h,onSectionChange:f,onOpenConversation:v,onOpenRecent:N,onOpenMachineDetails:m,onMachineUpgrade:g,onLaunchDetectedIde:j,onAddWorkspace:b,onBrowseDirectory:C,onLaunchWorkspaceProvider:A,onListSavedSessions:w}){const M=L=>L==="ide"?"IDE":L==="cli"?"CLI":"ACP",S=r.slice(0,4),k=s.slice(0,3),x=oh({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:C,onListSavedSessions:w}),E=o.useMemo(()=>S.map(L=>{const{metaText:T,updatedLabel:H}=Kc(L);return{key:`recent-launch:${L.id}`,primary:L.label,secondary:T,updatedLabel:H,onClick:()=>{const{options:B,selectedKey:D}=os({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspacePath:L.workspace});x.openLaunchConfirm({title:L.kind==="ide"?ss("restart-ide",L.label):L.providerSessionId?Ma(L.label):ss("start-fresh",L.label),description:L.kind==="ide"?rs("restart-ide"):L.providerSessionId?Aa():rs("start-fresh"),confirmLabel:L.kind==="ide"?Cs("restart-ide"):L.providerSessionId?Fr(!0):Cs("start-fresh"),busyLabel:L.kind==="ide"?Is("restart-ide"):L.providerSessionId?Ca(!0):Is("start-fresh"),workspaceOptions:B,selectedWorkspaceKey:D,details:[{label:"Mode",value:M(L.kind)},...L.providerType?[{label:"Provider",value:L.providerType}]:[]]},async()=>{const G=B.find(J=>J.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(G),await N({...L,workspace:(G==null?void 0:G.workspacePath)??null})})}}}),[x,N,S]),R=o.useMemo(()=>k.map(L=>({key:`recent-chat:${L.conversation.tabKey}`,primary:st(L.conversation),secondary:$m(L.conversation,{timestampLabel:L.timestamp?Mi(L.timestamp):null}),unread:L.unread,onClick:()=>v(L.conversation)})),[v,k]),I=x.showAllRecent?E:E.slice(0,4),P=E.length>0,K=R.length>0,z=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 ${z} 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:h,type:"button","aria-label":"Back",children:t.jsx(ua,{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:Tt(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:R.map(L=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${L.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:L.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:L.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.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:I.map(L=>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:L.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:L.primary}),L.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:L.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.key))}),E.length>4&&t.jsx("div",{className:"flex justify-center px-4 pt-2",children:t.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>x.setShowAllRecent(L=>!L),children:x.showAllRecent?"Show fewer":`Show ${E.length-4} more`})})]}),(x.hasIdeOptions||n.length>0||a.length>0)&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:t.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),t.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),t.jsx("select",{value:x.workspaceChoice,onChange:L=>x.handleWorkspaceChoiceChange(L.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:x.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[x.workspaceRows.map(L=>t.jsxs("option",{value:L.id,children:[L.id===x.defaultWorkspaceId?"⭐ ":"",Zr(L.path,L.label)||L.path]},L.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),x.workspaceChoice==="__custom__"&&t.jsxs("div",{className:"flex flex-col gap-2.5",children:[t.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start gap-3",children:[t.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(ks,{size:17})}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),t.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:x.resolvedWorkspacePath||x.browseCurrentPath||"No folder selected yet."})]})]})}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:x.openBrowseDialog,children:"Select workspace…"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{x.resolvedWorkspacePath&&b(x.resolvedWorkspacePath)},disabled:!x.resolvedWorkspacePath||x.browseBusy,children:"Save as workspace"})]})]}),x.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[x.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.activeLauncherKind==="ide"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>x.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.activeLauncherKind==="cli"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>x.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.activeLauncherKind==="acp"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>x.setActiveLauncherKind("acp"),children:"ACP"})]}),x.activeLauncherKind&&t.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[t.jsx("div",{className:"text-xs font-bold text-text-secondary",children:x.activeLauncherKind==="ide"?"Choose an IDE":x.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:x.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(L=>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:T,selectedKey:H}=os({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${L.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:T,selectedWorkspaceKey:H,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:L.name}]},async()=>{const B=T.find(D=>D.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(B),j(L.type,{workspacePath:(B==null?void 0:B.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:L.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},L.type)):(x.activeLauncherKind==="cli"?n:a).map(L=>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 T=x.activeLauncherKind==="cli"?"cli":"acp",{options:H,selectedKey:B}=os({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${L.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${T.toUpperCase()}`,workspaceOptions:H,selectedWorkspaceKey:B,details:[{label:"Mode",value:T.toUpperCase()},{label:"Provider",value:L.displayName}],showArgsInput:!0,showModelInput:T==="acp",initialArgs:"",initialModel:"",providerType:L.type},async()=>{const D=H.find(G=>G.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(D),A(T,L.type,{workspaceId:(D==null?void 0:D.workspaceId)??null,workspacePath:(D==null?void 0:D.workspacePath)??null,args:x.launchConfirmArgs,model:x.launchConfirmModel,resumeSessionId:x.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[L.icon?`${L.icon} `:"",L.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},L.type))})]}),l.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,x.canCreateMissingWorkspace&&t.jsx("div",{className:"mt-2",children:t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>b(x.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:g,children:[t.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick: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"})]})]})]})]}),x.browseDialogOpen&&t.jsx(nn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:x.browseCurrentPath,directories:x.browseDirectories,busy:x.browseBusy,error:x.browseError,confirmLabel:"Use this folder",onClose:()=>x.setBrowseDialogOpen(!1),onNavigate:L=>{x.loadBrowsePath(L)},onConfirm:L=>{x.chooseCustomWorkspacePath(L),x.setBrowseDialogOpen(!1)}}),x.launchConfirm&&t.jsx(Ha,{title:x.launchConfirm.title,description:x.launchConfirm.description,details:x.launchConfirm.details,workspaceOptions:x.launchConfirm.workspaceOptions,selectedWorkspaceKey:x.launchConfirmWorkspaceKey,onWorkspaceChange:x.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:x.launchConfirm.providerType?Fr(!!x.launchConfirmResumeId):x.launchConfirm.confirmLabel,busyLabel:x.launchConfirm.providerType?void 0:x.launchConfirm.busyLabel,busy:x.launchConfirmBusy,showArgsInput:x.launchConfirm.showArgsInput,argsValue:x.launchConfirmArgs,onArgsChange:x.setLaunchConfirmArgs,showModelInput:x.launchConfirm.showModelInput,modelValue:x.launchConfirmModel,onModelChange:x.setLaunchConfirmModel,historyProviderNode:x.launchConfirm.providerType&&(x.launchConfirmSessionsLoading||x.launchConfirmSavedSessions.length>0)&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),x.launchConfirmSessionsLoading&&t.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:Ia()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:x.launchConfirmTextFilter,onChange:L=>x.setLaunchConfirmTextFilter(L.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmWorkspaceFilter,onChange:L=>x.setLaunchConfirmWorkspaceFilter(L.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmModelFilter,onChange:L=>x.setLaunchConfirmModelFilter(L.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsxs("select",{value:x.launchConfirmSortMode,onChange:L=>x.setLaunchConfirmSortMode(L.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:x.launchConfirmResumableOnly,onChange:L=>x.setLaunchConfirmResumableOnly(L.target.checked),disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:x.launchConfirmResumeId,onChange:L=>x.setLaunchConfirmResumeId(L.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:Ym()}),x.filteredLaunchConfirmSavedSessions.map(L=>t.jsxs("option",{value:L.providerSessionId,disabled:!L.canResume,children:[L.title||L.providerSessionId," ",L.canResume?"":"(workspace missing)"]},L.providerSessionId))]}),!x.launchConfirmSessionsLoading&&x.launchConfirmSavedSessions.length>0&&x.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),x.launchConfirmResumeId&&(()=>{const L=x.filteredLaunchConfirmSavedSessions.find(H=>H.providerSessionId===x.launchConfirmResumeId);if(!L)return null;const T=Bc(L);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:T.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:T.providerSessionId}),t.jsx("div",{className:"mt-1",children:T.metaLine}),T.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:T.updatedLabel}),T.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:T.preview})]})})()]}),onConfirm:x.handleConfirmLaunch,onCancel:x.closeLaunchConfirm}),d&&t.jsx($c,{section:p,onSectionChange:f})]})}function ch(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 lh(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:ds(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):s.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,u,p,d;const a=Xs(n)?"cli":gs(n)?"acp":"ide",i=ds(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(Xs(n)?n.cliName||n.type:gs(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:gs(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((d=(p=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:p.call(u,-1))==null?void 0:d.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function dh(e,s){const r=new Map;for(const n of s){const a=qt(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((h,f)=>f.timestamp-h.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=Gn(n),u=a.filter(h=>h.unread||h.requiresAction).length,p=ch(n),d=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:Tt(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?Bm(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 kr(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 uh({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:v,setSelectedTabKey:N,setScreen:m,setSelectedMachineId:g,setSection:j,setMachineBackTarget:b,resetMachineAction:C}){const A=o.useRef(null),w=o.useCallback(M=>{if(!(M!=null&&M.sessionId))return;const S=Or(M,c),k=Math.max(Date.now(),es(M),S.lastUpdated||0);kr("mark_read:start",{tabKey:M.tabKey,sessionId:M.sessionId,displayPrimary:st(M),inboxBucket:S.inboxBucket,unread:S.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:es(M),readAt:k}),l(qt(M)||M.routeId,"mark_session_seen",{sessionId:M.sessionId,seenAt:k}).then(x=>{kr("mark_read:result",{tabKey:M.tabKey,sessionId:M.sessionId,result:x})}).catch(x=>{kr("mark_read:error",{tabKey:M.tabKey,sessionId:M.sessionId,error:x instanceof Error?x.message:String(x)})})},[c,l]);return o.useEffect(()=>{var S;if(!n){m("inbox"),N(((S=e[0])==null?void 0:S.tabKey)||null),A.current=null;return}if(i!=="chat"){A.current=null;return}const M=`${n.tabKey}:${n.sessionId||""}`;A.current!==M&&(A.current=M,w(n))},[e,w,i,n,m,N]),o.useEffect(()=>{if(!u)return;const M=e.find(S=>S.tabKey===u);M&&(N(M.tabKey),m("chat"),p==null||p())},[e,p,u,m,N]),o.useEffect(()=>{if(!d)return;const M=s.find(S=>S.id===d);M&&(g(M.id),C(),j("machines"),b("inbox"),m("machine"),h==null||h())},[s,h,d,C,b,m,j,g]),o.useEffect(()=>{f&&(j(f),m("inbox"),v==null||v())},[v,f,m,j]),o.useEffect(()=>{const M=r.filter(S=>S.inboxBucket==="task_complete"||S.unread);M.length!==0&&kr("inbox_state",{screen:i,selectedTabKey:a,items:M.map(S=>{const k=Or(S.conversation,c);return{liveState:k,tabKey:S.conversation.tabKey,sessionId:S.conversation.sessionId,displayPrimary:st(S.conversation),serverBucket:k.inboxBucket,computedBucket:S.inboxBucket,serverUnread:k.unread,computedUnread:S.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,activityAt:es(S.conversation)}})})},[r,c,i,a]),{markConversationRead:w}}function mh(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Fo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function fh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function ph({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,p]=o.useState(null),d=o.useCallback(()=>{i("idle"),l(""),p(null)},[]),h=o.useCallback(async(b,C,A)=>{var w;try{i("loading"),l(`Launching ${C}…`);const M={ideType:C,enableCdp:!0};(w=A==null?void 0:A.workspacePath)!=null&&w.trim()&&(M.workspace=A.workspacePath.trim()),await e(b,"launch_ide",M),i("done"),l(`${C} launch requested`)}catch(M){i("error"),l(M instanceof Error?M.message:"Launch IDE failed"),console.error("Launch IDE failed",M)}},[e]),f=o.useCallback(async(b,C,A)=>{if(C.trim())try{i("loading"),l(A!=null&&A.createIfMissing?"Creating folder…":"Saving workspace…");const w=await e(b,"workspace_add",{path:C.trim(),createIfMissing:(A==null?void 0:A.createIfMissing)===!0});if(w!=null&&w.success){i("done"),l(A!=null&&A.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((w==null?void 0:w.error)||"Could not save workspace")}catch(w){i("error"),l(w instanceof Error?w.message:"Could not save workspace")}},[e]),v=o.useCallback(async b=>{var C,A,w,M,S,k;try{i("loading"),l("Starting daemon upgrade…");const x=await e(b,"daemon_upgrade",{});if((C=x==null?void 0:x.result)!=null&&C.alreadyLatest){i("done"),l(`Already on v${((A=x==null?void 0:x.result)==null?void 0:A.version)||"latest"}.`);return}if((w=x==null?void 0:x.result)!=null&&w.upgraded||(M=x==null?void 0:x.result)!=null&&M.success){i("done"),l(`Upgrade to v${((S=x==null?void 0:x.result)==null?void 0:S.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((k=x==null?void 0:x.result)==null?void 0:k.error)||"Upgrade failed")}catch(x){i("error"),l(x instanceof Error?x.message:"Upgrade failed")}},[e]),N=o.useCallback(async(b,C,A,w)=>{var k,x,E;const M=Date.now(),S={machineId:b,kind:C,providerType:A,workspaceId:(w==null?void 0:w.workspaceId)||null,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:M};try{i("loading"),l(`Launching ${A}…`),p(S);const R={cliType:A};(k=w==null?void 0:w.workspacePath)!=null&&k.trim()?R.dir=w.workspacePath.trim():w!=null&&w.workspaceId&&(R.workspaceId=w.workspaceId),w!=null&&w.resumeSessionId&&(R.resumeSessionId=w.resumeSessionId),(x=w==null?void 0:w.args)!=null&&x.trim()&&(R.cliArgs=w.args.trim().split(/\s+/).filter(Boolean)),(E=w==null?void 0:w.model)!=null&&E.trim()&&(R.initialModel=w.model.trim());const I=await e(b,"launch_cli",R),P=(I==null?void 0:I.result)||I,K=(P==null?void 0:P.sessionId)||(P==null?void 0:P.id);if(I!=null&&I.success&&K){p(null),i("done"),l(`${A} launched`),s(Vt(K));return}if(I!=null&&I.success){i("loading"),l(`${A} launch requested — waiting for session…`);return}p(null),i("error"),l((I==null?void 0:I.error)||(P==null?void 0:P.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(R){if(fh(R)){i("loading"),l(`${A} launch requested — waiting for session…`);return}p(null),i("error"),l(R instanceof Error?R.message:`Could not launch ${C.toUpperCase()} workspace`)}},[s,e]),m=o.useCallback(async(b,C)=>{try{const A=await e(b,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),w=(A==null?void 0:A.result)??A;return Array.isArray(w==null?void 0:w.sessions)?w.sessions:[]}catch(A){return console.error("Failed to list saved sessions on mobile:",A),[]}},[e]),g=o.useCallback(async(b,C)=>sn(e,b,C),[e]);o.useEffect(()=>{if(!u)return;const b=Fo(u.workspacePath),C=r.find(w=>{var R,I,P,K;if(!w||w.type==="adhdev-daemon"||mh(w.daemonId||w.id)!==u.machineId||(w.transport==="acp"?"acp":w.transport==="pty"?"cli":null)!==u.kind||String(w.agentType||w.type||"")!==u.providerType)return!1;const x=String(w.providerSessionId||"");if(u.resumeSessionId&&x)return x===u.resumeSessionId;if(b){const z=Fo(w.workspace||w.runtimeWorkspaceLabel);return z?z===b:!1}return Number(w.lastUpdated||w._lastUpdate||w.timestamp||((K=(P=(I=(R=w.activeChat)==null?void 0:R.messages)==null?void 0:I.at)==null?void 0:P.call(I,-1))==null?void 0:K.timestamp)||0)>=u.startedAt-5e3});if(!C)return;const A=Gi({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:n});A&&(p(null),i("done"),l(`${u.providerType} launched`),s(Vt(A)))},[n,r,s,u]),o.useEffect(()=>{if(!u)return;const b=window.setTimeout(()=>{p(C=>!C||C.startedAt!==u.startedAt?C:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(b)},[u]);const j=o.useCallback(async(b,C)=>{if(C.kind==="ide"&&C.providerType){await h(b,C.providerType,{workspacePath:C.workspace||null});return}(C.kind==="cli"||C.kind==="acp")&&C.providerType&&await N(b,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[h,N]);return{machineAction:{state:a,message:c},resetMachineAction:d,handleLaunchDetectedIde:h,handleAddWorkspace:f,handleMachineUpgrade:v,handleLaunchWorkspaceProvider:N,handleListSavedSessions:m,handleBrowseDirectory:g,handleOpenRecent:j}}function hh({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:p}){const d=o.useCallback(j=>{i(j.tabKey),c("chat"),n(j)},[n,c,i]),h=o.useCallback(j=>{const b=e.find(C=>C.routeId===j.routeId&&C.streamSource==="native");b&&(i(b.tabKey),c("chat"),n(b))},[e,n,c,i]),f=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),v=o.useCallback((j,b="inbox")=>{l(j),a(),u("machines"),p(b),c("machine")},[a,p,c,u,l]),N=o.useCallback(j=>{const b=qt(j);b&&v(b,"chat")},[v]),m=o.useCallback(()=>{a(),c(r)},[r,a,c]),g=o.useCallback(j=>{u(j),c("inbox")},[c,u]);return{openConversation:d,openNativeConversation:h,backFromConversation:f,openMachine:v,openConversationMachine:N,backFromMachine:m,changeMachineSection:g}}function xh(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Sr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function bh({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:v,onOpenHistory:N,onOpenRemote:m,onStopCli:g,wsStatus:j,isConnected:b,onShowHiddenConversation:C,onShowAllHiddenConversations:A,onHideConversation:w,onOpenNewSession:M,liveSessionInboxState:S}){const[k,x]=o.useState(()=>{var y;return((y=e[0])==null?void 0:y.tabKey)||null}),[E,R]=o.useState(()=>e[0]?"chat":"inbox"),[I,P]=o.useState("chats"),[K,z]=o.useState(null),[L,T]=o.useState("inbox"),H=Ms(),B="0.9.8",D=o.useMemo(()=>e.find(y=>y.tabKey===k)||e[0]||null,[e,k]),G=o.useMemo(()=>D?r.find(y=>y.id===D.routeId):void 0,[r,D]),J=o.useMemo(()=>!D||Ge(D)||!Qe(D)?null:Ts(D),[D]),xe=o.useMemo(()=>r.filter(y=>y.type==="adhdev-daemon").sort(xa),[r]),re=o.useMemo(()=>xe.find(y=>y.id===K)||null,[xe,K]),ge=rn({sendDaemonCommand:a,activeConv:D||void 0,setActionLogs:i,isStandalone:c}),ye=ph({sendDaemonCommand:a,navigate:H,ides:r,conversations:e}),Q=o.useMemo(()=>e.map(y=>{const X=E==="chat"&&(D==null?void 0:D.tabKey)===y.tabKey,te=Qr(y,S,{hideOpenTaskCompleteUnread:!0,isOpenConversation:X}),ue=es(y),we=rc(y);return{conversation:y,timestamp:ue,preview:we,unread:te.unread,requiresAction:te.requiresAction,isWorking:te.isWorking,inboxBucket:te.inboxBucket}}),[e,S,E,D]),{markConversationRead:fe}=uh({conversations:e,machineEntries:xe,items:Q,selectedConversation:D,selectedTabKey:k,screen:E,liveSessionInboxState:S,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:v,setSelectedTabKey:x,setScreen:R,setSelectedMachineId:z,setSection:P,setMachineBackTarget:T,resetMachineAction:ye.resetMachineAction}),W=hh({conversations:e,selectedConversation:D,machineBackTarget:L,markConversationRead:fe,resetMachineAction:ye.resetMachineAction,setSelectedTabKey:x,setScreen:R,setSelectedMachineId:z,setSection:P,setMachineBackTarget:T}),q=o.useMemo(()=>Sr(Q.filter(y=>y.requiresAction)),[Q]),oe=o.useMemo(()=>Sr(Q.filter(y=>y.unread&&!y.requiresAction)),[Q]),he=o.useMemo(()=>Sr(Q.filter(y=>!y.unread&&!y.requiresAction&&y.isWorking)),[Q]),le=o.useMemo(()=>Sr(Q.filter(y=>!y.unread&&!y.requiresAction&&!y.isWorking)),[Q]),ve=o.useMemo(()=>re?Q.filter(y=>qt(y.conversation)===re.id):[],[Q,re]),ne=o.useMemo(()=>lh(re,r),[r,re]),pe=(re==null?void 0:re.version)||null,ce=!!re&&!!pe&&!0&&pe!==B,de=o.useMemo(()=>(re==null?void 0:re.availableProviders)||[],[re]),ae=o.useMemo(()=>de.filter(y=>y.category==="cli"&&y.installed!==!1).map(y=>({type:y.type,displayName:y.displayName||y.type,icon:y.icon})),[de]),je=o.useMemo(()=>de.filter(y=>y.category==="acp"&&y.installed!==!1).map(y=>({type:y.type,displayName:y.displayName||y.type,icon:y.icon})),[de]),U=o.useMemo(()=>dh(xe,Q),[Q,xe]),se=o.useCallback(async y=>{re&&await ye.handleOpenRecent(re.id,y)},[ye,re]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:E==="chat"&&D?t.jsx(Zp,{selectedConversation:D,isAcp:Ge(D),isStandalone:c,selectedIdeEntry:G,actionLogs:n,userName:l,isSendingChat:ge.isSendingChat,sendFeedbackMessage:ge.sendFeedbackMessage,isFocusingAgent:ge.isFocusingAgent,handleModalButton:ge.handleModalButton,handleRelaunch:ge.handleRelaunch,onBack:W.backFromConversation,onOpenNativeConversation:W.openNativeConversation,onOpenMachine:W.openConversationMachine,onHideConversation:w,onOpenHistory:N,onOpenRemote:m,onStopCli:g,cliViewMode:J,onSetCliViewMode:async y=>{if(D&&J!==y)try{await a(qt(D)||D.routeId,"set_cli_view_mode",{targetSessionId:D.sessionId,cliType:_t(D),mode:y})}catch(X){const te=Ba(X);$a(X)?console.warn(te?"CLI view mode result was lost after send; keeping optimistic mobile mode override:":"Skipped CLI view mode switch:",X instanceof Error?X.message:String(X)):console.error("Failed to switch CLI view mode:",X)}},handleSendChat:ge.handleSendChat,handleFocusAgent:ge.handleFocusAgent}):E==="machine"&&re?t.jsx(ih,{selectedMachineEntry:re,selectedMachineConversations:ve,selectedMachineRecentLaunches:ne,cliProviders:ae,acpProviders:je,selectedMachineNeedsUpgrade:ce,appVersion:B,machineAction:ye.machineAction,isStandalone:c,section:I,showBottomNav:L==="inbox",onBack:W.backFromMachine,onSectionChange:W.changeMachineSection,onOpenConversation:W.openConversation,onOpenRecent:se,onOpenMachineDetails:()=>H(`/machines/${re.id}`),onMachineUpgrade:()=>ye.handleMachineUpgrade(re.id),onLaunchDetectedIde:(y,X)=>ye.handleLaunchDetectedIde(re.id,y,X),onAddWorkspace:(y,X)=>ye.handleAddWorkspace(re.id,y,X),onBrowseDirectory:y=>ye.handleBrowseDirectory(re.id,y),onLaunchWorkspaceProvider:(y,X,te)=>ye.handleLaunchWorkspaceProvider(re.id,y,X,te),onListSavedSessions:y=>ye.handleListSavedSessions(re.id,y)}):t.jsx(th,{section:I,attentionItems:q,unreadItems:oe,workingItems:he,completedItems:le,hiddenConversations:s,machineCards:U,getAvatarText:xh,onOpenConversation:W.openConversation,onShowConversation:C,onShowAllHidden:A,onOpenNewSession:M,onOpenMachine:W.openMachine,onOpenSettings:()=>H("/settings"),onSectionChange:P,wsStatus:j,isConnected:b,isStandalone:c})})}function Mn(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function gh({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[p,d]=o.useState(null),h=o.useCallback(()=>{c.current=0,u(!1),d(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const f=o.useCallback(g=>{g.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),v=o.useCallback(g=>{if(!g.dataTransfer.types.includes("text/tab-key"))return;if(g.preventDefault(),!Mn(s,r)){d("merge");return}const j=g.currentTarget.getBoundingClientRect(),b=g.clientX-j.left,C=j.width/3;b<C?d("split-left"):b>C*2?d("split-right"):d("merge")},[s,r]),N=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),d(null))},[]),m=o.useCallback(g=>{c.current=0,u(!1);const j=g.dataTransfer.getData("text/tab-key"),b=j?e.some(A=>A.tabKey===j):!1,C=p;if(d(null),i(),!!j){if(g.preventDefault(),C==="split-left"&&Mn(s,r)){r==null||r(j,"split-left");return}if(C==="split-right"&&Mn(s,r)){r==null||r(j,"split-right");return}if(b){a(j);return}n==null||n(j)}},[e,p,s,r,n,a,i]);return{dragOver:l,dropAction:p,resetDragState:h,handleDragEnter:f,handleDragOver:v,handleDragLeave:N,handleDrop:m}}function yh(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 vh({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(s??null),[l,u]=o.useState(r??[]),[p,d]=o.useState(null),h=o.useRef(null),f=o.useRef(null),v=o.useRef(n),N=o.useRef(a);o.useEffect(()=>{v.current=n},[n]),o.useEffect(()=>{N.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{u(S=>{const k=yh(S,e);return k.length===S.length&&k.every((x,E)=>x===S[E])?S:k})},[e]);const m=o.useMemo(()=>{const S=p??l;if(S.length===0)return e;const k=new Map(S.map((x,E)=>[x,E]));return[...e].sort((x,E)=>{const R=k.get(x.tabKey)??999,I=k.get(E.tabKey)??999;return R-I})},[e,p,l]);o.useEffect(()=>{var k,x;if(m.length===0){i!==null&&(c(null),(k=v.current)==null||k.call(v,null));return}if(i&&m.some(E=>E.tabKey===i))return;const S=m[0].tabKey;S!==i&&(c(S),(x=v.current)==null||x.call(v,S))},[m,i]);const g=o.useMemo(()=>m.find(S=>S.tabKey===i),[m,i]),j=o.useCallback(S=>{var k;c(S),(k=v.current)==null||k.call(v,S)},[]),b=o.useCallback((S,k,x)=>{u(E=>{var K;const R=E.filter(z=>z!==S),I=R.indexOf(k);if(I<0)return E;const P=x==="left"?I:I+1;return R.splice(P,0,S),(K=N.current)==null||K.call(N,R),R}),d(null)},[]),C=o.useCallback((S,k,x)=>{const R=(l.length>0?l:e.map(K=>K.tabKey)).filter(K=>K!==S),I=R.indexOf(k);if(I<0)return;const P=x==="left"?I:I+1;R.splice(P,0,S),h.current=R,d(R)},[l,e]),A=o.useCallback(()=>{var k;const S=h.current;S&&(u(S),(k=N.current)==null||k.call(N,S))},[]),w=o.useCallback(()=>{h.current=null,d(null)},[]),M=o.useCallback(S=>{u(k=>{var E;const x=k.filter(R=>R!==S);return x.push(S),(E=N.current)==null||E.call(N,x),x})},[]);return{activeTabId:i,activeConv:g,sortedConversations:m,previewOrderRef:h,draggingTabRef:f,selectTab:j,handleTabReorder:b,updatePreviewOrder:C,commitPreviewOrder:A,clearPreviewOrder:w,moveTabToEnd:M,setDraggingTabKey:S=>{f.current=S}}}function wh({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 Fa({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",p=n?ic: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:p}),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:Bt,"aria-label":Bt,children:[t.jsx(ki,{size:14}),t.jsx("span",{children:Bt})]})}),c&&t.jsx(Ec,{}),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 Oc="adhdev-tab-shortcuts";function Wc(){try{return JSON.parse(localStorage.getItem(Oc)||"{}")}catch{return{}}}function Hc({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>Wc()),[l,u]=o.useState(null),p=o.useCallback(h=>{const f=[];return h.metaKey&&f.push(a?"⌘":"Meta"),h.ctrlKey&&f.push("Ctrl"),h.altKey&&f.push(a?"⌥":"Alt"),h.shiftKey&&f.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(f.push(h.key.length===1?h.key.toUpperCase():h.key),f.join("+"))},[a]),d=o.useCallback(h=>{c(h);try{localStorage.setItem(Oc,JSON.stringify(h))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const h=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){u(null);return}const v=p(f);if(!v)return;const N={...i};for(const[m,g]of Object.entries(N))g===v&&delete N[m];N[l]=v,d(N),u(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,i,d,p]),o.useEffect(()=>{if(!e)return;const h=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[v,N]of Object.entries(i))if(s.includes(v)&&p(f)===N){f.preventDefault(),r(),n(v);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,i,s,r,n,p]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:d}}const jh=o.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:p,onConversationActivated:d,onPreviewReorder:h,onReorderTab:f,onCommitPreviewOrder:v,onClearPreviewOrder:N,onDragStateReset:m,onDragTabKeyChange:g,onReceiveTab:j,onOpenContextMenu:b,longPressTimer:C,isGroupActive:A}){const w=As(s),M=w.isGenerating?"agent-tab-generating":w.isWaiting?"agent-tab-waiting":"",S=w.isReconnecting,k=o.useCallback(T=>{l.current=s.tabKey,g(s.tabKey),T.dataTransfer.setData("text/tab-key",s.tabKey),T.dataTransfer.effectAllowed="move"},[s.tabKey,l,g]),x=o.useCallback(()=>{l.current=null,g(null),v(),N(),m()},[l,g,v,N,m]),E=o.useCallback(T=>{const H=l.current;if(!(!H||H===s.tabKey)&&T.dataTransfer.types.includes("text/tab-key")){T.preventDefault(),T.stopPropagation();const B=T.currentTarget.getBoundingClientRect(),D=T.clientX<B.left+B.width/2?"left":"right";h(H,s.tabKey,D)}},[s.tabKey,l,h]),R=o.useCallback(T=>{T.preventDefault(),T.stopPropagation();const H=T.dataTransfer.getData("text/tab-key");if(H&&H!==s.tabKey){const B=T.currentTarget.getBoundingClientRect(),D=T.clientX<B.left+B.width/2?"left":"right";c.includes(H)?f(H,s.tabKey,D):j&&j(H)}N()},[s.tabKey,c,f,j,N]),I=o.useCallback(T=>{T.stopPropagation(),u(),p(s.tabKey),d(s)},[s,d,u,p]),P=o.useCallback(T=>{T.preventDefault(),b(T.clientX,T.clientY,s.tabKey)},[s.tabKey,b]),K=o.useCallback(T=>{const H=T.touches[0];C.current=setTimeout(()=>{b(H.clientX,H.clientY,s.tabKey)},600)},[s.tabKey,C,b]),z=o.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),L=["adhdev-dockview-tab",M,r&&"is-active",A&&"is-group-active",S&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:L,draggable:!0,onDragStart:k,onDragEnd:x,onDragOver:E,onDrop:R,onClick:I,onContextMenu:P,onTouchStart:K,onTouchEnd:z,onTouchMove:z,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:w.isGenerating?t.jsx("div",{className:"tab-spinner"}):w.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):S?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):w.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:st(s),children:st(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:S?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(s)}):w.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ts(s),t.jsx("span",{className:"connecting-dots"})]}):ts(s)})]}),i&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(e,s)=>e.conv===s.conv&&e.isActive===s.isActive&&e.isDraggedTab===s.isDraggedTab&&e.isTaskCompleteUnread===s.isTaskCompleteUnread&&e.shortcut===s.shortcut&&e.conversationKeys===s.conversationKeys&&e.isGroupActive===s.isGroupActive);function kh({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:f,onDragTabKeyChange:v,onReceiveTab:N,onHideTab:m,isGroupActive:g,allowTabShortcuts:j=!0}){const[b,C]=o.useState(null),A=o.useRef(null),w=o.useRef(null),M=o.useMemo(()=>e.map(P=>P.tabKey),[e]);tr("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:S,tabShortcuts:k,shortcutListening:x,setShortcutListening:E,saveShortcuts:R}=Hc({enabled:j,sortedTabKeys:e.map(P=>P.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!b)return;const P=K=>{const z=document.querySelector("[data-pane-context-menu]");z&&z.contains(K.target)||C(null)};return window.addEventListener("mousedown",P,!0),()=>window.removeEventListener("mousedown",P,!0)},[b]),o.useEffect(()=>{const P=w.current;if(!P)return;const K=z=>{Math.abs(z.deltaY)<=Math.abs(z.deltaX)||(z.preventDefault(),P.scrollLeft+=z.deltaY)};return P.addEventListener("wheel",K,{passive:!1}),()=>P.removeEventListener("wheel",K)},[]);const I=o.useCallback((P,K,z)=>{C({x:P,y:K,tabKey:z})},[]);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:w,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(jh,{conv:P,isActive:s===P.tabKey,isDraggedTab:a.current===P.tabKey,isTaskCompleteUnread:n.has(P.tabKey),shortcut:j?k[P.tabKey]:void 0,conversationKeys:M,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:f,onDragTabKeyChange:v,onReceiveTab:N,onOpenContextMenu:I,longPressTimer:A,isGroupActive:g},P.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),b&&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:b.x,top:b.y},children:[j&&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(),E(b.tabKey),C(null)},children:["⌨ ",k[b.tabKey]?`Change shortcut (${k[b.tabKey]})`:"Set shortcut"]}),k[b.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={...k};delete P[b.tabKey],R(P),C(null)},children:"✕ Remove shortcut"})]}),m&&t.jsxs(t.Fragment,{children:[j&&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(b.tabKey),C(null)},children:"🚫 Hide from Dashboard"})]})]}),j&&x&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>E(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick: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. ",S?"⌘+1":"Ctrl+1",", ",S?"⌥+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 Sh({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,userName:u,groupIndex:p,onFocus:d,isSplitMode:h,numGroups:f,onMoveTab:v,onReceiveTab:N,style:m,onActiveTabChange:g,initialActiveTabId:j,initialTabOrder:b,onTabOrderChange:C,onHideTab:A,isFocused:w,allowTabShortcuts:M=!0,onOpenNewSession:S,liveSessionInboxState:k}){const{sendCommand:x}=jt(),E=o.useRef(null),{activeTabId:R,activeConv:I,sortedConversations:P,draggingTabRef:K,selectTab:z,handleTabReorder:L,updatePreviewOrder:T,commitPreviewOrder:H,clearPreviewOrder:B,moveTabToEnd:D,setDraggingTabKey:G}=vh({conversations:e,initialActiveTabId:j,initialTabOrder:b,onActiveTabChange:g,onTabOrderChange:C}),J=rn({sendDaemonCommand:a,activeConv:I,setActionLogs:i,isStandalone:c}),{dragOver:xe,dropAction:re,resetDragState:ge,handleDragEnter:ye,handleDragOver:Q,handleDragLeave:fe,handleDrop:W}=gh({conversations:e,numGroups:f,onMoveTab:v,onReceiveTab:N,onOwnTabDrop:D,onClearPreviewOrder:B}),q=I&&!Ge(I)&&Ts(I)==="terminal",oe=o.useMemo(()=>I?s.find(ne=>ne.id===I.routeId):void 0,[s,I]),he=o.useMemo(()=>I?n.filter(ne=>ne.routeId===I.tabKey):[],[n,I]),le=o.useMemo(()=>new Set(P.filter(ne=>tu(ne,k,{isOpenConversation:ne.tabKey===R})).map(ne=>ne.tabKey)),[R,k,P]);tr("PaneGroup",{groupIndex:p,conversationCount:e.length,activeTabId:R,dragOver:xe});const ve=o.useCallback(ne=>{ne.streamSource==="agent-stream"&&ne.agentType&&x(ne.routeId,Dc(),{agentType:ne.agentType,...ne.sessionId&&{targetSessionId:ne.sessionId}}).catch(()=>{})},[x]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:d,style:{...m,outline:xe?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(kh,{conversations:P,activeTabId:R,groupIndex:p,numGroups:f,unreadTabKeys:le,draggingTabRef:K,onFocus:d,onSelectTab:z,onConversationActivated:ve,onPreviewReorder:T,onReorderTab:L,onCommitPreviewOrder:H,onClearPreviewOrder:B,onDragStateReset:ge,onDragTabKeyChange:G,onMoveTab:v,onReceiveTab:N,onHideTab:A,isGroupActive:w??!1,allowTabShortcuts:M}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ye,onDragOver:Q,onDragLeave:fe,onDrop:W,children:[xe&&t.jsx(wh,{dropAction:re,canSplit:!!(f<4&&v)}),I?t.jsx(Wa,{activeConv:I,clearToken:r[I.tabKey]||0,isCliTerminal:!!q,ideEntry:oe,terminalRef:E,handleModalButton:J.handleModalButton,handleRelaunch:J.handleRelaunch,handleSendChat:J.handleSendChat,isSendingChat:J.isSendingChat,sendFeedbackMessage:J.sendFeedbackMessage,handleFocusAgent:J.handleFocusAgent,isFocusingAgent:J.isFocusingAgent,actionLogs:he,userName:u,isInputActive:!h||!!w}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(Fa,{conversationsCount:e.length,isSplitMode:h,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:S})})]})]})}function Nh({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:p,isStandalone:d,hasRegisteredMachines:h,userName:f,focusedGroup:v,focusGroup:N,moveTabToGroup:m,splitTabRelative:g,closeGroup:j,handleResizeStart:b,groupActiveTabIds:C,setGroupActiveTab:A,groupTabOrders:w,setGroupTabOrder:M,toggleHiddenTab:S,onOpenNewSession:k,allowTabShortcuts:x=!0,liveSessionInboxState:E}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map((R,I)=>{const P=s&&n.length===r?`${n[I]}%`:void 0;return t.jsxs(St.Fragment,{children:[s&&I>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:K=>b(I-1,K),onDoubleClick:()=>j(I),title:"Drag to resize · Double-click to merge",children:t.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),t.jsx(Sh,{style:s?{flexBasis:P??`${100/r}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:R,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:p,isStandalone:d,hasRegisteredMachines:h,userName:f,groupIndex:I,isFocused:s&&v===I,onFocus:()=>N(I),isSplitMode:s,numGroups:r,onMoveTab:(K,z)=>{z==="left"&&I>0?m(K,I-1):z==="right"&&I<r-1?m(K,I+1):z==="split-left"&&r<4?g(K,I,"left"):z==="split-right"&&r<4&&g(K,I,"right")},onReceiveTab:K=>m(K,I),onActiveTabChange:K=>A(I,K),initialActiveTabId:C[I],initialTabOrder:w[I],onTabOrderChange:K=>M(I,K),onHideTab:S,onOpenNewSession:k,allowTabShortcuts:x,liveSessionInboxState:E})]},I)})})}function Fc({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?Ye.onScreenshot("ide-page",(d,h)=>{if(d!==e)return;const f=new FileReader;f.onload=()=>i(f.result),f.readAsDataURL(h)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var d;return e?((d=Ye.onStatus)==null?void 0:d.call(Ye,(h,f)=>{h===e&&f!=null&&f.screenshotUsage&&l(f.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const p=e?Ye.get(e):null;if(!(!p||r!=="connected"))return n!=="chat"&&s?p.startScreenshots(s):p.stopScreenshots(s),()=>{p.stopScreenshots(s)}},[n,r,s,e]);const u=o.useCallback(async(p,d)=>{const h=e?Ye.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(p,d,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const Uc="adhdev-dashboard-action-shortcuts",Ch=1200,Ih={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Mh(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function Ze(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 zc(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:Ze("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:Ze("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:Ze("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:Ze("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:Ze("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:Ze("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:Ze("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:Ze("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:Ze("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:Ze("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:Ze("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:Ze("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:Ze("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:Ze("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:Ze("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:Ze("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:Ze("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:Ze("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:Ze("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:Ze("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:Ze("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:Ze("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:Ze("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:Ze("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:Ze("toggleCliView",e)}]}function na(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Vr(e){const s=Object.fromEntries(zc(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Uc)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(Ih))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function Vc(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Ah({enabled:e=!0,onTrigger:s}){const r=Mh(),[n,a]=o.useState(()=>Vr(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),p=o.useRef({parts:[],timer:null}),d=o.useCallback(m=>{const g=[];return m.metaKey&&g.push(r?"⌘":"Meta"),m.ctrlKey&&g.push("Ctrl"),m.altKey&&g.push(r?"⌥":"Alt"),m.shiftKey&&m.key.length!==1&&g.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(g.push(Vc(m.key)),g.join("+"))},[r]),h=o.useCallback(m=>{a(m);try{localStorage.setItem(Uc,JSON.stringify(m))}catch{}},[]);o.useEffect(()=>{const m=Vr(r),g=Object.entries(n),j=Object.entries(m);g.length===j.length&&g.every(([b,C])=>m[b]===C)||h(m)},[n,r,h]);const f=o.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),v=o.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},Ch))},[]);o.useEffect(()=>{if(!i)return;const m=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){c(null),u([]);return}const j=d(g);if(!j)return;const C=!(g.metaKey||g.ctrlKey||g.altKey)&&/^[A-Z0-9]$/.test(j);if(l.length===0&&C){u([j]);return}const w=[...l,j].slice(0,2).join(" "),M={...n};for(const[S,k]of Object.entries(M))k===w&&delete M[S];M[i]=w,h(M),c(null),u([])};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[n,d,h,i,l]),o.useEffect(()=>{if(!e||i)return;const m=g=>{if(g.defaultPrevented)return;const j=d(g);if(!j)return;const b=g.metaKey||g.ctrlKey||g.altKey;if(na(g.target)&&!b)return;const C=p.current.parts,A=b?[j]:[...C.slice(-1),j].slice(-2),w=A.join(" "),M=A[A.length-1],S=Object.entries(n).filter(([,I])=>!!I),k=S.find(([,I])=>I===w);if(k){g.preventDefault(),f(),s(k[0]);return}if(S.some(([,I])=>I.startsWith(`${w} `))){g.preventDefault(),p.current.parts=A,v();return}const E=S.find(([,I])=>I===M);if(E){g.preventDefault(),f(),s(E[0]);return}if(S.some(([,I])=>I.startsWith(`${M} `))){g.preventDefault(),p.current.parts=[M],v();return}f()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[n,v,e,d,s,f,i]),o.useEffect(()=>()=>f(),[f]);const N=o.useMemo(()=>zc(r),[r]);return{isMac:r,actionDefinitions:N,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:h}}function Th({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 Gc(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function Uo({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!Gc(n):!0}function Lh({previousVisibleConversationCount:e,visibleConversationCount:s,ides:r}){return s>0||e<=0?!1:Gc(r)}const qc=o.createContext(null);function an(){const e=o.useContext(qc);if(!e)throw new Error("DashboardDockviewContext missing");return e}function _r(e){return st(e)||e.tabKey}function Rh(e){return`remote:${e}`}function Lt(e){return e.startsWith("remote:")}function zo(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function An(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 Nr(e,s){e.classList.remove(Hn.className,Fn.className),e.classList.add(s==="light"?Hn.className:Fn.className)}function Vo(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 Ph(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 _h(e,s,r){var c;const n=[s];let a;for(const l of n){let u;for(const p of l){const d=e.addPanel({id:p.tabKey,component:"conversation",title:_r(p),params:{kind:"conversation",tabKey:p.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=d.id)}a=u??a}return r??((c=s[0])==null?void 0:c.tabKey)??null}function Go(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Lt(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!==_r(n)&&a.api.setTitle(_r(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:_r(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 qo(e,s,r){var u,p;const n=r?Rh(r):null;for(const d of[...e.panels])Lt(d.id)&&(!n||d.id!==n)&&e.removePanel(d);if(!r||!n)return;const a=Dt(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=oc(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((p=e.panels.find(d=>!Lt(d.id)))==null?void 0:p.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function Dh({params:e,api:s}){var h;const r=an(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=rn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const f=[s.onDidActiveChange(v=>i(v.isActive)),s.onDidActiveGroupChange(v=>{if(!s.isActive&&!v.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const v of f)v.dispose()}},[s]);const u=o.useMemo(()=>c?r.ides.find(f=>f.id===c.routeId):void 0,[r.ides,c]),p=o.useMemo(()=>c?r.actionLogs.filter(f=>f.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(Fa,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const d=!Ge(c)&&Ts(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(Wa,{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:p,userName:r.userName,scrollToBottomRequestNonce:((h=r.scrollToBottomRequest)==null?void 0:h.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a})})}function Eh({params:e}){var u;const s=an(),r=o.useMemo(()=>Dt([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>s.ides.find(p=>p.id===e.routeId),[s.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=Fc({doId:a,targetSessionId:r?Fi(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(Ii,{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 $h(){const e=an();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(Fa,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Bh(e){var v,N;Ph(e);const s=an(),r=o.useCallback(m=>{"button"in m&&m.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const m=Dt([...s.conversationsByTabKey.values()],e.params.routeId),g=((v=e.api.group.activePanel)==null?void 0:v.id)===e.api.id,j=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${g?" is-active":""}${j?" 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=((N=e.api.group.activePanel)==null?void 0:N.id)===e.api.id,i=e.api.isGroupActive,c=Qr(n,s.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,u=c.isConnecting,p=c.isGenerating,d=c.isWaiting,h=c.unread,f=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:st(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:m=>{var g;m.preventDefault(),r(m),s.openTabContextMenu({x:m.clientX,y:m.clientY,tabKey:n.tabKey,sourceDocument:((g=m.target)==null?void 0:g.ownerDocument)??document})},children:[h&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:p?t.jsx("div",{className:"tab-spinner"}):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:st(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ts(n)}):t.jsx("span",{children:ts(n)})})]}),f&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:f,children:f})]})}function Kh({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:u,userName:p,toggleHiddenTab:d,actionShortcuts:h,registerActionHandlers:f,onActiveTabChange:v,onOpenNewSession:N,onRequestScrollToBottom:m,requestedActiveTabKey:g,requestedRemoteIdeId:j,onRequestedActiveTabConsumed:b,scrollToBottomRequest:C,liveSessionInboxState:A,layoutProfile:w}){var vt,We,It;const{theme:M}=Ra(),{sendCommand:S}=jt(),k=o.useRef(null),x=o.useRef(null),E=o.useRef(!1),R=o.useRef(!1),I=o.useRef(!1),P=o.useRef(null),K=o.useRef([]),[z,L]=o.useState(null),[T,H]=o.useState(!1),[B,D]=o.useState(!1),[G,J]=o.useState(0),xe=o.useRef(null),re=o.useRef(typeof window>"u"?{}:xp(w)),ge=o.useMemo(()=>new Map(e.map($=>[$.tabKey,$])),[e]),ye=o.useMemo(()=>{const $=k.current;return $?$.groups.some(O=>{try{const F=O.model.location.type;return F!=="floating"&&F!=="popout"?!1:O.panels.some(V=>ge.has(V.id))}catch{return!1}}):!1},[ge,G,e]),Q=o.useCallback(()=>{var $;($=k.current)==null||$.focus()},[]),fe=o.useCallback(($,O)=>{m==null||m($,O)},[m]),W=o.useCallback($=>{const O=document,F=$.document;for(const Y of O.querySelectorAll('link[rel="stylesheet"]')){const be=F.createElement("link");be.rel="stylesheet",be.href=Y.href,Y.crossOrigin&&(be.crossOrigin=Y.crossOrigin),F.head.appendChild(be)}for(const Y of O.querySelectorAll("style")){const be=F.createElement("style");be.textContent=Y.textContent,F.head.appendChild(be)}const V=[];for(const Y of O.styleSheets)try{for(const be of Y.cssRules)be instanceof CSSStyleRule&&(be.selectorText===":root"||be.selectorText==="html")&&V.push(be.cssText)}catch{}if(V.length>0){const Y=F.createElement("style");Y.textContent=V.join(`
43
- `),F.head.appendChild(Y)}const ie=O.documentElement.getAttribute("data-theme");ie&&F.documentElement.setAttribute("data-theme",ie),F.documentElement.style.colorScheme=ie==="light"?"light":"dark",F.body.className=O.body.className;const Se=O.documentElement.getAttribute("style");Se&&F.documentElement.setAttribute("style",Se);const Ie=F.getElementById("dv-popout-window");Ie instanceof HTMLElement&&(Ie.classList.add("adhdev-dockview"),Nr(Ie,M))},[M]),q=o.useCallback(()=>{var O;const $=k.current;if($)for(const F of $.groups)try{const V=(O=F.element)==null?void 0:O.ownerDocument;if(!V||V===document)continue;const ie=V.getElementById("dv-popout-window");ie instanceof HTMLElement&&(ie.classList.add("adhdev-dockview"),Nr(ie,M));const Se=document.documentElement.getAttribute("data-theme");Se&&V.documentElement.setAttribute("data-theme",Se),V.documentElement.style.colorScheme=Se==="light"?"light":"dark",V.body.className=document.body.className;const Ie=document.documentElement.getAttribute("style");Ie?V.documentElement.setAttribute("style",Ie):V.documentElement.removeAttribute("style")}catch{}},[M]),oe=o.useCallback(()=>{var O;const $=k.current;if($)for(const F of $.groups)try{const V=(O=F.element)==null?void 0:O.ownerDocument;if(!V||V===document)continue;const ie=V.getElementById("dv-popout-window");if(!(ie instanceof HTMLElement))continue;ie.classList.add("adhdev-dockview"),Nr(ie,M),ie.classList.toggle("is-showing-dockview-overlay",B),ie.classList.toggle("is-dragging-dockview",T)}catch{}},[T,B,M]),he=o.useCallback($=>{const O=k.current;if(!O)return;const F=O.getPanel($);F&&O.addPopoutGroup(F,{popoutUrl:"/popout.html",onDidOpen:({window:V})=>{W(V),U();const ie=ge.get($);V.document.title=ie?`${st(ie)} — ADHDev`:"ADHDev — Popout"}})},[ge,W]),le=o.useCallback($=>{const O=k.current,F=O==null?void 0:O.getPanel($);if(!O||!F)return;const V=O.groups.filter(ie=>{var Se;try{return((Se=ie.element)==null?void 0:Se.ownerDocument)===document}catch{return!0}});V.length>0?F.api.moveTo({group:V[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),ve=o.useCallback($=>{var V;const O=k.current;if(!O)return!1;const F=O.getPanel($);if(!F)return!1;try{return((V=F.group.element)==null?void 0:V.ownerDocument)!==document}catch{return!1}},[]),ne=o.useCallback($=>{ve($)&&le($),d($)},[ve,le,d]),pe=o.useCallback($=>{const O=k.current,F=O==null?void 0:O.getPanel($);!O||!F||O.addFloatingGroup(F,{width:600,height:500})},[]),ce=o.useCallback($=>{var F;const O=(F=k.current)==null?void 0:F.getPanel($);if(!O)return!1;try{return O.group.model.location.type==="floating"}catch{return!1}},[]),de=o.useCallback(()=>{var O,F;const $=(F=(O=k.current)==null?void 0:O.activePanel)==null?void 0:F.id;return!$||Lt($)?null:ge.has($)?$:null},[ge]),ae=o.useCallback($=>{const O=k.current,F=O==null?void 0:O.getPanel($);if(!O||!F)return;const V=O.groups.filter(ie=>{try{return ie.model.location.type==="grid"}catch{return!0}});V.length>0?F.api.moveTo({group:V[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),je=o.useCallback(()=>{var Se;const $=k.current;if(!$)return;const F=$.groups.filter(Ie=>{var Y;try{return((Y=Ie.element)==null?void 0:Y.ownerDocument)===document&&Ie.model.location.type==="grid"}catch{return!1}})[0]||null,V=[...$.panels];for(const Ie of V){const Y=(Se=Ie.group.element)==null?void 0:Se.ownerDocument,be=Ie.group.model.location.type;Y===document&&be==="grid"||(F&&F.id!==Ie.group.id?Ie.api.moveTo({group:F,position:"center"}):Ie.api.moveTo({position:"center"}))}const ie=$.activePanel;ie&&(ie.group.model.openPanel(ie),ie.api.setActive()),An(document)},[]),U=o.useCallback(()=>{var O,F;const $=k.current;if($)for(const V of $.groups){const ie=(O=V.element)==null?void 0:O.ownerDocument;if(!ie||ie===document)continue;const Se=ie.getElementById("dv-popout-window");if(!(Se instanceof HTMLElement))continue;let Ie=null,Y=ie.title||"ADHDev",be="Popout workspace";const Ee=V.activePanel;if(Ee)if(Ie=Ee.id,Lt(Ee.id)){const Pe=((F=Ee.params)==null?void 0:F.routeId)||Ee.id.slice(7),_=Dt([...ge.values()],Pe);Y=oc(_),be=_!=null&&_.machineName?`Remote view · ${_.machineName}`:"Remote view"}else{const Pe=ge.get(Ee.id);Y=Pe?st(Pe):Ee.title||Ee.id,be=Pe?ts(Pe):"Dockview panel"}ie.title=`${Y} — ADHDev`;const Oe=Array.from(ie.querySelectorAll("#adhdev-popout-header"));for(const Pe of Oe)Pe.remove();const Je=ie.createElement("div");Je.id="adhdev-popout-header",ie.body.appendChild(Je),Je.setAttribute("style",["position:absolute","top:0","left:0","right:0","height:52px","display:flex","align-items:center","justify-content:space-between","gap:12px","padding:0 14px","box-sizing:border-box","background:var(--surface-secondary)","border-bottom:1px solid var(--border-subtle)","z-index:5","backdrop-filter:blur(14px)"].join(";")),Je.innerHTML=`
44
- <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
45
- <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
46
- <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${zo(Y)}</div>
47
- <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${zo(be)}</div>
48
- </div>
49
- <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
50
- <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>
51
- <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>
52
- </div>
53
- `,Se.style.top="52px",Se.style.height="calc(100% - 52px)";const qe=Je.querySelector("[data-adhdev-popout-focus]");qe&&(qe.onclick=()=>{window.focus()});const ze=Je.querySelector("[data-adhdev-popout-dock]");ze&&(ze.disabled=!Ie,ze.style.opacity=Ie?"1":"0.5",ze.style.cursor=Ie?"pointer":"default",ze.onclick=()=>{var Pe;Ie&&le(Ie),(Pe=ie.defaultView)==null||Pe.focus()})}},[ge,le]),se=o.useCallback($=>{var V;const O=k.current,F=O==null?void 0:O.getPanel($);if(!(!O||!F)){F.group.model.openPanel(F),F.api.setActive(),fe($,"dockview-shortcut");try{const ie=F.group.model.location;ie.type==="popout"?ie.getWindow().focus():An((V=F.group.element)==null?void 0:V.ownerDocument)}catch{}}},[fe]),y=o.useCallback($=>{const O=k.current,F=O==null?void 0:O.activePanel,V=(O==null?void 0:O.activeGroup)||(F==null?void 0:F.group);if(!O||!F||!V)return;const ie=V.panels||[];if(ie.length<=1)return;const Se=ie.findIndex(be=>be.id===F.id);if(Se<0)return;const Ie=(Se+$+ie.length)%ie.length,Y=ie[Ie];Y&&(Y.group.model.openPanel(Y),Y.api.setActive(),Lt(Y.id)||fe(Y.id,"dockview-shortcut"))},[fe]),X=o.useCallback($=>{var qe;const O=k.current,F=(O==null?void 0:O.activeGroup)||((qe=O==null?void 0:O.activePanel)==null?void 0:qe.group);if(!O||!F)return;const V=O.groups||[],ie=V.find(ze=>ze.id===F.id);if(!ie)return;const Se=ie.element.getBoundingClientRect(),Ie=Se.left+Se.width/2,Y=Se.top+Se.height/2,be=(ze,Pe,_,ee)=>Math.max(0,Math.min(Pe,ee)-Math.max(ze,_)),Ee=ze=>{const Pe=ze.element.getBoundingClientRect(),_=Pe.left+Pe.width/2,ee=Pe.top+Pe.height/2;let me=0,Le=0,Ce=0,Me=!1;if($==="left"?(Me=_<Ie,me=Math.max(0,Se.left-Pe.right),Le=Math.abs(ee-Y),Ce=be(Se.top,Se.bottom,Pe.top,Pe.bottom)):$==="right"?(Me=_>Ie,me=Math.max(0,Pe.left-Se.right),Le=Math.abs(ee-Y),Ce=be(Se.top,Se.bottom,Pe.top,Pe.bottom)):$==="above"?(Me=ee<Y,me=Math.max(0,Se.top-Pe.bottom),Le=Math.abs(_-Ie),Ce=be(Se.left,Se.right,Pe.left,Pe.right)):(Me=ee>Y,me=Math.max(0,Pe.top-Se.bottom),Le=Math.abs(_-Ie),Ce=be(Se.left,Se.right,Pe.left,Pe.right)),!Me)return Number.POSITIVE_INFINITY;const Ae=Ce>0?0:120;return me*3+Le+Ae};let Oe=null,Je=Number.POSITIVE_INFINITY;for(const ze of V){if(ze.id===ie.id)continue;const Pe=Ee(ze);Number.isFinite(Pe)&&(Pe>=Je||(Je=Pe,Oe=ze))}return Oe||void 0},[]),te=o.useCallback($=>{var V;const O=X($);if(!O)return;const F=O.activePanel||O.panels[0];F&&(O.model.openPanel(F),F.api.setActive(),Lt(F.id)||fe(F.id,"dockview-focus"),An((V=O.element)==null?void 0:V.ownerDocument))},[X,fe]),ue=o.useCallback(($,O)=>{const F=k.current,V=F==null?void 0:F.activePanel,ie=(F==null?void 0:F.activeGroup)||(V==null?void 0:V.group);if(!F||!V||!ie)return;let Se=X($);!Se&&(O!=null&&O.createGroupIfMissing)&&(Se=F.addGroup({referenceGroup:ie,direction:$})),Se&&(V.api.moveTo({group:Se,position:"center"}),V.group.model.openPanel(V),V.api.setActive(),Lt(V.id)||fe(V.id,O!=null&&O.createGroupIfMissing?"dockview-split":"dockview-move"))},[X,fe]),{isMac:we,tabShortcuts:Ne,shortcutListening:Be,setShortcutListening:Ke,saveShortcuts:Fe}=Hc({sortedTabKeys:e.map($=>$.tabKey),onFocus:Q,onSelectTab:se}),Ue=o.useCallback(()=>{var F;const $=k.current;if(!$)return;const O=$.activePanel;if(O){if(Lt(O.id)){const V=((F=O.params)==null?void 0:F.routeId)||O.id.slice(7),ie=Dt(e,V);ie!=null&&ie.tabKey&&Ke(ie.tabKey);return}ge.has(O.id)&&Ke(O.id)}},[ge,se,Ke,e]),ot=o.useCallback($=>{const O=[];return $.metaKey&&O.push(we?"⌘":"Meta"),$.ctrlKey&&O.push("Ctrl"),$.altKey&&O.push(we?"⌥":"Alt"),$.shiftKey&&$.key.length!==1&&O.push(we?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes($.key)?null:(O.push(Vc($.key)),O.join("+"))},[we]),rt=o.useCallback($=>{var O,F;switch($){case"splitActiveTabRight":ue("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":ue("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const V=de();V&&pe(V);return}case"popoutActiveTab":{const V=de();V&&he(V);return}case"dockActiveTab":{const V=de();if(!V)return;ve(V)?le(V):ce(V)&&ae(V);return}case"focusLeftPane":te("left");return;case"focusRightPane":te("right");return;case"focusUpPane":te("above");return;case"focusDownPane":te("below");return;case"moveActiveTabToLeftPane":ue("left");return;case"moveActiveTabToRightPane":ue("right");return;case"moveActiveTabToUpPane":ue("above");return;case"moveActiveTabToDownPane":ue("below");return;case"selectPreviousGroupTab":y(-1);return;case"selectNextGroupTab":y(1);return;case"setActiveTabShortcut":Ue();return;case"hideCurrentTab":{const V=(F=(O=k.current)==null?void 0:O.activePanel)==null?void 0:F.id;V&&!Lt(V)&&ne(V);return}default:return}},[y,ae,te,pe,de,ne,ce,ve,le,ue,he,Ue]);o.useEffect(()=>{if(!z)return;const $=z.sourceDocument,O=$.defaultView??window,F=V=>{const ie=$.querySelector("[data-dockview-tab-context-menu]");ie&&ie.contains(V.target)||L(null)};return O.addEventListener("mousedown",F,!0),O!==window&&window.addEventListener("mousedown",()=>L(null),!0),()=>{O.removeEventListener("mousedown",F,!0),O!==window&&window.removeEventListener("mousedown",()=>L(null),!0)}},[z]);const dt=o.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:ge,hasDetachedConversationPanels:ye,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:N,liveSessionInboxState:A,sendDaemonCommand:a,setActionLogs:i,toggleHiddenTab:ne,userName:p,scrollToBottomRequest:C,tabShortcuts:Ne,openTabContextMenu:({x:$,y:O,tabKey:F,sourceDocument:V})=>L({x:$,y:O,tabKey:F,sourceDocument:V??document}),popoutTab:he,moveTabBackToMain:le,isTabInPopout:ve,floatTab:pe,isTabFloating:ce}),[n,s,ge,ye,r,c,l,N,A,a,i,ne,p,C,Ne,he,le,ve,pe,ce]),yt=z?Th({isTabInPopout:ve(z.tabKey),isTabFloating:ce(z.tabKey),tabShortcut:Ne[z.tabKey],actionShortcuts:h}):[],ut=o.useCallback($=>{var V;const O=k.current;if((((V=O==null?void 0:O.activePanel)==null?void 0:V.id)??null)===$.id){$.group.model.openPanel($);return}$.group.model.openPanel($),$.api.setActive()},[]),Xe=o.useCallback(($,O="requested-tab")=>{if(!$)return!1;const F=k.current;if(!F)return!1;const V=F.getPanel($);return V?(ut(V),fe($,O),b==null||b(),!0):!1},[ut,b,fe]),nt=o.useCallback(()=>{if(I.current)return!1;const $=Xe(P.current,"stored-layout-restore");return $&&(I.current=!0),$},[Xe]),ke=o.useCallback(()=>{var O;const $=k.current;$&&hp(w,{activeTabId:((O=$.activePanel)==null?void 0:O.id)??null,layout:$.toJSON()})},[w]),De=o.useCallback(()=>{bp(w,re.current)},[w]),$e=o.useCallback($=>{var V,ie,Se,Ie;const O=k.current;if(!O)return{kind:"grid"};const F=O.toJSON();for(const Y of F.floatingGroups||[])if((ie=(V=Y.data)==null?void 0:V.views)!=null&&ie.includes($)&&Y.position)return{kind:"floating",position:Y.position};for(const Y of F.popoutGroups||[])if((Ie=(Se=Y.data)==null?void 0:Se.views)!=null&&Ie.includes($))return{kind:"popout",position:Y.position,popoutUrl:Y.url};return{kind:"grid"}},[]),tt=o.useCallback($=>{const O=k.current;if(!O)return;const F=O.getPanel($),V=re.current[$];if(!F||!V||V.kind==="grid")return;if(F.group.model.location.type===V.kind){delete re.current[$],De();return}if(V.kind==="floating"){O.addFloatingGroup(F,{x:V.position.left??24,y:V.position.top??24,width:V.position.width,height:V.position.height}),delete re.current[$],De();return}delete re.current[$],De()},[De]);o.useEffect(()=>(f==null||f({setShortcutForActiveTab:Ue,restoreHiddenTabToSavedLocation:tt,activateConversationTab:se,resetAllPanelsToMain:je,activatePreviousTabInGroup:()=>y(-1),activateNextTabInGroup:()=>y(1),floatActiveTab:()=>{const $=de();$&&pe($)},popoutActiveTab:()=>{const $=de();$&&he($)},dockActiveTab:()=>{const $=de();$&&(ve($)?le($):ce($)&&ae($))},splitActiveTabRight:()=>ue("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>ue("below",{createGroupIfMissing:!0}),focusLeftPane:()=>te("left"),focusRightPane:()=>te("right"),focusUpPane:()=>te("above"),focusDownPane:()=>te("below"),moveActiveTabToLeftPane:()=>ue("left"),moveActiveTabToRightPane:()=>ue("right"),moveActiveTabToUpPane:()=>ue("above"),moveActiveTabToDownPane:()=>ue("below")}),()=>f==null?void 0:f(null)),[y,ae,pe,te,de,ce,ve,ue,le,he,f,je,tt,se,Ue]);const lt=o.useCallback(()=>{const $=x.current;if(!$)return;const O=$.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const F of O)F.setAttribute("data-adhdev-force-hidden","true")},[]),mt=o.useCallback(()=>{const $=x.current;if(!$)return;const O=$.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const F of O)F.removeAttribute("data-adhdev-force-hidden")},[]),Z=o.useCallback(()=>{const $=x.current;if(!$)return;const O=$.querySelectorAll(".dv-drop-target-container");for(const ie of O)ie.remove();const F=$.querySelectorAll(".dv-drop-target-dropzone");for(const ie of F)ie.remove();const V=$.querySelectorAll(".dv-drop-target");for(const ie of V)ie.classList.remove("dv-drop-target")},[]),Te=o.useCallback(()=>{H(!1),D(!1),mt(),lt(),Z(),!(typeof window>"u")&&(xe.current!=null&&window.clearTimeout(xe.current),window.requestAnimationFrame(()=>{lt(),Z()}),xe.current=window.setTimeout(()=>{lt(),Z(),xe.current=null},80))},[mt,lt,Z]),Re=o.useCallback($=>{var F;k.current=$.api;const O=pp(w);if(P.current=(O==null?void 0:O.activeTabId)??null,O!=null&&O.layout&&$.api.fromJSON(O.layout,{reuseExistingPanels:!1}),R.current=Uo({hasStoredLayout:!!(O!=null&&O.layout),initialDataLoaded:u,visibleConversationCount:e.length,ides:r}),R.current||(Go($.api,e),qo($.api,e,j)),$.api.totalPanels===0&&e.length>0){const V=_h($.api,e,g);if(V){const ie=$.api.getPanel(V);ie&&ut(ie)}}else!R.current&&!Xe(g)&&nt();E.current=!0,$.api.onDidActivePanelChange(V=>{var Se;if(P.current=(V==null?void 0:V.id)??null,I.current=!0,U(),V&&Lt(V.id)){const Ie=((Se=V.params)==null?void 0:Se.routeId)||V.id.slice(7),Y=Dt(e,Ie);v((Y==null?void 0:Y.tabKey)??null),ke();return}if(v((V==null?void 0:V.id)??null),ke(),!V)return;const ie=ge.get(V.id);(ie==null?void 0:ie.streamSource)==="agent-stream"&&ie.agentType&&S(ie.routeId,Dc(),{agentType:ie.agentType,...ie.sessionId&&{targetSessionId:ie.sessionId}}).catch(()=>{})}),$.api.onDidLayoutChange(()=>{ke(),U(),J(V=>V+1)}),$.api.onWillDragPanel(()=>{H(!0),D(!1),lt()}),$.api.onWillDragGroup(()=>{H(!0),D(!1),lt()}),$.api.onWillShowOverlay(()=>{mt(),D(!0)}),$.api.onDidMovePanel(Te),$.api.onDidDrop(Te),$.api.onDidAddGroup(V=>{requestAnimationFrame(()=>{var ie,Se;try{const Ie=(ie=V.element)==null?void 0:ie.ownerDocument;if(!Ie||Ie===document)return;(Se=Ie.getElementById("dv-popout-window"))==null||Se.classList.add("adhdev-dockview");const Y=document.documentElement.getAttribute("data-theme");Y&&Ie.documentElement.setAttribute("data-theme",Y),Ie.body.className=document.body.className;const be=document.documentElement.getAttribute("style");be&&Ie.documentElement.setAttribute("style",be)}catch{}U(),J(Ie=>Ie+1)})}),v(((F=$.api.activePanel)==null?void 0:F.id)??null)},[ut,Xe,Te,mt,ge,r,u,w,lt,v,ke,g,j,S,U,e]);o.useLayoutEffect(()=>{const $=k.current;if(!$||!E.current||R.current&&Uo({hasStoredLayout:!0,initialDataLoaded:u,visibleConversationCount:e.length,ides:r}))return;R.current&&(R.current=!1);const O=K.current,F=new Set(O),V=e.map(Oe=>Oe.tabKey),ie=new Set(V),Se=Lh({previousVisibleConversationCount:O.length,visibleConversationCount:e.length,ides:r});let Ie=!1;for(const Oe of O)ie.has(Oe)||Se||(re.current[Oe]=$e(Oe),Ie=!0);Ie&&De(),Se||(Go($,e),qo($,e,j));const Y=V.filter(Oe=>!F.has(Oe));let be=!1;for(const Oe of Y){const Je=$.getPanel(Oe),qe=re.current[Oe];if(!Je||!qe||qe.kind==="grid")continue;if(Je.group.model.location.type===qe.kind){delete re.current[Oe],be=!0;continue}if(qe.kind==="floating"){$.addFloatingGroup(Je,{x:qe.position.left??24,y:qe.position.top??24,width:qe.position.width,height:qe.position.height}),delete re.current[Oe],be=!0;continue}}if(be&&De(),K.current=V,g&&Xe(g))return;!$.activePanel&&$.panels[0]&&ut($.panels[0]),!!($.activePanel&&$.getPanel($.activePanel.id))||nt()},[ut,Xe,nt,r,u,De,$e,g,j,e]),o.useEffect(()=>{E.current&&Xe(g)},[Xe,g]),o.useEffect(()=>{if(!T||typeof window>"u")return;const $=()=>Te();return window.addEventListener("pointerup",$),window.addEventListener("mouseup",$),window.addEventListener("dragend",$),()=>{window.removeEventListener("pointerup",$),window.removeEventListener("mouseup",$),window.removeEventListener("dragend",$)}},[Te,T]),o.useEffect(()=>()=>{typeof window>"u"||xe.current!=null&&window.clearTimeout(xe.current)},[]),o.useEffect(()=>{const $=F=>{const V=F.target;if(!V)return;const ie=V.querySelector("[data-tab-key]")||V.closest("[data-tab-key]");if(ie){const Se=ie.getAttribute("data-tab-key");if(Se&&F.dataTransfer){const Ie=V.closest(".dv-tab")||ie.closest(".dv-tab")||ie;F.dataTransfer.effectAllowed="move",F.dataTransfer.setData("text/tab-key",Se),Ie instanceof HTMLElement&&F.dataTransfer.setDragImage(Ie,Math.max(12,Math.round(Ie.clientWidth/2)),Math.max(10,Math.round(Ie.clientHeight/2)))}}};window.addEventListener("dragstart",$);const O=Vo(k.current);for(const F of O)F.addEventListener("dragstart",$);return()=>{window.removeEventListener("dragstart",$);for(const F of O)F.removeEventListener("dragstart",$)}},[G]),o.useEffect(()=>{var O;const $=(O=x.current)==null?void 0:O.querySelector(".adhdev-dockview");$ instanceof HTMLElement&&Nr($,M),q(),U(),oe()},[U,oe,q,M]),o.useEffect(()=>{U(),oe()},[U,oe]),o.useEffect(()=>{const $=O=>{if(O.defaultPrevented||Be)return;const F=ot(O);if(!F)return;const V=O.metaKey||O.ctrlKey||O.altKey;na(O.target)&&!V||Vr(we).setActiveTabShortcut!==F||(O.preventDefault(),O.stopPropagation(),Ue())};return window.addEventListener("keydown",$,!0),()=>window.removeEventListener("keydown",$,!0)},[ot,we,Be,Ue]),o.useEffect(()=>{const $=x.current;if(!$)return;const O=F=>{var Y,be;if(!F.isTrusted)return;const V=(be=(Y=F.target)==null?void 0:Y.closest)==null?void 0:be.call(Y,".dv-scrollable");if(!V)return;F.preventDefault(),F.stopPropagation();const ie=Math.abs(F.deltaX),Se=Math.abs(F.deltaY),Ie=ie>Se?F.deltaX:F.deltaY;V.dispatchEvent(new WheelEvent("wheel",{deltaY:Ie,deltaMode:F.deltaMode,bubbles:!1,cancelable:!0}))};return $.addEventListener("wheel",O,{passive:!1,capture:!0}),()=>$.removeEventListener("wheel",O,{capture:!0})},[]),o.useEffect(()=>{const $=Vo(k.current);if($.length===0)return;const O=$.map(F=>{let V=[],ie=null;const Se=()=>{ie!=null&&F.clearTimeout(ie),ie=null,V=[]},Ie=()=>{ie!=null&&F.clearTimeout(ie),ie=F.setTimeout(()=>{ie=null,V=[]},1200)},Y=Ee=>{if(!Ee.ctrlKey&&!Ee.metaKey&&!Ee.altKey)return;const Oe=ot(Ee);if(!Oe)return;const Je=Wc();for(const[qe,ze]of Object.entries(Je))if(e.some(Pe=>Pe.tabKey===qe)&&ze===Oe){Ee.preventDefault(),se(qe);return}},be=Ee=>{if(Ee.defaultPrevented||Be)return;const Oe=ot(Ee);if(!Oe)return;const Je=Ee.metaKey||Ee.ctrlKey||Ee.altKey;if(na(Ee.target)&&!Je)return;const qe=Vr(we),ze=Object.entries(qe).filter(([Ae,ft])=>!!ft&&(Ae==="splitActiveTabRight"||Ae==="splitActiveTabDown"||Ae==="floatActiveTab"||Ae==="popoutActiveTab"||Ae==="dockActiveTab"||Ae==="focusLeftPane"||Ae==="focusRightPane"||Ae==="focusUpPane"||Ae==="focusDownPane"||Ae==="moveActiveTabToLeftPane"||Ae==="moveActiveTabToRightPane"||Ae==="moveActiveTabToUpPane"||Ae==="moveActiveTabToDownPane"||Ae==="selectPreviousGroupTab"||Ae==="selectNextGroupTab"||Ae==="setActiveTabShortcut"||Ae==="hideCurrentTab")),Pe=Je?[Oe]:[...V.slice(-1),Oe].slice(-2),_=Pe.join(" "),ee=Pe[Pe.length-1],me=ze.find(([,Ae])=>Ae===_);if(me){Ee.preventDefault(),Se(),rt(me[0]);return}if(ze.some(([,Ae])=>Ae.startsWith(`${_} `))){Ee.preventDefault(),V=Pe,Ie();return}const Ce=ze.find(([,Ae])=>Ae===ee);if(Ce){Ee.preventDefault(),Se(),rt(Ce[0]);return}if(ze.some(([,Ae])=>Ae.startsWith(`${ee} `))){Ee.preventDefault(),V=[ee],Ie();return}Se()};return F.addEventListener("keydown",Y),F.addEventListener("keydown",be),()=>{Se(),F.removeEventListener("keydown",Y),F.removeEventListener("keydown",be)}});return()=>{for(const F of O)F()}},[ot,we,G,se,Be,rt,e]);const at=M==="light"?Hn:Fn,ht=((It=(We=(vt=k.current)==null?void 0:vt.activePanel)==null?void 0:We.group.element)==null?void 0:It.ownerDocument)??document;return t.jsxs(qc.Provider,{value:dt,children:[t.jsx("div",{ref:x,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(Ol,{className:`h-full min-h-0 min-w-0 adhdev-dockview${T?" is-dragging-dockview":""}${B?" is-showing-dockview-overlay":""}`,components:{conversation:Dh,remote:Eh},defaultTabComponent:Bh,watermarkComponent:$h,onReady:Re,singleTabMode:"default",tabAnimation:"smooth",theme:at,popoutUrl:"/popout.html"})}),z&&Vs.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:z.x,top:z.y},children:yt.map($=>{if($.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},$.id);let O=t.jsx(Dd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{};switch($.id){case"dockInWindow":case"dockBackToGrid":O=t.jsx($d,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ae(z.tabKey),L(null)};break;case"moveBackToMain":O=t.jsx(_d,{size:13,className:"shrink-0 opacity-70"}),F=()=>{le(z.tabKey),L(null)};break;case"floatAsPanel":O=t.jsx(Ed,{size:13,className:"shrink-0 opacity-70"}),F=()=>{pe(z.tabKey),L(null)};break;case"openInNewWindow":O=t.jsx(Pd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{he(z.tabKey),L(null)};break;case"setShortcut":F=V=>{V.stopPropagation(),Ke(z.tabKey),L(null)};break;case"removeShortcut":O=t.jsx(wt,{size:13,className:"shrink-0 opacity-70"}),F=()=>{const V={...Ne};delete V[z.tabKey],Fe(V),L(null)};break;case"hideTab":O=t.jsx(wi,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ne(z.tabKey),L(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 ${$.tone==="muted"?"text-text-muted":""}`,onClick:F,children:[O,t.jsx("span",{className:"flex-1 min-w-0",children:$.label}),$.shortcut?t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:$.shortcut}):null]},$.id)})}),z.sourceDocument.body),Be&&Vs.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:()=>Ke(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:$=>$.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. ",we?"⌘+1":"Ctrl+1",", ",we?"⌥+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"})]})}),ht.body)]})}const Yc="adhdev-recent-launch-args-v1",Oh=8;function Wh(e){return String(e||"").trim().replace(/\s+/g," ")}function Xc(e,s){return`${e.trim()}::${s.trim()}`}function Jc(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Yc)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function Hh(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Yc,JSON.stringify(e))}catch{}}function Qc(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=Jc().byKey[Xc(r,n)])==null?void 0:i.items)||[]}function Zc(e,s,r){var d;const n=String(e||"").trim(),a=String(s||"").trim(),i=Wh(r);if(!n||!a||!i)return;const c=Jc(),l=Xc(n,a),u=((d=c.byKey[l])==null?void 0:d.items)||[],p=[i,...u.filter(h=>h!==i)].slice(0,Oh);c.byKey[l]={items:p},Hh(c)}function el(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Dr({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 tl({busy:e,savedSessionsLoading:s,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?Bc(n):null;return t.jsxs(Dr,{title:"Saved history",description:Ia(),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:Jm()})]}),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 Tn(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 Cr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Fh({machines:e,ides:s,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:i,onLaunchProvider:c,onListSavedSessions:l}){var lt,mt;const u=nr(),p=o.useMemo(()=>[...e].sort(xa),[e]),[d,h]=o.useState(((lt=p[0])==null?void 0:lt.id)||""),f=o.useMemo(()=>p.find(Z=>Z.id===d)||p[0],[d,p]),v=o.useMemo(()=>((f==null?void 0:f.workspaces)||[]).map(Z=>({id:Z.id,path:Z.path,label:Z.label})),[f]),N=(f==null?void 0:f.defaultWorkspaceId)||null,[m,g]=o.useState(""),[j,b]=o.useState(""),[C,A]=o.useState(Tn(p[0])),[w,M]=o.useState(""),[S,k]=o.useState(""),[x,E]=o.useState([]),[R,I]=o.useState(""),[P,K]=o.useState([]),[z,L]=o.useState(!1),[T,H]=o.useState(!1),[B,D]=o.useState(""),[G,J]=o.useState(!1),[xe,re]=o.useState(()=>pt()),[ge,ye]=o.useState(null),[Q,fe]=o.useState(!1),[W,q]=o.useState(""),[oe,he]=o.useState(!1),[le,ve]=o.useState(""),[ne,pe]=o.useState([]),[ce,de]=o.useState(!1),[ae,je]=o.useState(""),[U,se]=o.useState(!1),y=o.useRef(null),X=o.useRef(0);o.useEffect(()=>{var Z;!d&&((Z=p[0])!=null&&Z.id)&&h(p[0].id)},[d,p]),o.useEffect(()=>{!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||u(f.id,{minFreshMs:3e4}).catch(()=>{})},[u,f]);const te=o.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(Z=>Z.category==="cli"&&Z.installed!==!1),[f]),ue=o.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(Z=>Z.category==="acp"&&Z.installed!==!1),[f]),we=o.useMemo(()=>((f==null?void 0:f.detectedIdes)||[]).map(Z=>({id:Z.type,label:Z.name||Z.type,meta:Z.running?"Detected locally":"Available to open"})),[f]),Ne=o.useMemo(()=>C==="cli"?te.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"CLI provider"})):C==="acp"?ue.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"ACP provider"})):we,[ue,C,te,we]);o.useEffect(()=>{var Te;if(!f)return;if(y.current!==f.id){y.current=f.id,g(N||((Te=v[0])==null?void 0:Te.id)||"__home__"),b(""),A(Tn(f)),M(""),k(""),I(""),K([]),H(!1),D(""),re(pt()),q("");return}g(Re=>{var at;return Re==="__custom__"||Re==="__home__"||v.some(ht=>ht.id===Re)?Re:N||((at=v[0])==null?void 0:at.id)||"__home__"}),A(Re=>Re==="ide"&&we.length>0||Re==="cli"&&te.length>0||Re==="acp"&&ue.length>0?Re:Tn(f))},[ue.length,te.length,N,we.length,f,v]),o.useEffect(()=>{var Z;C&&(Ne.some(Te=>Te.id===w)||M(((Z=Ne[0])==null?void 0:Z.id)||""))},[C,Ne,w]);const Be=o.useCallback(async(Z,Te)=>{const Re=X.current+1;return X.current=Re,L(!0),D(""),l(Z,Te).then(at=>{X.current===Re&&K(at)}).catch(at=>{X.current===Re&&(K([]),D(at instanceof Error?at.message:"Could not load saved sessions"))}).finally(()=>{X.current===Re&&(L(!1),H(!0))})},[l]),Ke=o.useCallback((Z,Te)=>{E(Qc(Z,Te))},[]);o.useEffect(()=>{X.current+=1,I(""),re(pt()),!f||!w||C==="ide"?E([]):Ke(f.id,w),H(!1),K([]),D(""),L(!1)},[C,Ke,Be,f,w]),o.useEffect(()=>{if(!R)return;const Z=P.find(Te=>Te.providerSessionId===R);Z!=null&&Z.canResume||I("")},[P,R]);const Fe=m==="__custom__"?j.trim():m==="__home__"?"":((mt=v.find(Z=>Z.id===m))==null?void 0:mt.path)||"",Ue=o.useMemo(()=>f?s.filter(Z=>Z.id!==f.id&&Z.daemonId===f.id).map(Z=>Z.workspace):[],[s,f]),ot=o.useMemo(()=>((f==null?void 0:f.recentLaunches)||[]).map(Z=>Z.workspace),[f]),rt=o.useCallback(Z=>{const Te=String(Z.workspace||"").trim();if(!Te)return;const Re=v.find(at=>Cr(at.path)===Cr(Te));if(Re){g(Re.id),b("");return}g("__custom__"),b(Te)},[v]),dt=o.useCallback(Z=>{const Te=String(Z.workspace||"").trim();if(!Te)return{workspaceId:null,workspacePath:null};const Re=v.find(at=>Cr(at.path)===Cr(Te));return Re?{workspaceId:Re.id,workspacePath:null}:{workspaceId:null,workspacePath:Te}},[v]),yt=o.useMemo(()=>P.find(Z=>Z.providerSessionId===R)||null,[P,R]),ut=o.useMemo(()=>{var Te;if(C!=="cli"||!f||!w)return null;const Z=((Te=te.find(Re=>Re.type===w))==null?void 0:Te.displayName)||w;return{routeId:f.id,daemonId:f.id,providerSessionId:R||void 0,transport:"pty",mode:"chat",agentName:Z,agentType:w,status:"idle",title:Z,messages:[],ideType:w,workspaceName:Fe,displayPrimary:Z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${f.id}:${w}`,machineName:Tt(f,{fallbackId:f.id})}},[C,te,Fe,f,R,w]),Xe=o.useCallback(()=>{var Te;if(!f)return;g("__custom__"),he(!0),je("");const Z=tn(f.platform,en(j.trim(),Fe,Ue,ot,f.defaultWorkspacePath,(Te=v.find(Re=>Re.id===N))==null?void 0:Te.path,v.map(Re=>Re.path)));de(!0),n(f.id,Z).then(Re=>{ve(Re.path),b(Re.path),pe(Re.directories)}).catch(Re=>{je(Re instanceof Error?Re.message:"Could not load folder")}).finally(()=>de(!1))},[j,N,ot,Ue,n,Fe,f,v]),nt=o.useCallback(Z=>{f&&(de(!0),je(""),n(f.id,Z).then(Te=>{ve(Te.path),b(Te.path),pe(Te.directories)}).catch(Te=>{je(Te instanceof Error?Te.message:"Could not load folder")}).finally(()=>de(!1)))},[n,f]),ke=o.useCallback(async()=>{if(!f||!Fe)return;se(!0),q("");const Z=await a(f.id,Fe);if(se(!1),!Z.ok){q(Z.error||"Could not save workspace");return}q("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,Fe,f]),De=o.useCallback(async()=>{if(!f||!C||!w)return;fe(!0),q("");const Z=S.trim()?S.trim().split(/\s+/).filter(Boolean):[],Te=C==="ide"?await i(f.id,w,{workspacePath:Fe||null}):await c(f.id,C,w,{workspaceId:m!=="__home__"&&m!=="__custom__"?m:null,workspacePath:m==="__custom__"&&Fe||null,resumeSessionId:C==="cli"&&R?R:null,cliArgs:Z});if(fe(!1),!Te.ok){q(Te.error||"Could not start session");return}C!=="ide"&&S.trim()&&(Zc(f.id,w,S),Ke(f.id,w)),r()},[C,S,Ke,r,i,c,Fe,f,R,w,m]),$e=C?lc(C,C==="cli"&&!!R):"Start",tt=C?dc(C,C==="cli"&&!!R):"Starting…";return f?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 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 or resume saved history."})]}),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:r,"aria-label":"Close new session dialog",children:t.jsx(wt,{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(Dr,{title:"Machine",children:t.jsx("select",{value:f.id,onChange:Z=>h(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:Q,children:p.map(Z=>t.jsx("option",{value:Z.id,children:Tt(Z,{fallbackId:Z.id})},Z.id))})}),t.jsxs(Dr,{title:"Workspace",description:"Saved workspace is preferred. Home and custom folders are still available.",action:t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Xe,disabled:Q,children:"Browse…"}),children:[t.jsxs("select",{value:m,onChange:Z=>{const Te=Z.target.value;g(Te),Te==="__custom__"?Xe():q("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Q,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),v.map(Z=>t.jsxs("option",{value:Z.id,children:[Z.id===N?"⭐ ":"",Zr(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:m==="__home__"?"Launch without a workspace.":Fe||"Select a workspace folder."}),m==="__custom__"&&Fe&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Xe,disabled:Q,children:[t.jsx(ks,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ke,disabled:Q||U,children:U?"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:te.length>0},{id:"ide",label:"IDE",enabled:we.length>0},{id:"acp",label:"ACP",enabled:ue.length>0}].map(Z=>t.jsx("button",{type:"button",className:`btn btn-sm ${C===Z.id?"btn-primary":"btn-secondary"}`,onClick:()=>A(Z.id),disabled:!Z.enabled||Q,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:C==="ide"?"Choose IDE":C==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Ne.map(Z=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${w===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>M(Z.id),disabled:Q,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)),Ne.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."})]})]}),C!=="ide"&&t.jsxs(Dr,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:S,onChange:Z=>k(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:Q}),x.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:x.map(Z=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>k(Z),disabled:Q,title:Z,children:Z},Z))})]}),C==="cli"&&t.jsx(tl,{busy:Q,savedSessionsLoading:z,savedSessionsError:B,selectedSession:yt,onRefresh:()=>{!f||!w||Be(f.id,w)},onOpenHistory:()=>{!f||!w||(J(!0),el({hasLoadedInitialResults:T,isLoading:z})&&Be(f.id,w))},onClearSelection:()=>I("")}),W&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${W.includes("saved")||W.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:W})]}),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:r,disabled:Q,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:De,disabled:Q||!C||!w||m==="__custom__"&&!Fe,children:[t.jsx(pa,{size:14}),Q?tt:$e]})]})]})}),oe&&t.jsx(nn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:le,directories:ne,busy:ce,error:ae,onClose:()=>he(!1),onNavigate:nt,onConfirm:Z=>{b(Z),ve(Z),g("__custom__"),he(!1)}}),G&&ut&&t.jsx(Ta,{activeConv:ut,ides:[],isCreatingChat:!1,isRefreshingHistory:z,savedSessions:P,isSavedSessionsLoading:z,isResumingSavedSessionId:ge,savedHistoryFilters:xe,onSavedHistoryFiltersChange:re,onClose:()=>J(!1),onNewChat:()=>{I(""),J(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!f||!w||Be(f.id,w)},onResumeSavedSession:Z=>{if(!f||!w||ge||!Z.canResume)return;const Te=dt(Z);I(Z.providerSessionId),rt(Z),ye(Z.providerSessionId),J(!1),fe(!0),q(""),c(f.id,"cli",w,{workspaceId:Te.workspaceId,workspacePath:Te.workspacePath,resumeSessionId:Z.providerSessionId}).then(Re=>{if(!Re.ok){q(Re.error||"Could not resume session");return}r()}).finally(()=>{fe(!1),ye(Re=>Re===Z.providerSessionId?null:Re)})}})]}):null}function Uh({isMobile:e,showMobileChatMode:s,visibleConversationCount:r}){const[n,a]=o.useState(!1),[i,c]=o.useState(!1),[l,u]=o.useState(!1),[p,d]=o.useState(!1),[h,f]=o.useState(!1),[v,N]=o.useState("quickstart"),[m,g]=o.useState("workspace"),j=o.useMemo(()=>!s&&!e,[s,e]),b=o.useCallback(k=>{a(k),k&&c(!1)},[]),C=o.useCallback(k=>{c(k),k&&a(!1)},[]),A=o.useCallback(()=>{N(r===0?"quickstart":"shortcuts"),g("workspace"),u(!0),a(!1),c(!1)},[r]),w=o.useCallback(()=>{u(!1)},[]),M=o.useCallback(()=>{d(!0)},[]),S=o.useCallback(()=>{d(!1)},[]);return o.useEffect(()=>{if(!j){f(!1);return}f(!0);const k=window.setTimeout(()=>{f(!1)},1e4);return()=>window.clearTimeout(k)},[j]),{inboxOpen:n,hiddenOpen:i,shortcutHelpOpen:l,newSessionOpen:p,guideNudgeVisible:h,guideTab:v,shortcutSection:m,isDesktopDashboard:j,setGuideTab:N,setShortcutSection:g,handleInboxOpenChange:b,handleHiddenOpenChange:C,handleOpenShortcutHelp:A,closeShortcutHelp:w,openNewSession:M,closeNewSession:S}}function zh(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 Vh(e){return e instanceof Error?e.message:String(e||"")}function Gh(e){const s=Vh(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function qh({showMobileChatMode:e,isMobile:s,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetActiveCliViewMode:p,mobileChatConversations:d,hiddenConversations:h,ides:f,actionLogs:v,sendDaemonCommand:N,setActionLogs:m,isStandalone:g,initialDataLoaded:j,userName:b,requestedMobileTabKey:C,onRequestedMobileTabConsumed:A,requestedMachineId:w,onRequestedMachineConsumed:M,requestedMobileSection:S,onRequestedMobileSectionConsumed:k,containerRef:x,isSplitMode:E,numGroups:R,groupSizes:I,groupedConvs:P,clearedTabs:K,focusedGroup:z,focusGroup:L,moveTabToGroup:T,splitTabRelative:H,closeGroup:B,handleResizeStart:D,groupActiveTabIds:G,setGroupActiveTab:J,groupTabOrders:xe,setGroupTabOrder:re,toggleHiddenTab:ge,visibleConversations:ye,requestedDesktopTabKey:Q,onRequestedDesktopTabConsumed:fe,onDesktopActiveTabChange:W,onRequestScrollToBottom:q,onHideConversation:oe,onShowHiddenConversation:he,onShowAllHiddenConversations:le,scrollToBottomRequest:ve,machineEntries:ne,layoutProfile:pe,onBrowseMachineDirectory:ce,onSaveMachineWorkspace:de,onLaunchMachineIde:ae,onLaunchMachineProvider:je,onListMachineSavedSessions:U,notifications:se,notificationUnreadCount:y,liveSessionInboxState:X,onMarkNotificationRead:te,onMarkNotificationUnread:ue,onDeleteNotification:we}){const Ne=St.useRef(null),{inboxOpen:Be,hiddenOpen:Ke,shortcutHelpOpen:Fe,newSessionOpen:Ue,guideNudgeVisible:ot,guideTab:rt,shortcutSection:dt,isDesktopDashboard:yt,setGuideTab:ut,setShortcutSection:Xe,handleInboxOpenChange:nt,handleHiddenOpenChange:ke,handleOpenShortcutHelp:De,closeShortcutHelp:$e,openNewSession:tt,closeNewSession:lt}=Uh({isMobile:s,showMobileChatMode:e,visibleConversationCount:ye.length}),mt=St.useCallback(Y=>{var be;Vs.flushSync(()=>{he(Y)}),(be=Ne.current)==null||be.restoreHiddenTabToSavedLocation(Y.tabKey)},[he]),Z=St.useCallback(Y=>{var Ee;const be=d.find(Oe=>Yn(Oe,Y))||h.find(Oe=>Yn(Oe,Y));be&&(h.some(Oe=>Oe.tabKey===be.tabKey)&&mt(be),W(be.tabKey),(Ee=Ne.current)==null||Ee.activateConversationTab(be.tabKey),q(be.tabKey,"notification-open")),te(Y.id),nt(!1)},[mt,h,d,W,te,q]),Te=St.useCallback(()=>{var be;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((be=Ne.current)==null||be.resetAllPanelsToMain(),ke(!1))},[ke]),Re=St.useCallback(async Y=>{var qe;if(!r)return;const be=(qe=r.modalButtons)==null?void 0:qe[Y];if(!be)return;const Ee=Js(r);if(!Ee)return;const Oe=be.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Je=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Oe);try{await N(Ee,"resolve_action",{button:be,action:Je?"approve":"reject",buttonIndex:Y,...ws(r)})}catch(ze){Gh(ze)||console.error("[Shortcut approval] Failed:",ze)}},[r,N]),{isMac:at,actionDefinitions:ht,actionShortcuts:vt,shortcutListening:We,shortcutListeningDraft:It,setShortcutListening:$,setShortcutListeningDraft:O,saveShortcuts:F}=Ah({enabled:yt&&!Fe,onTrigger:Y=>{var be,Ee,Oe,Je,qe,ze,Pe,_,ee,me,Le,Ce,Me,Ae,ft,it;if(Y==="openShortcutHelp"){De();return}if(Y==="hideCurrentTab"){r&&oe(r);return}if(Y==="toggleHiddenTabs"){ke(!Ke);return}if(Y==="openHistoryForActiveTab"){r&&!Ge(r)&&i(r);return}if(Y==="openRemoteForActiveTab"){r&&!Qe(r)&&!Ge(r)&&c(r);return}if(Y==="splitActiveTabRight"){(be=Ne.current)==null||be.splitActiveTabRight();return}if(Y==="splitActiveTabDown"){(Ee=Ne.current)==null||Ee.splitActiveTabDown();return}if(Y==="floatActiveTab"){(Oe=Ne.current)==null||Oe.floatActiveTab();return}if(Y==="popoutActiveTab"){(Je=Ne.current)==null||Je.popoutActiveTab();return}if(Y==="dockActiveTab"){(qe=Ne.current)==null||qe.dockActiveTab();return}if(Y==="focusLeftPane"){(ze=Ne.current)==null||ze.focusLeftPane();return}if(Y==="focusRightPane"){(Pe=Ne.current)==null||Pe.focusRightPane();return}if(Y==="focusUpPane"){(_=Ne.current)==null||_.focusUpPane();return}if(Y==="focusDownPane"){(ee=Ne.current)==null||ee.focusDownPane();return}if(Y==="moveActiveTabToLeftPane"){(me=Ne.current)==null||me.moveActiveTabToLeftPane();return}if(Y==="moveActiveTabToRightPane"){(Le=Ne.current)==null||Le.moveActiveTabToRightPane();return}if(Y==="moveActiveTabToUpPane"){(Ce=Ne.current)==null||Ce.moveActiveTabToUpPane();return}if(Y==="moveActiveTabToDownPane"){(Me=Ne.current)==null||Me.moveActiveTabToDownPane();return}if(Y==="triggerPrimaryApprovalAction"){Re(0);return}if(Y==="triggerSecondaryApprovalAction"){Re(1);return}if(Y==="triggerTertiaryApprovalAction"){Re(2);return}if(Y==="setActiveTabShortcut"){(Ae=Ne.current)==null||Ae.setShortcutForActiveTab();return}if(Y==="selectPreviousGroupTab"){(ft=Ne.current)==null||ft.activatePreviousTabInGroup();return}if(Y==="selectNextGroupTab"){(it=Ne.current)==null||it.activateNextTabInGroup();return}!r||!Qe(r)||Ge(r)||Y==="toggleCliView"&&p(u==="chat"?"terminal":"chat")}}),V=St.useCallback(()=>{$e(),$(null),O([])},[$e,$,O]),ie=St.useMemo(()=>dt==="all"?ht:ht.filter(Y=>zh(Y)===dt),[ht,dt]),Se=St.useCallback(()=>{const Y=Object.fromEntries(ht.map(be=>[be.id,""]));F(Y)},[ht,F]),Ie=St.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const Y=Object.fromEntries(ht.map(be=>[be.id,be.defaultShortcut]));F(Y)},[ht,F]);return St.useEffect(()=>{const Y=be=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?be.metaKey&&be.key.toLowerCase()==="w":be.ctrlKey&&be.key.toLowerCase()==="w")&&(be.preventDefault(),r&&oe&&oe(r))};return window.addEventListener("keydown",Y),()=>window.removeEventListener("keydown",Y)},[r,oe]),St.useEffect(()=>{if(!Fe||We)return;const Y=be=>{be.key==="Escape"&&(be.preventDefault(),V())};return window.addEventListener("keydown",Y,!0),()=>window.removeEventListener("keydown",Y,!0)},[V,Fe,We]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(zm,{activeConv:r,wsStatus:n,isConnected:a,conversations:ye,hiddenConversations:h,onOpenHistory:i,onHideConversation:oe,onShowConversation:mt,onShowAllHidden:le,onResetPanelsToMain:Te,notifications:se,notificationUnreadCount:y,onOpenNotification:Z,onMarkNotificationRead:te,onMarkNotificationUnread:ue,onDeleteNotification:we,inboxOpen:Be,onInboxOpenChange:nt,hiddenOpen:Ke,onHiddenOpenChange:ke,onOpenNewSession:s?void 0:tt,actionShortcuts:vt,onOpenRemote:()=>{!r||Qe(r)||Ge(r)||c(r)},onStopCli:l,activeCliViewMode:u,onSetCliViewMode:p}),e?t.jsx(bh,{conversations:d,hiddenConversations:h,ides:f,actionLogs:v,sendDaemonCommand:N,setActionLogs:m,isStandalone:g,userName:b,requestedActiveTabKey:C,onRequestedActiveTabConsumed:A,requestedMachineId:w,onRequestedMachineConsumed:M,requestedMobileSection:S,onRequestedMobileSectionConsumed:k,onOpenHistory:i,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowHiddenConversation:mt,onShowAllHiddenConversations:le,onOpenNewSession:tt,liveSessionInboxState:X}):s?t.jsx(Nh,{containerRef:x,isSplitMode:E,numGroups:R,groupSizes:I,groupedConvs:P,clearedTabs:K,ides:f,actionLogs:v,sendDaemonCommand:N,setActionLogs:m,isStandalone:g,hasRegisteredMachines:ne.length>0,userName:b,focusedGroup:z,focusGroup:L,moveTabToGroup:T,splitTabRelative:H,closeGroup:B,handleResizeStart:D,groupActiveTabIds:G,setGroupActiveTab:J,groupTabOrders:xe,setGroupTabOrder:re,toggleHiddenTab:ge,onOpenNewSession:tt,allowTabShortcuts:!1,liveSessionInboxState:X}):t.jsx(Kh,{visibleConversations:ye,clearedTabs:K,ides:f,actionLogs:v,sendDaemonCommand:N,setActionLogs:m,isStandalone:g,hasRegisteredMachines:ne.length>0,initialDataLoaded:j,userName:b,toggleHiddenTab:ge,actionShortcuts:vt,registerActionHandlers:Y=>{Ne.current=Y},onActiveTabChange:W,requestedActiveTabKey:Q,onRequestedActiveTabConsumed:fe,onRequestScrollToBottom:q,scrollToBottomRequest:ve,onOpenNewSession:tt,liveSessionInboxState:X,layoutProfile:pe}),Ue&&t.jsx(Fh,{machines:ne,ides:f,onClose:lt,onBrowseDirectory:ce,onSaveWorkspace:de,onLaunchIde:ae,onLaunchProvider:je,onListSavedSessions:U}),Fe&&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:V,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:Y=>Y.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:V,"aria-label":"Close dashboard guide",children:t.jsx(wt,{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(Y=>t.jsx("button",{type:"button",className:`btn btn-sm ${rt===Y.id?"btn-primary":"btn-secondary"}`,onClick:()=>ut(Y.id),children:Y.label},Y.id))}),rt==="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 ",at?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),rt==="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."]})]})]})]}),rt==="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(Y=>t.jsx("button",{type:"button",className:`btn btn-sm ${dt===Y.id?"btn-primary":"btn-secondary"}`,onClick:()=>Xe(Y.id),children:Y.label},Y.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Se,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:Ie,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:ie.map(Y=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${We===Y.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:Y.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Y.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:Y.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:We===Y.id?It.length>0?`${It.join(" ")} ...`:"Listening...":vt[Y.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{$(Y.id),O([])},children:We===Y.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const be={...vt};be[Y.id]="",F(be)},children:"Disable"})]})]})},Y.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",at?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&t.jsxs("button",{type:"button",onClick:De,className:`fixed right-4 bottom-24 z-40 hidden md:inline-flex items-center rounded-full border border-border-subtle bg-bg-primary/88 backdrop-blur py-2 text-xs text-text-secondary hover:text-text-primary transition-all ${ot?"gap-2 px-2.5":"justify-center w-10 px-0"}`,style:{boxShadow:"0 6px 18px rgba(0,0,0,0.12)"},title:"Dashboard guide","aria-label":"Open dashboard guide",children:[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:"?"}),ot&&t.jsx("span",{children:"Guide"})]})]})}const Ln=[{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 Yh({onClose:e}){const[s,r]=o.useState(0),n=Ln[s],a=s===Ln.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(wt,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Ln.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:`
54
- @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
55
- @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
56
- `})]})}function Xh({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 Jh({ideData:e,allIdes:s,connectionStates:r,ideName:n,preferredTabKey:a}){const[i,c]=o.useState(()=>a||"native"),l=o.useMemo(()=>mc(s),[s]),u=o.useMemo(()=>e?La(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),p=o.useMemo(()=>u.find(m=>m.streamSource==="native"),[u]),d=o.useMemo(()=>u.filter(m=>m.streamSource==="agent-stream"),[u]),h=o.useMemo(()=>e?Dt(u,e.id):null,[u,e]);o.useEffect(()=>{a&&c(a)},[a]),o.useEffect(()=>{if(a||!h)return;const m=h.streamSource==="native"?"native":h.tabKey;!m||i===m||i==="native"&&c(m)},[i,h,a]),o.useEffect(()=>{var m;i!=="native"&&(d.some(g=>g.tabKey===i)||c(((m=d[0])==null?void 0:m.tabKey)||"native"))},[i,d]),o.useEffect(()=>{i==="native"&&(p||d[0]&&c(d[0].tabKey))},[i,p,d]);const f=o.useMemo(()=>i==="native"&&p?p:d.find(m=>m.tabKey===i)||h||p||d[0],[i,p,h,d]),v=o.useMemo(()=>d.map(m=>({tabKey:m.tabKey,title:ac(m)||n,status:m.status})),[d,n]),N=o.useCallback(m=>{if(m)return u.find(g=>Yn(g,{sessionId:m,routeId:m,tabKey:m,providerSessionId:m}))},[u]);return{activeChatTab:i,setActiveChatTab:c,activeConv:f,conversations:u,extensionTabs:v,hasExtensions:v.length>0,resolveConversationByTarget:N}}function Qh({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:i,setActionLogs:c,isStandalone:l,userName:u,onOpenHistory:p,onConversationChange:d,onClose:h}){const[f,v]=o.useState("split"),[N,m]=o.useState(()=>zt(e)?"native":e.tabKey),g=o.useRef(null),j=o.useMemo(()=>s||r.find(T=>T.id===e.routeId),[e.routeId,s,r]),b=o.useMemo(()=>et((j==null?void 0:j.type)||""),[j==null?void 0:j.type]),{conversations:C,extensionTabs:A,hasExtensions:w}=Jh({ideData:j,allIdes:r,connectionStates:n,ideName:b||"IDE",preferredTabKey:zt(e)?void 0:e.tabKey}),M=o.useMemo(()=>j?Dt(C,j.id):null,[j,C]);o.useEffect(()=>{const T=g.current,H={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(g.current=H,!(T&&T.routeId===H.routeId&&T.tabKey===H.tabKey&&T.streamSource===H.streamSource)){if(zt(e)){m("native");return}m(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(N==="native"){if(C.some(T=>T.streamSource==="native"))return;(M==null?void 0:M.streamSource)==="agent-stream"&&m(M.tabKey);return}if(!C.some(T=>T.tabKey===N)){if((M==null?void 0:M.streamSource)==="agent-stream"){m(M.tabKey);return}m("native")}},[C,N,M]);const S=o.useMemo(()=>N==="native"?C.find(T=>T.streamSource==="native")||e:C.find(T=>T.tabKey===N)||e,[e,C,N]),k=Cc(S),x=o.useMemo(()=>k.status||k.modalMessage||k.modalButtons?{...S,...k.status?{status:k.status}:{},...k.modalMessage!==void 0?{modalMessage:k.modalMessage}:{},...k.modalButtons!==void 0?{modalButtons:k.modalButtons}:{}}:S,[S,k]),E=sr(x),R=rn({sendDaemonCommand:i,activeConv:x,setActionLogs:c,isStandalone:l}),{connScreenshot:I,screenshotUsage:P,handleRemoteAction:K}=Fc({doId:E,targetSessionId:Fi(x),connState:x.connectionState||"new",viewMode:f}),z=o.useMemo(()=>a.filter(T=>T.routeId===x.tabKey),[a,x.tabKey]);o.useEffect(()=>{d==null||d(x)},[x,d]),o.useEffect(()=>{const T=H=>{H.key==="Escape"&&h()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[h]);const L=o.useCallback(T=>{T.stopPropagation()},[]);return t.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:h,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:L,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(Ct,{size:16})}),t.jsx("span",{className:"truncate",children:ya(S)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,children:"Close"})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[t.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(T=>{const H=f===T;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${H?"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:()=>v(T),title:T==="split"?"Split view":"Remote only",children:T==="split"?t.jsx(wd,{size:15}):t.jsx(Ct,{size:15})},T)})}),t.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),t.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>p(S),title:"Chat History",children:[t.jsx(ma,{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:h,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${f==="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:[f!=="remote"&&t.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[t.jsx(Xh,{hasExtensions:w,ideName:b||"IDE",activeChatTab:N,extensionTabs:A,onSelectTab:m}),t.jsx(Ai,{activeConv:x,onModalButton:R.handleModalButton}),t.jsx(Zn,{activeConv:x,ideEntry:j,showMetaChips:!1,handleSendChat:R.handleSendChat,isSendingChat:R.isSendingChat,sendFeedbackMessage:R.sendFeedbackMessage,handleFocusAgent:R.handleFocusAgent,isFocusingAgent:R.isFocusingAgent,actionLogs:z,userName:u})]}),t.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${f==="split"?"order-1 md:order-2":""}`,children:t.jsx(Ii,{addLog:()=>{},connState:x.connectionState||"new",connScreenshot:I,screenshotUsage:P,transportType:x.transport,onAction:K})})]})]})})}function Zh({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=Om(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 ex({historyModal:e,remoteDialog:s,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:i}){var c;return t.jsxs(t.Fragment,{children:[t.jsx(Hm,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&t.jsx(Ta,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),s.conversation&&t.jsx(Qh,{activeConv:s.conversation,ideEntry:s.ideEntry,ides:s.ides,connectionStates:s.connectionStates,actionLogs:s.actionLogs,sendDaemonCommand:s.sendDaemonCommand,setActionLogs:s.setActionLogs,isStandalone:s.isStandalone,userName:s.userName,onOpenHistory:s.onOpenHistory,onConversationChange:s.onConversationChange,onClose:s.onClose}),r.open&&r.targetConv&&(Qe(r.targetConv)||Ge(r.targetConv))&&t.jsx(Zh,{activeConv:r.targetConv,canSaveAndStop:Qe(r.targetConv)&&!Ge(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),t.jsx(uc,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),i.open&&t.jsx(Yh,{onClose:i.onClose})]})}function tx({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(er,{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=Tt(c,{fallbackId:c.id}),u=n[c.id],p=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",p]}),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(wt,{size:16})})]})}function sx(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function rx(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 nx(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){const s=e.machine;return typeof(s==null?void 0:s.cpus)!="number"||typeof(s==null?void 0:s.totalMem)!="number"||typeof(s==null?void 0:s.arch)!="string"||typeof(s==null?void 0:s.release)!="string"}function ox(e){return{metadataDaemonIds:e.map(s=>s.id),runtimeDaemonIds:e.filter(s=>ax(s)).map(s=>s.id)}}function ix(){var Ya,Xa,Ja,Qa;const{sendCommand:e}=jt(),s=nr(),r=Nc(),n=la(),a=Ms(),[i,c]=Wl(),l=i.get("activeTab"),u=((Ya=n.state)==null?void 0:Ya.openRemoteForTabKey)||null,p=((Xa=n.state)==null?void 0:Xa.openMachineId)||null,d=((Ja=n.state)==null?void 0:Ja.mobileSection)||null,h=tc(),f=h.ides||[],v=h.initialLoaded??!0,{updateRouteChats:N,setToasts:m}=h,[g,j]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),b=h.toasts||[],C=h.wsStatus||"connected",A=h.isConnected??!0,w=h.connectionStates||{},M=h.showReconnected||!1,{layoutProfile:S,groupAssignments:k,updateGroupAssignments:x,focusedGroup:E,updateFocusedGroup:R,focusGroup:I,groupActiveTabIds:P,updateGroupActiveTabIds:K,setGroupActiveTab:z,groupTabOrders:L,updateGroupTabOrders:T,setGroupTabOrder:H,groupSizes:B,updateGroupSizes:D,isMobile:G,hasHydratedStoredLayout:J,hydrateStoredLayout:xe,focusConversationTab:re}=vp(),[ge,ye]=o.useState(()=>Da());o.useEffect(()=>Bf(ye),[]);const Q=o.useMemo(()=>sx({isMobile:G,mobileViewMode:ge}),[G,ge]),[fe,W]=o.useState([]),[q,oe]=o.useState({}),[he,le]=o.useState({});tr("Dashboard",{ideCount:f.length,toastCount:b.length,focusedGroup:E,groupCount:Object.keys(k).length,actionLogCount:fe.length});const ve=o.useMemo(()=>f.filter(He=>He.type==="adhdev-daemon").sort(xa),[f]),ne=ve[0],pe=!!ne;o.useEffect(()=>{const{metadataDaemonIds:He,runtimeDaemonIds:kt}=ox(ve);for(const Et of He)s(Et,{minFreshMs:3e4}).catch(()=>{});for(const Et of kt)r(Et,{minFreshMs:3e4}).catch(()=>{})},[s,r,ve]);const ce=(ne==null?void 0:ne.terminalBackend)||null,de=ne?Tt(ne,{fallbackId:ne.id}):null,ae=(ne==null?void 0:ne.id)||null,je=o.useMemo(()=>Yf(f,q),[f,q]),{hiddenTabs:U,hideTarget:se,toggleTarget:y,showTarget:X,showAllTabs:te}=qf(),{conversations:ue,visibleConversations:we,visibleTabKeys:Ne,resolveConversationBySessionId:Be,resolveConversationByTarget:Ke}=ap({ides:je,connectionStates:w,clearedTabs:he,hiddenTabs:U}),Fe=o.useMemo(()=>new Map(ue.map(He=>[He.tabKey,He])),[ue]);Mm(we,Q),o.useEffect(()=>{Object.keys(q).length!==0&&oe(He=>Xf(He,f))},[f,q]);const Ue=o.useMemo(()=>eu(f),[f]),{notifications:ot,unreadCount:rt}=Dp({conversations:ue,liveSessionInboxState:Ue}),{handleMarkDashboardNotificationRead:dt,handleMarkDashboardNotificationUnread:yt,handleDeleteDashboardNotification:ut}=Ep({notifications:ot,sendDaemonCommand:e}),Xe=o.useRef(null),nt=o.useRef(null),ke=o.useRef(null),De=o.useRef(null),$e=o.useRef(null),{containerRef:tt,normalizedGroupAssignments:lt,numGroups:mt,isSplitMode:Z,groupedConvs:Te,moveTabToGroup:Re,closeGroup:at,handleResizeStart:ht,splitTabRelative:vt}=Ip({groupAssignments:k,updateGroupAssignments:x,updateFocusedGroup:R,updateGroupActiveTabIds:K,updateGroupTabOrders:T,groupSizes:B,updateGroupSizes:D,isMobile:G,visibleConversations:we,visibleTabKeys:Ne}),{activeConv:We,openDesktopConversation:It,requestScrollToBottom:$,scrollToBottomRequest:O,setDesktopActiveTab:F}=Vp({isMobile:G,conversations:ue,visibleConversations:we,groupActiveTabIds:P,focusedGroup:E,groupedConvs:Te,setSearchParams:c});o.useEffect(()=>{const He=()=>{ke.current&&(clearTimeout(ke.current),ke.current=null),De.current&&(clearTimeout(De.current),De.current=null),$e.current&&(document.removeEventListener("visibilitychange",$e.current),$e.current=null),nt.current=null};if(G){He(),Xe.current=null;return}if(!(We!=null&&We.sessionId)){He(),Xe.current=null;return}const kt=Or(We,Ue),Et=nx({tabKey:We.tabKey,historySessionId:rr(We)||"",lastMessageHash:We.lastMessageHash||"",lastMessageAt:Number(We.lastMessageAt||0),timestamp:es(We),liveState:kt}),ir=Et.autoReadKey,cr=rx({autoReadKey:ir,shouldMarkSeen:Et.shouldMarkSeen,completedKey:Xe.current,pendingKey:nt.current});if(!Et.shouldMarkSeen){cr.shouldCancelPending&&He(),Xe.current=ir;return}if(!cr.shouldSchedule)return;cr.shouldCancelPending&&He();const Za=()=>{if(document.visibilityState!=="visible"||Xe.current===ir)return;Xe.current=ir,nt.current=null,ke.current=null,De.current=null,$e.current&&(document.removeEventListener("visibilitychange",$e.current),$e.current=null);const lr=Et.readAt;e(We.daemonId||We.routeId,"mark_session_seen",{sessionId:We.sessionId,seenAt:lr}).catch(()=>{})};if(nt.current=cr.nextPendingKey,document.visibilityState==="visible"){ke.current=setTimeout(Za,1500);const lr=()=>{document.visibilityState!=="visible"&&ke.current&&(clearTimeout(ke.current),ke.current=null)};$e.current=lr,document.addEventListener("visibilitychange",lr);return}const eo=()=>{document.visibilityState==="visible"&&(De.current&&clearTimeout(De.current),De.current=setTimeout(Za,800),$e.current&&(document.removeEventListener("visibilitychange",$e.current),$e.current=null))};$e.current=eo,document.addEventListener("visibilitychange",eo)},[We,G,Ue,e]),o.useEffect(()=>()=>{ke.current&&clearTimeout(ke.current),De.current&&clearTimeout(De.current),$e.current&&document.removeEventListener("visibilitychange",$e.current)},[]);const{requestedDesktopTabKey:V,requestedMobileTabKey:ie,consumeRequestedActiveTab:Se}=op({isMobile:G,urlActiveTab:l,resolveConversationBySessionId:Be,setSearchParams:c}),{remoteDialogConv:Ie,remoteDialogIdeEntry:Y,remoteDialogActiveConv:be,setRemoteDialogActiveConv:Ee,openRemoteDialog:Oe,closeRemoteDialog:Je,cliStopDialogOpen:qe,cliStopTargetConv:ze,requestCliStop:Pe,cancelCliStop:_,confirmCliStop:ee}=Yp({isMobile:G,location:n,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:V,conversations:ue,ides:f,resolveConversationByTarget:Ke,activeConv:We,sendDaemonCommand:e}),{historyModalOpen:me,openHistoryModal:Le,closeHistoryModal:Ce,historyTargetConv:Me,isSavedSessionHistoryTarget:Ae,isHistoryCreatingChat:ft,isHistoryRefreshingHistory:it,handleHistorySwitchSession:Ls,handleHistoryNewChat:cl,handleHistoryRefresh:ll,savedHistorySessions:dl,savedHistoryFilters:ul,setSavedHistoryFilters:ml,isSavedHistoryLoading:fl,resumingSavedHistorySessionId:pl,handleRefreshSavedHistory:hl,handleResumeSavedHistorySession:xl}=Gp({activeConv:We,remoteDialogConv:Ie,remoteDialogActiveConv:be,ides:f,sendDaemonCommand:e,updateRouteChats:N,setToasts:m,setClearedTabs:le,setSearchParams:c}),bl=o.useMemo(()=>we,[we]),or=G&&ge==="chat",gl=o.useMemo(()=>ue.filter(He=>Ea(U,He)),[ue,U]),Va=o.useCallback(He=>{const kt=new URLSearchParams(i);kt.set("activeTab",He),c(kt,{replace:!0})},[i,c]),{trackPendingLaunch:yl}=Hp({ides:f,conversations:ue,onOpenSession:Va}),{handleBrowseMachineDirectory:vl,handleSaveMachineWorkspace:wl,handleLaunchMachineIde:jl,handleLaunchMachineProvider:kl,handleListMachineSavedSessions:Sl,setActiveCliViewMode:Nl}=Fp({sendDaemonCommand:e,trackPendingLaunch:yl,onOpenSession:Va,activeConv:We,ides:f,setCliViewModeOverrides:oe});Jf({visibleConversations:we,clearedTabs:he,setClearedTabs:le,setActionLogs:W}),ip({ides:f,sendDaemonCommand:e,setToasts:m,resolveConversationByTarget:Ke});const{isRefreshingHistory:Cl,handleRefreshHistory:Il}=Pc({sendDaemonCommand:e,activeConv:We,chats:(Qa=f.find(He=>He.id===(We==null?void 0:We.routeId)))==null?void 0:Qa.chats,updateRouteChats:N,setToasts:m,setClearedTabs:le});jp({urlActiveTab:G&&!or?l:null,conversations:ue,resolveConversationBySessionId:Be,normalizedGroupAssignments:lt,hasHydratedStoredLayout:G&&!or?J:!0,hydrateStoredLayout:G&&!or?xe:()=>{},focusConversationTab:re,setSearchParams:c,historyModalOpen:me,activeConv:We,isRefreshingHistory:Cl,ides:f,handleRefreshHistory:Il});const Ml=o.useMemo(()=>!We||!Qe(We)||Ge(We)?null:Ts(We),[We]),{versionMismatchDaemons:Al,hasRequiredVersionDaemons:Ga,appVersion:Tl,versionBannerDismissed:Ll,setVersionBannerDismissed:Rl,upgradingDaemons:Pl,handleBannerUpgrade:_l}=Mp({ides:f,sendDaemonCommand:e}),qa=o.useCallback(He=>{X(He),It(He)},[It,X]),Dl=o.useCallback(He=>{se(He)},[se]);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(Fm,{terminalBackend:ce,isStandalone:pe,machineLabel:de,machineKey:ae}),(!Ll||Ga)&&t.jsx(tx,{daemons:Al,targetVersion:Tl,required:Ga,upgradingDaemons:Pl,onUpgrade:_l,onDismiss:()=>Rl(!0)}),t.jsx(qh,{showMobileChatMode:or,isMobile:G,activeConv:We,wsStatus:C,isConnected:A,onOpenHistory:He=>{He&&Ee(He),Le()},onOpenRemote:Oe,onStopCli:Pe,activeCliViewMode:Ml,onSetActiveCliViewMode:Nl,mobileChatConversations:bl,ides:f,actionLogs:fe,sendDaemonCommand:e,setActionLogs:W,isStandalone:pe,initialDataLoaded:v,userName:h.userName,requestedMobileTabKey:ie,onRequestedMobileTabConsumed:Se,requestedMachineId:p,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:Z,numGroups:mt,groupSizes:B,groupedConvs:Te,clearedTabs:he,focusedGroup:E,focusGroup:I,moveTabToGroup:Re,splitTabRelative:vt,closeGroup:at,handleResizeStart:ht,groupActiveTabIds:P,setGroupActiveTab:z,groupTabOrders:L,setGroupTabOrder:H,toggleHiddenTab:He=>y(Fe.get(He)||{tabKey:He}),visibleConversations:we,hiddenConversations:gl,requestedDesktopTabKey:V,onRequestedDesktopTabConsumed:Se,onDesktopActiveTabChange:F,onRequestScrollToBottom:$,onHideConversation:Dl,onShowHiddenConversation:qa,onShowAllHiddenConversations:te,scrollToBottomRequest:O,machineEntries:ve,layoutProfile:S,onBrowseMachineDirectory:vl,onSaveMachineWorkspace:wl,onLaunchMachineIde:jl,onLaunchMachineProvider:kl,onListMachineSavedSessions:Sl,notifications:ot,notificationUnreadCount:rt,liveSessionInboxState:Ue,onMarkNotificationRead:dt,onMarkNotificationUnread:yt,onDeleteNotification:ut}),t.jsx("style",{children:`
57
- body { overflow: hidden; overscroll-behavior: none; }
58
- `}),t.jsx(ex,{historyModal:{open:me,targetConv:Me,ides:f,isCreatingChat:ft,isRefreshingHistory:Ae?!1:it,savedSessions:dl,savedHistoryFilters:ul,onSavedHistoryFiltersChange:ml,isSavedSessionsLoading:fl,isResumingSavedSessionId:pl,onClose:Ce,onNewChat:cl,onSwitchSession:Ls,onRefreshHistory:Ae?hl:ll,onResumeSavedSession:xl},remoteDialog:{conversation:Ie,ideEntry:Y,ides:f,connectionStates:w,actionLogs:fe,sendDaemonCommand:e,setActionLogs:W,isStandalone:pe,userName:h.userName,onOpenHistory:He=>{He&&Ee(He),Le()},onConversationChange:Ee,onClose:Je},cliStopDialog:{open:qe,targetConv:ze,onCancel:_,onStopNow:async()=>{await ee("hard")},onSaveAndStop:async()=>{await ee("save")}},connectionBanner:{wsStatus:C,showReconnected:M,onReconnect:h.retryServerConnection},toastOverlay:{toasts:b,onDismiss:He=>m(kt=>kt.filter(Et=>Et.id!==He)),onClick:He=>{if(He.targetKey){const kt=Ke(He.targetKey);kt&&(re(kt.tabKey,lt),qa(kt),$(kt.tabKey,"toast-open"))}}},onboarding:{open:g,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}j(!1)}}})]})}function cx({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,u]=o.useState(null),[p,d]=o.useState(null),[h,f]=o.useState(!1),[v,N]=o.useState(null),[m,g]=o.useState(!1),[j,b]=o.useState(""),C=o.useRef(null),A=o.useCallback(B=>{C.current=B},[]),w=o.useCallback((B,D,G=!1)=>{c(J=>[...J.slice(-100),{timestamp:Date.now(),level:B,message:D}]),setTimeout(()=>{var J;return(J=a.current)==null?void 0:J.scrollIntoView({behavior:"smooth"})},100),G&&ct.showToast(D,B==="error"||B==="warn"?"warning":"success")},[a]),M=o.useCallback(B=>{const D=B instanceof Error?B.message:String(B||"");return D.includes("P2P command timeout")||D.includes("P2P not connected")||D.includes("P2P not available")},[]),S=o.useCallback(async(B,D)=>{var G;if(!e||l)return!1;u(B),w("info",`Launching ${et(B)}${D!=null&&D.workspace?` in ${D.workspace}`:""}...`);try{const J={ideType:B,enableCdp:!0};(G=D==null?void 0:D.workspace)!=null&&G.trim()?J.workspace=D.workspace.trim():D!=null&&D.useDefaultWorkspace&&(J.useDefaultWorkspace=!0);const xe=await r(e,"launch_ide",J);return w(xe!=null&&xe.success?"info":"error",xe!=null&&xe.success?`${et(B)} launched`:`Failed: ${xe==null?void 0:xe.error}`,!0),!!(xe!=null&&xe.success)}catch(J){return w("error",`Launch error: ${J.message}`,!0),!1}finally{u(null)}},[e,l,w,r]),k=o.useCallback(async B=>{if(!e)return{success:!1};const{cliType:D,dir:G,workspaceId:J,useDefaultWorkspace:xe,useHome:re,argsStr:ge,model:ye,resumeSessionId:Q}=B;if(!D)return w("warn","Select a CLI or ACP provider first",!0),{success:!1};const fe=ge?ge.split(/\s+/).filter(Boolean):void 0,W=(G==null?void 0:G.trim())||(J?"(saved id)":xe?"(default workspace)":re?"(home)":"");w("info",`Launching ${D}${W?` in ${W}`:""}${ye?` (model: ${ye})`:""}...`),d(D);try{const q={cliType:D,cliArgs:fe,initialModel:ye||void 0};G!=null&&G.trim()?q.dir=G.trim():J?q.workspaceId=J:xe?q.useDefaultWorkspace=!0:re&&(q.useHome=!0),Q&&(q.resumeSessionId=Q);const oe=await r(e,"launch_cli",q),he=(oe==null?void 0:oe.result)||oe;return oe!=null&&oe.success?(w("info",`${D} launched`,!0),(he==null?void 0:he.launchSource)==="home"?w("info","📂 Running in home directory (explicit choice)"):(he==null?void 0:he.launchSource)==="defaultWorkspace"&&w("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:he==null?void 0:he.sessionId}):(w("error",`Failed: ${(oe==null?void 0:oe.error)||(he==null?void 0:he.error)}`,!0),(oe==null?void 0:oe.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&N({cliType:D,argsStr:ge,model:ye}),{success:!1,sessionId:he==null?void 0:he.sessionId})}catch(q){return M(q)?(w("warn",`${D} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(w("error",`Launch error: ${q.message}`,!0),{success:!1})}finally{d(null)}},[e,w,M,r]),x=o.useCallback(async(B,D,G,J)=>e?B?D.trim()?k({cliType:B,dir:D,argsStr:G,model:J}):(N({cliType:B,argsStr:G,model:J}),{success:!1}):(w("warn","Select a provider",!0),{success:!1}):{success:!1},[e,w,k]),E=o.useCallback(async(B,D,G)=>{if(e&&window.confirm(`Stop ${B}?
59
- This will terminate the process.`))try{const J=await r(e,"stop_cli",{cliType:B,dir:D,targetSessionId:G});J!=null&&J.success?w("info",`${B} stopped`,!0):w("error",`Stop failed: ${(J==null?void 0:J.error)||"Unknown error"}`,!0)}catch(J){w("error",`Stop failed: ${J.message}`,!0)}},[e,w,r]),R=o.useCallback(async B=>{try{await r(B.daemonId,"restart_ide",{ideType:B.type}),w("info",`${et(B.type)} restart initiated`,!0)}catch(D){w("error",`Restart failed: ${D.message}`,!0)}},[w,r]),I=o.useCallback(async B=>{if(window.confirm(`Stop ${et(B.type)}?
60
- This will disconnect CDP and optionally kill the process.`))try{const D=await r(B.daemonId,"stop_ide",{ideType:B.type,killProcess:!0});D!=null&&D.success?w("info",`${et(B.type)} stopped`,!0):w("error",`Stop failed: ${(D==null?void 0:D.error)||"Unknown error"}`,!0)}catch(D){w("error",`Stop failed: ${D.message}`,!0)}},[w,r]),P=o.useCallback(async()=>{if(e)try{const B=await r(e,"detect_ides",{});w("info",`Found ${((B==null?void 0:B.result)||[]).length} IDE(s)`,!0)}catch(B){w("error",`Detection failed: ${B.message}`,!0)}},[e,w,r]),K=o.useCallback(async B=>{if(!e||!B.trim())return!1;f(!0);try{const D=await r(e,"workspace_add",{path:B.trim()});return D!=null&&D.success?(w("info",`Workspace added: ${B.trim()}`),!0):(w("error",(D==null?void 0:D.error)||"workspace_add failed"),!1)}catch(D){return w("error",D.message),!1}finally{f(!1)}},[e,w,r]),z=o.useCallback(async B=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){f(!0);try{const D=await r(e,"workspace_remove",{id:B});D!=null&&D.success?w("info","Workspace removed",!0):w("error",(D==null?void 0:D.error)||"workspace_remove failed",!0)}catch(D){w("error",D.message,!0)}finally{f(!1)}}},[e,w,r]),L=o.useCallback(async B=>{var D;if(e){f(!0);try{const G=await r(e,"workspace_set_default",B===null?{clear:!0}:{id:B});if(G!=null&&G.success){w("info",B?"Default workspace updated":"Default workspace cleared",!0);const J=typeof G.defaultWorkspacePath=="string"?G.defaultWorkspacePath:"";J&&((D=C.current)==null||D.call(C,J))}else w("error",(G==null?void 0:G.error)||"workspace_set_default failed",!0)}catch(G){w("error",G.message,!0)}finally{f(!1)}}},[e,w,r]),T=o.useCallback(async B=>{var G;if(!e||!B.trim())return;const D=B.trim();f(!0);try{const J=await r(e,"workspace_set_default",{path:D});J!=null&&J.success?(w("info","Default workspace set from history"),(G=C.current)==null||G.call(C,D)):w("error",(J==null?void 0:J.error)||"Could not set default (path missing on disk?)")}catch(J){w("error",J.message)}finally{f(!1)}},[e,w,r]),H=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:j}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:j})}catch(B){w("warn",`Live nickname updated, but account sync failed: ${B.message}`)}w("info",`Nickname set to "${j||"(cleared)"}"`),g(!1)}catch(B){w("error",`Failed: ${B.message}`)}},[e,j,s,w,n,r]);return{logs:i,launchingIde:l,launchingAgentType:p,workspaceBusy:h,launchPick:v,setLaunchPick:N,editingNickname:m,setEditingNickname:g,nicknameInput:j,setNicknameInput:b,addLog:w,handleLaunchIde:S,runLaunchCliCore:k,handleLaunchCli:x,handleStopCli:E,handleRestartIde:R,handleStopIde:I,handleDetectIdes:P,handleWorkspaceAdd:K,handleWorkspaceRemove:z,handleWorkspaceSetDefault:L,handleWorkspaceResumePath:T,handleSaveNickname:H,setOnDefaultWorkspaceChanged:A}}function lx({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var R;const{workspaceBusy:l,handleWorkspaceAdd:u,handleWorkspaceRemove:p,handleWorkspaceSetDefault:d}=i,[h,f]=o.useState(!1),[v,N]=o.useState(""),[m,g]=o.useState([]),[j,b]=o.useState(!1),[C,A]=o.useState(""),w=o.useCallback(async I=>{b(!0),A("");try{const P=await sn(c,e,I);N(P.path),g(P.directories)}catch(P){A(P instanceof Error?P.message:"Could not load folder")}finally{b(!1)}},[e,c]),M=o.useCallback(()=>{f(!0);const I=[...r.map(K=>K.workspace),...n.map(K=>K.workspace),...a.map(K=>K.workspace)],P=tn(s.platform,en(I,s.defaultWorkspacePath,(s.workspaces||[]).map(K=>K.path)));w(P)},[a,n,r,w,s.defaultWorkspacePath,s.platform,s.workspaces]),S=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,k=s.availableMem??s.freeMem??s.totalMem,x=S&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-k)/s.totalMem*100))):0,E=((R=s.loadavg)==null?void 0:R[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(ji,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?nu(s.uptime):"Waiting…"}),t.jsx(mr,{icon:t.jsx(Ct,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(mr,{icon:t.jsx(fa,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(mr,{icon:t.jsx(kd,{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(uo,{value:S?Math.min(Math.round(E/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:S?`${E.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(uo,{value:x,max:100,label:"Memory",color:"#3b82f6",detail:S?`${fn(s.totalMem-k)} / ${fn(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${fn(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(ks,{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:I=>void d(I.target.value===""?null:I.target.value),children:[t.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(I=>t.jsx("option",{value:I.id,children:I.label||I.path},I.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:M,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(I=>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:[I.id===s.defaultWorkspaceId&&t.jsx("span",{className:"text-[10px]",children:"⭐"}),t.jsx("span",{className:"font-medium text-text-primary truncate",children:Zr(I.path,I.label)})]}),t.jsx("div",{className:"font-mono truncate text-[10px]",title:I.path,children:I.path})]}),t.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void p(I.id),children:"Remove"})]},I.id))})]}),h&&t.jsx(nn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:v,directories:m,busy:j,error:C,confirmLabel:"Add workspace",onClose:()=>f(!1),onNavigate:I=>{w(I)},onConfirm:I=>{(async()=>{if(!I)return;await u(I)&&f(!1)})()}})]})}function dx(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 ux(e,s,r){const n=[];for(const[a,i]of Object.entries(e.settings)){const c=i;if(c.length===0)continue;const l=s.find(u=>u.type===a);n.push({type:a,displayName:(l==null?void 0:l.displayName)||a,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:c,values:e.values[a]||{}})}return n}function Rn(e){if(!e||typeof e!="object")return!1;const s=e;return(s.sourceMode==="normal"||s.sourceMode==="no-upstream")&&typeof s.disableUpstream=="boolean"&&(s.explicitProviderDir===null||typeof s.explicitProviderDir=="string")&&typeof s.userDir=="string"&&typeof s.upstreamDir=="string"&&Array.isArray(s.providerRoots)}function Yo(e){if(!e||typeof e!="object")return null;if(Rn(e))return e;const s=e,r=s.result;return Rn(r)?r:Rn(s.sourceConfig)?s.sourceConfig:null}function mx(e){const s=e.trim();return s||null}const Xo=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],fx=[{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 px({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[u,p]=o.useState([]),[d,h]=o.useState(""),[f,v]=o.useState([]),[N,m]=o.useState(""),g=o.useRef(null),j=o.useRef(null),b=k=>{p(x=>x.includes(k)?x.filter(E=>E!==k):[...x,k])},C=()=>p([...Xo]),A=()=>p([]);o.useEffect(()=>{var k;(k=g.current)==null||k.scrollIntoView({behavior:"smooth"})},[f]),o.useEffect(()=>()=>{j.current&&clearInterval(j.current)},[]);const w=o.useCallback(()=>{j.current&&clearInterval(j.current),j.current=setInterval(async()=>{try{const k=await r(e,"provider_auto_fix_status",{providerType:s.type});(k==null?void 0:k.running)===!1&&a==="running"&&(i("done"),v(x=>[...x,`
61
- ✅ Auto-fix completed!`]),j.current&&clearInterval(j.current))}catch{}},3e3)},[e,s.type,r,a]),M=async()=>{if(u.length!==0){i("running"),v(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,d?`💬 Comment: ${d}`:"",""]),m("");try{const k=await r(e,"provider_auto_fix",{providerType:s.type,functions:u,agent:c,...d?{comment:d}:{}});k!=null&&k.success&&(k!=null&&k.started||k!=null&&k.running)?(v(x=>[...x,"✅ Agent started. Monitoring progress..."]),w()):(i("error"),m((k==null?void 0:k.error)||"Failed to start auto-fix"))}catch(k){i("error"),m((k==null?void 0:k.message)||"Connection failed")}}},S=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),v(k=>[...k,`
62
- ⚠️ Auto-fix cancelled.`]),i("done"),j.current&&clearInterval(j.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:k=>k.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:fx.map(k=>t.jsxs("button",{onClick:()=>l(k.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===k.value?k.color+"66":"var(--border-subtle)",background:c===k.value?k.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===k.value?k.color:"var(--text-primary)"},children:k.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:k.desc})]},k.value))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:C,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),t.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),t.jsx("button",{onClick:A,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Xo.map(k=>t.jsxs("button",{onClick:()=>b(k),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(k)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(k)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(k)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(k)?"☑ ":"☐ ",k]},k))})]}),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:k=>h(k.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:[f.map((k,x)=>t.jsx("div",{className:k.startsWith("✅")?"text-green-400":"",style:k.startsWith("❌")||k.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:k},x)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:g})]}),N&&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:N})]})]}),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:M,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:S,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"),v([]),m("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function hx({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var w;const i=s.filter(M=>M.category==="ide"),[c,l]=o.useState(((w=i[0])==null?void 0:w.type)||""),[u,p]=o.useState(""),[d,h]=o.useState(""),[f,v]=o.useState(!1),[N,m]=o.useState(""),[g,j]=o.useState(!1),b=M=>{const S=M.toLowerCase().replace(/[^a-z0-9-]/g,"");p(S),(!d||d===C(u))&&h(C(S))},C=M=>M.split("-").map(S=>S.charAt(0).toUpperCase()+S.slice(1)).join(" "),A=async()=>{if(!(!u||!d||!c)){v(!0),m("");try{const M=await r(e,"provider_clone",{type:u,name:d,category:"ide",location:"user",cloneFrom:c});M!=null&&M.success||M!=null&&M.created?(j(!0),a==null||a(u)):m((M==null?void 0:M.error)||"Failed to create provider")}catch(M){m((M==null?void 0:M.message)||"Connection failed")}v(!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:M=>M.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[t.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:g?t.jsxs("div",{className:"text-center py-6",children:[t.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),t.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[t.jsx("code",{className:"text-violet-400",children:u})," has been created at ",t.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",u,"/"]})]}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",t.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",u]})," or use Auto-Fix to implement scripts."]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(M=>t.jsxs("button",{onClick:()=>l(M.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===M.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===M.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:M.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===M.type?"#a78bfa":"var(--text-secondary)"},children:M.displayName})]},M.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:M=>b(M.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:M=>h(M.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"})]}),N&&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:N})]})}),t.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:g?t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:A,disabled:!u||!d||f,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||f?.4:1},children:f?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function xx({machineId:e,providers:s,sendDaemonCommand:r}){var R;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[p,d]=o.useState("all"),[h,f]=o.useState(null),[v,N]=o.useState(!1),[m,g]=o.useState(null),[j,b]=o.useState("normal"),[C,A]=o.useState(""),[w,M]=o.useState(!1),S=o.useCallback(async()=>{if(e)try{const I=await r(e,"get_provider_source_config",{}),P=Yo(I);P&&(g(P),b(P.sourceMode),A(P.explicitProviderDir||""))}catch{}},[e,r]),k=o.useCallback(async()=>{if(e){c(!0);try{const I=await r(e,"get_provider_settings",{}),P=dx(I);if(P){const K=ux(P,s);K.sort((z,L)=>z.category.localeCompare(L.category)||z.displayName.localeCompare(L.displayName)),a(K)}}catch{}c(!1)}},[e,s,r]);o.useEffect(()=>{n.length===0&&k(),m||S()},[]);const x=async(I,P,K)=>{u(`${I}.${P}`),a(z=>z.map(L=>L.type===I?{...L,values:{...L.values,[P]:K}}:L));try{const z=await r(e,"set_provider_setting",{providerType:I,key:P,value:K});z!=null&&z.success||k()}catch{k()}u(null)},E=async()=>{M(!0);try{const I=await r(e,"set_provider_source_config",{providerSourceMode:j,providerDir:mx(C)}),P=Yo(I);P?(g(P),b(P.sourceMode),A(P.explicitProviderDir||"")):await S(),await k()}catch{await S()}M(!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(I=>t.jsx("button",{onClick:()=>d(I),className:`machine-btn text-[10px] px-2 py-0.5 ${p===I?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:I.toUpperCase()},I))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>N(!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:k,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:S,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:j,onChange:I=>b(I.target.value),className:"machine-input text-[11px]",children:[t.jsx("option",{value:"normal",children:"normal"}),t.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),t.jsx("input",{type:"text",value:C,onChange:I=>A(I.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void E(),disabled:w,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:w?"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:"})," ",((R=m==null?void 0:m.providerRoots)==null?void 0:R.join(" → "))||"loading…"]})]})]}),p!=="all"&&n.filter(I=>I.category===p).length>1&&(()=>{const I=n.filter(L=>L.category===p),P=new Map;for(const L of I)for(const T of L.schema){if(T.type!=="boolean")continue;const H=P.get(T.key),B=!!(L.values[T.key]??T.default);H?(H.onCount+=B?1:0,H.total+=1):P.set(T.key,{label:T.label||T.key,onCount:B?1:0,total:1})}const K=[...P.entries()].filter(([,L])=>L.total===I.length);if(K.length===0)return null;const z=async(L,T)=>{for(const H of I)await x(H.type,L,T)};return t.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[t.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",p.toUpperCase()," providers (",I.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:K.map(([L,T])=>{const H=T.onCount===T.total,B=T.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:T.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",T.onCount,"/",T.total,")"]}),t.jsx("button",{onClick:()=>void z(L,!0),disabled:H,className:`machine-btn text-[9px] px-1.5 py-px ${H?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void z(L,!1),disabled:B,className:`machine-btn text-[9px] px-1.5 py-px ${B?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},L)})})]})})(),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(I=>p==="all"||I.category===p).map(I=>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:I.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:I.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:I.category==="acp"?"rgba(139,92,246,0.08)":I.category==="cli"?"rgba(59,130,246,0.08)":I.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:I.category==="acp"?"#a78bfa":I.category==="cli"?"#60a5fa":I.category==="ide"?"#86efac":"var(--status-warning)"},children:I.category}),I.category==="ide"&&t.jsx("button",{onClick:()=>f(s.find(P=>P.type===I.type)||{type:I.type,name:I.displayName,displayName:I.displayName,icon:I.icon,category:I.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:I.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===`${I.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:()=>x(I.type,P.key,!(I.values[P.key]??P.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:I.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:I.values[P.key]??P.default?21:3}})}):P.type==="number"?t.jsx("input",{type:"number",value:Number(I.values[P.key]??P.default??0)||0,min:P.min,max:P.max,onChange:K=>{const z=parseInt(K.target.value)||0;P.min!==void 0&&z<P.min||P.max!==void 0&&z>P.max||x(I.type,P.key,z)},className:"machine-input w-20 text-center text-[11px]"}):P.type==="select"&&P.options?t.jsx("select",{value:String(I.values[P.key]??P.default??""),onChange:K=>x(I.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(I.values[P.key]??P.default??""),onBlur:K=>x(I.type,P.key,K.target.value),className:"machine-input w-[120px] text-[11px]"})})]},P.key))})]},I.type))}),h&&t.jsx(px,{machineId:e,provider:h,sendDaemonCommand:r,onClose:()=>f(null)}),v&&t.jsx(hx,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>N(!1),onCreated:()=>{N(!1),k()}})]})}const bx=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function gx({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function yx(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function vx(e){return e.trim().toLowerCase()}function on(e,s){const r=vx(s);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function Ua(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Qs(e,s=220){const r=Ua(e);return r?r.length>s?`${r.slice(0,s)}…`:r:""}function wx(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 sl(e,s){return e.filter(r=>on([r.level,r.message],s))}function jx(e,s){return e.split(`
63
- `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>on([r],s))}function rl(e,s){return e.filter(r=>on([r.level,r.category,r.stage,r.interactionId,Ua(r.payload)],s))}function nl(e,s){return e.filter(r=>on([r.kind,r.topic,r.interactionId,Ua(r.payload)],s))}function Jo(e){return e==="warn"||e==="error"}function kx({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=>Jo(a.level)).length+r.filter(a=>Jo(a.level)).length}}function Sx({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(`
64
- `)):s.length>0&&a.push(["[daemon logs]",...s].join(`
65
- `)),r.length>0&&a.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${Qs(i.payload,500)}`.trim())].join(`
66
- `)),n.length>0&&a.push(["[browser events]",...n.map(i=>`${new Date(i.ts).toISOString()} ${i.kind}${i.topic?` topic=${i.topic}`:""} ${Qs(i.payload,500)}`.trim())].join(`
67
- `)),a.join(`
68
-
69
- `)}function Nx({daemonLogs:e,trace:s,webEvents:r,daemonLogKind:n,daemonFetchError:a,traceFetchError:i,searchQuery:c}){const l=sl(e,c),u=rl(s,c),p=nl(r,c),d=l.filter(v=>v.level==="warn"||v.level==="error").map(v=>({source:"daemon",level:v.level,timestamp:v.timestamp,label:"daemon",detail:v.message})),h=u.filter(v=>v.level==="warn"||v.level==="error").map(v=>({source:"trace",level:v.level,timestamp:v.ts,label:`${v.category}.${v.stage}`,detail:Qs(v.payload,320)||`${v.category}.${v.stage}`})),f=[...d,...h].sort((v,N)=>N.timestamp-v.timestamp);return{daemonCount:l.length,traceCount:u.length,webCount:p.length,issueCount:f.length,latestIssue:f[0]||null,hasAnyData:n==="text"||l.length>0||u.length>0||p.length>0,hasBlockingError:!!(a||i)}}function Qo(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Zo(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 Pn(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 Cx({machineId:e,sendDaemonCommand:s}){var U,se;const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[u,p]=o.useState([]),[d,h]=o.useState([]),[f,v]=o.useState(0),[N,m]=o.useState(0),[g,j]=o.useState(null),[b,C]=o.useState(!0),[A,w]=o.useState("info"),[M,S]=o.useState("info"),[k,x]=o.useState("all"),[E,R]=o.useState(""),[I,P]=o.useState(!0),[K,z]=o.useState(!0),[L,T]=o.useState(""),[H,B]=o.useState(""),[D,G]=o.useState(0),[J,xe]=o.useState({daemon:!0,trace:!1,web:!1}),re=o.useRef(null),ge=o.useRef(!1),ye=o.useMemo(()=>yx(u,k),[u,k]),Q=o.useMemo(()=>sl(r,E),[r,E]),fe=o.useMemo(()=>jx(c,E),[c,E]),W=o.useMemo(()=>rl(ye,E),[ye,E]),q=o.useMemo(()=>nl(d,E),[d,E]),oe=o.useMemo(()=>M==="issues"?Q.filter(y=>y.level==="warn"||y.level==="error"):M==="info"?Q.filter(y=>y.level!=="debug"):Q,[Q,M]),he=o.useMemo(()=>M==="all"?fe:[],[fe,M]),le=o.useMemo(()=>M==="issues"?W.filter(y=>y.level==="warn"||y.level==="error"):M==="info"?W.filter(y=>y.level!=="debug"):W,[W,M]),ve=o.useMemo(()=>M==="issues"?[]:q,[q,M]),ne=o.useMemo(()=>kx({daemonLogs:Q,daemonRawLines:fe,trace:W,webEvents:q}),[Q,fe,W,q]),pe=o.useMemo(()=>Nx({daemonLogs:r,trace:ye,webEvents:d,daemonLogKind:a,daemonFetchError:L,traceFetchError:H,searchQuery:E}),[L,a,r,ye,E,H,d]),ce=o.useCallback(async()=>{if(!e)return;const[y,X]=await Promise.allSettled([s(e,"get_logs",{count:200,minLevel:A,since:f}),s(e,"get_debug_trace",gx({count:120,since:N,category:k}))]);if(y.status==="fulfilled"){const te=y.value,ue=(te==null?void 0:te.result)||te,we=wx(ue);if(P(!1),T((te==null?void 0:te.success)===!1?String((te==null?void 0:te.error)||"Could not load daemon logs"):""),i(we.kind),l(we.rawText),we.entries.length>0){n(Be=>(f>0?[...Be,...we.entries]:we.entries).slice(-300));const Ne=we.entries.reduce((Be,Ke)=>Math.max(Be,Number(Ke.timestamp||0)),f);Ne>f&&v(Ne)}else we.kind!=="structured"&&f===0&&n([])}else P(!1),T(y.reason instanceof Error?y.reason.message:"Could not load daemon logs");if(X.status==="fulfilled"){const te=X.value,ue=(te==null?void 0:te.result)||te;if((te==null?void 0:te.success)===!1)B(String((te==null?void 0:te.error)||"Could not load daemon trace"));else if(Array.isArray(ue==null?void 0:ue.trace)){B(""),p(ue.trace.slice(-120));const we=ue.trace.reduce((Ne,Be)=>Math.max(Ne,Number(Be.ts||0)),N);we>N&&m(we)}else B(""),p([]);z(!1)}else z(!1),B(X.reason instanceof Error?X.reason.message:"Could not load daemon trace");h(js.list({limit:120})),j(Date.now())},[f,N,A,e,s,k]);o.useEffect(()=>{if(!e||(ce(),!b))return;const y=setInterval(()=>{ce()},3e3);return()=>clearInterval(y)},[b,ce,e,D]),o.useEffect(()=>{if(b&&(oe.length>0||he.length>0||le.length>0||ve.length>0)){const y=ge.current?"smooth":"instant";setTimeout(()=>{var X;(X=re.current)==null||X.scrollIntoView({behavior:y}),ge.current=!0},50)}},[oe.length,he.length,le.length,ve.length,b]),o.useEffect(()=>{p([]),m(0),z(!0)},[k]);const de=((U=pe.latestIssue)==null?void 0:U.level)==="error"?"danger":((se=pe.latestIssue)==null?void 0:se.level)==="warn"?"warning":"good",ae=L||H?"danger":b?"good":"neutral",je=o.useCallback(async()=>{var X;const y=Sx({daemonLogs:oe,daemonRawLines:he,trace:le,webEvents:ve});if(!y.trim()){ct.showToast("복사할 visible logs가 없습니다.","info");return}try{await((X=navigator.clipboard)==null?void 0:X.writeText(y)),ct.showToast("Visible logs를 클립보드에 복사했습니다.","success")}catch(te){ct.showToast(te instanceof Error?te.message:"Could not copy visible logs","warning")}},[oe,he,le,ve]);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(y=>t.jsx("button",{onClick:()=>{w(y),n([]),l(""),i("empty"),v(0),P(!0)},className:`machine-btn text-[10px] px-2 py-0.5 ${A===y?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:y.toUpperCase()},y)),t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider ml-3 mr-1",children:"Trace"}),bx.map(y=>t.jsx("button",{onClick:()=>x(y.value),className:`machine-btn text-[10px] px-2 py-0.5 ${k===y.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:y.label},y.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+ (${ne.info})`},{id:"issues",label:`Issues (${ne.issues})`},{id:"all",label:`All (${ne.all})`}].map(y=>t.jsx("button",{type:"button",onClick:()=>S(y.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${M===y.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:y.label},y.id))}),t.jsx("input",{value:E,onChange:y=>R(y.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:()=>{je()},className:"machine-btn",children:"Copy visible"}),t.jsx("button",{onClick:()=>C(y=>!y),className:`machine-btn ${b?"text-green-500 border-green-500/30":""}`,children:b?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>G(y=>y+1),className:"machine-btn",children:"↻ Refresh"}),t.jsx("button",{onClick:()=>{n([]),l(""),i("empty"),p([]),h([]),v(0),m(0),j(null),T(""),B(""),P(!0),z(!0),js.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 ${Pn(pe.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+he.length," · trace ",le.length," · web ",ve.length]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:E.trim()?`Filtered by “${E.trim()}”`:"Showing the latest buffered entries"})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${Pn(de)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Attention needed"}),pe.latestIssue?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[pe.latestIssue.source," · ",pe.latestIssue.label]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:pe.latestIssue.detail}),t.jsxs("div",{className:"text-[10px] text-text-muted mt-2",children:[pe.issueCount," warn/error signal(s) · ",Qo(pe.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 ${Pn(ae)}`,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:L||H?"Needs attention":b?"Live polling every 3s":"Paused"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",Qo(g)]}),(L||H)&&t.jsxs("div",{className:"text-[11px] text-red-300 mt-2 space-y-1",children:[L&&t.jsxs("div",{children:["Daemon logs: ",L]}),H&&t.jsxs("div",{children:["Daemon trace: ",H]})]})]})]}),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:()=>xe(y=>({...y,daemon:!y.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"?`${he.length} visible raw line(s) from file fallback`:`${oe.length} visible structured line(s)`})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:J.daemon?"Hide":"Show"})]}),J.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:[I&&!pe.hasAnyData&&!L&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!I&&L&&a==="empty"&&t.jsx("div",{className:"p-6 text-center text-red-300",children:L}),!I&&a==="empty"&&!L&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),a==="text"&&he.length===0&&c&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:M==="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"&&he.map((y,X)=>t.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:y},`raw-${X}`)),a!=="text"&&oe.map((y,X)=>t.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Zo(y.level)}`,children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(y.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:y.level==="error"?"ERR":y.level==="warn"?"WRN":y.level==="debug"?"DBG":"INF"}),t.jsx("span",{className:"break-words",children:y.message})]},`log-${X}`))]})]}),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:()=>xe(y=>({...y,trace:!y.trace})),children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",k==="session_host"?" · session_host only":""]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[le.length," visible trace event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:J.trace?"Hide":"Show"})]}),J.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&&le.length===0&&!H&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!K&&H&&le.length===0&&t.jsx("div",{className:"p-6 text-center text-red-300",children:H}),!K&&le.length===0&&!H&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:E.trim()?"No trace entries match the current search.":k==="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."}),le.map(y=>t.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Zo(y.level)}`,children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(y.ts).toLocaleTimeString()}),t.jsx("span",{children:y.level.toUpperCase()}),t.jsxs("span",{children:[y.category,".",y.stage]}),y.interactionId&&t.jsxs("span",{children:["ix=",y.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Qs(y.payload,360)||"No payload"})]},y.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:()=>xe(y=>({...y,web:!y.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:[ve.length," visible browser event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:J.web?"Hide":"Show"})]}),J.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:[ve.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:E.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),ve.map(y=>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(y.ts).toLocaleTimeString()}),t.jsx("span",{children:y.kind}),y.topic&&t.jsxs("span",{children:["topic=",y.topic]}),y.interactionId&&t.jsxs("span",{children:["ix=",y.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Qs(y.payload,360)||"No payload"})]},y.id))]})]})]}),t.jsx("div",{ref:re})]})}function Ix(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 al(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 Mx(e){var a;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=al((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 Ax(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function _n(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 Dn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function En(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function ei(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 Tx(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Lx(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 Rx(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 Px({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),p=zf(e,{enabled:!!e,includeSessions:!0,limit:yo,intervalMs:lm}),d=p.diagnostics,h=p.loading,f=p.applyDiagnostics,v=o.useMemo(()=>Ix({diagnostics:d,loading:h,refreshing:l,error:n}),[d,h,l,n]),N=o.useMemo(()=>new Map(s.map(R=>[R.sessionId||R.id,R])),[s]),m=o.useCallback(async()=>{if(e){u(!0);try{const R=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:yo}),I=Dn(R);if(!(I!=null&&I.success))throw new Error((I==null?void 0:I.error)||"Could not load hosted runtime diagnostics");f(I.diagnostics||I.result||null),a("")}catch(R){const I=R instanceof Error?R.message:"Could not load hosted runtime diagnostics";a(I)}finally{u(!1)}}},[f,e,r]);o.useEffect(()=>{!e||d||h||l||m()},[d,h,e,m,l]);const g=o.useCallback(async(R,I)=>{const P=`${R}:${I.sessionId}`;if(!(R==="session_host_stop_session"&&!window.confirm(`Stop ${I.displayName}?
70
- This will terminate the hosted runtime.`))){c(P);try{const K=await r(e,R,{sessionId:I.sessionId}),z=Dn(K);if(!(z!=null&&z.success))throw new Error((z==null?void 0:z.error)||"Session host action failed");const L=R==="session_host_resume_session"?"resumed":R==="session_host_restart_session"?"restarted":"stopped";ct.showToast(`Session host ${L}: ${I.displayName}`,"success"),await m()}catch(K){const z=K instanceof Error?K.message:"Session host action failed";ct.showToast(z,"warning"),a(z)}finally{c(K=>K===P?null:K)}}},[e,m,r]),j=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
71
- 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 I=await r(e,"session_host_prune_duplicate_sessions",{}),P=Dn(I);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const K=P.result||{},z=Array.isArray(K.prunedSessionIds)?K.prunedSessionIds.length:0,L=typeof K.duplicateGroupCount=="number"?K.duplicateGroupCount:0;ct.showToast(`Pruned ${z} duplicate runtime(s) across ${L} group(s)`,"success"),await m()}catch(I){const P=I instanceof Error?I.message:"Duplicate prune failed";ct.showToast(P,"warning"),a(P)}finally{c(I=>I==="session_host_prune_duplicate_sessions"?null:I)}}},[e,m,r]),b=o.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((R,I)=>(I.lastActivityAt||0)-(R.lastActivityAt||0)),[d==null?void 0:d.sessions]),C=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)||[]}:Mx(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),A=C.liveRuntimes,w=C.recoverySnapshots,M=C.inactiveRecords,S=o.useMemo(()=>Rx(A),[A]),k=o.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),x=o.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(R=>R.level==="warn"||R.level==="error")||null,[d==null?void 0:d.recentLogs]),E=(R,I)=>{var G;const P=i===`session_host_resume_session:${R.sessionId}`,K=i===`session_host_restart_session:${R.sessionId}`,z=i===`session_host_stop_session:${R.sessionId}`,L=al(R.meta),T=N.get(R.sessionId),H=R.attachedClients.length===1?"1 client":`${R.attachedClients.length} clients`,B=I==="recovery"?"Recover":"Resume",D=Ax(I);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:R.displayName||(T==null?void 0:T.cliName)||R.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Lx(R.lifecycle)}`,children:R.lifecycle}),L&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:L})]}),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:R.workspaceLabel||(T==null?void 0:T.runtimeWorkspaceLabel)||R.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:R.runtimeKey}),R.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",R.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((G=R.writeOwner)==null?void 0:G.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Tx(R.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(bi,{size:11})," ",H]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",ei(R.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:[I==="recovery"&&(R.lifecycle==="interrupted"||R.lifecycle==="failed"||R.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{g("session_host_resume_session",R)},children:P?`${B}ing…`:B}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{g("session_host_restart_session",R)},children:K?"Restarting…":"Restart"}),I==="live"&&(R.lifecycle==="running"||R.lifecycle==="starting"||R.lifecycle==="interrupted")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{g("session_host_stop_session",R)},children:z?"Stopping…":"Stop"})]})]})},R.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(ls,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Xm()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[S>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{j()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${S})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${v.toneClass}`,children:v.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{m()},disabled:h||l,children:[t.jsx(er,{size:13}),h||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(qs,{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:w.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:ei(d.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:En(d.hostStartedAt)})]})]}),x&&t.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[t.jsx(qs,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:x.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[En(x.timestamp),x.sessionId?` · ${x.sessionId}`:""]})]}),t.jsxs("div",{className:"mb-4 space-y-4",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(fa,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:_n("live")}),A.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:A.map(R=>E(R,"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(ls,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:_n("recovery")}),w.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:w.map(R=>E(R,"recovery"))})]}),M.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:_n("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:M.map(R=>E(R,"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"}),k.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:k.map(R=>{var P;const I=b.find(K=>K.sessionId===R.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:(I==null?void 0:I.displayName)||((P=N.get(R.sessionId))==null?void 0:P.cliName)||R.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[R.action,R.lifecycle?` · ${R.lifecycle}`:"",R.detail?` · ${R.detail}`:"",R.error?` · ${R.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${R.success===!1?"text-red-300":"text-text-secondary"}`,children:En(R.timestamp)})]},`${R.sessionId}:${R.timestamp}:${R.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 _x({machine:e,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return t.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:t.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[t.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),t.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),t.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?t.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>t.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{a(null),n({cliType:s.cliType,workspaceId:i.id,argsStr:s.argsStr,model:s.model})},children:[t.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:s.cliType,useDefaultWorkspace:!0,argsStr:s.argsStr,model:s.model})},children:"Default workspace"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:s.cliType,useHome:!0,argsStr:s.argsStr,model:s.model})},children:"Home directory"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function $n({icon:e,children:s}){return t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,t.jsx("span",{children:s})]})}function Bn({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 Dx({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=Fs(e,"0.9.8");return t.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[l.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx($n,{icon:t.jsx(Ft,{size:13}),children:"Current Chats"}),t.jsx(Bn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(h=>{const f=Xn(h);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(h),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:st(h)}),f>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Jr(f)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:us(h)})]},h.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx($n,{icon:t.jsx(ji,{size:13}),children:"Recent Launches"}),t.jsx(Bn,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const{metaText:f,updatedLabel:v}=Kc(h);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(h),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:h.label}),v&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:v})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:f})]},h.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx($n,{icon:t.jsx(qs,{size:13}),children:"Daemon Update"}),t.jsx(Bn,{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(er,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Ex(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const $x={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 Ir(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Kn({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:p}){const d=Ms(),{handleLaunchIde:h,handleStopCli:f,handleRestartIde:v,handleStopIde:N,handleDetectIdes:m,launchingIde:g,launchingAgentType:j,addLog:b}=c,[C,A]=o.useState(null),w=o.useCallback(_=>{_&&d(Vt(_))},[d]),M=$x[e],S=e==="ide",k=e==="acp",x=o.useMemo(()=>n.filter(_=>_.category===e&&(e==="ide"||_.installed!==!1)),[e,n]),E=o.useMemo(()=>new Map(x.map(_=>[_.type,_.displayName||_.type])),[x]),[R,I]=o.useState(""),[P,K]=o.useState(""),[z,L]=o.useState([]),[T,H]=o.useState(""),[B,D]=o.useState(""),[G,J]=o.useState([]),[xe,re]=o.useState(!1),[ge,ye]=o.useState(!1),[Q,fe]=o.useState(""),[W,q]=o.useState(!1),[oe,he]=o.useState(()=>pt()),[le,ve]=o.useState(null),[ne,pe]=o.useState(p?"__custom__":u||s.defaultWorkspaceId||""),[ce,de]=o.useState(p||""),[ae,je]=o.useState([]),[U,se]=o.useState(!1),[y,X]=o.useState(""),[te,ue]=o.useState([]),[we,Ne]=o.useState(!1),[Be,Ke]=o.useState(""),Fe=o.useRef(null),[Ue,ot]=o.useState(null),rt=o.useRef("__home__"),[dt,yt]=o.useState("__home__"),[ut,Xe]=o.useState(!1),nt=o.useRef(0),ke=ae.filter(_=>!a.some(ee=>ee.type===_&&bt(ee.status)!=="stopped")),De=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!ne&&pe(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(p){pe("__custom__"),de(p);return}u&&(pe(u),de(""))},[u,p]),o.useEffect(()=>{S||R&&(x.some(_=>_.type===R)||(I(""),D("")))},[x,S,R]);const $e=(()=>{if(ne==="__custom__")return ce.trim();if(!ne)return"";const _=(s.workspaces||[]).find(ee=>ee.id===ne);return(_==null?void 0:_.path)||""})(),tt=o.useCallback(_=>{const ee=De.current[_];ee&&(clearTimeout(ee),delete De.current[_]),je(me=>me.includes(_)?me.filter(Le=>Le!==_):me)},[]),lt=o.useRef(new Set),mt=o.useCallback(async _=>{if(l){Ne(!0),Ke("");try{const ee=await sn(l,r,_);X(ee.path),de(ee.path),ue(ee.directories)}catch(ee){Ke(ee instanceof Error?ee.message:"Could not load folder")}finally{Ne(!1)}}},[r,l]),Z=o.useCallback(()=>{if(!l)return;pe("__custom__"),se(!0);const _=a.map(me=>me.workspace),ee=tn(s.platform,en(ce.trim(),$e,p,_,s.defaultWorkspacePath,(s.workspaces||[]).map(me=>me.path)));mt(ee)},[ce,p,mt,s.defaultWorkspacePath,s.platform,s.workspaces,a,$e,l]),Te=o.useCallback(_=>{const ee=String(_.workspace||"").trim();if(!ee)return;const me=(s.workspaces||[]).find(Le=>Ir(Le.path)===Ir(ee));if(me){pe(me.id),de("");return}pe("__custom__"),de(ee)},[s.workspaces]),Re=o.useCallback(_=>{const ee=String(_.workspace||"").trim();if(!ee)return{workspaceId:null,workspacePath:"",useHome:!0};const me=(s.workspaces||[]).find(Le=>Ir(Le.path)===Ir(ee));return me?{workspaceId:me.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ee,useHome:!1}},[s.workspaces]),at=o.useCallback(async _=>{if(!l||!_||e!=="cli"){J([]),re(!1),ye(!1),fe("");return}const ee=nt.current+1;nt.current=ee,re(!0),fe("");try{const me=await l(r,"list_saved_sessions",{providerType:_,kind:"cli",limit:30});if(nt.current!==ee)return;const Le=(me==null?void 0:me.result)??me;J(Array.isArray(Le==null?void 0:Le.sessions)?Le.sessions:[])}catch(me){if(nt.current!==ee)return;J([]),fe(me instanceof Error?me.message:"Could not load saved sessions")}finally{nt.current===ee&&(re(!1),ye(!0))}},[e,r,l]),ht=o.useMemo(()=>{if(e!=="cli"||!R)return null;const _=E.get(R)||R;return{routeId:r,daemonId:r,providerSessionId:B||void 0,transport:"pty",mode:"chat",agentName:_,agentType:R,status:"idle",title:_,messages:[],ideType:R,workspaceName:$e,displayPrimary:_,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${R}`}},[e,r,E,$e,B,R]),vt=o.useCallback(_=>{if(e==="ide"||!_){L([]);return}L(Qc(r,_))},[e,r]);o.useEffect(()=>{nt.current+=1,D(""),vt(R),ye(!1),J([]),fe(""),re(!1)},[e,vt,at,R]);const We=o.useMemo(()=>G.find(_=>_.providerSessionId===B)||null,[G,B]);o.useEffect(()=>{if(!B)return;const _=G.find(ee=>ee.providerSessionId===B);_!=null&&_.canResume||D("")},[G,B]);const It=o.useCallback((_,ee)=>{Fe.current=ee,rt.current=_.selectedWorkspaceKey||"__home__",yt(_.selectedWorkspaceKey||"__home__"),ot(_)},[]),$=o.useCallback(()=>{Fe.current&&(Xe(!0),Fe.current().finally(()=>{Fe.current=null,Xe(!1),ot(null)}))},[]),O=o.useCallback(_=>{if(!_)return;je(me=>me.includes(_)?me:[...me,_]);const ee=De.current[_];ee&&clearTimeout(ee),De.current[_]=setTimeout(()=>{je(me=>me.includes(_)?me.filter(Le=>Le!==_):me),delete De.current[_]},2e4)},[]);o.useEffect(()=>{for(const ee of a)bt(ee.status)!=="stopped"&&(ae.includes(ee.type)&&!lt.current.has(ee.type)&&(lt.current.add(ee.type),b("info",`${E.get(ee.type)||ee.type} launched`,!0)),tt(ee.type));const _=new Set(a.filter(ee=>bt(ee.status)!=="stopped").map(ee=>ee.type));lt.current.forEach(ee=>{!ae.includes(ee)&&!_.has(ee)&&lt.current.delete(ee)})},[b,tt,a,ae,E]),o.useEffect(()=>()=>{Object.values(De.current).forEach(clearTimeout),De.current={}},[]);const[F,V]=o.useState({}),[ie,Se]=o.useState(null);o.useEffect(()=>{if(!S||!r||!l)return;(async()=>{try{const ee=await l(r,"get_ide_extensions",{}),me=(ee==null?void 0:ee.result)||ee;me!=null&&me.success&&(me!=null&&me.ideExtensions)&&V(me.ideExtensions)}catch{}})()},[S,r,l]);const Ie=_=>S?et(_.type):e==="cli"?_.cliName:_.acpName,Y=S?s.detectedIdes||[]:[],be=o.useCallback(async _=>{const ee=(_==null?void 0:_.type)||R,me=(_==null?void 0:_.workspacePath)??$e;if(S){await h(ee,me?{workspace:me}:void 0)&&O(ee);return}const Le=await c.runLaunchCliCore({cliType:ee,dir:_!=null&&_.workspaceId?void 0:me||void 0,workspaceId:(_==null?void 0:_.workspaceId)||void 0,useHome:(_==null?void 0:_.useHome)||!(_!=null&&_.workspaceId)&&!me,argsStr:(_==null?void 0:_.argsStr)??(P||void 0),model:(_==null?void 0:_.model)??(k&&T||void 0),resumeSessionId:(_==null?void 0:_.resumeSessionId)||!k&&e==="cli"&&ee===R&&B||void 0});if(Le.success||Le.pending){const Ce=(_==null?void 0:_.argsStr)??P;!S&&(Ce!=null&&Ce.trim())&&(Zc(r,ee,Ce),vt(ee)),O(ee),Le.success&&Le.sessionId&&w(Le.sessionId)}},[c,h,k,S,P,T,vt,O,r,w,$e,B,R]),Ee=lc(S?"ide":k?"acp":"cli",!S&&!k&&!!B),Oe=dc(S?"ide":k?"acp":"cli",!S&&!k&&!!B),Je=()=>{var Ce;const _=S?et(R):E.get(R)||R,ee=!S&&!k&&!!B,{options:me,selectedKey:Le}=os({machine:s,currentWorkspaceId:ne&&ne!=="__custom__"?ne:null,currentWorkspacePath:$e});It({title:ee?Ma(_):ss("start-fresh",_),description:ee?Aa():rs("start-fresh"),confirmLabel:Ee,busyLabel:Oe,workspaceOptions:me,selectedWorkspaceKey:Le,details:[{label:"Mode",value:M.label},{label:"Provider",value:_},...!S&&e==="cli"&&B?[{label:"Resume",value:((Ce=G.find(Me=>Me.providerSessionId===B))==null?void 0:Ce.title)||B}]:[],...!S&&P.trim()?[{label:"Arguments",value:P.trim()}]:[],...k&&T.trim()?[{label:"Model",value:T.trim()}]:[]]},async()=>{const Me=me.find(Ae=>Ae.key===rt.current);Me!=null&&Me.workspaceId?(pe(Me.workspaceId),de("")):Me!=null&&Me.workspacePath?(pe("__custom__"),de(Me.workspacePath)):(pe(""),de("")),await be({workspaceId:(Me==null?void 0:Me.workspaceId)??null,workspacePath:(Me==null?void 0:Me.workspacePath)??"",useHome:!(Me!=null&&Me.workspaceId)&&!(Me!=null&&Me.workspacePath)})})},qe=_=>{S?N(_):f(_.type,_.workspace,_.id)},ze=o.useCallback(async(_,ee,me=!1)=>{if(_.mode===ee){me&&_.sessionId&&w(_.sessionId);return}if(!l||!_.sessionId){me&&_.sessionId&&w(_.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:_.sessionId,cliType:_.type,mode:ee}),me&&w(_.sessionId)}catch(Le){const Ce=Ba(Le);$a(Le)?console.warn(Ce?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Le instanceof Error?Le.message:String(Le)):console.error("Failed to switch CLI view mode:",Le)}},[r,w,l]),Pe=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:ne,onChange:_=>{const ee=_.target.value;if(pe(ee),ee==="__custom__"&&l){Z();return}ee!=="__custom__"&&de("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(s.workspaces||[]).length>0?t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map(_=>t.jsxs("option",{value:_.id,children:[_.id===s.defaultWorkspaceId?"⭐ ":"",Zr(_.path,_.label)]},_.id)),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]}):t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]})}),ne==="__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:Z,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:ce,onChange:_=>de(_.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:ne==="__custom__"?$e?t.jsx("span",{className:"font-mono truncate block",title:$e,children:$e}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":$e?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:ne===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:$e,children:$e})]}):"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 ${M.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 ",M.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:S?Y.length>0?Y.map(_=>{const ee=a.find(Ae=>(Ae.type||"").toLowerCase()===(_.type||"").toLowerCase()&&bt(Ae.status)!=="stopped"),me=_.running||!!ee,Le=!!ee&&ee.cdpConnected,Ce=ae.includes(_.type||_.id||""),Me=R===(_.type||"");return t.jsxs("button",{onClick:()=>{if(Le&&ee){const Ae=ee.sessionId;Ae?d(Vt(Ae),{state:{openRemoteForTabKey:Ae}}):d("/dashboard",{state:{openRemoteForTabKey:ee.id}});return}Ce||I(Ae=>Ae===(_.type||"")?"":_.type||"")},disabled:!!g||Ce,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Le?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Me?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:g&&g!==_.type?.4:1},children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(_.type)}),me&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Le?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.name||et(_.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Le?"text-green-400":Ce?"text-orange-400":Me?"text-accent-primary":"text-text-muted"}`,children:Le?"Open Session":Ce?"Starting...":Me?"Configure":"Select"})]})]},_.type)}):t.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",t.jsxs("button",{onClick: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(yd,{size:14})," Scan System"]})]}):x.length>0?x.map(_=>{const ee=R===_.type,me=ae.includes(_.type),Ce=!!a.find(Me=>Me.type===_.type&&bt(Me.status)!=="stopped");return t.jsxs("button",{onClick:()=>I(Me=>Me===_.type?"":_.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ee?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:_.icon}),Ce&&t.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${me?"text-orange-400":ee?"text-accent-primary":"text-text-muted"}`,children:me?"Starting...":ee?"Configure":"Select"})]})]},_.type)}):t.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",t.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),R&&(S?Y.find(_=>_.type===R):x.find(_=>_.type===R))&&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:S?et(R):E.get(R)||R})]}),Pe,!S&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!k&&e==="cli"&&t.jsx(tl,{busy:!!j||!!g||ae.includes(R),savedSessionsLoading:xe,savedSessionsError:Q,selectedSession:We,onRefresh:()=>void at(R),onOpenHistory:()=>{R&&(q(!0),el({hasLoadedInitialResults:ge,isLoading:xe})&&at(R))},onClearSelection:()=>D("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[k&&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:T,onChange:_=>H(_.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:_=>K(_.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"}),z.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:z.map(_=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>K(_),title:_,children:_},_))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:Je,disabled:!!j||!!g||ae.includes(R),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:j===R||g===R?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+ae.filter(_=>!a.some(ee=>ee.type===_&&bt(ee.status)!=="stopped")).length,")"]}),a.length===0&&ke.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 ",M.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[ke.map(_=>t.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i(_)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:S?et(_):E.get(_)||_}),t.jsx("div",{className:"text-[11px] text-text-muted",children:j===_?"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:${_}`)),a.map(_=>{const ee=S?_:null,me=!S&&!k?_:null,Le=bt(_.status);return t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center mb-2",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i(_.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ie(_),(ee==null?void 0:ee.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",ee.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:_.workspace||"—"}),(me==null?void 0:me.mode)&&t.jsx("span",{className:me.mode==="chat"?"text-violet-400":"text-text-secondary",children:me.mode==="chat"?"Chat view":"Terminal view"})]}),me&&(me.runtimeKey||me.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[me.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 ",me.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 Ce;(Ce=navigator.clipboard)==null||Ce.writeText(`adhdev attach ${me.runtimeKey}`),A(me.runtimeKey||null),window.setTimeout(()=>{A(Me=>Me===me.runtimeKey?null:Me)},1200)},children:C===me.runtimeKey?"Copied":"Copy"})]}),me.runtimeWriteOwner&&t.jsx("span",{style:{color:me.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:me.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Ex(me.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 ${Le==="stopped"?"bg-red-500/[0.08] text-red-500":Le==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Le}),S&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Ce=_.sessionId;if(Ce){d(Vt(Ce),{state:{openRemoteForTabKey:Ce}});return}d("/dashboard",{state:{openRemoteForTabKey:_.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:t.jsx(Ct,{size:13})}),t.jsx("button",{onClick:()=>{const Ce=_.workspace||"",{options:Me,selectedKey:Ae}=os({machine:s,currentWorkspacePath:Ce});It({title:ss("restart-ide",et(_.type)),description:rs("restart-ide"),confirmLabel:Cs("restart-ide"),busyLabel:Is("restart-ide"),workspaceOptions:Me,selectedWorkspaceKey:Ae,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:et(_.type)}]},async()=>{const ft=Me.find(Ls=>Ls.key===rt.current),it=(ft==null?void 0:ft.workspacePath)??"";if(it&&it!==Ce){await be({type:_.type,workspacePath:it});return}await v(_)})},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(er,{size:14})})]}),k&&t.jsx("button",{onClick:()=>{const Ce=_.sessionId;Ce&&w(Ce)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!_.sessionId,children:t.jsx(Ft,{size:14})}),me&&Le!=="stopped"&&t.jsxs(t.Fragment,{children:[me.mode&&t.jsx(Na,{mode:me.mode,onChange:Ce=>void ze(me,Ce,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Ce=_.sessionId;Ce&&w(Ce)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!_.sessionId,children:me.mode==="chat"?t.jsx(Ft,{size:14}):t.jsx(Ct,{size:13})})]}),Le==="stopped"?t.jsx("button",{onClick:()=>{const Ce=_.workspace||"",Me=S?et(_.type):Ie(_),{options:Ae,selectedKey:ft}=os({machine:s,currentWorkspacePath:Ce});It({title:ss("restart-stopped",Me),description:rs("restart-stopped"),confirmLabel:Cs("restart-stopped"),busyLabel:Is("restart-stopped"),workspaceOptions:Ae,selectedWorkspaceKey:ft,details:[{label:"Mode",value:M.label},{label:"Provider",value:Me}]},async()=>{const it=Ae.find(Ls=>Ls.key===rt.current);await be({type:_.type,workspaceId:(it==null?void 0:it.workspaceId)??null,workspacePath:(it==null?void 0:it.workspacePath)??"",useHome:!(it!=null&&it.workspaceId)&&!(it!=null&&it.workspacePath)})})},disabled:ae.includes(_.type),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-green-500/20 text-green-400 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",title:"Restart",children:ae.includes(_.type)?"⏳":t.jsx(pa,{size:14})}):t.jsx("button",{onClick:()=>qe(_),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(wt,{size:14})})]})]}),ee&&ee.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ee.aiAgents.map(Ce=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Li(Ce.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Ce.name," · ",bt(Ce.status)]},Ce.id))}),ee&&(F[ee.type]||[]).length>0&&l&&t.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[t.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:(F[ee.type]||[]).map(Ce=>t.jsxs("button",{disabled:ie===`${ee.type}.${Ce.type}`,onClick:async()=>{const Me=`${ee.type}.${Ce.type}`;Se(Me);try{await l(r,"set_ide_extension",{ideType:ee.type,extensionType:Ce.type,enabled:!Ce.enabled}),V(Ae=>({...Ae,[ee.type]:(Ae[ee.type]||[]).map(ft=>ft.type===Ce.type?{...ft,enabled:!ft.enabled}:ft)}))}catch(Ae){console.error("Extension toggle failed:",Ae)}finally{Se(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 ${Ce.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 ${Ce.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Ce.name,t.jsx("span",{className:"text-[9px] font-normal",children:Ce.enabled?"ON":"OFF"})]},Ce.type))})]})]},_.id)})]}),U&&l&&t.jsx(nn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:y,directories:te,busy:we,error:Be,confirmLabel:"Use this folder",onClose:()=>se(!1),onNavigate:_=>{mt(_)},onConfirm:_=>{de(_),pe("__custom__"),se(!1)}}),Ue&&t.jsx(Ha,{title:Ue.title,description:Ue.description,details:Ue.details,workspaceOptions:Ue.workspaceOptions,selectedWorkspaceKey:dt,onWorkspaceChange:_=>{rt.current=_,yt(_)},confirmLabel:Ue.confirmLabel,busyLabel:Ue.busyLabel,busy:ut,onConfirm:$,onCancel:()=>{Fe.current=null,ot(null)}}),W&&ht&&t.jsx(Ta,{activeConv:ht,ides:[],isCreatingChat:!1,isRefreshingHistory:xe,savedSessions:G,isSavedSessionsLoading:xe,isResumingSavedSessionId:le,savedHistoryFilters:oe,onSavedHistoryFiltersChange:he,onClose:()=>q(!1),onNewChat:()=>{D(""),q(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{at(R)},onResumeSavedSession:_=>{if(!_.canResume||le)return;const ee=Re(_);D(_.providerSessionId),Te(_),ve(_.providerSessionId),q(!1),be({type:_.providerType,workspaceId:ee.workspaceId,workspacePath:ee.workspacePath,useHome:ee.useHome,resumeSessionId:_.providerSessionId}).finally(()=>{ve(me=>me===_.providerSessionId?null:me)})}})]})}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 Bx({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:p,initialWorkspacePath:d,sendDaemonCommand:h}){var m;const[f,v]=o.useState(u);o.useEffect(()=>{v(u)},[u]);const N=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(g=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${f===g.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>v(g.id),children:[t.jsx("span",{children:g.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${f===g.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:N[g.id]})]},g.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(m=ti.find(g=>g.id===f))==null?void 0:m.helper})]}),f==="ide"&&t.jsx(Kn,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:p,initialWorkspacePath:d}),f==="cli"&&t.jsx(Kn,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:p,initialWorkspacePath:d}),f==="acp"&&t.jsx(Kn,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:p,initialWorkspacePath:d})]})}function Kx({onNicknameSynced:e}={}){var ve,ne,pe,ce,de,ae,je,U,se;const{id:s}=Hl(),r=Ms(),n=la(),{sendCommand:a}=jt(),i=nr(),c=Nc(),l=tc(),u=l.ides||[],p=l.initialLoaded??!0,d=u.find(y=>y.id===s&&y.type==="adhdev-daemon"),h=u.some(y=>y.type==="adhdev-daemon"),[f,v]=o.useState("workspace"),[N,m]=o.useState("ide"),g=o.useRef(null),[j,b]=o.useState(null),C=o.useRef("__home__"),[A,w]=o.useState("__home__"),[M,S]=o.useState(!1),k=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||f!=="overview")return;const y=d.machine;(typeof(y==null?void 0:y.cpus)!="number"||typeof(y==null?void 0:y.totalMem)!="number"||typeof(y==null?void 0:y.arch)!="string"||typeof(y==null?void 0:y.release)!="string")&&c(s,{minFreshMs:3e4}).catch(()=>{})},[f,c,d,s]),Uf(s&&f==="overview"?[s]:[],{enabled:f==="overview",intervalMs:am});const x=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},E=cx({machineId:s,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:k});o.useEffect(()=>ct.onToast(X=>{l.setToasts(ue=>{if(ue.some(Be=>Be.message===X.message&&X.timestamp-Be.timestamp<3e3))return ue;const Ne={id:X.id,message:X.message,type:X.type,timestamp:X.timestamp,targetKey:X.targetKey,actions:X.actions};return[...ue.slice(-4),Ne]});const te=X.duration||5e3;setTimeout(()=>l.setToasts(ue=>ue.filter(we=>we.id!==X.id)),te)}),[l]);const R=(d==null?void 0:d.availableProviders)||[],I={};for(const y of R)I[y.type]=y.icon;const P=y=>I[y]||"",K=d?{id:d.id,hostname:Ri(d,{fallbackId:d.id}),platform:((ve=d.machine)==null?void 0:ve.platform)||"unknown",arch:((ne=d.machine)==null?void 0:ne.arch)||"",cpus:((pe=d.machine)==null?void 0:pe.cpus)||0,totalMem:((ce=d.machine)==null?void 0:ce.totalMem)||0,freeMem:(de=d.machine)==null?void 0:de.freeMem,availableMem:(ae=d.machine)==null?void 0:ae.availableMem,loadavg:(je=d.machine)==null?void 0:je.loadavg,uptime:(U=d.machine)==null?void 0:U.uptime,release:((se=d.machine)==null?void 0:se.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,z=u.filter(y=>y.daemonId===s&&y.type!=="adhdev-daemon").filter(y=>!Xs(y)&&!gs(y)).map(y=>({id:y.id,sessionId:y.sessionId,type:y.type,version:y.version||"",instanceId:y.instanceId||"",status:y.status,workspace:y.workspace||null,terminals:y.terminals||0,aiAgents:uu(y.aiAgents||(y.agents||[]).map(X=>({id:X.name,name:X.name,status:X.status,version:X.version}))),activeChat:y.activeChat||null,chats:y.chats||[],childSessions:y.childSessions||[],cdpConnected:y.cdpConnected||!1,daemonId:s})),L=u.filter(y=>y.daemonId===s&&Xs(y)).map(y=>({id:y.id,sessionId:y.sessionId,type:y.type,cliName:y.cliName||y.type,status:y.status,workspace:y.workspace||"",activeChat:y.activeChat||null,providerSessionId:y.providerSessionId,mode:y.mode,runtimeKey:y.runtimeKey,runtimeDisplayName:y.runtimeDisplayName,runtimeWorkspaceLabel:y.runtimeWorkspaceLabel,runtimeWriteOwner:y.runtimeWriteOwner||null,runtimeAttachedClients:y.runtimeAttachedClients||[],daemonId:s})),T=u.filter(y=>y.daemonId===s&&gs(y)).map(y=>({id:y.id,sessionId:y.sessionId,type:y.type,acpName:y.cliName||y.type,status:y.status,workspace:y.workspace||"",activeChat:y.activeChat||null,providerSessionId:y.providerSessionId,daemonId:s})),H=d?Tt(d,{fallbackId:s}):"",B="workspace",D=n.state,G=D==null?void 0:D.initialMachineTab,J=D==null?void 0:D.initialWorkspaceCategory,xe=D==null?void 0:D.initialWorkspaceId,re=D==null?void 0:D.initialWorkspacePath,ge=G==="ides"||G==="clis"||G==="acps"?"workspace":G||B,ye=G==="ides"?"ide":G==="clis"?"cli":G==="acps"?"acp":J,Q=[...z.map(y=>{var X,te,ue,we,Ne;return{id:`ide:${y.type}:${y.workspace||""}`,label:((X=y.activeChat)==null?void 0:X.title)||y.type,kind:"ide",providerType:y.type,subtitle:y.workspace||void 0,workspace:y.workspace||void 0,lastLaunchedAt:((Ne=(we=(ue=(te=y.activeChat)==null?void 0:te.messages)==null?void 0:ue.at)==null?void 0:we.call(ue,-1))==null?void 0:Ne.timestamp)||0}}),...L.map(y=>{var X,te,ue,we,Ne;return{id:`cli:${y.type}:${y.workspace||""}`,label:((X=y.activeChat)==null?void 0:X.title)||y.cliName,kind:"cli",providerType:y.type,providerSessionId:y.providerSessionId,subtitle:y.workspace||void 0,workspace:y.workspace||void 0,lastLaunchedAt:((Ne=(we=(ue=(te=y.activeChat)==null?void 0:te.messages)==null?void 0:ue.at)==null?void 0:we.call(ue,-1))==null?void 0:Ne.timestamp)||0}}),...T.map(y=>{var X,te,ue,we,Ne;return{id:`acp:${y.type}:${y.workspace||""}`,label:((X=y.activeChat)==null?void 0:X.title)||y.acpName,kind:"acp",providerType:y.type,providerSessionId:y.providerSessionId,subtitle:ds(y.summaryMetadata)||y.workspace||void 0,workspace:y.workspace||void 0,lastLaunchedAt:((Ne=(we=(ue=(te=y.activeChat)==null?void 0:te.messages)==null?void 0:ue.at)==null?void 0:we.call(ue,-1))==null?void 0:Ne.timestamp)||0}})].sort((y,X)=>(X.lastLaunchedAt||0)-(y.lastLaunchedAt||0)),fe=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(y=>({id:y.id,label:y.title||y.providerName||y.providerType,kind:y.kind,providerType:y.providerType,providerSessionId:y.providerSessionId,subtitle:ds(y.summaryMetadata)||y.workspace||void 0,workspace:y.workspace,summaryMetadata:y.summaryMetadata,lastLaunchedAt:y.lastLaunchedAt})):Q,W=o.useMemo(()=>{var X;const y=((X=l.connectionStates)==null?void 0:X[s||""])||void 0;return u.filter(te=>te.daemonId===s&&te.type!=="adhdev-daemon").flatMap(te=>La(te,{connectionStates:s&&y?{[s]:y}:void 0,defaultConnectionState:y})).filter(te=>!(te.transport==="pty"&&te.mode==="terminal")).sort((te,ue)=>Xn(ue)-Xn(te))},[u,l.connectionStates,s]),q=o.useCallback(y=>{const X=ja(y);X&&r(Vt(X))},[r]),oe=o.useCallback(()=>{g.current&&(S(!0),g.current().finally(()=>{g.current=null,S(!1),b(null)}))},[]),he=o.useCallback(y=>{if(!K)return;const{options:X,selectedKey:te}=os({machine:K,currentWorkspacePath:y.workspace}),ue=async()=>{m(y.kind),v("workspace")};g.current=async()=>{const we=X.find(Ke=>Ke.key===C.current),Ne=(we==null?void 0:we.workspacePath)??null,Be=(we==null?void 0:we.workspaceId)??null;if(y.kind==="ide"&&y.providerType){await E.handleLaunchIde(y.providerType,Ne?{workspace:Ne}:void 0);return}if((y.kind==="cli"||y.kind==="acp")&&y.providerType){await E.runLaunchCliCore({cliType:y.providerType,dir:Be?void 0:Ne||"",workspaceId:Be||void 0,model:y.kind==="acp"&&_i(y.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:y.providerSessionId});return}await ue()},C.current=te,w(te),b({title:y.kind==="ide"?ss("restart-ide",y.label):y.providerSessionId?Ma(y.label):ss("start-fresh",y.label),description:y.kind==="ide"?rs("restart-ide"):y.providerSessionId?Aa():rs("start-fresh"),confirmLabel:y.kind==="ide"?Cs("restart-ide"):y.providerSessionId?Fr(!0):Cs("start-fresh"),busyLabel:y.kind==="ide"?Is("restart-ide"):y.providerSessionId?Ca(!0):Is("start-fresh"),workspaceOptions:X,details:[{label:"Mode",value:y.kind.toUpperCase()},...y.providerType?[{label:"Provider",value:y.providerType}]:[]]})},[E,K]);if(o.useEffect(()=>{v(ge)},[B,ge,s]),o.useEffect(()=>{ye&&m(ye)},[ye,s]),!K)return p?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:x,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 le=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ct,{size:14})," Workspace"]}),count:z.length+L.length+T.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(ls,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Yr,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(vd,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(bd,{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:x,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:[E.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:E.nicknameInput,onChange:y=>E.setNicknameInput(y.target.value),onKeyDown:y=>{y.key==="Enter"&&E.handleSaveNickname(),y.key==="Escape"&&E.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:E.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:()=>E.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:()=>{E.setEditingNickname(!0),E.setNicknameInput(K.machineNickname||"")},title:"Click to set nickname",children:H}),t.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),t.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[t.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[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:le.map(y=>t.jsxs("button",{onClick:()=>v(y.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===y.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[y.label,y.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===y.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:y.count})]},y.id))})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:t.jsx("div",{className:"max-w-7xl mx-auto h-full",children:t.jsxs("div",{className:"h-full",children:[f==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(Dx,{machineEntry:d,providers:R,recentLaunches:fe,currentConversations:W,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:he,onOpenConversation:q}),t.jsx(Bx,{machine:K,machineId:s,providers:R,ideSessions:z,cliSessions:L,acpSessions:T,actions:E,getIcon:P,initialCategory:N,initialWorkspaceId:xe,initialWorkspacePath:re,sendDaemonCommand:a})]}),f==="providers"&&t.jsx(xx,{machineId:s,providers:R,sendDaemonCommand:a}),f==="overview"&&t.jsx(lx,{machineId:s,machine:K,ideSessions:z,cliSessions:L,acpSessions:T,actions:E,sendDaemonCommand:a}),f==="session-host"&&t.jsx(Px,{machineId:s,cliSessions:L,sendDaemonCommand:a}),f==="logs"&&t.jsx(Cx,{machineId:s,sendDaemonCommand:a})]})})}),E.launchPick&&K&&t.jsx(_x,{machine:K,launchPick:E.launchPick,actions:E}),j&&t.jsx(Ha,{title:j.title,description:j.description,details:j.details,workspaceOptions:j.workspaceOptions,selectedWorkspaceKey:A,onWorkspaceChange:y=>{C.current=y,w(y)},confirmLabel:j.confirmLabel,busyLabel:j.busyLabel,busy:M,onConfirm:oe,onCancel:()=>{g.current=null,b(null)}}),t.jsx(uc,{toasts:l.toasts||[],onDismiss:y=>l.setToasts(X=>X.filter(te=>te.id!==y)),onClickToast:y=>{y.targetKey&&r(Vt(y.targetKey))}}),t.jsx("style",{children:`
72
- @keyframes toast-in {
73
- from { opacity: 0; transform: translateX(40px); }
74
- to { opacity: 1; transform: translateX(0); }
75
- }
76
- `})]})}function za(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Ox(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=za();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 $t(e,s){return await fetch(Ox(e),{credentials:"same-origin",...s})}function ol(){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 Wx{constructor(){Ve(this,"adapters",new Map);Ve(this,"states",new Map);Ve(this,"runtimeListeners",new Map);Ve(this,"screenshotCallbacks",new Map);Ve(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 $t(`/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 Ot=new Wx;function Hx(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=za();return r?`${s}?token=${encodeURIComponent(r)}`:s}const Mr=Hx(),si=3e3,Fx=3e4;let Rt=null,Ux=0;const Gr=new Map;let Jt=null,zs=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 $s(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function zx(e){return e==="connected"?"connected":e}async function Er(e,s,r){const n=pc(e,r||{}),a=Rt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++Ux}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{Gr.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);Gr.set(i,{resolve:p=>{clearTimeout(u),c(p)},reject:p=>{clearTimeout(u),l(p)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function aa(e,s){const r=Rt;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}}function Vx(e,s,r){const n=Rt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=pc(e,{sessionId:s,targetSessionId:s,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}class Gx{constructor(s){Ve(this,"daemonId");Ve(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN}get connectionState(){return(Rt==null?void 0:Rt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Er(this.daemonId,s,r)}async sendInput(s,r){return Er(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Jt&&(clearInterval(Jt),Jt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Er(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());Ot.emitScreenshot(this.daemonId,a)}}catch{}};r(),Jt=setInterval(r,2e3)}stopScreenshots(s){Jt&&(clearInterval(Jt),Jt=null)}}let At=null;function qx(e){return(!At||At.daemonId!==e)&&(At=new Gx(e)),At}function Yx({children:e}){const s=o.useRef(Gs()),r=Gs();s.current=r;const{setUserName:n}=cs(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((m,g)=>{l(m),zs==null||zs(m,g)},[]),p=o.useRef(null),d=o.useRef(),h=o.useRef(si),f=o.useRef(!0),v=o.useRef(!1),N=o.useRef("initial_connect");return o.useEffect(()=>{f.current=!0,v.current=!1;function m(){var b,C;if(!f.current||((b=p.current)==null?void 0:b.readyState)===WebSocket.OPEN||((C=p.current)==null?void 0:C.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Mr}...`),$s("connect_attempt",{url:Mr,reason:N.current,delayMs:h.current});let j;try{j=new WebSocket(Mr)}catch(A){console.error("[Standalone WS] Failed to create WebSocket:",A),g();return}p.current=j,j.onopen=()=>{if(!f.current){j.close();return}u("connected"),h.current=si,$s("open",{url:Mr,reason:N.current}),Gt.resubscribeAll({sendData:aa}),console.log("[Standalone WS] Connected")},Rt=j,j.onmessage=A=>{var w,M;try{const S=JSON.parse(A.data);if((S.type==="command_result"||S.type==="error")&&S.requestId){const k=Gr.get(S.requestId);k&&(Gr.delete(S.requestId),S.type==="error"?k.reject(new Error(((w=S.data)==null?void 0:w.message)||"Command failed")):k.resolve(S.data));return}if(S.type==="session_output"){const k=S.sessionId||S.cliId||S.cliType;k&&Ot.emitSessionOutput(k,typeof S.data=="string"?S.data:"",typeof S.seq=="number"?S.seq:void 0);return}if(S.type==="runtime_snapshot"){Ot.emitRuntimeSnapshot(S.sessionId,typeof S.text=="string"?S.text:"",typeof S.seq=="number"?S.seq:0,!!S.truncated,typeof S.cols=="number"?S.cols:void 0,typeof S.rows=="number"?S.rows:void 0);return}if(S.type==="topic_update"){const k=S.update;k&&Gt.publish(k);return}if(S.type==="status"||S.type==="initial_state"){const k=S.data;if(!k)return;const{injectEntries:x,markLoaded:E,getIdes:R}=s.current,I=k.instanceId||"standalone",P=R().find(L=>L.id===I),K=qx(I);Ot.register(I,K),Ot.setState(I,"connected"),u("connected",I),Ot.emitStatus(I,k);const z=Hr(k,{daemonId:I,existingDaemon:P,existingEntries:R()});ri("ws_status",{type:S.type,daemonId:I,sessions:(k.sessions||[]).map(L=>({id:L.id,parentId:L.parentId,providerType:L.providerType,kind:L.kind,transport:L.transport,unread:L.unread,inboxBucket:L.inboxBucket,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,title:L.title})),recentLaunches:(k.recentLaunches||[]).map(L=>({id:L.id,providerType:L.providerType,kind:L.kind,workspace:L.workspace,lastLaunchedAt:L.lastLaunchedAt}))}),ri("entries",{daemonId:I,entries:z.filter(L=>L.type!=="adhdev-daemon").map(L=>({id:L.id,type:L.type,unread:L.unread,inboxBucket:L.inboxBucket,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,sessionId:L.sessionId}))}),z.length>0&&x(z,{authoritativeDaemonIds:[I]}),E(),c.current!==I&&((M=i.current)==null||M.call(i),c.current=I,i.current=Gt.subscribe({sendData:aa},I,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${I}`,params:{includeSessions:!0}},L=>{if(L.topic!=="daemon.metadata")return;const T=s.current.getIdes(),H=T.find(D=>D.id===I),B=Hr(L.status,{daemonId:I,existingDaemon:H,existingEntries:T,timestamp:L.timestamp});B.length>0&&s.current.injectEntries(B),L.userName&&a.current&&a.current(L.userName)}))}}catch(S){console.error("[Standalone WS] Parse error:",S)}},j.onclose=A=>{f.current&&(At==null||At.stopScreenshots(),At&&Ot.setState(At.daemonId,"disconnected"),u("disconnected"),p.current=null,N.current=`close:${A.code}${A.wasClean?":clean":":unclean"}`,$s("close",{code:A.code,reason:A.reason||"",wasClean:A.wasClean}),g())},j.onerror=A=>{v.current||!f.current||(N.current="error",$s("error",{message:A instanceof Event?"event":String(A),readyState:j.readyState}),console.warn("[Standalone WS] Error, will reconnect:",A))}}function g(){if(!f.current)return;clearTimeout(d.current);const j=h.current;console.log(`[Standalone WS] Reconnecting in ${j}ms...`),$s("schedule_reconnect",{reason:N.current,delayMs:j}),d.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,Fx),m()},j)}return m(),()=>{var j;f.current=!1,v.current=!0,(j=i.current)==null||j.call(i),i.current=null,c.current=null,clearTimeout(d.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,Rt=null),At&&(At.stopScreenshots(),Ot.unregister(At.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function Xx({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(zs=(c,l)=>{r(c),l&&a(l)},()=>{zs=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=zx(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(id,{connectionOverrides:i,children:t.jsx(Yx,{children:e})})}const il="adhdev_standalone_font_preferences",is={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"}],Zs=[{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"}],Jx=new Set(cn.map(e=>e.id)),Qx=new Set(Zs.map(e=>e.id));function Kt(e){const s=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:$r("chat",s.chat),code:$r("code",s.code),terminal:$r("terminal",s.terminal)}}function $r(e,s){const r=is[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"?Jx:Qx).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function Br(e,s){var a;const r=$r(e,s);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?cn:Zs;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function Zx(e){const s=Kt(e),r=Br("chat",s.chat),n=Br("code",s.code),a=Br("terminal",s.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Zt(e,s=document.documentElement){const r=Kt(e),n=Zx(r);s.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))s.style.setProperty(a,i);return r}function oa(e){const s=Kt(e);try{localStorage.setItem(il,JSON.stringify(s))}catch{}return s}function eb(){try{const e=localStorage.getItem(il);if(e)return Kt(JSON.parse(e))}catch{}return is}function tb(){return Zt(eb())}function Bs(e,s){var n;const r=e==="chat"?cn:Zs;return((n=r.find(a=>a.id===s))==null?void 0:n.label)||r[0].label}const sb=[{id:"dashboard",path:"/dashboard",icon:t.jsx(xi,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(ls,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(Yr,{}),label:"Settings"}];function rb({children:e}){const s=Ms(),r=la(),n=o.useMemo(()=>sb.map(i=>({...i,active:r.pathname.startsWith(i.path),onSelect:()=>s(i.path)})),[r.pathname,s]),a=o.useMemo(()=>[{id:"docs",label:t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Docs"}),t.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:t.jsx(gi,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:t.jsx(yi,{}),active:r.pathname==="/about",onSelect:()=>s("/about"),title:"About"}],[r.pathname,s]);return t.jsx(xf,{brand:({collapsed:i})=>t.jsxs(t.Fragment,{children:[t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&t.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:i})=>i?null:t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.8"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,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"})]}),children:e})}const nb=[{icon:t.jsx(ls,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Ft,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(vi,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Ct,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(Ys,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(gi,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],ab=[{icon:t.jsx(jd,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(xi,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(Xr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(xd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(bi,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(gd,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],ob=[{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 ib(){return t.jsxs(gc,{icon:t.jsx(yi,{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.9.8"]}),children:[t.jsx(Nt,{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(Nt,{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:nb.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(Nt,{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:hc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:bc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:xc.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(Nt,{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:ab.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(Nt,{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:ob.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(vc,{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(Rd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function On(e,s,r){return{...e,[s]:r}}function Wn({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:Br(e,n)})]})]})]})}function cb({value:e,savedValue:s,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:u}){const p=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(Wn,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:cn,onChange:d=>i(On(e,"chat",d))}),t.jsx(Wn,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Zs,onChange:d=>i(On(e,"code",d))}),t.jsx(Wn,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Zs,onChange:d=>i(On(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: ",Bs("chat",e.chat.preset)," · Code: ",Bs("code",e.code.preset)," · Terminal: ",Bs("terminal",e.terminal.preset)]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Bs("chat",is.chat.preset)," / ",Bs("code",is.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||!p,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||!p,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 lb(){const{ides:e}=cs(),s=e.find(W=>W.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=jt(),{userName:a}=cs(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[p,d]=o.useState(null),[h,f]=o.useState(is),[v,N]=o.useState(!1),[m,g]=o.useState(""),[j,b]=o.useState(""),[C,A]=o.useState("127.0.0.1"),[w,M]=o.useState(""),[S,k]=o.useState(""),[x,E]=o.useState(""),[R,I]=o.useState(""),[P,K]=o.useState(""),[z,L]=o.useState(!1),T=async()=>{const q=await(await $t("/auth/session")).json();u(q)},H=async()=>{const q=await(await $t("/api/v1/standalone/preferences")).json();d(q),A(q.standaloneBindHost);const oe=Kt(q.standaloneFontPreferences);f(oe),Zt(oe),oa(oe)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([T(),H()]).catch(W=>{I(W instanceof Error?W.message:String(W))})},[]),o.useEffect(()=>{Zt(h)},[h]);const B=W=>{const q=W.target.value.trim();s!=null&&s.id&&q!==a&&n(s.id,"set_user_name",{userName:q}).catch(console.error)},[D,G]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),J=W=>{G(W);try{localStorage.setItem("adhdev_sound",W?"1":"0")}catch{}},xe=async()=>{g(""),b(""),N(!0);try{const W=Kt(h),q=await $t("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:W})}),oe=await q.json();if(!q.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to save standalone font preferences");const he=Kt(oe.standaloneFontPreferences);d(oe),f(he),Zt(he),oa(he),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(W){g(W instanceof Error?W.message:String(W))}finally{N(!1)}},re=()=>{const W=Kt(p==null?void 0:p.standaloneFontPreferences);g(""),b(""),f(W),Zt(W)},ge=()=>{g(""),b(""),f(is),Zt(is)},ye=async()=>{I(""),K(""),L(!0);try{const W=await $t("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),q=await W.json();if(!W.ok)throw new Error((q==null?void 0:q.error)||"Failed to save standalone network preference");d(q),A(q.standaloneBindHost),K(q.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){I(W instanceof Error?W.message:String(W))}finally{L(!1)}},Q=async()=>{if(I(""),K(""),S.trim().length<4){I("Password must be at least 4 characters.");return}if(S!==x){I("New password and confirmation do not match.");return}L(!0);try{const W=await $t("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,newPassword:S})}),q=await W.json();if(!W.ok)throw new Error((q==null?void 0:q.error)||"Failed to save password");u(q),await H(),M(""),k(""),E(""),K(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),ol()}catch(W){I(W instanceof Error?W.message:String(W))}finally{L(!1)}},fe=async()=>{I(""),K(""),L(!0);try{const W=await $t("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,clear:!0})}),q=await W.json();if(!W.ok)throw new Error((q==null?void 0:q.error)||"Failed to clear password");u(q),await H(),M(""),k(""),E(""),K("Standalone password disabled.")}catch(W){I(W instanceof Error?W.message:String(W))}finally{L(!1)}};return t.jsxs(gc,{icon:t.jsx(Yr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(gr,{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(gr,{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(Nt,{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.9.8"]}),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:(p==null?void 0:p.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:(p==null?void 0:p.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(Nt,{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:C==="127.0.0.1",onChange:()=>A("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:C==="0.0.0.0",onChange:()=>A("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:()=>{ye()},disabled:z,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:z?"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 ",(p==null?void 0:p.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),t.jsx(Nt,{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."}),R&&t.jsx(gr,{variant:"error",children:R}),P&&t.jsx(gr,{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:w,onChange:W=>M(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:S,onChange:W=>k(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:x,onChange:W=>E(W.target.value)})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{Q()},disabled:z,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:z?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&t.jsx("button",{type:"button",onClick:()=>{fe()},disabled:z,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(Nt,{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(Nt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(Nf,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Nt,{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(Af,{})]}),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($f,{})]}),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(cb,{value:h,savedValue:Kt(p==null?void 0:p.standaloneFontPreferences),saving:v,error:m,notice:j,onChange:f,onSave:()=>{xe()},onResetToSaved:re,onResetToDefaults:ge})]}),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(Of,{})]})]})}),t.jsx(Nt,{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(jf,{}),t.jsx(Qt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ld,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:D,onChange:J})]})}),t.jsx(Nt,{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(hd,{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:B,onKeyDown:W=>{W.key==="Enter"&&W.currentTarget.blur()}})]})})})]})}pf();Df();tb();const db=fi({baseUrl:"",getToken:za});function ub({children:e}){const[s,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[p,d]=o.useState(!1),h=async()=>{a(!0),u("");try{const N=await(await $t("/auth/session")).json();r(N)}catch(v){u(v instanceof Error?v.message:String(v))}finally{a(!1)}};o.useEffect(()=>{h()},[]),o.useEffect(()=>{if(!s||s.required&&!s.authenticated)return;let v=!1;return(async()=>{try{const N=await $t("/api/v1/standalone/preferences");if(!N.ok)return;const m=await N.json();if(v)return;const g=Kt(m.standaloneFontPreferences);Zt(g),oa(g)}catch{}})(),()=>{v=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const f=async v=>{v.preventDefault(),d(!0),u("");try{const N=await $t("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),m=await N.json();if(!N.ok)throw new Error((m==null?void 0:m.error)||"Login failed");r(m),c(""),ol()}catch(N){u(N instanceof Error?N.message:String(N))}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:f,children:[t.jsx("input",{type:"password",value:i,onChange:v=>c(v.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:p||!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:p?"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 ni(){const{ides:e,initialLoaded:s}=cs();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(Un,{to:`/machines/${r.id}`,replace:!0}):t.jsx(Un,{to:"/dashboard",replace:!0})}function mb(){const e=o.useMemo(()=>({sendCommand:Er,sendData:aa,sendPtyInput:Vx}),[]);return t.jsx(Fl,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(dd,{client:db,children:t.jsx(ub,{children:t.jsx(Xx,{children:t.jsx(md,{value:e,children:t.jsx(rb,{children:t.jsxs(Ul,{children:[t.jsx(Yt,{path:"/dashboard",element:t.jsx(ix,{})}),t.jsx(Yt,{path:"/machine",element:t.jsx(ni,{})}),t.jsx(Yt,{path:"/machines/:id",element:t.jsx(Kx,{})}),t.jsx(Yt,{path:"/machines",element:t.jsx(ni,{})}),t.jsx(Yt,{path:"/about",element:t.jsx(ib,{})}),t.jsx(Yt,{path:"/settings",element:t.jsx(lb,{})}),t.jsx(Yt,{path:"*",element:t.jsx(Un,{to:"/dashboard",replace:!0})})]})})})})})})})}_m({connectionManager:Ot});zl(document.getElementById("root")).render(t.jsx(mb,{}));