@adhdev/daemon-standalone 0.9.77-rc.50 → 0.9.77-rc.57

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.
@@ -0,0 +1,170 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-Cn_eJIrc.js","assets/vendor-BoAU5RMW.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
+ var jf=Object.defineProperty;var Nf=(e,t,r)=>t in e?jf(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var ee=(e,t,r)=>Nf(e,typeof t!="symbol"?t+"":t,r);import{r as c,j as s,M as Ro,a as Cf,b as Tf,c as If,R as Et,d as hn,t as Af,e as Mf,u as Nr,D as _f,f as Yi,g as Ji,h as Po,i as Rf,k as Pf,l as Lf,B as Ef,m as Df,n as ps,N as Qi,o as $f}from"./vendor-BoAU5RMW.js";import*as ze from"path";import{join as ks}from"path";import{mkdir as Bf,realpath as Hc,stat as Of,access as Ff}from"fs/promises";import*as Dt from"fs";import{existsSync as Ot,mkdirSync as Lo,readFileSync as Ma,writeFileSync as _a,chmodSync as Wf,statSync as Uf,appendFileSync as Td,renameSync as Kf,constants as Hf}from"fs";import{execFile as Id,execSync as zf,exec as Vf}from"child_process";import{promisify as Ad}from"util";import*as vt from"os";import{homedir as Gf}from"os";import{randomUUID as yn}from"crypto";import{EventEmitter as qf}from"events";import"net";import"http";import"module";import"stream";import"chokidar";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.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 o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).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 Xf(e={}){const t=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>t&&r.splice(0,r.length-t),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 pr=Xf();function zc(e){const t={};for(const r of e)r.transport&&(t[r.transport]=(t[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:t}}function Yf(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Md(e,t){if(!e)return t??null;if(!t)return e??null;const r=Object.prototype.hasOwnProperty.call(e,"messages"),n=Object.prototype.hasOwnProperty.call(e,"activeModal");return{...t,...e,messages:r?e.messages??[]:t.messages,activeModal:n?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}}function qr(e,t){const r=Yf(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(t==null?void 0:t.parentSessionId)??null,providerSessionId:e.providerSessionId??(t==null?void 0:t.providerSessionId),providerName:r??(t==null?void 0:t.providerName)??(t==null?void 0:t.cliName)??(t==null?void 0:t.type)??e.providerName??e.providerType,title:e.title??(t==null?void 0:t.title)??r??(t==null?void 0:t.providerName)??e.providerName??e.providerType,workspace:e.workspace??(t==null?void 0:t.workspace)??null,mode:e.mode??(t==null?void 0:t.mode),capabilities:e.capabilities??(t==null?void 0:t.sessionCapabilities)??(t==null?void 0:t.capabilities)??[],cdpConnected:e.cdpConnected??(t==null?void 0:t.cdpConnected),activeChat:Md(e.activeChat,t==null?void 0:t.activeChat),controlValues:e.controlValues??(t==null?void 0:t.controlValues),providerControls:e.providerControls??(t==null?void 0:t.providerControls),summaryMetadata:e.summaryMetadata??(t==null?void 0:t.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(t==null?void 0:t.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(t==null?void 0:t.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(t==null?void 0:t.lastMessagePreview),lastMessageRole:e.lastMessageRole??(t==null?void 0:t.lastMessageRole),lastMessageAt:e.lastMessageAt??(t==null?void 0:t.lastMessageAt),lastMessageHash:e.lastMessageHash??(t==null?void 0:t.lastMessageHash),unread:e.unread??(t==null?void 0:t.unread),lastSeenAt:e.lastSeenAt??(t==null?void 0:t.lastSeenAt),inboxBucket:e.inboxBucket??(t==null?void 0:t.inboxBucket),completionMarker:e.completionMarker??(t==null?void 0:t.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(t==null?void 0:t.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(t==null?void 0:t.surfaceHidden),resume:e.resume??(t==null?void 0:t.resume),runtimeKey:e.runtimeKey??(t==null?void 0:t.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(t==null?void 0:t.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(t==null?void 0:t.runtimeWorkspaceLabel),settings:e.settings??(t==null?void 0:t.settings)}}function _d(e,t,r){if(!(t!=null&&t.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const n=t.map(a=>{const i=e.find(o=>o.id===a.id);return i?qr(a,i):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(t.map(i=>i.id));for(const i of e)a.has(i.id)||n.push(i)}return n}function Vc(e){return!!e&&typeof e=="object"&&"text"in e}function Eo(e,t){const r=(t==null?void 0:t.joiner)??" ",n=(t==null?void 0:t.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(i=>typeof i=="string"?i:Vc(i)?String(i.text||""):"").join(r):Vc(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function fr(e){return Eo(e,{normalizeWhitespace:!0})}const Rd=c.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,connectionRetryStatuses:void 0}),Pd=c.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Gc(e){var r,n;let t=0;return e.activeChat!==void 0&&(t+=4),(r=e.childSessions)!=null&&r.length&&(t+=2),e.workspace&&(t+=1),e.machine&&(t+=1),(n=e.agents)!=null&&n.length&&(t+=1),t}function Ld(e,t,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=t.version??r.version??e.version,i=t.serverVersion??e.serverVersion??r.serverVersion,o=t.versionMismatch===!0||e.versionMismatch===!0,l=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,d=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),i&&(n.serverVersion=i),d&&(n.versionUpdateReason=d),a&&i&&a===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||o&&a&&i&&a!==i)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function Jf(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function ei(e){if(!e||typeof e!="object")return"";const t=e,r=Jf(fr(t.content).slice(0,512));return[String(t.id||""),String(t._localId||""),String(t._turnKey||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),r].join(":")}function Qf(e,t){if(!Array.isArray(e))return e;if(t!=null&&t.has(e))return{count:e.length,sharedRef:!0};let r=2166136261;for(const n of e){const a=ei(n);for(let i=0;i<a.length;i+=1)r^=a.charCodeAt(i),r=Math.imul(r,16777619)>>>0}return{count:e.length,hash:r.toString(16).padStart(8,"0"),first:ei(e[0]),last:ei(e[e.length-1])}}function Zi(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function eo(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(Zi(e)&&Zi(t)){const o=e.messages;Array.isArray(o)&&o===t.messages&&r.add(o)}if(Array.isArray(e)&&Array.isArray(t)){const o=Math.min(e.length,t.length);for(let l=0;l<o;l+=1)eo(e[l],t[l],r);return}const n=e,a=t,i=new Set([...Object.keys(n),...Object.keys(a)]);for(const o of i)o!=="messages"&&eo(n[o],a[o],r)}function en(e,t){return Array.isArray(e)?e.map(r=>en(r,t)):!e||typeof e!="object"?e:Zi(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Qf(a,t):en(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,en(n,t)]))}function Zf(e,t){try{const r=new WeakSet;return eo(e,t,r),JSON.stringify(en(e,r))===JSON.stringify(en(t,r))}catch{return!1}}function to(e,t,r){return Zf(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Ed(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function em(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function qc(e,t,r,n){var l;const a=(l=t.chats)!=null&&l.length?t.chats:e.chats,i=_d(e.childSessions,t.childSessions,{preserveMissing:n}),o=Md(t.activeChat,e.activeChat);return Ld(e,t,{...e,...t,chats:a,childSessions:i,activeChat:o,_lastUpdate:r})}function tm(e,t,r){var a,i;const n={};t.status&&t.status!==e.status&&(n.status=t.status),t.cdpConnected!==void 0&&(n.cdpConnected=t.cdpConnected),t.childSessions!==void 0&&(n.childSessions=_d(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((i=e.chats)!=null&&i.length)&&(n.chats=t.chats);for(const o 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","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])em(n,t,o);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function sm(e,t,r,n){const a=tm(e,t,n),i=Object.keys(a).length>0?Ld(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return to(e,i,r)}function rm(e){const t=new Set(e.map(i=>i.id)),r=new Set,n=new Set,a=new Set;for(const i of e){const o=Ed(i);o&&r.add(o),o&&i.type!=="adhdev-daemon"&&n.add(o),o&&i.type==="adhdev-daemon"&&i._sessionListAuthoritative&&a.add(o)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function nm(e,t,r,n,a,i){return!a.has(t)||!i.has(t)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function am(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function im(e,t,r){var h,f;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(m=>({...m,_lastUpdate:n}));const i=new Map;for(const m of t)i.set(m.id,m);const{incomingIds:o,incomingDaemonIds:l,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:u}=rm(e);for(const m of e){const v=i.get(m.id);if(!v){i.set(m.id,{...m,_lastUpdate:n});continue}const b=Gc(m),p=Gc(v),g=Ed(m),y=!a.has(g);if(b>p){const j=qc(v,m,n,y);i.set(m.id,to(v,j,n));continue}if(b<p){i.set(m.id,sm(v,m,n,y));continue}const x=m.timestamp||n,N=v._lastUpdate||v.timestamp||0;if(x>=N){const j=qc(v,m,n,y);i.set(m.id,to(v,j,n));continue}(h=m.chats)!=null&&h.length&&!((f=v.chats)!=null&&f.length)&&i.set(m.id,{...v,chats:m.chats})}for(const[m,v]of i){const b=v.daemonId||m.split(":")[0];if(!l.has(b))continue;if(a.has(b)&&u.has(b)&&!o.has(m)){i.delete(m);continue}const p=n-(v._lastUpdate||v.timestamp||0);nm(v,b,p,o,a,d)&&i.delete(m)}for(const[m,v]of i){const b=v.daemonId||m.split(":")[0];if(am(v,b,l,d,i))continue;n-(v._lastUpdate||v.timestamp||0)>3e5&&v.status!=="online"&&i.delete(m)}return Array.from(i.values())}function om(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function cm({children:e,connectionOverrides:t}){const[r,n]=c.useState([]),[a,i]=c.useState(!1),[o,l]=c.useState([]),[d,u]=c.useState(void 0),h=c.useRef(r);c.useEffect(()=>{h.current=r},[r]);const f=c.useCallback((y,x)=>{n(N=>{let j=!1;const w=N.map(A=>A.id!==y||A.chats===x?A:(j=!0,{...A,chats:x}));return j?w:N})},[]),m=c.useCallback((y,x)=>{n(N=>{const j=N.length===0?y:im(y,N,x),w=!om(N,j);return w&&pr.record({kind:"dashboard.entries_applied",payload:{incoming:zc(y),next:zc(j)}}),w?j:N})},[]),v=c.useCallback(()=>i(!0),[]),b=c.useMemo(()=>({injectEntries:m,markLoaded:v,getIdes:()=>h.current}),[m,v]),p=t,g=c.useMemo(()=>({ides:r,updateRouteChats:f,initialLoaded:a,toasts:o,setToasts:l,wsStatus:(p==null?void 0:p.wsStatus)??"connected",isConnected:(p==null?void 0:p.isConnected)??!0,connectionStates:(p==null?void 0:p.connectionStates)??{},connectionTransports:(p==null?void 0:p.connectionTransports)??{},showReconnected:(p==null?void 0:p.showReconnected)??!1,retryConnection:p==null?void 0:p.retryConnection,retryServerConnection:p==null?void 0:p.retryServerConnection,connectionLoginUrl:p==null?void 0:p.connectionLoginUrl,isP2PActive:(p==null?void 0:p.isP2PActive)??!1,p2pStates:(p==null?void 0:p.p2pStates)??{},userRole:p==null?void 0:p.userRole,connectionRetryStatuses:p==null?void 0:p.connectionRetryStatuses,userName:d,setUserName:u}),[r,f,a,o,p==null?void 0:p.wsStatus,p==null?void 0:p.isConnected,p==null?void 0:p.connectionStates,p==null?void 0:p.connectionTransports,p==null?void 0:p.showReconnected,p==null?void 0:p.retryConnection,p==null?void 0:p.retryServerConnection,p==null?void 0:p.connectionLoginUrl,p==null?void 0:p.isP2PActive,p==null?void 0:p.p2pStates,p==null?void 0:p.userRole,p==null?void 0:p.connectionRetryStatuses,d]);return s.jsx(Pd.Provider,{value:b,children:s.jsx(Rd.Provider,{value:g,children:e})})}function Ss(){return c.useContext(Rd)}function pn(){return c.useContext(Pd)}function Dd(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${t}${l.startsWith("/")?"":"/"}${l}`}function i(l){const d=r==null?void 0:r(),u=a(l),h=l.startsWith("http")?new URL(u):new URL(u,typeof window<"u"?window.location.origin:"http://localhost");return d&&h.searchParams.set("token",d),!l.startsWith("http")&&!t?`${h.pathname}${h.search}${h.hash}`:h.toString()}async function o(l,d={}){const u={"Content-Type":"application/json",...d.headers||{}},h=r==null?void 0:r();h&&(u.Authorization=`Bearer ${h}`);const f=a(l),m=new AbortController,v=setTimeout(()=>m.abort(),15e3);try{const b=await fetch(f,{...d,headers:u,signal:m.signal});if(b.status===401)throw n==null||n(),new Error("Unauthorized");if(!b.ok){const p=await b.json().catch(()=>({error:b.statusText}));throw new Error(p.error||`API Error: ${b.status}`)}return b.json()}finally{clearTimeout(v)}}return{getDaemons:()=>o("/api/v1/daemons"),getDaemonStatus:l=>o(`/api/v1/daemons/${l}/status`),sendCommand:(l,d,u={})=>o(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:d,payload:u})}),execTerminal:(l,d,u)=>o(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:u})}),sendAgentMessage:(l,d,u)=>o(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:u})}),getAgentStatus:l=>o(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,d,u)=>o(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:u?"approve":"reject"})}),getMuxState:l=>o(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>o(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,d,u={})=>o(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:u})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:o}}const lm=Dd({baseUrl:"http://localhost:3847"}),dm=c.createContext(lm);function um({client:e,children:t}){return s.jsx(dm.Provider,{value:e,children:t})}const hm={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},$d=c.createContext(hm);function pm({value:e,children:t}){return s.jsx($d.Provider,{value:e,children:t})}function Ct(){return c.useContext($d)}function fm(e){let t=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)t^=n.charCodeAt(a),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function mm(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function xm(e){return e?fm([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),mm(e.content)]):""}const He={size:18};function Bd({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function Do({size:e=He.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function ys({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),s.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),s.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),s.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function Od({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"9",cy:"7",r:"4"}),s.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),s.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function gm({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function bm({size:e=He.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.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 Fd({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),s.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"}),s.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),s.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function ym({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.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"}),s.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),s.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),s.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),s.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function Ra({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.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 Wd({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),s.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function vm({size:e=He.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function cs({size:e=He.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.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 Bt({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function $o({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("polyline",{points:"14 2 14 8 20 8"}),s.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),s.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function wm({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function zs({size:e=He.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.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 vn({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function fn({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.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"}),s.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function mr({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M12 22v-5"}),s.jsx("path",{d:"M9 8V2"}),s.jsx("path",{d:"M15 8V2"}),s.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function Rn({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"5",r:"2"}),s.jsx("circle",{cx:"5",cy:"19",r:"2"}),s.jsx("circle",{cx:"19",cy:"19",r:"2"}),s.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),s.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),s.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function Sm({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"12 2 2 7 12 12 22 7 12 2"}),s.jsx("polyline",{points:"2 12 12 17 22 12"}),s.jsx("polyline",{points:"2 17 12 22 22 17"})]})}function Ud({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Bo({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.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"}),s.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"}),s.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Kd({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function km({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),s.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),s.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function Oo({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"4 17 10 11 4 5"}),s.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function jm({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Fo({size:e=He.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Hd({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function It({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Nm({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.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"}),s.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"}),s.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),s.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function Cm({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),s.jsx("path",{d:"M12 2v6"}),s.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Tm({size:e=He.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.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 Im({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),s.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 Pa({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function Am({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"5"}),s.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),s.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),s.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),s.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),s.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),s.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),s.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),s.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function Mm({size:e=He.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function _m({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Rm({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),s.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Pm({size:e=He.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function Lm({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),s.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 Em({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.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"}),s.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"}),s.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 Dm({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),s.jsx("path",{d:"M13 2h9v9"}),s.jsx("path",{d:"M22 2L13 11"})]})}function $m({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function Bm({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),s.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),s.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),s.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),s.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),s.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),s.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),s.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),s.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),s.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function Om({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),s.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 Fm({size:e=He.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const Wo="adhdev_chat_activity_visible",Xc=new Set(["hidden","debug","internal"]),Yc=new Set(["visible","user","chat"]),Wm=new Set(["debug","trace","internal"]),Um=new Set(["tool_call","terminal_command","runtime_activity"]),Km=new Set(["runtime_status","provider_chrome","control"]),Hm=new Set(["thought","tool","terminal"]);function zd(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function er(e){return typeof e=="string"?e.trim().toLowerCase():""}function ti(e,t,r){return e[r]??(t==null?void 0:t[r])}function Jc(e,t,r){const n=e;return r.some(a=>n[a]===!0||(t==null?void 0:t[a])===!0)}function zm(e,t){const r=er(e.kind);return r||(t==="tool"?"tool":"standard")}function si(e,t,r){const n=zd(e),a=typeof(n==null?void 0:n.label)=="string"?n.label.trim():"";return a||(t==="terminal"||r==="terminal_command"?"Terminal":t==="tool"||r==="tool_call"?"Tool":t==="thought"?"Thought":r==="runtime_activity"?"Runtime":"Activity")}function Vm(e){const t=e.content;return Array.isArray(t)&&t.some(r=>!!r&&typeof r=="object"&&r.type!=="text")}function Uo(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=zd(e),r=er(e.role),n=zm(e,r),a=er(ti(e,t,"visibility")),i=er(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),o=er(ti(e,t,"audience")),l=er(ti(e,t,"source")),d=Xc.has(a)||Xc.has(i)||Wm.has(o)||Jc(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),u=Yc.has(a)||Yc.has(i)||o==="chat"||Jc(e,t,["userFacing"]),h=Hm.has(n)||Um.has(l);if(d)return{surface:h?"activity":"internal",isUserFacing:!1,isActivityFacing:h,isInternal:!h,role:r,kind:n,label:si(e,n,l)};if(u)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:si(e,n,l)};if((r==="system"||n==="system")&&Vm(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:"Chat"};if(Km.has(l)||r==="system"||n==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:r,kind:n,label:"Internal"};if(h)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:r,kind:n,label:si(e,n,l)};const f=(r==="user"||r==="human"||r==="assistant")&&(n==="standard"||n==="");return{surface:f?"chat":"internal",isUserFacing:f,isActivityFacing:!1,isInternal:!f,role:r,kind:n,label:f?"Chat":"Internal"}}function Gm(e){return(Array.isArray(e)?e:[]).filter(t=>Uo(t).isUserFacing)}function Vd(e){return(Array.isArray(e)?e:[]).filter(t=>Uo(t).isActivityFacing)}function qm(e,t,r){return!r||t.length===0?e:[...e,...t].sort((n,a)=>{const i=Number(n.receivedAt??n.timestamp??0)||0,o=Number(a.receivedAt??a.timestamp??0)||0;if(i!==o)return i-o;const l=Number(n.index??0)||0,d=Number(a.index??0)||0;return l-d})}function Qc(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(Wo))==="1"}catch{return!1}}function Xm(e,t=typeof localStorage<"u"?localStorage:void 0){try{t==null||t.setItem(Wo,e?"1":"0")}catch{}}const Gd=[Cf,{singleTilde:!1}],qd=[Gd,Tf,If],Ym=[Gd],Ko=200,Jm=80,Zc=650,Pr=new Map;function ha(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function Qm(e,t){if(!Array.isArray(e)||e.length===0)return"0:empty";const r=String(t||"").trim();if(r)return`${e.length}:${r}`;const n=e[e.length-1];return`${e.length}:${xm(n)}`}function Zm(e,t,r,n){return e||!t?!1:ha(r,n)}function ex({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=Jm,bottomThresholdPx:a=Ko}){const i=Math.max(0,Number(e)||0),o=Math.max(0,Number(t)||0),l=Math.max(0,Number(r)||0);return Math.max(0,o-l)<=0?{showTop:!1,showBottom:!1}:{showTop:i>n,showBottom:Math.max(0,o-i-l)>a}}function tx(e){return ex({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Xr(e,t=Ko){return!!e&&e.fromBottom>=t}function sx(e,t){return ha(e,t)?!Xr(e):!0}function rx({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function nx({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function ri(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function Xd(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function ax(e,t,r){return Number(e.receivedAt||r[pa(e,t)]||0)||0}function Yd(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function ix(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function Lr(e,t){if(!e)return t;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||t}catch{return e.split(/[\\/]/).filter(Boolean).pop()||t}}function ni(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 Pn(e,t,r){return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2 text-sm",role:"note",children:[s.jsx("span",{className:"font-medium",children:e}),t?s.jsx("span",{className:"ml-1 break-all",children:t}):null,r?s.jsx("div",{className:"mt-1 opacity-80",style:{whiteSpace:"pre-wrap"},children:r}):null]})}function el(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Yd(e)?s.jsx(Ro,{remarkPlugins:qd,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function Er({parts:e,renderAsPreformatted:t}){return s.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return s.jsx("div",{children:el(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=ni(r),i=r.alt||r.description||Lr(r.uri,"image");return a?s.jsx("img",{src:a,alt:i,className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):s.jsx("div",{children:Pn("Image",i,r.mimeType)},`image-fallback-${n}`)}if(r.type==="audio"){const a=ni(r);return a?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("audio",{controls:!0,src:a,className:"max-w-full"}),r.transcript?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:r.transcript}):null]},`audio-${n}`):s.jsx("div",{children:Pn("Audio",Lr(r.uri,"audio"),r.transcript||r.mimeType)},`audio-fallback-${n}`)}if(r.type==="video"){const a=ni(r),i=r.title||r.name||r.alt||Lr(r.uri,"video"),o=[r.transcript,r.description,r.mimeType].filter(Boolean).join(`
3
+ `);return s.jsxs("div",{className:"flex flex-col gap-1",children:[a?s.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):Pn("Video",i,o),a&&o?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:o}):null]},`video-${n}`)}if(r.type==="resource_link"){const a=r.title||r.name||Lr(r.uri,"resource"),i=[r.description,r.mimeType].filter(Boolean).join(`
4
+ `);return s.jsxs("div",{className:"flex flex-col gap-1",children:[r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",download:!0,className:"underline break-all",children:a}):Pn("Resource",a,i),r.uri&&i?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:i}):null]},`resource-link-${n}`)}if(r.type==="resource"&&r.resource){const a=Lr(r.resource.uri,"resource");if(r.resource.text)return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[s.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),el(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return s.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${n}`)}return null})})}function pa(e,t){const r=e,n=Eo(e.content,{joiner:`
5
+ `});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:${t}`].filter(Boolean).join("|")}const ox=c.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(Ro,{remarkPlugins:Ym,children:t.text}),s.jsx("span",{className:"action-time",children:Xd(t.timestamp)})]})},(e,t)=>e.log===t.log),cx=c.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:o,onToggleTextExpanded:l}){var S,k,O;const d=(t.role||"").toLowerCase(),u=d==="user"||d==="human",h=t.kind||(d==="tool"?"tool":"standard"),f=Uo(t),m=ix(t.content)?t.content:null,v=!!(m!=null&&m.some(P=>P.type!=="text")),b=Eo(t.content,{joiner:`
6
+ `});if(f.isActivityFacing&&h!=="thought"&&h!=="tool"&&h!=="terminal"){const P=f.label||"Activity";return s.jsxs("div",{className:"self-start chat-msg-activity","data-chat-activity-row":"true",children:[s.jsxs("div",{className:"chat-msg-activity-meta","aria-label":"Activity message",children:[s.jsx("span",{className:"activity-dot"}),s.jsx("span",{children:P})]}),v&&m?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(Er,{parts:m,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:b})]})}if(h==="thought"){const P=typeof((S=t.meta)==null?void 0:S.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":f.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(Tm,{size:13}),s.jsx("span",{children:P})]}),s.jsx("div",{className:"chat-msg-body",children:b})]})}if(h==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":f.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-tool-meta","aria-label":"Tool message",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),s.jsx("span",{className:"tool-label",children:"Tool"})]}),v&&m?s.jsx("div",{className:"tool-text w-full",children:s.jsx(Er,{parts:m,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:b})]});if(h==="terminal"){const P=(k=t.meta)!=null&&k.isRunning?"⏳":"✅",I=typeof((O=t.meta)==null?void 0:O.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":f.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:P}),s.jsx("span",{children:I})]}),v&&m?s.jsx("div",{className:"chat-msg-body",children:s.jsx(Er,{parts:m,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:b})]})}if(h==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:v&&m?s.jsx(Er,{parts:m,renderAsPreformatted:!1}):b.slice(0,100)});const p=t.meta,y=(typeof(p==null?void 0:p.renderMode)=="string"?p.renderMode.trim():"")==="preformatted",x=b,N=!1,j=x,w=y,A=!w&&Yd(j),M=["chat-message-row",u?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:M,children:(x||v||u)&&s.jsxs("div",{className:`chat-bubble ${u?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${x||v?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:u?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:Xd(r)})]}),(x||v)&&s.jsx("div",{className:"chat-markdown",children:v&&m?s.jsx(Er,{parts:m,renderAsPreformatted:w}):w?s.jsx("pre",{className:"chat-preformatted",children:j}):A?s.jsx(Ro,{remarkPlugins:qd,children:j}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:j})}),N]})})},(e,t)=>e.message===t.message&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),lx=c.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:o=!1,contextKey:l="",receivedAtMap:d={},lastMessageHash:u,showActivityMessages:h=!1,emptyState:f,onLoadMore:m,isLoadingMore:v,hasMoreHistory:b,hiddenLiveCount:p=0,loadError:g,scrollToBottomRequestNonce:y,isVisible:x=!0},N){const j=c.useRef(null),w=c.useRef(null),A=c.useRef(null),M=c.useRef(0),S=c.useRef(""),k=c.useRef(""),O=c.useRef(!1),P=c.useRef(null),I=c.useRef(!1),W=c.useRef(null),K=c.useRef(!1),[R,T]=c.useState(new Set),[C,F]=c.useState({showTop:!1,showBottom:!1}),L=c.useRef(!1),D=c.useRef(!1),H=c.useRef(x),Q=c.useRef(x),ge=c.useRef(null);Q.current=x;const ue=()=>{const re=j.current;return re?re.scrollHeight-re.scrollTop-re.clientHeight<Ko:!0},Z=c.useCallback(()=>{const re=j.current,q=re?tx(re):{showTop:!1,showBottom:!1};F(je=>je.showTop===q.showTop&&je.showBottom===q.showBottom?je:q)},[]),xe=c.useCallback((re="auto")=>{var je;const q=j.current;q&&(q.scrollTo({top:q.scrollHeight,behavior:re}),(je=q.ownerDocument.defaultView)==null||je.requestAnimationFrame(()=>Z()))},[Z]),Se=c.useCallback((re="auto")=>{var je;const q=j.current;q&&(q.scrollTo({top:0,behavior:re}),(je=q.ownerDocument.defaultView)==null||je.requestAnimationFrame(()=>Z()))},[Z]),be=c.useCallback(()=>{var Pe;const re=j.current,q=(Pe=window.getSelection)==null?void 0:Pe.call(window);if(!re||!q||q.rangeCount===0||q.isCollapsed){K.current=!1;return}const je=q.anchorNode,we=q.focusNode;K.current=!!(je&&we&&re.contains(je)&&re.contains(we))},[]),Y=c.useMemo(()=>{const re=Gm(t),q=Vd(t);return qm(re,q,h)},[t,h]),he=Y.length===t.length?u:void 0,ye=Qm(Y,he),se=c.useCallback(()=>{const re=j.current;if(!re||!l||!Q.current)return;const q={top:re.scrollTop,fromBottom:Math.max(0,re.scrollHeight-re.scrollTop-re.clientHeight),messageFingerprint:ye};ge.current={contextKey:l,snapshot:q},Pr.set(l,q)},[l,ye]),de=c.useCallback((re="auto")=>{P.current!=null&&cancelAnimationFrame(P.current),P.current=requestAnimationFrame(()=>{P.current=null,xe(re)})},[xe]),Ce=c.useCallback(()=>{L.current=!1,I.current=!0,D.current=!0,W.current!=null&&window.clearTimeout(W.current),W.current=window.setTimeout(()=>{I.current=!1,W.current=null},Zc)},[]);c.useEffect(()=>{const re=!O.current,q=k.current!==l;if(k.current=l,re||q){O.current=!0;const we=l?Pr.get(l):null,Pe=!!we&&ha(we,ye);L.current=Pe?Xr(we):!1,I.current=sx(we,ye),K.current||(Pe?requestAnimationFrame(()=>{const Re=j.current;Re&&(ri(Re,we),L.current=Xr(we),Z(),D.current=!0)}):de("auto")),M.current=Y.length,S.current=ye;return}Y.length>M.current;const je=ye!==S.current;rx({hasSelection:K.current,userScrolledUp:L.current,hasChatContentChanged:je})&&de("auto"),M.current=Y.length,S.current=ye},[ye,l,Y.length,de,Z]),c.useEffect(()=>{y&&(Ce(),K.current||de("auto"))},[Ce,de,y]),c.useEffect(()=>{const re=H.current;re&&!x&&se(),Q.current=x,H.current=x;const q=l?Pr.get(l):null;if(Zm(re,x,q,ye)){if(!q)return;L.current=Xr(q),I.current=!1,K.current||requestAnimationFrame(()=>{const je=j.current;je&&(ri(je,q),Z())});return}},[x,l,ye,Ce,se,de,Z]),c.useEffect(()=>()=>{const re=ge.current;re&&Pr.set(re.contextKey,re.snapshot),P.current!=null&&cancelAnimationFrame(P.current),W.current!=null&&window.clearTimeout(W.current)},[]),c.useEffect(()=>{const re=w.current,q=j.current;if(!re||!q)return;const je=()=>{W.current!=null&&window.clearTimeout(W.current),W.current=window.setTimeout(()=>{I.current=!1,W.current=null},Zc)},we=new ResizeObserver(()=>{Z();const Pe=I.current;nx({hasSelection:K.current,userScrolledUp:L.current,contextAutoScrollActive:Pe})&&(de("auto"),Pe&&je())});return we.observe(re),q!==re&&we.observe(q),()=>{we.disconnect(),W.current!=null&&(window.clearTimeout(W.current),W.current=null)}},[de,l,Z]),c.useImperativeHandle(N,()=>({scrollToBottom:(re="smooth")=>{xe(re)}}),[xe]),c.useEffect(()=>{const re=j.current;if(!re)return;let q;const je=()=>{se(),clearTimeout(q),q=setTimeout(()=>{L.current=!ue(),Z()},50)};return re.addEventListener("scroll",je,{passive:!0}),()=>{re.removeEventListener("scroll",je),clearTimeout(q)}},[se,Z]),c.useEffect(()=>(document.addEventListener("selectionchange",be),()=>document.removeEventListener("selectionchange",be)),[be]);const pe=c.useRef(0),me=c.useRef(!1);c.useEffect(()=>{const re=j.current;if(!re||!me.current||pe.current===0)return;const q=re.scrollHeight-pe.current;q>0&&(re.scrollTop=q),Z(),se(),pe.current=0,me.current=!1},[Y.length,se,Z]),c.useEffect(()=>{if(D.current||!l)return;const re=Pr.get(l),q=j.current;if(!(!re||!q)){if(!ha(re,ye)){xe("auto"),D.current=!0;return}ri(q,re),L.current=Xr(re),Z(),D.current=!0}},[l,ye,Y.length,xe,Z]);const oe=()=>{const re=j.current;re&&(pe.current=re.scrollHeight),me.current=!0,m==null||m()},fe=()=>{L.current=!0,Se("smooth"),se()},ce=()=>{Ce(),xe("smooth"),se()},E=c.useMemo(()=>{const re=Y.map((Pe,Re)=>({type:"message",data:Pe,index:Re,ts:ax(Pe,Re,d)}));if(!r||r.length===0)return re;const q=[...r].sort((Pe,Re)=>Pe.timestamp-Re.timestamp).map((Pe,Re)=>({type:"action",data:Pe,index:Re,ts:Pe.timestamp})),je=[];let we=0;for(const Pe of re){for(;we<q.length&&Pe.ts>0&&q[we].ts<Pe.ts;)je.push(q[we++]);je.push(Pe)}for(;we<q.length;)je.push(q[we++]);return je},[Y,r,d]),z=p>0||!!b,le=p>0?`↑ Show ${Math.min(p,80)} earlier messages${p>80?` (${p} hidden)`:""}`:g?`↻ ${g}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:j,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:w,className:"chat-container-content",children:[v&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),z&&!v&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:oe,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${g&&p===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:le})}),E.length===0&&!z&&(f||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),E.map(re=>{if(re.type==="action"){const Ae=re.data;return s.jsx(ox,{log:Ae},`action-${re.index}`)}const q=re.data,je=re.index,we=pa(q,je),Pe=q.receivedAt||d[we],Re=`${l}-${we}`,B=R.has(Re);return s.jsx(cx,{message:q,receivedAt:Pe,agentName:n,userName:a,isCliMode:i,isTextExpanded:B,onToggleTextExpanded:()=>T(Ae=>{const Ee=new Set(Ae);return B?Ee.delete(Re):Ee.add(Re),Ee})},`msg-${we}`)}),o&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),s.jsx("div",{className:"min-h-10",ref:A})]})}),(C.showTop||C.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[C.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:fe,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),C.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:ce,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),dx=c.memo(lx,(e,t)=>e.messages===t.messages&&e.actionLogs===t.actionLogs&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isWorking===t.isWorking&&e.contextKey===t.contextKey&&e.receivedAtMap===t.receivedAtMap&&e.lastMessageHash===t.lastMessageHash&&e.showActivityMessages===t.showActivityMessages&&e.emptyState===t.emptyState&&e.onLoadMore===t.onLoadMore&&e.isLoadingMore===t.isLoadingMore&&e.hasMoreHistory===t.hasMoreHistory&&e.hiddenLiveCount===t.hiddenLiveCount&&e.loadError===t.loadError&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isVisible===t.isVisible),ux="modulepreload",hx=function(e){return"/"+e},tl={},px=function(t,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));a=Promise.allSettled(r.map(d=>{if(d=hx(d),d in tl)return;tl[d]=!0;const u=d.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${h}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":ux,u||(f.as="script"),f.crossOrigin="",f.href=d,l&&f.setAttribute("nonce",l),document.head.appendChild(f),u)return new Promise((m,v)=>{f.addEventListener("load",m),f.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return a.then(o=>{for(const l of o||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})};let sl=!1;const Jd=c.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:i="measured"},o)=>{const l=c.useRef(null),[d,u]=c.useState(null),h=c.useRef([]),f=c.useRef(!1),m=c.useRef(!1),v=c.useRef(!1),b=c.useRef(!1),p=()=>{const g=l.current;if(g){f.current&&(g.clear(),f.current=!1);for(const y of h.current)g.write(y.data,y.onProcessed);h.current=[],m.current&&(g.fit(),m.current=!1),v.current&&(g.bumpResize(),v.current=!1),b.current&&(g.scrollToTop(),b.current=!1)}};return c.useImperativeHandle(o,()=>({write:(g,y)=>{l.current?l.current.write(g,y):h.current.push({data:g,onProcessed:y})},clear:()=>{l.current?l.current.clear():(h.current=[],f.current=!0)},reset:()=>{l.current&&typeof l.current.reset=="function"?l.current.reset():(h.current=[],f.current=!0)},resize:(g,y)=>{l.current&&typeof l.current.resize=="function"&&l.current.resize(g,y)},fit:()=>{l.current?l.current.fit():m.current=!0},bumpResize:()=>{l.current?l.current.bumpResize():v.current=!0},scrollToTop:()=>{l.current?l.current.scrollToTop():b.current=!0},getSelection:()=>{var g,y;return((y=(g=l.current)==null?void 0:g.getSelection)==null?void 0:y.call(g))||""},getVisibleText:()=>{var g,y;return((y=(g=l.current)==null?void 0:g.getVisibleText)==null?void 0:y.call(g))||""}}),[]),c.useEffect(()=>{d&&p()},[d]),c.useEffect(()=>{let g=!1;return px(()=>import("./terminal-Cn_eJIrc.js"),__vite__mapDeps([0,1,2])).then(y=>{sl||(sl=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),g||u(()=>y.GhosttyTerminalView)}).catch(y=>{console.error("[CliTerminal] failed to load terminal renderer",y)}),()=>{g=!0}},[]),d?s.jsx(d,{ref:l,onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:i,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});Jd.displayName="CliTerminal";function Ln({label:e,value:t,sub:r,icon:n}){return s.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsx("span",{className:"text-base flex items-center",children:n}),s.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),s.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:t}),r&&s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function rl({value:e,max:t,label:r,color:n="#8b5cf6",detail:a,compact:i=!1}){const o=t>0?Math.min(Math.round(e/t*100),100):0,l=o>85?"#ef4444":o>60?"var(--status-warning)":n;return i?s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-0.5",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),s.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[o,"%"]})]}),s.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${o}%`,background:l}})})]}):s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-1.5",children:[s.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),s.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[o,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${o}%`,background:`linear-gradient(90deg, ${l}, ${l}cc)`}})}),a&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function fx({cursorPos:e,viewportRef:t,imgRef:r}){var x;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(x=t.current)==null?void 0:x.getBoundingClientRect();if(!i)return null;const o=n.naturalWidth||a.width,l=n.naturalHeight||a.height,d=o/l,u=a.width/a.height;let h,f,m,v;d>u?(h=a.width,f=a.width/d,m=0,v=(a.height-f)/2):(f=a.height,h=a.height*d,m=(a.width-h)/2,v=0);const b=a.left-i.left+m+h*e.nx,p=a.top-i.top+v+f*e.ny,g=Math.max(8,Math.min(i.width-8,b)),y=Math.max(8,Math.min(i.height-8,p));return s.jsxs("div",{style:{position:"absolute",left:g-8,top:y-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[s.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),s.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 mx({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:o,setImeText:l,handleImeSubmit:d,isConnActive:u,zoom:h,isMobile:f,mobileFillZoom:m,onZoomOut:v,onZoomReset:b,onZoomIn:p,transportType:g,screenshotUsage:y,lastActionStatus:x}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:N=>N.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[s.jsxs("div",{onClick:t,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:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{n(N=>!N),i(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&s.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:s.jsx("input",{type:"text",placeholder:"Type & Enter...",value:o,autoFocus:!0,onTouchStart:N=>N.stopPropagation(),onChange:N=>l(N.target.value),onKeyDown:N=>{d(N)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{i(N=>!N),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:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:u?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:u?"#22c55e":"#eab308",boxShadow:u?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:u?"#22c55e":"#eab308"},children:u?"Connected":"WS"})]}),h>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(h*100),"%"]}),g==="direct"&&s.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"&&s.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"}),y&&y.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:y.budgetExhausted?"#ef4444":"#c4b5fd",background:y.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:y.budgetExhausted?"TURN blocked":`TURN ${y.dailyUsedMinutes}/${y.dailyBudgetMinutes}m`}),x&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:x})]})]}),a&&s.jsxs("div",{onTouchStart:N=>N.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",h<=(f?m:1)+.01?f?"FILL":"FIT":`${Math.round(h*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:N=>{N.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:"−"}),s.jsx("button",{onClick:N=>{N.stopPropagation(),b()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:f?"FILL":"FIT"}),s.jsx("button",{onClick:N=>{N.stopPropagation(),p()},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 xx({waitingLabel:e,waitingHint:t,transportType:r}){return s.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[s.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:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),s.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),s.jsx("div",{className:"text-[11px] text-white/40",children:t}),r==="relay"&&s.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function gx(){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 nl(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 wn(e,t){const r=c.useRef(null),n=c.useRef(0);c.useEffect(()=>{if(!gx())return;n.current+=1;const a=r.current;if(!a){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([o,l])=>[o,nl(l)]))}),r.current=t;return}const i=Object.keys({...a,...t}).filter(o=>!Object.is(a[o],t[o]));i.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:i,snapshot:Object.fromEntries(i.map(o=>[o,nl(t[o])]))}),r.current=t})}function bx({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:o,panXRef:l,panYRef:d,setPanX:u,setPanY:h,setZoom:f,lastWheelTimeRef:m,onAction:v,setLastActionStatus:b,spawnRippleFromNormalized:p,clampPan:g,isMobile:y,mobileFillZoom:x}){const[N,j]=c.useState(null),w=c.useRef(null),A=c.useRef(null),M=c.useRef(null),S=c.useRef(!1),k=c.useRef(null),O=c.useRef(0),P=c.useRef(null),I=c.useRef(1),W=c.useRef({x:0,y:0}),K=c.useRef(!1),R=c.useRef(n),T=c.useRef(v),C=30,F=550,L=18,D=60,H=400,Q=12,ge=()=>{if(w.current)return;const xe={nx:.5,ny:.5};w.current=xe,j(xe)};return c.useEffect(()=>{R.current=n,n==="mouse"&&ge()},[n]),c.useEffect(()=>{T.current=v},[v]),c.useEffect(()=>{const xe=e.current;if(!xe)return;const Se=de=>{if(!r.current)return null;const Ce=r.current.getBoundingClientRect();return!Ce.width||!Ce.height?null:{nx:Math.max(0,Math.min(1,(de.clientX-Ce.left)/Ce.width)),ny:Math.max(0,Math.min(1,(de.clientY-Ce.top)/Ce.height))}},be=(de,Ce)=>{if(!r.current)return{dnx:0,dny:0};const pe=r.current,me=pe.getBoundingClientRect(),oe=pe.naturalWidth||me.width,fe=pe.naturalHeight||me.height,ce=oe/fe,E=me.width/me.height;let z,le;return ce>E?(z=me.width,le=me.width/ce):(le=me.height,z=me.height*ce),{dnx:de/z,dny:Ce/le}},Y=(de,Ce,pe)=>{if(pe<=1.05)return;const me=-(de-.5)*100,oe=-(Ce-.5)*100,fe=g(me,oe,pe);(Math.abs(fe.x-l.current)>.1||Math.abs(fe.y-d.current)>.1)&&(u(fe.x),h(fe.y),l.current=fe.x,d.current=fe.y)},he=de=>{const Ce=t.current;if(Ce&&de.target instanceof Node&&Ce.contains(de.target))de.preventDefault();else return;if(de.touches.length===1){const pe=de.touches[0];A.current={x:pe.clientX,y:pe.clientY,time:Date.now()},M.current={x:pe.clientX,y:pe.clientY},K.current||(S.current=!1),k.current=setTimeout(()=>{if(!S.current&&!K.current)if(S.current=!0,R.current==="mouse"){const me=w.current||{nx:.5,ny:.5};b("Right Click"),p(me.nx,me.ny,"right"),T.current("input_click",{...me,button:"right"}).catch(()=>{})}else{const me=Se(pe);me&&(b("Right Click"),p(me.nx,me.ny,"right"),T.current("input_click",{...me,button:"right"}).catch(()=>{}))}},500);return}if(de.touches.length===2){k.current&&clearTimeout(k.current),S.current=!0,K.current=!0;const pe=de.touches[1].clientX-de.touches[0].clientX,me=de.touches[1].clientY-de.touches[0].clientY;P.current=Math.sqrt(pe*pe+me*me),I.current=o.current,W.current={x:(de.touches[0].clientX+de.touches[1].clientX)/2,y:(de.touches[0].clientY+de.touches[1].clientY)/2}}},ye=de=>{const Ce=t.current;if(Ce&&de.target instanceof Node&&Ce.contains(de.target)&&de.preventDefault(),de.touches.length===1&&M.current){const pe=de.touches[0],me=pe.clientX-M.current.x,oe=pe.clientY-M.current.y;if(!S.current&&A.current){const fe=pe.clientX-A.current.x,ce=pe.clientY-A.current.y;Math.sqrt(fe*fe+ce*ce)>8&&(S.current=!0,k.current&&clearTimeout(k.current))}if(S.current)if(R.current==="mouse"){const fe=be(me,oe),ce=w.current||{nx:.5,ny:.5},E=Math.max(0,Math.min(1,ce.nx+fe.dnx)),z=Math.max(0,Math.min(1,ce.ny+fe.dny));w.current={nx:E,ny:z},j({nx:E,ny:z}),b(`Cursor: ${Math.round(E*100)}%, ${Math.round(z*100)}%`),Y(E,z,o.current);const le=Date.now();le-m.current>=30&&(m.current=le,T.current("input_mouseMoved",{nx:E,ny:z}).catch(()=>{}))}else if(o.current>1){const fe=t.current;if(fe){const ce=fe.clientWidth,E=fe.clientHeight,z=l.current+me/ce*100,le=d.current+oe/E*100,re=g(z,le,o.current);u(re.x),h(re.y),l.current=re.x,d.current=re.y}}else{const fe=Se(pe);if(fe){const ce=Date.now();ce-m.current>=40&&(m.current=ce,b("Scroll"),T.current("input_wheel",{nx:fe.nx,ny:fe.ny,deltaX:Math.round(-me*2.5),deltaY:Math.round(-oe*2.5)}).catch(()=>{}))}}M.current={x:pe.clientX,y:pe.clientY};return}if(de.touches.length===2&&P.current!==null){const pe=de.touches[1].clientX-de.touches[0].clientX,me=de.touches[1].clientY-de.touches[0].clientY,fe=Math.sqrt(pe*pe+me*me)/P.current,ce=(de.touches[0].clientX+de.touches[1].clientX)/2,E=(de.touches[0].clientY+de.touches[1].clientY)/2,z=ce-W.current.x,le=E-W.current.y,re=Math.abs(fe-1)>.03;if(R.current==="mouse"){if(re){const q=Math.max(i,Math.min(5,I.current*fe));f(q),o.current=q}else if(Math.abs(z)>2||Math.abs(le)>2){const q=w.current||{nx:.5,ny:.5},je=Date.now();je-m.current>=30&&(m.current=je,b("Scroll"),T.current("input_wheel",{nx:q.nx,ny:q.ny,deltaX:Math.round(-z*3),deltaY:Math.round(-le*3)}).catch(()=>{}))}}else{const q=Math.max(i,Math.min(5,I.current*fe));f(q),o.current=q;const je=t.current;if(je&&q>1){const we=je.clientWidth,Pe=je.clientHeight,Re=l.current+z/we*100,B=d.current+le/Pe*100,Ae=g(Re,B,q);u(Ae.x),h(Ae.y),l.current=Ae.x,d.current=Ae.y}}W.current={x:ce,y:E}}},se=de=>{var Ce;if(k.current&&clearTimeout(k.current),P.current=null,de.touches.length===1&&K.current){const pe=de.touches[0];A.current={x:pe.clientX,y:pe.clientY,time:Date.now()},M.current={x:pe.clientX,y:pe.clientY},S.current=!0;return}if(de.touches.length===0){if(K.current){K.current=!1,S.current=!1;return}if(de.changedTouches.length===1){const pe=de.changedTouches[0],me=Date.now(),oe=me-(((Ce=A.current)==null?void 0:Ce.time)||0),fe=A.current?pe.clientX-A.current.x:0,ce=A.current?pe.clientY-A.current.y:0,E=Math.sqrt(fe*fe+ce*ce);if(R.current==="mouse"){if(oe<C||oe>F||E>L){S.current=!1;return}const z=w.current||Se(pe);z&&(b(`Click: ${Math.round(z.nx*100)}%, ${Math.round(z.ny*100)}%`),p(z.nx,z.ny,"left"),T.current("input_click",{...z}).catch(()=>{}))}else{if(S.current){S.current=!1;return}if(oe<D||oe>H||E>Q){S.current=!1;return}const z=Se(pe);if(!z)return;me-O.current<300?(b("Double tap"),p(z.nx,z.ny,"double"),T.current("input_click",{...z,clickCount:2}).catch(()=>{}),O.current=0):(b(`Tap: ${Math.round(z.nx*100)}%, ${Math.round(z.ny*100)}%`),p(z.nx,z.ny,"left"),T.current("input_click",{...z}).catch(()=>{}),O.current=me)}}S.current=!1}};return xe.addEventListener("touchstart",he,{passive:!1}),xe.addEventListener("touchmove",ye,{passive:!1}),xe.addEventListener("touchend",se,{passive:!1}),()=>{xe.removeEventListener("touchstart",he),xe.removeEventListener("touchmove",ye),xe.removeEventListener("touchend",se),k.current&&clearTimeout(k.current)}},[e,t,r,i,o,l,d,u,h,f,m,b,p,g]),{cursorPos:N,cursorPosRef:w,handleToggleInputMode:()=>{a(xe=>{const Se=xe==="touch"?"mouse":"touch";return Se==="mouse"&&ge(),Se})},handleZoomReset:()=>{const xe=y?x:1;f(xe),o.current=xe,u(0),h(0),l.current=0,d.current=0}}}function Qd({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const o=c.useRef(null),l=c.useRef(null),d=c.useRef(null),[u,h]=c.useState(null),[f,m]=c.useState(""),[,v]=c.useState(!1),[b,p]=c.useState([]),g=c.useRef(0),[y,x]=c.useState(!1),[N,j]=c.useState(!1),w=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[A,M]=c.useState(w?"mouse":"touch"),[S,k]=c.useState(1),O=c.useRef(!1),[P,I]=c.useState(1),[W,K]=c.useState(0),[R,T]=c.useState(0);wn("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:A,zoom:P,panX:W,panY:R,isMenuOpen:y,isImeOpen:N});const C=c.useRef(0),F=c.useRef(P),L=c.useRef(W),D=c.useRef(R);c.useEffect(()=>{F.current=P},[P]),c.useEffect(()=>{L.current=W},[W]),c.useEffect(()=>{D.current=R},[R]),c.useEffect(()=>{var oe;(oe=o.current)==null||oe.focus()},[]);const H=r==="connected",Q=n,ge=H?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ue=H?"The remote stream is warming up":"Waiting for the remote stream to catch up";c.useEffect(()=>{if(!w||O.current||!Q)return;const oe=d.current,fe=l.current;if(!oe||!fe)return;const ce=()=>{const E=fe.clientWidth,z=fe.clientHeight,le=oe.naturalWidth,re=oe.naturalHeight;if(!le||!re||!E||!z)return;const q=Math.min(E/le,z/re),we=Math.max(E/le,z/re)/q;we>1.01&&(k(we),I(we),F.current=we),O.current=!0};oe.complete&&oe.naturalWidth?ce():oe.addEventListener("load",ce,{once:!0})},[Q,w]);const Z=.5;c.useEffect(()=>{P<=Z&&(K(0),T(0))},[P,Z]);const xe=(oe,fe,ce)=>{if(ce<=Z)return{x:0,y:0};const E=(ce-1)/(2*ce)*100,z=(ce-1)/(2*ce)*100;return{x:Math.max(-E,Math.min(E,oe)),y:Math.max(-z,Math.min(z,fe))}},Se=(oe,fe)=>{if(!d.current)return null;const ce=d.current.getBoundingClientRect();return!ce.width||!ce.height?null:{nx:Math.max(0,Math.min(1,(oe-ce.left)/ce.width)),ny:Math.max(0,Math.min(1,(fe-ce.top)/ce.height))}},be=(oe,fe,ce)=>{const E=l.current;if(!E)return;const z=E.getBoundingClientRect(),le=++g.current;p(re=>[...re,{id:le,x:oe-z.left,y:fe-z.top,type:ce}]),setTimeout(()=>p(re=>re.filter(q=>q.id!==le)),600)},Y=(oe,fe,ce)=>{const E=d.current,z=l.current;if(!E||!z)return;const le=E.getBoundingClientRect(),re=z.getBoundingClientRect(),q=E.naturalWidth||le.width,je=E.naturalHeight||le.height,we=q/je,Pe=le.width/le.height;let Re,B,Ae,Ee;we>Pe?(Re=le.width,B=le.width/we,Ae=0,Ee=(le.height-B)/2):(B=le.height,Re=le.height*we,Ae=(le.width-Re)/2,Ee=0);const Ve=le.left-re.left+Ae+Re*oe,Ge=le.top-re.top+Ee+B*fe,Ze=++g.current;p(et=>[...et,{id:Ze,x:Ve,y:Ge,type:ce}]),setTimeout(()=>p(et=>et.filter(at=>at.id!==Ze)),600)},he=async oe=>{var ce;const fe=Se(oe.clientX,oe.clientY);if(fe){h(`Click: ${Math.round(fe.nx*100)}%, ${Math.round(fe.ny*100)}%`),be(oe.clientX,oe.clientY,"left"),(ce=o.current)==null||ce.focus();try{const E=await e("input_click",{nx:fe.nx,ny:fe.ny});E!=null&&E.success||t(`❌ Click failed: ${E==null?void 0:E.error}`)}catch(E){t(`❌ Click error: ${E.message||E}`)}}},ye=async(oe,fe,ce,E=0)=>{try{await e("input_key",{type:ce?"char":"keyDown",key:oe,code:fe,text:ce?oe:void 0,unmodifiedText:ce?oe:void 0,modifiers:E})}catch(z){t(`❌ Key error: ${z.message||z}`)}},se=async oe=>{if(oe.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(oe.key)&&oe.preventDefault();let ce=0;oe.altKey&&(ce|=1),oe.ctrlKey&&(ce|=2),oe.metaKey&&(ce|=4),oe.shiftKey&&(ce|=8),h(`Key: ${oe.key}`),await ye(oe.key,oe.code,oe.key.length===1,ce)},de=async oe=>{if(oe.key==="Enter"){if(oe.nativeEvent.isComposing)return;if(f){const fe=f;m(""),h(`IME Sent: ${fe}`);try{const ce=await e("input_type",{text:fe});ce!=null&&ce.success||t(`❌ IME error: ${ce==null?void 0:ce.error}`)}catch(ce){t(`❌ IME error: ${ce.message}`)}}else h("Key: Enter"),await ye("Enter","Enter",!1)}};c.useEffect(()=>{const oe=o.current;if(!oe)return;const fe=ce=>{var E;if((E=d.current)!=null&&E.contains(ce.target)){ce.preventDefault();const z=Date.now();if(z-C.current<40)return;C.current=z;const le=Se(ce.clientX,ce.clientY);if(!le)return;h(`Scroll: ${Math.round(ce.deltaY)}`),e("input_wheel",{nx:le.nx,ny:le.ny,deltaX:Math.round(ce.deltaX),deltaY:Math.round(ce.deltaY)}).catch(()=>{})}};return oe.addEventListener("wheel",fe,{passive:!1}),()=>oe.removeEventListener("wheel",fe)},[e]);const{cursorPos:Ce,handleToggleInputMode:pe,handleZoomReset:me}=bx({containerRef:o,viewportRef:l,imgRef:d,inputMode:A,setInputMode:M,minZoom:Z,zoomRef:F,panXRef:L,panYRef:D,setPanX:K,setPanY:T,setZoom:I,lastWheelTimeRef:C,onAction:e,setLastActionStatus:h,spawnRippleFromNormalized:Y,clampPan:xe,isMobile:w,mobileFillZoom:S});return s.jsxs("div",{ref:o,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:se,onContextMenu:oe=>oe.preventDefault(),onFocus:()=>v(!0),onBlur:()=>v(!1),tabIndex:0,children:[s.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[Q?s.jsx("img",{ref:d,src:Q,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${P}) translate(${W}%, ${R}%)`,transformOrigin:"center center",cursor:A==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:he,onContextMenu:oe=>oe.preventDefault(),onDragStart:oe=>oe.preventDefault()}):s.jsx(xx,{waitingLabel:ge,waitingHint:ue,transportType:i}),A==="mouse"&&Q&&s.jsx(fx,{cursorPos:Ce,viewportRef:l,imgRef:d}),b.map(oe=>{const ce={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[oe.type];return s.jsxs("div",{style:{position:"absolute",left:oe.x,top:oe.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ce}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),s.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${ce}, 0.9)`,boxShadow:`0 0 12px rgba(${ce}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},oe.id)})]}),s.jsx(mx,{inputMode:A,onToggleInputMode:pe,isImeOpen:N,setIsImeOpen:j,isMenuOpen:y,setIsMenuOpen:x,imeText:f,setImeText:m,handleImeSubmit:de,isConnActive:H,zoom:P,isMobile:w,mobileFillZoom:S,onZoomOut:()=>I(oe=>Math.max(.5,oe-.25)),onZoomReset:me,onZoomIn:()=>I(oe=>Math.min(5,oe+.25)),transportType:i,screenshotUsage:a,lastActionStatus:u}),s.jsx("style",{children:`
7
+ @keyframes slideUp {
8
+ from { opacity: 0; transform: translateY(6px); }
9
+ to { opacity: 1; transform: translateY(0); }
10
+ }
11
+ @keyframes slideUpSidebar {
12
+ from { opacity: 0; transform: translateY(6px); }
13
+ to { opacity: 1; transform: translateY(0); }
14
+ }
15
+ @keyframes click-ripple-ring {
16
+ 0% { transform: scale(0.3); opacity: 1; }
17
+ 100% { transform: scale(2.2); opacity: 0; }
18
+ }
19
+ @keyframes click-ripple-dot {
20
+ 0% { transform: scale(1); opacity: 0.9; }
21
+ 50% { transform: scale(1.8); opacity: 0.6; }
22
+ 100% { transform: scale(0.5); opacity: 0; }
23
+ }
24
+ @keyframes remote-float {
25
+ 0% { transform: translateY(0px); }
26
+ 50% { transform: translateY(-7px); }
27
+ 100% { transform: translateY(0px); }
28
+ }
29
+ `})]})}function La(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,i=Date.now()-e,o=Math.floor(i/1e3);if(o<a)return n;const l=Math.floor(o/60);if(l<60)return`${l}m${r}`;const d=Math.floor(l/60);if(d<24)return`${d}h${r}`;const u=Math.floor(d/24);return u<7?`${u}d${r}`:new Date(e).toLocaleDateString()}const Zd=e=>La(e);function yx(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 Cr(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function vx(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...yx(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 t}function fa(e,t){if(e.sessionId){const r=t.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 Ea(e,t,r){const n=fa(e,t),a=Cr(e),i=a.isReconnecting,o=a.isConnecting,l=a.isGenerating,d=a.isWaiting,u=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d,h=n.inboxBucket==="working"||l,m=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:m,requiresAction:u,isWorking:h,isReconnecting:i,isConnecting:o,isGenerating:l,isWaiting:d,inboxBucket:u?"needs_attention":h?"working":m?"task_complete":"idle"}}function wx(e,t,r){return Ea(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function eu({activeConv:e,onModalButton:t}){const[r,n]=c.useState(null);if(c.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Cr(e).isWaiting||!e.modalButtons)return null;const i=l=>{r||(n(l),t(l))},o=l=>l.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return s.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&&s.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)}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[s.jsx(fn,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,d)=>{const u=o(l).toLowerCase(),h=/^(run|approve|accept|yes|allow|always)/.test(u),f=/^(reject|deny|delete|remove|abort)/.test(u),m=r===l,v=r!==null;return s.jsx("button",{onClick:()=>i(l),disabled:v,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${h?"font-extrabold":f?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${v&&!m?"opacity-40":"opacity-100"} ${v?"cursor-not-allowed":"cursor-pointer"}`,style:h?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:f?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:m?"⏳ ...":o(l)},d)})})]})]})}const Ho="adhdev_controls_bar_visible",so="adhdev:controlsbarvisibilitychange";function ai(e){if(!e)return!1;try{return e.getItem(Ho)==="1"}catch{return!1}}function Sx(e,t){if(t)try{t.setItem(Ho,e?"1":"0")}catch{}}function kx(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(so,{detail:{visible:e}}))}function zo(){const[e,t]=c.useState(()=>typeof window>"u"?!1:ai(window.localStorage)),r=c.useRef(e),n=c.useCallback((o,l=!0)=>{r.current=o,t(o),typeof window<"u"&&Sx(o,window.localStorage),l&&kx(o)},[]);c.useEffect(()=>{const o=d=>{const u=d.detail,h=typeof(u==null?void 0:u.visible)=="boolean"?u.visible:ai(window.localStorage);r.current=h,t(h)},l=d=>{if(d.key!==Ho)return;const u=ai(window.localStorage);r.current=u,t(u)};return window.addEventListener(so,o),window.addEventListener("storage",l),()=>{window.removeEventListener(so,o),window.removeEventListener("storage",l)}},[]);const a=c.useCallback(o=>{n(o)},[n]),i=c.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:i}}var jx=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Nx(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function kt(e,t){if(Nx(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":jx.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 ma(e){return kt(e)==="generating"}function al(e,t){return kt(e,t)==="waiting_approval"}function ht(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Cx(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const r=Math.floor(t/60),n=t%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 ii(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Da(e,t){const r=typeof t=="string"?t.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 Tx(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const t=e.split("_"),r=t[t.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function Ix(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Ax(e){return Tx(e.trim().replace(/\.local$/i,""))}function Mx(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function tu(e,t={}){var a,i;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(i=e.system)==null?void 0:i.hostname].find(o=>typeof o=="string"&&o.trim().length>0&&!Ix(o));if(r&&r!=="Unknown")return Ax(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function $t(e,t={}){return Mx(e)||tu(e,t)}function su(e){return!e||!Array.isArray(e.items)?[]:e.items.map(t=>String((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim()).filter(Boolean)}function ru(e,t,r={}){const n=String(t).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 Vs(e,t){return su(e).join(" · ")}function mn(e){return e.transport==="pty"}function or(e){return e.transport==="acp"}function _x(e,t){var r,n;return(r=t==null?void 0:t.providerLabels)!=null&&r[e]?t.providerLabels[e]:(n=t==null?void 0:t.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:ht(e)}function il(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),o=ht(r||"").trim().toLowerCase();return n===a||n===i||n===o}function Rx(e,t=[],r=[]){var d,u,h,f;const n=kt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(n==="waiting_approval")return"waiting_approval";if(n==="generating")return"generating";const a=t.find(m=>al(m.status,{activeModal:m.activeModal})||ma(m.status));if(a)return kt(a.status,{activeModal:a.activeModal});const i=r.find(m=>al(m.status,{activeModal:m.activeModal})||ma(m.status));if(i)return kt(i.status,{activeModal:i.activeModal});if(n&&n!=="idle")return n;const o=kt((d=t[0])==null?void 0:d.status,{activeModal:(u=t[0])==null?void 0:u.activeModal});if(o!=="idle")return o;const l=kt((h=r[0])==null?void 0:h.status,{activeModal:(f=r[0])==null?void 0:f.activeModal});return l!=="idle"?l:"idle"}function Px(e){return kt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Lx(e){if(!Array.isArray(e)||e.length<=1)return e;const t=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=t.get(a),o=kt(n.status);if(!i){t.set(a,{...n,status:o});continue}const l=r.indexOf(i.status||"idle"),d=r.indexOf(o||"idle");d>=0&&(l<0||d<l)&&t.set(a,{...n,status:o})}return Array.from(t.values())}function Ex(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function Dx(e){var r,n;const t=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return t&&Ex(t.receivedAt)||0}function $x(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ro(e){return Math.max($x(e),Dx(e.activeChat))}function Bx(e,t,r,n,a,i){const o=t-e;if(o!==0)return o;const l=r.localeCompare(n);return l!==0?l:a.localeCompare(i)}function Vo(e,t){return Bx(ro(e),ro(t),$t(e,{fallbackId:e.id}),$t(t,{fallbackId:t.id}),e.id,t.id)}const nu="adhdev_notification_prefs",ol={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Ox(){try{const e=localStorage.getItem(nu);if(e){const t=JSON.parse(e);return{...ol,...t}}}catch{}return{...ol}}function Fx(e){try{localStorage.setItem(nu,JSON.stringify(e))}catch{}}let as=Ox(),Jn=[];function Wx(){Jn.forEach(e=>e())}function Ux(e){as={...as,...e},Fx(as),Wx()}function Kx(){const[,e]=c.useState(0);c.useEffect(()=>{const r=()=>e(n=>n+1);return Jn.push(r),()=>{Jn=Jn.filter(n=>n!==r)}},[]);const t=c.useCallback(r=>{Ux(r)},[]);return[{...as},t]}function tn(e){if(!as.globalEnabled)return!1;switch(e){case"disconnect":return as.disconnectAlert;case"completion":return as.completionAlert;case"approval":return as.approvalAlert;case"browser":return as.browserNotifications;default:return!0}}const Hx={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function au(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function iu(){return"Notification"in window&&Notification.permission==="granted"}let Ns=null;function zx(e){return e!==!1}async function Vx(){if(Ns!==null)return Ns;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Ns=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Ns=!!await e.pushManager.getSubscription(),Ns):(Ns=!1,!1)}catch{return Ns=!1,!1}}function no(e,t,r){if(iu())try{const n=new Notification(e,{body:t,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function Gx(e,t={}){const r={...Hx,...t},n=c.useRef(new Map),a=c.useRef(0),[i,o]=c.useState(null);c.useEffect(()=>{let d=!1;return Vx().then(u=>{d||o(u)}),()=>{d=!0}},[]);const l=c.useCallback((d,u,h)=>{const f=Date.now();f-a.current<r.throttleMs||(a.current=f,no(d,u,h))},[r.throttleMs]);c.useEffect(()=>{var d;if(!(!r.enabled||!iu())&&tn("browser")&&!zx(i)){if(document.hasFocus()){for(const u of e)n.current.set(u.id,kt(u.status,{activeModal:u.activeModal}));return}for(const u of e){const h=n.current.get(u.id),f=kt(u.status,{activeModal:u.activeModal}),m=u.name||u.id;if(r.onApproval&&tn("approval")&&f==="waiting_approval"&&h!=="waiting_approval"){const v=((d=u.activeModal)==null?void 0:d.message)||"Action requires your approval";l(`🔔 ${m} — Approval needed`,v.slice(0,120),`approval-${u.id}`)}r.onComplete&&tn("completion")&&ma(h)&&f==="idle"&&l(`✅ ${m} — Task complete`,"Agent has finished generating",`complete-${u.id}`),r.onError&&f==="error"&&h!=="error"&&l(`⚠️ ${m} — Error`,"Agent encountered an error",`error-${u.id}`),n.current.set(u.id,f)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,i,l])}const qx=/^(run|approve|accept|yes|allow|always)/,Xx=/^(run|approve|accept|yes|allow|always|proceed|save)/,Yx=/^(reject|deny|delete|remove|abort|cancel|no)/;function Go(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Jx(e){const t=Go(e).toLowerCase();return qx.test(t)?"primary":Yx.test(t)?"danger":"default"}function Qx(e){return Xx.test(Go(e).toLowerCase())?"approve":"reject"}function Zx(e){return e.map((t,r)=>({label:Go(t),variant:Jx(t),action:Qx(t),button:t,buttonIndex:r}))}function eg(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function tg(e,t,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,t,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,t,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class sg{constructor(){ee(this,"dedupMap",new Map);ee(this,"DEDUP_WINDOW_MS",5e3);ee(this,"DEDUP_MAX_SIZE",50);ee(this,"DEDUP_CLEANUP_AGE_MS",1e4);ee(this,"toastCallbacks",[]);ee(this,"statusEventCallbacks",[]);ee(this,"resolveActionFn",null);ee(this,"viewRequestRespondFn",null);ee(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,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(t){if(t.daemonId){const a=this.ides.find(i=>i.id===t.daemonId&&i.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const i=this.ides.find(o=>o.id===a&&o.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(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}handleRawEvent(t,r){var b;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),i=n||t.daemonId||"",o=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),l=`${i}:${t.event}:${o}`;if(this.isDuplicate(l))return;for(const p of this.statusEventCallbacks)p(t);const d=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,u=(d==null?void 0:d.type)||"";let h=ht(u);const f=this.resolveOwningDaemon(t);if(f){const p=$t(f,{fallbackId:f.id});p&&(h=!u||u==="adhdev-daemon"?p:`${p}/${h}`)}let m="",v="info";if(t.event==="agent:generating_completed"){const p=t.duration?` (${t.duration}s)`:"";m=`✅ ${h} agent task completed${p}`,v="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started")if(t.event==="agent:waiting_approval"){if(m=`⚡ ${h} approval needed`,v="warning",(b=t.modalButtons)!=null&&b.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(t);if(!p)return;const g=this.resolveActionFn,y=Zx(t.modalButtons).map(j=>({label:j.label,variant:j.variant,onClick:()=>{g(p,"resolve_action",{action:j.action,button:j.button,buttonIndex:j.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),x=eg(h,t.modalMessage,m),N=Date.now();this.emitToast({id:N,message:x,type:v,timestamp:N,targetKey:n||p,actions:y,duration:15e3}),m=""}}else if(t.event==="monitor:long_generating"){const p=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";m=`⚠️ ${h} agent is taking a long time${p}`,v="warning",tn("browser")&&!document.hasFocus()&&no(`⚠️ ${h} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const p=t.requesterName||"A team member",g=t.requestId,y=t.orgId;if(m=`👁️ ${p} wants to view your session`,v="warning",g&&y&&this.viewRequestRespondFn){const x=Date.now(),N=tg(y,g,this.viewRequestRespondFn,(j,w)=>console.error(`[EventManager] ${j} view request failed:`,w));this.emitToast({id:x,message:m,type:v,timestamp:x,actions:N,duration:3e4}),m=""}tn("browser")&&!document.hasFocus()&&no("👁️ View Request",`${p} wants to view your session`,`view-request-${g}`)}else t.event==="team:view_request_approved"?(m="✅ View request approved",v="success"):t.event==="team:view_request_rejected"&&(m=`❌ ${t.targetName||"Team member"} declined your view request`,v="warning");if(m){const p=Date.now();this.emitToast({id:p,message:m,type:v,timestamp:p,targetKey:n||t.daemonId,duration:5e3})}}}const ct=new sg,cl=new Map;function xa(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function cr(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function $a(e){return xa(e)?xa(e.result)?e.result:e:null}function rg(e){const t=$a(e);return!t||!xa(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function En(e){const t=$a(e);return!t||!xa(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Dr(e){const t=$a(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Dn(e){const t=$a(e);return!!t&&t.success===!1}function ng(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.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 ag(e,t){return e&&cr(e.currentValue)?e.currentValue:t}function ig(e,t){return cr(t)?cr(e)?typeof e=="string"&&e.trim()==="":!0:!1}function og(e,t){var i,o;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(cr(l))return l}const n=(i=t.controlValues)==null?void 0:i[e];if(cr(n))return n;const a=(o=t.defaultValues)==null?void 0:o[e];return cr(a)?a:void 0}function Qn(e,t){return e.options||t[e.id]||[]}const cg={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 lg(e,t,r){var n;return((n=cg[t])==null?void 0:n.has(r.id))===!0}function qo(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!lg(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function oi(e,t){return{value:t}}function dg(e,t,r){var a;return r?((a=Qn(e,t).find(i=>i.value===r))==null?void 0:a.label)||r:""}const ug={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function hg({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:o}){const{sendCommand:l}=Ct(),d=`${e}:${t||n}`,u=ug[n]||"#94a3b8",[h,f]=c.useState({}),m=c.useRef({}),v=c.useRef(o);m.current=h,v.current=o;const b=c.useRef(0),p={};for(const C of i||[])C.defaultValue!==void 0&&(p[C.id]=C.defaultValue);const g={...p,...o||{},...Date.now()<b.current?h:{}};c.useEffect(()=>{o&&Date.now()>b.current&&f({})},[o]);const[y,x]=c.useState(cl.get(d)||{}),[N,j]=c.useState(null),[w,A]=c.useState(null),M=c.useCallback(async(C,F={})=>{const L={...F,...t&&{targetSessionId:t}};return await l(e,C,L)},[e,t,l]),S=c.useCallback(async(C,F={})=>{const L=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await M("invoke_provider_script",{...L,scriptName:C,...F})},[M,n,r,t]),k=c.useCallback((C,F,L)=>{const D=ag(L,F);f(H=>({...H,[C.id]:D})),ng(L==null?void 0:L.effects)},[]),O=c.useCallback((C,F)=>{f(L=>{const D={...L};return F===void 0?delete D[C.id]:D[C.id]=F,D}),b.current=0},[]);if(!i||i.length===0)return null;const P=qo(i,{hostIdeType:r,providerType:n});if(P.length===0)return null;const I=async C=>{if(N===C.id){j(null);return}if(Qn(C,y).length>0){j(C.id);return}if(C.dynamic&&C.listScript){A(C.id);try{const L=await S(C.listScript,{}),D=rg(L);if(!D){const ge=Dr(L);ge&&ct.showToast(ge,"warning");return}const H=D.options;x(ge=>{const ue={...ge,[C.id]:H};return cl.set(d,ue),ue});const Q=og(C.id,{localOverrideUntil:b.current,localValues:m.current,controlValues:v.current,defaultValues:p});if(ig(Q,D.currentValue)){const ge=D.currentValue;f(ue=>({...ue,[C.id]:ge}))}j(C.id)}catch(L){const D=L instanceof Error?L.message:`Could not load ${C.label}`;ct.showToast(D,"warning")}finally{A(null)}}},W=async(C,F)=>{j(null);const L=(o==null?void 0:o[C.id])??p[C.id];f(D=>({...D,[C.id]:F})),b.current=Date.now()+5e3;try{if(!C.setScript)return;const D=await S(C.setScript,oi(C,F)),H=En(D);if(H&&!H.ok||Dn(D))throw new Error((H==null?void 0:H.error)||Dr(D)||`Could not update ${C.label}`);k(C,F,H)}catch(D){O(C,L);const H=D instanceof Error?D.message:`Could not update ${C.label}`;ct.showToast(H,"warning")}},K=async C=>{const F=Qn(C,y).map(ue=>ue.value);if(F.length===0)return;const L=String(g[C.id]||""),H=(F.indexOf(L)+1)%F.length,Q=F[H];if(typeof Q!="string")return;const ge=(o==null?void 0:o[C.id])??p[C.id];f(ue=>({...ue,[C.id]:Q})),b.current=Date.now()+5e3;try{if(!C.setScript)return;const ue=await S(C.setScript,oi(C,Q)),Z=En(ue);if(Z&&!Z.ok||Dn(ue))throw new Error((Z==null?void 0:Z.error)||Dr(ue)||`Could not update ${C.label}`);k(C,Q,Z)}catch(ue){O(C,ge);const Z=ue instanceof Error?ue.message:`Could not update ${C.label}`;ct.showToast(Z,"warning")}},R=async C=>{const L=!g[C.id],D=(o==null?void 0:o[C.id])??p[C.id];f(H=>({...H,[C.id]:L})),b.current=Date.now()+5e3;try{if(!C.setScript)return;const H=await S(C.setScript,oi(C,L)),Q=En(H);if(Q&&!Q.ok||Dn(H))throw new Error((Q==null?void 0:Q.error)||Dr(H)||`Could not update ${C.label}`);k(C,L,Q)}catch(H){O(C,D);const Q=H instanceof Error?H.message:`Could not update ${C.label}`;ct.showToast(Q,"warning")}},T=async C=>{if(!C.invokeScript)return;if(C.confirmMessage){const L=[C.confirmTitle,C.confirmMessage,C.confirmLabel].filter(H=>typeof H=="string"&&H.trim().length>0);if(!window.confirm(L.join(`
30
+
31
+ `)))return}const F=(o==null?void 0:o[C.id])??p[C.id];try{const L=await S(C.invokeScript),D=En(L);if(D&&!D.ok||Dn(L))throw new Error((D==null?void 0:D.error)||Dr(L)||`Could not run ${C.label}`);D&&k(C,F??!0,D)}catch(L){O(C,F);const D=L instanceof Error?L.message:`Could not run ${C.label}`;ct.showToast(D,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${u}33`,background:`${u}12`,color:u},children:a}),P.map(C=>{const F=String(g[C.id]||""),L=dg(C,y,F),D=N===C.id,H=w===C.id,Q=Qn(C,y),ge="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(C.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${ge} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:D?`${u}55`:"var(--border-default)",background:D?`${u}10`:"var(--surface-tertiary)",color:F?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void I(C),title:C.label,children:[C.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:C.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:H?"Loading…":L||C.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),D&&Q.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>j(null)}),s.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:[s.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:C.label}),Q.map(ue=>s.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:ue.value===F?`${u}14`:"transparent",color:ue.value===F?"var(--text-primary)":"var(--text-secondary)",borderLeft:ue.value===F?`2px solid ${u}`:"2px solid transparent"},title:ue.description||ue.label,onMouseEnter:Z=>{Z.currentTarget.style.background=`${u}10`},onMouseLeave:Z=>{Z.currentTarget.style.background=ue.value===F?`${u}14`:"transparent"},onClick:()=>void W(C,ue.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ue.label}),ue.value===F&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:u},children:"✓"})]},ue.value))]})]})]},C.id);case"cycle":return s.jsxs("button",{type:"button",className:`${ge} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:F?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void K(C),title:`Click to cycle: ${Q.map(ue=>ue.label).join(" → ")}`,children:[C.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:C.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:L||C.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},C.id);case"toggle":return s.jsxs("button",{type:"button",className:`${ge} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:F?`${u}44`:"var(--border-default)",background:F?`${u}14`:"var(--surface-tertiary)",color:F?u:"var(--text-muted)"},onClick:()=>void R(C),"aria-pressed":!!F,children:[C.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:C.icon}),C.label]},C.id);case"action":return s.jsxs("button",{type:"button",className:`${ge} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void T(C),children:[C.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:C.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:C.resultDisplay==="inline"&&F?`${C.label}: ${F}`:C.label})]},C.id);case"display":return s.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:F?"var(--text-primary)":"var(--text-muted)"},children:[C.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:C.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:F?`${C.label}: ${F}`:C.label})]},C.id);default:return null}})]})})}function pg({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:o,controls:l,controlValues:d}){const{isVisible:u}=zo(),h=qo(l,{hostIdeType:a,providerType:i});return!e||t||h.length===0||!u?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(hg,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:o,controls:h,controlValues:d})})}const $r=5,ou=10*1024*1024;function fg({hasDraft:e,isBusy:t=!1}){return!e||t}function mg(e){return new Promise((t,r)=>{const n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(e)})}async function xg(e){if(e.size>ou)return null;const t=await mg(e),r=t.indexOf(",");if(r<0)return null;const n=t.slice(r+1);return{mimeType:e.type||"image/png",data:n,name:e.name,previewUrl:t}}function gg(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const cu=c.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:o,isActive:l=!0,showControlsToggle:d=!1,animateVisibility:u=!0,onControlsToggle:h,messageInput:f}){const m=c.useRef(null),v=c.useRef(null),[b,p]=c.useState(""),[g,y]=c.useState([]),[x,N]=c.useState(null),[j,w]=c.useState(!1),A=c.useRef(!1),{isVisible:M,toggleVisibility:S}=zo(),k=gg(f),O=!!b.trim()||g.length>0;c.useEffect(()=>{p(""),y([]),N(null)},[t]),c.useEffect(()=>{var C;l&&((C=m.current)==null||C.focus({preventScroll:!0}))},[t,l]);const P=c.useCallback(async C=>{N(null);const F=Array.from(C).filter(ue=>ue.type.startsWith("image/"));if(F.length===0)return;const L=$r-g.length;if(L<=0){N(`Max ${$r} images`);return}const D=F.slice(0,L);if(D.filter(ue=>ue.size>ou).length>0){N("Image too large (max 10 MB)");return}const ge=(await Promise.all(D.map(xg))).filter(ue=>ue!==null);y(ue=>[...ue,...ge])},[g.length]),I=c.useCallback(C=>{y(F=>F.filter((L,D)=>D!==C))},[]),W=c.useCallback(async()=>{const C=b.trim();if(!C&&g.length===0||a||A.current)return;A.current=!0;const F=g.length>0?[...g]:void 0;try{await o(C,F)!==!1&&(p(""),y([]),N(null))}finally{A.current=!1}},[b,g,a,o]),K=c.useCallback(C=>{k&&(C.preventDefault(),w(!0))},[k]),R=c.useCallback(()=>w(!1),[]),T=c.useCallback(C=>{k&&(C.preventDefault(),w(!1),C.dataTransfer.files.length>0&&P(C.dataTransfer.files))},[k,P]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",u?"transition-all duration-200 ease-out":"",j?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?200:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,onDragOver:K,onDragLeave:R,onDrop:T,children:[g.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:g.map((C,F)=>s.jsxs("div",{className:"relative group w-14 h-14 rounded-lg overflow-hidden border border-border-subtle shrink-0",style:{background:"var(--surface-secondary)"},children:[s.jsx("img",{src:C.previewUrl,alt:C.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>I(F),className:"absolute top-0.5 right-0.5 w-4 h-4 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-[10px] leading-none","aria-label":`Remove ${C.name}`,children:"✕"})]},F))}),s.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[d&&s.jsx("button",{type:"button",onClick:()=>{S(),h==null||h()},"aria-label":M?"Hide controls":"Show controls","aria-pressed":M,title:M?"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:s.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),k&&s.jsxs(s.Fragment,{children:[s.jsx("input",{ref:v,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:C=>{C.target.files&&P(C.target.files),C.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var C;return(C=v.current)==null?void 0:C.click()},disabled:g.length>=$r,title:g.length>=$r?`Max ${$r} images`:"Attach image",className:"h-10 w-8 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 disabled:opacity-40","aria-label":"Attach image",children:s.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"})})})]}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("input",{ref:m,type:"text",placeholder:i||(k&&g.length>0?"Add a message (optional)...":`Send message to ${r}...`),value:b,onChange:C=>p(C.target.value),onPaste:C=>{if(k&&C.clipboardData.files.length>0&&Array.from(C.clipboardData.files).some(D=>D.type.startsWith("image/"))){C.preventDefault(),P(C.clipboardData.files);return}const F=C.clipboardData.getData("text");F&&p(L=>L+F),C.preventDefault()},onKeyDown:C=>{if(C.key==="Enter"){if(C.nativeEvent.isComposing){C.preventDefault();return}C.preventDefault(),W()}},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))"}})}),s.jsx("button",{onClick:()=>{W()},disabled:fg({hasDraft:O,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${O&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:O&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":"Send message",children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:O?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),(x||k&&j)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${x?"text-red-400":"text-[var(--accent-primary)]"}`,children:x||"Drop image here"}),i&&!x&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),it=e=>e.transport==="pty",Tr=(e,t)=>it(e)?e.mode||"terminal":"chat",lu=(e,t)=>it(e)&&Tr(e)==="terminal",nt=e=>e.transport==="acp",bg=180;function vs(e){return e.streamSource!=="agent-stream"}function Ys(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function du(e){return e.machineName||""}function Sn(e){return Ys(e)}function ts(e){return e.agentType||""}function ga(e){return e.hostIdeType||""}function Xo(e){return e.displayPrimary||e.agentName||"Agent"}function uu(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function yg(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function hu(e){const t=yg(e),r=fr(t==null?void 0:t.content),n=fr(e.lastMessagePreview);return r||n||""}function vg(e,t=bg){const r=fr(e);if(!r||t<=0)return"";const n=Array.from(r);return n.length<=t?r:`${n.slice(0,Math.max(0,t-1)).join("").trimEnd()}…`}function wg(e){return vg(hu(e)||e.displaySecondary||"")}function pu(e){return[e.displaySecondary,du(e)].filter(Boolean)}function xr(e){return e.agentName||ht(ts(e))}function Sg(e){var t,r;if(!vs(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return ht(ga(e)||ts(e))}function fu(e){return vs(e)?e.sessionId:e.nativeSessionId}function ll(e){return vs(e)?"native":e.tabKey}function kg(e){return e.sessionId}function jg(e,t){if(t)return vs(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function Ng(e,t){const r=ts(e),n=vs(e),a=it(e)||nt(e),i=n?a?xr(e)||(t==null?void 0:t.cliName)||ht(ga(e)||r):t!=null&&t.type?ht(t.type):ht(ga(e)||r):xr(e);return{isNativeConversation:n,isCli:it(e),isAcp:nt(e),isCliTerminal:lu(e),providerType:r,displayLabel:i,targetEntry:jg(e,t)}}function Ps(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:it(e)||nt(e)?{agentType:ts(e)}:e.streamSource==="agent-stream"?{agentType:ts(e)}:t}function gr(e){return e?Sn(e):""}function Br(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Yo(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Cg(e){const t=e instanceof Error?e.message:String(e||""),r=t.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.":t||"Unable to send message right now."}function mu(){return"select_session"}function Tg(){return"open_panel"}function Ig({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function Ag(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function dl(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function ba(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Jo(e){return e instanceof Error?e.message:String(e||"")}function ul(e){const t=Jo(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function hl(e,t){const r=Jo(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function Mg(e,t,r){const n=Ps(r);if(!t||t.length===0)return{message:e,...n};const a=t.map(i=>({type:"image",mimeType:i.mimeType,data:i.data,alt:i.name}));return e&&a.push({type:"text",text:e}),{message:e,input:{parts:a,textFallback:e},...n}}function Ba({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,i]=c.useState(!1),[o,l]=c.useState(!1),[d,u]=c.useState(null),h=c.useRef(!1),f=c.useRef(null);c.useEffect(()=>{u(null)},[t==null?void 0:t.tabKey]);const m=c.useCallback(async(g,y)=>{if(!t||h.current)return!1;const x=g.trim(),N=Yo(t);if(Ig({hasMessage:!!x,blockedMessage:N,sendInFlight:h.current}))return N&&u(N),!1;const j=Date.now(),w={tabKey:t.tabKey,message:x,timestamp:j};if(Ag(f.current,w))return u(null),!0;h.current=!0,l(!0),u(null),f.current=w;try{const A=gr(t);if(!A)return f.current=dl(f.current,w),u("Unable to send message right now."),!1;const M=await e(A,"send_chat",Mg(x,y,t)),S=ba(M);if(S!=null&&S.deduplicated)return u(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 u(null),!0}catch(A){const M=Jo(A);return M.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",M):console.warn("Send blocked/failed",A),f.current=dl(f.current,w),u(Cg(A)),!1}finally{h.current=!1,l(!1)}},[t,e]),v=c.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(g){console.error("Relaunch failed",g)}},[t,e]),b=c.useCallback(async g=>{if(t)try{const x=(t.modalButtons||[]).indexOf(g),N=g.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),j=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N),w=gr(t);if(!w)return;const A=await e(w,"resolve_action",{button:g,action:j?"approve":"reject",...x>=0&&{buttonIndex:x},...Ps(t)}),M=ba(A);M.success||r(S=>[...S,{routeId:t.tabKey,text:hl(g,M==null?void 0:M.error),timestamp:Date.now()}])}catch(y){ul(y)||console.error("[ModalButton] Error:",y),r(x=>[...x,{routeId:t.tabKey,text:ul(y)?hl(g,y):`❌ **${g}** error`,timestamp:Date.now()}])}},[t,e,r]),p=c.useCallback(async()=>{if(!(!t||a)){i(!0);try{await e(t.routeId,Tg(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(g){console.error("Focus agent failed",g)}finally{i(!1)}}},[t,a,e]);return{isSendingChat:o,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:m,handleRelaunch:v,handleModalButton:b,handleFocusAgent:p}}const _g=10,Rg=8e3,Pg=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function Lg(e){return e.replace(/(Authorization\s*:\s*Bearer\s+)[^\s'"`]+/gi,"$1[REDACTED:bearer]").replace(/(Bearer\s+)[A-Za-z0-9._~+\/-]{12,}=*/gi,"$1[REDACTED:bearer]").replace(/\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]{20,}\b/g,"[REDACTED:github-token]").replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:api-key]").replace(/\b(?:adk|adm)_[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:adhdev-token]").replace(/((?:api[_-]?key|token|secret|password|passwd|client[_-]?secret)\s*[:=]\s*)[^\s,'"`}&]+/gi,"$1[REDACTED:secret]").replace(/([?&](?:api[_-]?key|token|secret|password|client_secret)=)[^&#\s]+/gi,"$1[REDACTED:secret]")}function ao(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(Pg.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=Lg(e);return n.length>8e3?`${n.slice(0,8e3)}…[truncated ${n.length-8e3} chars]`:n}if(typeof e!="object")return String(e);if(r>=6)return"[MaxDepth]";if(Array.isArray(e)){const n=e.slice(-20).map(a=>ao(a,t,r+1));return e.length>20?[{truncatedBefore:e.length-20},...n]:n}return Object.fromEntries(Object.entries(e).slice(0,80).map(([n,a])=>[n,ao(a,n,r+1)]))}function Or(e,t){return Array.isArray(e)?e.slice(-t):[]}function Eg(e,t=Date.now()){const r=e&&t-e.firstAt<=Rg,n=r?e.count+1:1;return n>=_g?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function xu(e){var n,a;const{activeConv:t}=e,r={version:1,createdAt:new Date(e.now??Date.now()).toISOString(),url:e.locationHref??(typeof window<"u"?window.location.href:void 0),activeConversation:{routeId:t.routeId,tabKey:t.tabKey,sessionId:t.sessionId,providerSessionId:t.providerSessionId,transport:t.transport,agentName:t.agentName,agentType:t.agentType,hostIdeType:t.hostIdeType,status:t.status,connectionState:t.connectionState,title:t.title,workspaceName:t.workspaceName,displayPrimary:t.displayPrimary,displaySecondary:t.displaySecondary,streamSource:t.streamSource,lastMessageHash:t.lastMessageHash},messageCounts:{live:((n=e.chatTailState.liveMessages)==null?void 0:n.length)??t.messages.length,activeConversation:t.messages.length,visible:e.visibleMessages.length,history:((a=e.chatTailState.historyMessages)==null?void 0:a.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:Or(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:Or(t.messages,10),visibleMessagesTail:Or(e.visibleMessages,5),historyMessagesTail:Or(e.chatTailState.historyMessages,5),actionLogsTail:Or(e.actionLogs.filter(i=>i.routeId===t.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chatTail:{hasLiveSnapshot:!!e.chatTailState.hasLiveSnapshot,hasMoreHistory:!!e.chatTailState.hasMoreHistory,historyError:e.chatTailState.historyError||null},ui:e.ui,browser:typeof navigator<"u"?{userAgent:navigator.userAgent,language:navigator.language,online:navigator.onLine}:null};return ao(r)}function gu(e,t={}){const r=e&&typeof e=="object"?e:{},n=t.locatorCopyStatus??(t.locatorCopied===!1?"failed":"copied"),a=n==="copied"?"locator copied":n==="manual"?"locator shown for manual copy":"locator copy failed";return r.delivery==="daemon_file"?`Chat debug signal sent${typeof r.bundleId=="string"&&r.bundleId.trim()?` (${r.bundleId})`:""}; saved on daemon, ${a}.`:`Chat debug signal sent; ${a}.`}async function bu(e){var t;if(typeof navigator<"u"&&((t=navigator.clipboard)!=null&&t.writeText)&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(e),"copied"}catch(r){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",r)}if(typeof document<"u"&&document.body){let r=null;try{if(r=document.createElement("textarea"),r.value=e,r.setAttribute("readonly","true"),r.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(r),r.focus(),r.select(),document.execCommand("copy"))return"copied"}catch{}finally{r==null||r.remove()}}if(typeof window<"u"&&typeof window.prompt=="function")try{return window.prompt("Copy ADHDev chat debug locator:",e),"manual"}catch{}return"failed"}function yu(e){const t=e&&typeof e=="object"?e:{};if(t.delivery==="daemon_file"){const r=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(t.bundleId||"")}`,`savedPath: ${String(t.savedPath||"")}`,`sizeBytes: ${String(t.sizeBytes||"")}`,`createdAt: ${String(t.createdAt||"")}`];return t.summary&&typeof t.summary=="object"&&r.push("","summary:",JSON.stringify(t.summary,null,2)),Array.isArray(t.warnings)&&t.warnings.length>0&&r.push("","warnings:",...t.warnings.map(n=>`- ${String(n)}`)),r.join(`
32
+ `)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
33
+
34
+ \`\`\`json
35
+ ${JSON.stringify(t.bundle,null,2)}
36
+ \`\`\``:`# ADHDev Chat Debug Bundle
37
+
38
+ \`\`\`json
39
+ ${JSON.stringify(t,null,2)}
40
+ \`\`\``}function ci(e,t){return`${e}:${t}`}function Dg(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Fr(e,t){Dg()&&console.debug(`[subscription-manager] ${e}`,t)}class $g{constructor(){ee(this,"active",new Map);ee(this,"retryTimers",new Map)}subscribe(t,r,n,a,i){var h;const o=ci(n.topic,n.key),l=this.active.get(o);let d=!0;if(l)l.handlers.add(a),l.lastUpdate&&a(l.lastUpdate);else{const f={daemonId:r,request:n,handlers:new Set([a])};this.active.set(o,f),Fr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((h=t.sendData)==null?void 0:h.call(t,r,n))??!1,!d&&(i!=null&&i.retryIntervalMs)&&this.scheduleRetry(o,t,i.retryIntervalMs)}const u=()=>{var v;this.clearRetry(o);const f=this.active.get(o);if(!f||(f.handlers.delete(a),f.handlers.size>0))return;this.active.delete(o);const m={type:"unsubscribe",topic:n.topic,key:n.key};Fr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(v=t.sendData)==null||v.call(t,r,m)};return u.initialSendAccepted=d,u}publish(t){const r=ci(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,pr.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),n.handlers.forEach(a=>{a(t),pr.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,r,n){const a=ci(t,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(t){var r;Fr("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=t.sendData)==null||r.call(t,n.daemonId,n.request)}resubscribeForDaemon(t,r){var a;const n=Array.from(this.active.values()).filter(i=>i.daemonId===t);Fr("resubscribe_daemon",{daemonId:t,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)}scheduleRetry(t,r,n){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var l;this.retryTimers.delete(t);const i=this.active.get(t);if(!i)return;const o=((l=r.sendData)==null?void 0:l.call(r,i.daemonId,i.request))??!1;Fr("subscribe_retry",{id:t,accepted:o,topic:i.request.topic,key:i.request.key}),o||this.scheduleRetry(t,r,n)},n);this.retryTimers.set(t,a)}clearRetry(t){const r=this.retryTimers.get(t);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(t))}}const os=new $g;function Bg(e,t){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===t&&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,settings:n.settings});for(const i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const o=r.get(i.id)||{};r.set(i.id,{...o,...i})}}return r}function Og(e){const t=[],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 t.push(n);return{topLevel:t,childrenByParent:r}}function li(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function Fg(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function Wg(e){Fg()&&console.debug("[dashboard-conversations] statusPayloadToEntries",e.map(t=>({id:t.id,daemonId:t.daemonId,sessionId:t.sessionId,instanceId:t.instanceId,providerSessionId:t.providerSessionId,transport:t.transport,type:t.type})))}function ya(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:o}=t,l=o||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:u,childrenByParent:h}=Og(d),f=Bg(i,n),m=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,v=u.filter(g=>g.kind==="workspace"&&g.transport==="cdp-page"),b=u.filter(g=>g.kind==="agent"&&g.transport==="pty"),p=u.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},...m&&{machine:m,platform:m.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},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:v.some(g=>!!g.cdpConnected)});for(const g of v){const y=f.get(g.id),x=qr(g,y),N=(h.get(g.id)||[]).map(j=>qr(j,f.get(j.id)));r.push({id:`${n}:ide:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,status:x.cdpConnected?"online":"detected",daemonId:n,instanceId:li(n,g.id),workspace:x.workspace,terminals:0,childSessions:N,agents:N.map(j=>({id:j.id,name:j.providerName||j.providerType,type:j.providerType,status:j.status})),activeChat:x.activeChat,chats:[],cdpConnected:x.cdpConnected,...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},...x.settings!==void 0&&{settings:x.settings},...x.messageInput!==void 0&&{messageInput:x.messageInput},timestamp:l})}for(const g of b){const y=f.get(g.id),x=qr(g,y);r.push({id:`${n}:cli:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,agentType:x.providerType,status:x.status||"running",daemonId:n,instanceId:li(n,g.id),cliName:x.providerName||x.providerType,mode:x.mode||(y==null?void 0:y.mode)||"terminal",workspace:x.workspace||"",activeChat:x.activeChat,...x.resume!==void 0&&{resume:x.resume},...x.runtimeKey!==void 0&&{runtimeKey:x.runtimeKey},...x.runtimeDisplayName!==void 0&&{runtimeDisplayName:x.runtimeDisplayName},...x.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:x.runtimeWorkspaceLabel},...x.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:x.runtimeWriteOwner},...x.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:x.runtimeAttachedClients},...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},...x.settings!==void 0&&{settings:x.settings},...x.messageInput!==void 0&&{messageInput:x.messageInput},timestamp:l,_isCli:!0})}for(const g of p){const y=f.get(g.id),x=qr(g,y);r.push({id:`${n}:acp:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,agentType:x.providerType,status:x.status||"running",daemonId:n,instanceId:li(n,g.id),cliName:x.providerName||x.providerType,mode:"chat",workspace:x.workspace||"",activeChat:x.activeChat,...x.runtimeKey!==void 0&&{runtimeKey:x.runtimeKey},...x.runtimeDisplayName!==void 0&&{runtimeDisplayName:x.runtimeDisplayName},...x.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:x.runtimeWorkspaceLabel},...x.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:x.runtimeWriteOwner},...x.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:x.runtimeAttachedClients},...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},...x.settings!==void 0&&{settings:x.settings},...x.messageInput!==void 0&&{messageInput:x.messageInput},timestamp:l,_isAcp:!0})}return Wg(r),r}const Ug=15e3,Kg=15e3,Hg=6e4,zg=1200,pl=12,Vg=8e3,Gg=4e3,di=new Map,ui=new Map,$n=new Set,sn=new Map;function qg(e){if(!e||typeof e!="object")return null;const t=e,r=t.status;if(r&&typeof r=="object")return r;const n=t.result;if(n&&typeof n=="object"&&"status"in n){const a=n.status;if(a&&typeof a=="object")return a}return t}function fl(e,t){const r=sn.get(e);!r||r.size===0||(sn.delete(e),r.forEach(n=>n(t)))}function Xg(e,t){return new Promise(r=>{const n=sn.get(e)||new Set;sn.set(e,n);const a=o=>{clearTimeout(i),n.delete(a),n.size===0&&sn.delete(e),r(o)},i=setTimeout(()=>a(!1),t);n.add(a)})}function kn(){const{sendCommand:e,sendData:t}=Ct(),{injectEntries:r,getIdes:n}=pn();return c.useCallback(async(a,i)=>{if(!a)return;const o=(i==null?void 0:i.minFreshMs)??Hg,l=ui.get(a)||0;if(!(i!=null&&i.force)&&$n.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<o)return;const d=di.get(a);if(d)return d;const u=(async()=>{if(t&&!$n.has(a)){const p=os.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},g=>{const y=n(),x=y.find(j=>j.id===a),N=ya(g.status,{daemonId:a,existingDaemon:x,existingEntries:y,timestamp:g.timestamp});N.length>0&&r(N),ui.set(a,Date.now()),fl(a,!0)});if(p.initialSendAccepted?$n.add(a):$n.delete(a),!(i!=null&&i.force)&&p.initialSendAccepted&&await Xg(a,zg))return}const h=await e(a,"get_status_metadata"),f=qg(h);if(!f)return;const m=n(),v=m.find(p=>p.id===a),b=ya(f,{daemonId:a,existingDaemon:v,existingEntries:m,timestamp:f.timestamp||Date.now()});b.length>0&&r(b,{authoritativeDaemonIds:[a]}),ui.set(a,Date.now()),fl(a,!0)})().finally(()=>{di.delete(a)});return di.set(a,u),u},[n,r,e,t])}function Yg(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const Jg=60,Qg=50;function vu(e={}){return e.isCliLike?Qg:Jg}function Zg(e={}){return vu(e)}function Pt(e){return(typeof e=="string"?e.trim():"")||void 0}function is(e,t){const r=Pt(t);return r?`${e}:${r}`:void 0}function bs(e,t,r){const n=is(t,r),a=Pt(r);n&&e.push(n),a&&e.push(a)}function ar(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function wu(e){return Pt(e.providerSessionId)||Pt(e.sessionId)||Pt(e.tabKey)||Pt(e.routeId)}function Qo(e){return ar([Pt(e.providerSessionId),Pt(e.sessionId)])}function lr(e){const t=[];return bs(t,"provider",e.providerSessionId),bs(t,"session",e.sessionId),bs(t,"tab",e.tabKey),bs(t,"route",e.routeId),ar(t)}function eb(e){const t=[];return Pt(e.providerSessionId)?(bs(t,"provider",e.providerSessionId),ar(t)):Pt(e.sessionId)?(bs(t,"session",e.sessionId),ar(t)):Pt(e.tabKey)?(bs(t,"tab",e.tabKey),ar(t)):Pt(e.routeId)?(bs(t,"route",e.routeId),ar(t)):[]}function Zo(e){return is("provider",e.providerSessionId)||is("session",e.sessionId)||is("tab",e.tabKey)||is("route",e.routeId)||"unknown:"}function jn(e){return Qo(e)[0]}function tb(e){const t=Pt(e.providerSessionId),r=Pt(e.sessionId),n=Pt(e.tabKey),a=Pt(e.routeId),i=[is("provider",t),is("session",r),is("tab",n),is("route",a)].filter(d=>typeof d=="string"),o=lr({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=Zo({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:wu({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:jn({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:o}}function io(e,t){const r=tb(e);return eb(t).some(n=>r.lookupKeys.includes(n))}const Nn=60,sb=1e3,ec=12e4,rb=new Set(["generating","waiting_approval","starting","streaming","working"]),ml=new Map;function Su(e,t){return`${e}::${t}`}function oo(e=Nn){return{liveMessages:[],hasLiveSnapshot:!1,cursor:nb([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function nb(e,t=Nn){return{tailLimit:t}}function xl(e,t){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("|")}class ab{constructor(t){ee(this,"manager");ee(this,"sendData");ee(this,"daemonId");ee(this,"sessionId");ee(this,"historySessionId");ee(this,"subscriptionKey");ee(this,"fallbackRecentCount");ee(this,"snapshot");ee(this,"transportSubscription",null);ee(this,"listeners",new Set);ee(this,"retainCount",0);ee(this,"loadHistoryPromise",null);ee(this,"pendingDisconnectTimer",null);this.manager=t.manager||os,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount??0),this.snapshot=oo(Math.max(0,t.tailLimit??Nn))}updateOptions(t){if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount)),t.tailLimit!==void 0){const r=Math.max(0,t.tailLimit);r!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect()))}}getSnapshot(){return this.snapshot}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}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(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=this.snapshot.hasLiveSnapshot,a=n?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),i=await t({offset:this.snapshot.historyOffset,excludeRecentCount:a}),o=Array.isArray(i.messages)?i.messages:[],l=!n&&o.length===0&&i.hasMore!==!0&&this.fallbackRecentCount>0;this.snapshot={...this.snapshot,historyMessages:[...o,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+o.length,hasMoreHistory:l?!0:i.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}:{},...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),t=>{this.handleUpdate(t)},{retryIntervalMs:sb}))}disconnect(){var t;(t=this.transportSubscription)==null||t.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(t=>t(this.snapshot))}handleUpdate(t){if(t.error)return;const r=Array.isArray(t.messages)?t.messages:[],n={tailLimit:this.snapshot.cursor.tailLimit};xl(this.snapshot.liveMessages)===xl(r)&&this.snapshot.cursor.tailLimit===n.tailLimit||(this.snapshot={...this.snapshot,liveMessages:r,hasLiveSnapshot:!0,cursor:n},this.emit())}}function ku(e){const t=Su(e.daemonId,e.sessionId),r=ml.get(t);if(r)return r.updateOptions(e),r;const n=new ab(e);return ml.set(t,n),n}function ib(e,t){return{...e,loadHistoryPage:t}}function ob(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function cb(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(rb.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=t.now??Date.now(),a=Math.max(0,Number(t.recentActivityMs??ec)),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 lb(e=ec){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function db(e,t={}){const r=new Set,n=[];for(const a of e){if(!cb(a,t))continue;const i=Sn(a),o=a.sessionId||"";if(!i||!o)continue;const l=Su(i,o);if(r.has(l))continue;r.add(l);const d=jn(a);n.push({daemonId:i,sessionId:o,historySessionId:d||o,subscriptionKey:`daemon:${i}:session:${o}`})}return n.sort(ob),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function ub(e,t){const{sendData:r,sendCommand:n}=Ct(),a=(t==null?void 0:t.enabled)!==!1,i=Sn(e),o=e.sessionId||"",l=jn(e)||o,d=`daemon:${i}:session:${o}`,u=Math.max(0,(t==null?void 0:t.tailLimit)??Nn),h=c.useMemo(()=>!a||!i||!o?null:ku({daemonId:i,sessionId:o,historySessionId:l,subscriptionKey:d,sendData:r,tailLimit:u,fallbackRecentCount:e.messages.length}),[e.messages.length,i,a,l,r,o,d,u]),[f,m]=c.useState(()=>(h==null?void 0:h.getSnapshot())||oo(u));c.useEffect(()=>{if(!h){m(oo(u));return}h.retain(),m(h.getSnapshot());const b=h.subscribe(p=>{m(p)});return()=>{b(),h.release()}},[h,u]);const v=c.useCallback(async()=>{!h||!i||!o||await h.loadHistoryPage(async({offset:b,excludeRecentCount:p})=>{const g=e.agentType,y=await n(i,"chat_history",{agentType:g,offset:b,limit:30,targetSessionId:o,historySessionId:l,excludeRecentCount:p}),x=y&&typeof y=="object"&&"result"in y?y.result||{}:y||{};return{messages:Array.isArray(x.messages)?x.messages:[],hasMore:x.hasMore===!0}})},[e.agentType,h,i,l,n,o]);return c.useMemo(()=>ib(f,v),[v,f])}function hb(e,t){const{sendData:r}=Ct(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??Nn),i=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??ec)),o=lb(i),[l,d]=c.useState(0);c.useEffect(()=>{if(!n||e.length===0)return;const h=setInterval(()=>{d(f=>f+1)},o);return()=>{clearInterval(h)}},[e.length,n,o]);const u=c.useMemo(()=>db(e,{recentActivityMs:i}),[e,i,l]);c.useEffect(()=>{if(!n||!r||u.descriptors.length===0)return;const h=u.descriptors.map(f=>ku({...f,sendData:r,tailLimit:a}));return h.forEach(f=>{f.retain()}),()=>{h.forEach(f=>f.release())}},[u.signature,n,r,a])}function pb(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function gl(e){const t=String(e.role||"").toLowerCase();if(t!=="user"&&t!=="assistant")return!1;const r=String(e.kind||"standard").toLowerCase();return r===""||r==="standard"}function fb(e,t){if(e.length===0)return[];if(t.some(gl))return[];const r=[],n=new Set;for(let a=e.length-1;a>=0&&r.length<2;a-=1){const i=e[a];if(!i||!gl(i))continue;const o=String(i.role||"").toLowerCase();n.has(o)||(n.add(o),r.unshift(i))}return r}function mb(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,a=Math.max(0,r.length-n),i=a>0?r.slice(0,a):[],o=a>0?r.slice(-n):r,l=fb(i,o),d=l.length>0?[...l,...o]:o;return t.length===0?d:[...t,...d]}function xb(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function gb(e){return xb(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function bb(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function yb(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function vb(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function ju(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function Nu(e){const t=typeof e.completionMarker=="string"?e.completionMarker.trim():"";return t||(e.lastMessageHash?e.lastMessageHash:e.lastMessageAt?String(e.lastMessageAt):e.lastUpdated?String(e.lastUpdated):"")}function wb(e){return ju(e)?!1:e.inboxBucket==="task_complete"&&Nu(e).length>0}function bl(e){return e.branch||"detached HEAD"}function Sb(e){if(e.error)return`${bl(e)} · Git error: ${e.error}`;const t=[bl(e)];return e.changedFiles>0?t.push(bb(e.changedFiles,"file")+" changed"):e.dirty||t.push("clean"),e.ahead>0&&t.push(`ahead ${e.ahead}`),e.behind>0&&t.push(`behind ${e.behind}`),e.hasConflicts&&t.push("conflicts"),t.join(" · ")}function kb(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${Sb(t)}`}function jb(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function Nb(e,t={}){if(t.enabled===!1)return[];if(!vb(e))return[];const r=ju(e)?"working":wb(e)?"complete":null;if(!r)return[];const n=r==="complete"?Nu(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${yb(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:kb(r,e.git),timestamp:jb(e,e.git),meta:{source:"git-system-bubble",phase:r,workspace:e.workspacePath,repoRoot:e.git.repoRoot,branch:e.git.branch,changedFiles:e.git.changedFiles,hasConflicts:e.git.hasConflicts}}]}const Cb=60;function co({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:o,actionLogs:l,userName:d,scrollToBottomRequestNonce:u,isInputActive:h=!0,isVisible:f=!0}){var Ce,pe,me,oe,fe,ce,E;const m=c.useRef(new Map),v=c.useRef(void 0),b=kn(),{sendCommand:p}=Ct(),{isVisible:g}=zo();wn("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const y=Et.useMemo(()=>Cr(e),[e.status,e.connectionState]),x=c.useMemo(()=>Ng(e,t),[e,t]),N=c.useMemo(()=>{var z;return qo((z=x.targetEntry)==null?void 0:z.providerControls,{hostIdeType:e.hostIdeType,providerType:x.providerType})},[e.hostIdeType,x.providerType,(Ce=x.targetEntry)==null?void 0:Ce.providerControls]),j=vu({isCliLike:x.isCli||x.isAcp}),w=Zg({isCliLike:x.isCli||x.isAcp}),A=ub(e,{enabled:f&&!!e.sessionId,tailLimit:w}),[M,S]=c.useState(j),[k,O]=c.useState(()=>Qc()),P=e.tabKey,I=A.historyMessages,W=A.hasMoreHistory,K=A.historyError,R=pb(e,A),T=Vd(R).length;c.useEffect(()=>{S(j)},[j,P]);const C=Math.max(0,R.length-M),F=Xo(e),L=Sn(e),D=gb(e),H=Yo(e),Q=a||H,ge=!!H,[ue,Z]=c.useState(!1);c.useEffect(()=>{const z=x.targetEntry;L&&(!z||z.providerControls===void 0||z.controlValues===void 0)&&b(L,{minFreshMs:3e4}).catch(()=>{})},[L,x.isAcp,(pe=x.targetEntry)==null?void 0:pe.providerControls,(me=x.targetEntry)==null?void 0:me.controlValues,b]);const xe=c.useCallback(async()=>{if(!ue){if(R.length>M){S(z=>Math.min(R.length,z+Cb));return}Z(!0);try{await A.loadHistoryPage()}finally{Z(!1)}}},[A,ue,R.length,M]),{allMessages:Se,receivedAtMap:be}=c.useMemo(()=>{const z=mb({historyMessages:I,liveMessages:R,visibleLiveCount:M}),le=Nb(e),re=le.length>0?[...z,...le]:z,q={};return re.forEach((je,we)=>{const Pe=`${e.tabKey}:${pa(je,we)}`;let Re=Yg(je)||m.current.get(Pe)||0;Re||(Re=Date.now(),m.current.set(Pe,Re)),q[pa(je,we)]=Re}),{allMessages:re,receivedAtMap:q}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,C,I,R,M]),Y=c.useMemo(()=>l.filter(z=>z.routeId===e.tabKey).sort((z,le)=>z.timestamp-le.timestamp),[l,e.tabKey]),he=c.useCallback(async()=>{var we,Pe;if(!L)return;const z=xu({activeConv:e,visibleMessages:Se,actionLogs:l,controls:(we=x.targetEntry)==null?void 0:we.providerControls,controlValues:(Pe=x.targetEntry)==null?void 0:Pe.controlValues,visibleBarControlCount:N.length,chatTailState:{liveMessages:A.liveMessages,hasLiveSnapshot:A.hasLiveSnapshot,hasMoreHistory:W,historyError:K,historyMessages:I},ui:{controlsVisible:g,visibleLiveCount:M,activityVisible:k,activityCount:T,hiddenLiveCount:C,isInputActive:h,isVisible:f}}),le=await p(L,"get_chat_debug_bundle",{agentType:x.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:z}),re=ba(le),q=yu(re),je=await bu(q);je==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),ct.showToast(gu(re,{locatorCopyStatus:je}),je==="failed"?"warning":"success")},[e,l,T,Se,g,A.hasLiveSnapshot,A.liveMessages,x.providerType,(oe=x.targetEntry)==null?void 0:oe.controlValues,(fe=x.targetEntry)==null?void 0:fe.providerControls,L,W,C,I,h,f,K,p,k,N.length,M]),ye=c.useCallback(()=>{O(z=>{const le=!z;return Xm(le),le})},[]);c.useEffect(()=>{const z=le=>{le.key===Wo&&O(Qc())};return window.addEventListener("storage",z),()=>window.removeEventListener("storage",z)},[]);const se=c.useCallback(()=>{const z=Eg(v.current);v.current=z.state,z.shouldCollect&&he().catch(le=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",le),ct.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[he]),de=c.useMemo(()=>{if(R.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.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:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((y.isGenerating||e.status==="streaming")&&Z(!1),e.status==="not_monitored"&&D)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(mr,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:i,disabled:o,className:"btn btn-primary",children:o?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(zs,{size:14})," Open ",F," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&D)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Ud,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:i,disabled:o,className:"btn btn-primary",children:o?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(zs,{size:14})," Open ",F," Panel"]})}),s.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"&&!ue)return!W&&I.length===0?s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"No messages yet"})]}):s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,D,i,W,I.length,o,ue,R.length,F,y.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[s.jsx("div",{className:"chat-activity-toggle-bar",children:s.jsxs("button",{type:"button",className:`chat-activity-toggle ${k?"chat-activity-toggle-active":""}`,onClick:ye,"aria-pressed":k,title:"Show tool, terminal, and runtime activity rows",children:[s.jsx("span",{className:"chat-activity-toggle-dot"}),"Activity",T>0&&s.jsx("span",{className:"chat-activity-toggle-count",children:T})]})}),s.jsx(dx,{messages:Se,actionLogs:Y,agentName:xr(e)||F||"Agent",userName:d,isCliMode:x.isCli||x.isAcp,isWorking:y.isGenerating,contextKey:e.tabKey,receivedAtMap:be,lastMessageHash:e.lastMessageHash,showActivityMessages:k,onLoadMore:xe,isLoadingMore:ue,hasMoreHistory:W,hiddenLiveCount:C,loadError:K??void 0,emptyState:de,scrollToBottomRequestNonce:u,isVisible:f}),s.jsx(pg,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:x.providerType,displayLabel:x.displayLabel,controls:(ce=x.targetEntry)==null?void 0:ce.providerControls,controlValues:(E=x.targetEntry)==null?void 0:E.controlValues,isActive:h,isCliTerminal:x.isCliTerminal}),!x.isCliTerminal&&s.jsx(cu,{contextKey:e.tabKey,panelLabel:F,isSending:n,isBusy:ge,statusMessage:Q,onSend:r,isActive:h,showControlsToggle:N.length>0,onControlsToggle:se,messageInput:e.messageInput})]})}let Cu=Ss;function Tu(){return Cu()}class Tb{constructor(){ee(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{var n;(n=this.listeners.get(t))==null||n.delete(r)}}emit(t,...r){var n;(n=this.listeners.get(t))==null||n.forEach(a=>a(...r))}}let Iu=new Tb;class Ib{sendPtyInput(t,r,n){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,r){return!1}get(t){}onScreenshot(t,r){return()=>{}}onRuntimeEvent(t,r,n){return()=>{}}requestRuntimeSnapshot(t,r,n){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let xt=new Ib;function Ab(e){e.dashboardWS&&(Iu=e.dashboardWS),e.connectionManager&&(xt=e.connectionManager),e.useDaemonsHook&&(Cu=e.useDaemonsHook)}const Mb=.5,_b=1.25;function ft(e){return Xo(e)}function Gs(e){return pu(e).join(" · ")}function Au(e){const t=hu(e);return t||(e.title?e.title:Gs(e)||"No messages yet")}function Mu(e,t){const{isReconnecting:r,isConnecting:n}=Cr(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function Rb(e,t){const r=["Chat",...pu(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function Ls(e){return Mu(e)||Gs(e)}function Pb(e){return`${ft(e)} · ${Au(e)}`}function Lb(e){const t=ga(e),r=t?ht(t):xr(e);return`${ft(e)} — ${r||"Agent"}`}function Eb(e){return xr(e)||"CLI"}function _u(e){return uu(e)}function Ru(e){return e?`Remote · ${ft(e)||e.workspaceName||"Session"}`:"Remote"}function Db({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:o=!0,isInputActive:l=!0}){var ne;Ss();const{sendPtyInput:d}=Ct(),[u,h]=c.useState(!1),f=c.useRef(!1);f.current=u;const[m,v]=c.useState("Runtime terminal unavailable"),[b,p]=c.useState(!1),[g,y]=c.useState(null),[x,N]=c.useState(!1),[j,w]=c.useState(!1),[A,M]=c.useState(1),[S,k]=c.useState(!1),[O,P]=c.useState({width:0,height:0}),[I,W]=c.useState({width:0,height:0}),[K,R]=c.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[T,C]=c.useState(null),F=c.useRef(null),L=c.useRef(null),D=c.useRef(!1),H=c.useRef(!1),Q=c.useRef(o),ge=c.useRef(0),ue=c.useRef(!1),Z=c.useRef(""),xe=c.useRef(null),Se=c.useRef(!1),be=c.useRef(!1),Y=c.useRef(null),he=c.useRef(null),ye=c.useRef(null),se=32*1024,de=()=>{var $,X,te,ae;return((X=($=F.current)==null?void 0:$.ownerDocument)==null?void 0:X.defaultView)||((ae=(te=L.current)==null?void 0:te.ownerDocument)==null?void 0:ae.defaultView)||window},Ce=$=>{const X=de();return{ownerWindow:X,frameId:X.requestAnimationFrame($)}},pe=()=>{const $=Y.current;if($){try{$.ownerWindow.cancelAnimationFrame($.frameId)}catch{}Y.current=null}},me=()=>{const $=he.current;if($){try{$.ownerWindow.clearTimeout($.timeoutId)}catch{}he.current=null}},oe=()=>{const $=ye.current;if($){try{$.ownerWindow.clearTimeout($.timeoutId)}catch{}ye.current=null}},fe=()=>{o&&Y.current===null&&(Y.current=Ce(()=>{at()}))},ce=e.tabKey,E=e.sessionId||"",z=e.daemonId||((ne=e.routeId)==null?void 0:ne.split(":")[0])||e.routeId||"",le=Yo(e),re=u?i||le:m,q=Mb,je=_b,we=.05,Pe=()=>{const $=I.width,X=I.height;if(!Number.isFinite(O.width)||O.width<=0||!Number.isFinite(O.height)||O.height<=0||!Number.isFinite($)||$<=0||!Number.isFinite(X)||X<=0)return 1;const te=O.width/$,ae=O.height/X;return Number(Math.min(je,Math.max(q,Math.min(te,ae))).toFixed(2))},Re=Pe(),B=D.current&&A>Re,Ae=Number.isFinite(I.width)&&I.width>0?Math.max(O.width,Math.round(I.width*A)):O.width,Ee=Number.isFinite(I.height)&&I.height>0?Math.max(O.height,Math.round(I.height*A)):O.height,Ve=()=>{Ce(()=>{const $=L.current;$&&($.scrollLeft=0,$.scrollTop=$.scrollHeight-$.clientHeight)})},Ge=()=>{var $,X;ge.current=0,ue.current=!1,Z.current="",xe.current=null,Se.current=!1,be.current=!1,D.current||(H.current=!1,M(1)),Y.current!==null&&pe(),h(!1),v("Runtime terminal unavailable"),oe(),me(),y(null),C(null),k(!1),p(!1),N(!1),w(!1),(X=($=r.current)==null?void 0:$.reset)==null||X.call($)},Ze=()=>{var $,X;ge.current=0,ue.current=!1,Z.current="",xe.current=null,Se.current=!1,be.current=!1,Y.current!==null&&pe(),h(!0),v(""),oe(),me(),y(null),C(null),k(!1),p(!1),N(!1),w(!1),(X=($=r.current)==null?void 0:$.reset)==null||X.call($)},et=()=>{be.current&&(be.current=!1,Ce(()=>{var $,X;(X=($=r.current)==null?void 0:$.scrollToTop)==null||X.call($)}))},at=()=>{if(Y.current=null,!o)return;const $=Z.current;if(!$)return;const X=$.slice(0,se);Z.current=$.slice(X.length);const te=r.current;if(!te){Z.current=X+Z.current,fe();return}te.write(X,()=>{if(Z.current.length>0){fe();return}et()})},gt=$=>{$&&(Z.current+=$,fe())},St=($,X=0,te,ae,Ne={})=>{var Be,Ie,Oe,We;const $e=!!Ne.force;!$e&&X>0&&ge.current>=X||!$e&&X===0&&ue.current||(ge.current=X,X>0&&N(!0),h(!0),v(""),typeof te=="number"&&typeof ae=="number"&&te>0&&ae>0&&((Ie=(Be=r.current)==null?void 0:Be.resize)==null||Ie.call(Be,te,ae)),Z.current="",(We=(Oe=r.current)==null?void 0:Oe.reset)==null||We.call(Oe),$?gt($):et())};c.useEffect(()=>{Ge()},[E]),c.useEffect(()=>{var X;if(!E)return;const $=((X=xt.onRuntimeEvent)==null?void 0:X.call(xt,E,te=>{if(!(!te||te.sessionId!==E)){if(te.type==="runtime_snapshot"){if(!o){xe.current={text:te.text||"",seq:te.seq||0,cols:te.cols,rows:te.rows,force:!!te.force};return}St(te.text||"",te.seq||0,te.cols,te.rows,{force:!!te.force});return}if(te.type==="session_output"){ue.current=!0,typeof te.seq=="number"&&(ge.current=Math.max(ge.current,te.seq),te.seq>0&&N(!0)),f.current||h(!0),f.current||v(""),typeof te.data=="string"&&gt(te.data);return}if(te.type==="session_cleared"){if(!o){Se.current=!0,Z.current="",xe.current=null;return}Ze();return}if(te.type==="session_io_error"){const ae=typeof te.error=="string"&&te.error?te.error:typeof te.reason=="string"&&te.reason?te.reason:"unknown error";h(!1),v(`Runtime input failed: ${ae}`);return}}},z))||(()=>{});return()=>{$()}},[z,E,r,o]);const jt=async($={})=>{var X;if(!z||!E)return{success:!1,error:"daemonId and sessionId are required"};$.preserveStatus||v($.loadingMessage||"Loading runtime terminal...");try{const te=await((X=xt.requestRuntimeSnapshot)==null?void 0:X.call(xt,z,E,{sinceSeq:$.sinceSeq,force:$.force}));return te&&te.success===!1?($.preserveStatus||(h(!1),v(`Runtime terminal unavailable: ${te.error}`)),te):te||{success:!0}}catch(te){const ae=(te==null?void 0:te.message)||String(te);return $.preserveStatus||(h(!1),v(`Runtime terminal unavailable: ${ae}`)),{success:!1,error:ae}}},Me=async $=>{var $e,Be;const X=(($e=F.current)==null?void 0:$e.ownerDocument)||document,te=X.defaultView||window,ae=(Be=te.navigator)==null?void 0:Be.clipboard;if(ae!=null&&ae.writeText&&te.isSecureContext)try{return await ae.writeText($),!0}catch{}let Ne=null;try{return Ne=X.createElement("textarea"),Ne.value=$,Ne.setAttribute("readonly","true"),Ne.style.position="fixed",Ne.style.left="-9999px",Ne.style.top="0",X.body.appendChild(Ne),Ne.focus(),Ne.select(),X.execCommand("copy")}catch{return!1}finally{Ne==null||Ne.remove()}},qe=$=>{me(),C($);const X=de();he.current={ownerWindow:X,timeoutId:X.setTimeout(()=>{he.current=null,C(te=>te===$?null:te)},2200)}},st=$=>{oe(),y($);const X=de();ye.current={ownerWindow:X,timeoutId:X.setTimeout(()=>{ye.current=null,y(te=>te===$?null:te)},2200)}},Xe=async()=>{var Ne,$e,Be,Ie;const $=(($e=(Ne=r.current)==null?void 0:Ne.getSelection)==null?void 0:$e.call(Ne))||"",X=((Ie=(Be=r.current)==null?void 0:Be.getVisibleText)==null?void 0:Ie.call(Be))||"",te=$.trimEnd()||X.trimEnd();if(!te){qe("Nothing to copy");return}if(!await Me(te)){qe("Copy failed");return}qe($.trimEnd()?"Copied selection":"Copied visible terminal")},ot=$=>{if(!u||!o)return;((d==null?void 0:d(z,E,$))??!1)||qe("Terminal input failed")},U=async()=>{if(b)return;p(!0),y("Loading older terminal output..."),be.current=!0;const $=await jt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:u});if(p(!1),($==null?void 0:$.success)===!1){be.current=!1,y(`Older terminal output unavailable: ${$.error}`);return}w(!0),st("Older terminal output loaded"),Ce(()=>{var X;(X=r.current)==null||X.bumpResize()})};c.useEffect(()=>{var X,te;if(!E)return;z&&((X=xt.getState)==null?void 0:X.call(xt,z))==="connected"&&jt();const $=(te=xt.onStateChange)==null?void 0:te.call(xt,(ae,Ne)=>{ae!==z||Ne!=="connected"||jt()});return()=>{$==null||$()}},[z,E,r]),c.useEffect(()=>{t&&Ge()},[t,ce,r]),c.useEffect(()=>{var ae,Ne;const $=F.current,X=(Ne=(ae=$==null?void 0:$.ownerDocument)==null?void 0:ae.defaultView)==null?void 0:Ne.ResizeObserver;if(!$||!X)return;const te=new X($e=>{const Be=$e[0];if(!Be)return;const{width:Ie,height:Oe}=Be.contentRect;P(We=>{const Le=Math.round(Ie),tt=Math.round(Oe);return We.width===Le&&We.height===tt?We:{width:Le,height:tt}})});return te.observe($),()=>te.disconnect()},[]),c.useEffect(()=>{if(D.current)return;const $=Pe();!Number.isFinite($)||$<=0||M(X=>H.current?$<X-we?$:X:(H.current=!0,$))},[I.height,I.width,O.height,O.width]),c.useEffect(()=>{B&&Ve()},[B,Ee,Ae]),c.useEffect(()=>{var te;const $=Q.current;if(Q.current=o,!o)return;$||w(!1),Se.current&&(Se.current=!1,Ze());const X=xe.current;X&&(xe.current=null,St(X.text,X.seq,X.cols,X.rows,{force:!!X.force})),z&&E&&((te=xt.getState)==null?void 0:te.call(xt,z))==="connected"&&jt(),Z.current&&Y.current===null&&fe(),Ce(()=>{var ae;(ae=r.current)==null||ae.bumpResize()})},[z,o,E]),c.useEffect(()=>()=>{Y.current!==null&&pe(),me(),oe()},[]),c.useEffect(()=>{const $=ae=>{var $e;const Ne=ae.detail;Ne!=null&&Ne.sessionId&&Ne.sessionId!==E||u&&(($e=r.current)==null||$e.bumpResize())},X=de(),te=X===window?[window]:[window,X];for(const ae of te)ae.addEventListener("adhdev:fit-cli-terminal",$);return()=>{for(const ae of te)ae.removeEventListener("adhdev:fit-cli-terminal",$)}},[u,E,r]);const J=u&&x&&!j&&(K.atTop||!K.canScroll)||b||!!g;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:F,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[J&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{U()},disabled:!E||b,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:b?"Loading older...":"Load older terminal output"}),g&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:g})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[T&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:T}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Xe()},disabled:!u,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>k($=>!$),disabled:!u,"aria-label":"Open terminal control keys","aria-expanded":S,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),S&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":"Terminal control keys",className:"absolute right-0 top-10 w-56 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>k(!1),"aria-label":"Close terminal control keys",children:"×"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>ot("\x1B"),children:"Esc"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>ot(" "),children:"Tab"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>ot("\r"),children:"Enter"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>ot("\x1B[A"),"aria-label":"Arrow up",children:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>ot("\x1B[D"),"aria-label":"Arrow left",children:"←"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>ot("\x1B[B"),"aria-label":"Arrow down",children:"↓"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>ot("\x1B[C"),"aria-label":"Arrow right",children:"→"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>ot(""),children:"Ctrl-C"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>ot(""),children:"Ctrl-D"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>ot(""),children:"Bksp"})]})]})]}),s.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:()=>{D.current=!0,M($=>{const X=Math.max(Re,Number(($-.1).toFixed(2)));return X>Re&&Ve(),X})},title:"Shrink terminal viewport",children:"-"}),s.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:()=>{D.current=!0,M($=>{const X=Math.min(je,Number(($+.1).toFixed(2)));return X>Re&&Ve(),X})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:L,className:B?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:Ae>0?`${Ae}px`:"100%",height:Ee>0?`${Ee}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:I.width>0?`${I.width}px`:"100%",height:I.height>0?`${I.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:A},children:s.jsx(Jd,{ref:r,readOnly:!u||!o,sizingMode:"measured",onViewportMetrics:W,onScrollMetrics:R,onInput:$=>{!u||(d==null||d(z,E,$))}})})})}),!u&&s.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:m})]}),s.jsx(cu,{contextKey:e.tabKey,panelLabel:ft(e),isSending:a,isBusy:!!le,statusMessage:re,onSend:async $=>le?!1:n($),isActive:l&&o,showControlsToggle:!1,animateVisibility:!1})]})}const $b=5e3,Bb=12e3;function Ob(e){return e==="disconnected"||e==="reconnecting"}function Fb({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=$b,reconnectActionDelayMs:i=Bb}){const o=Ob(e),[l,d]=c.useState(()=>!o||a<=0),[u,h]=c.useState(()=>!o||i<=0),f=c.useRef(!1);c.useEffect(()=>{if(!o){d(!1);return}if(f.current=!1,a<=0){f.current=!0,d(!0);return}d(!1);const w=setTimeout(()=>{f.current=!0,d(!0)},a);return()=>clearTimeout(w)},[a,o]),c.useEffect(()=>{if(!o){h(!1);return}if(i<=0){h(!0);return}h(!1);const w=setTimeout(()=>{h(!0)},i);return()=>clearTimeout(w)},[i,o]);const m=o?l:e==="offline"||e==="auth_failed",v=!!(n&&e!=="auth_failed"&&(!o||u)),b=c.useMemo(()=>!t||e!=="connected"?!1:a<=0||f.current,[a,t,e]),p=e==="auth_failed"?"red":e==="offline"?"orange":"accent",g={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))"},y={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)"},x={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},N="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",j={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[m&&s.jsx("div",{className:N,style:j,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:g[p],border:y[p],color:x[p]},children:[s.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}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&"Network offline",e==="disconnected"&&"Reconnecting",e==="reconnecting"&&"Reconnecting",e==="auth_failed"&&(r?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),v&&s.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm: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==null?void 0:n(),disabled:e==="offline",children:"Reconnect now"})]})}),b&&s.jsx("div",{className:N,style:j,children:s.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:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function Wb({terminalBackend:e,isStandalone:t=!1,machineLabel:r,machineKey:n}){const a=c.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,o]=c.useState(!1);if(c.useEffect(()=>{if(!a){o(!1);return}try{o(localStorage.getItem(a)==="1")}catch{o(!1)}},[a]),!t||!e||e.backend!=="xterm"||i)return null;const l=(r==null?void 0:r.trim())||"This machine",d=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}o(!0)};return s.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:[s.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[s.jsxs("span",{children:[l," is using `xterm` fallback."]}),s.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),s.jsx("button",{type:"button",onClick:d,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 tc({mode:e,onChange:t,compact:r=!1}){const n=r?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?s.jsx(Oo,{size:n}):s.jsx(cs,{size:n})})}const Qt="New session",Pu="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 Ub(e){if(!e||e.isGitRepo===!1||e.reason==="not_git_repo")return null;if(e.hasConflicts)return`${e.branch||"Git"} · conflicts${e.changedFiles>0?` ${e.changedFiles}`:""}`;const t=[e.branch||"Git"];return e.changedFiles>0&&t.push(`±${e.changedFiles}`),e.ahead>0&&t.push(`↑${e.ahead}`),e.behind>0&&t.push(`↓${e.behind}`),t.length===1&&e.dirty&&t.push("dirty"),t.join(" ")}function Kb(e){return!e||e.isGitRepo===!1||e.reason==="not_git_repo"?null:e.hasConflicts?"conflict":e.error?"error":e.dirty||e.changedFiles>0||e.ahead>0||e.behind>0?"dirty":"quiet"}function Hb(e){switch(e){case"conflict":return"border-red-500/25 bg-red-500/[0.08] text-red-400";case"error":return"border-yellow-500/25 bg-yellow-500/[0.08] text-yellow-500";case"dirty":return"border-orange-500/25 bg-orange-500/[0.08] text-orange-400";case"quiet":default:return"border-emerald-500/15 bg-emerald-500/[0.06] text-emerald-500"}}function br({git:e,className:t="",compact:r=!1}){const n=Ub(e),a=Kb(e);if(!n||!a)return null;const i=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return s.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${Hb(a)} ${t}`.trim(),title:i.join(" · ")||n,"data-git-tone":a,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:n})]})}function zb({wsStatus:e,isConnected:t,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,o=a.filter(l=>l==="connecting"||l==="new"||l==="checking").length;return r>0&&o>0&&i===0?{tone:"limited",title:"Connected to dashboard",subtitle:"Connecting to machine..."}:t?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function yl({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function vl({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const o=La(e.updatedAt),l=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",o].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),i()},children:"Delete"})]})]})}function Vb({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:o,activeCliViewMode:l,onSetCliViewMode:d,onHideConversation:u,hiddenConversations:h=[],onShowConversation:f,onShowAllHidden:m,onResetPanelsToMain:v,inboxOpen:b,onInboxOpenChange:p,hiddenOpen:g,onHiddenOpenChange:y,onOpenNewSession:x,onOpenDashboardGuide:N,guideNudgeVisible:j=!1,actionShortcuts:w,notifications:A,notificationUnreadCount:M,onOpenNotification:S,onMarkNotificationRead:k,onMarkNotificationUnread:O,onDeleteNotification:P,onOpenGitDialog:I}){const{ides:W,p2pStates:K={}}=Ss(),R=!!e&&it(e)&&!nt(e),T=!!e&&nt(e),C=l||(e?lu(e)?"terminal":"chat":null),[F,L]=c.useState(!1),D=c.useRef(null),H=c.useRef(null),Q=W.filter(se=>se.type==="adhdev-daemon"),ge=zb({wsStatus:t,isConnected:r,daemonCount:Q.length,p2pStates:K}),ue=ge.subtitle,Z=ge.tone==="connected"?"#22c55e":ge.tone==="limited"?"#eab308":"#ef4444",xe=ge.tone==="connected"?"0 0 4px #22c55e80":ge.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",Se=c.useMemo(()=>A.filter(se=>!se.readAt),[A]),be=c.useMemo(()=>A.filter(se=>!!se.readAt),[A]),Y=c.useMemo(()=>Se.slice(0,9),[Se]),he=M;c.useEffect(()=>{if(!b)return;const se=de=>{var Ce;(Ce=D.current)!=null&&Ce.contains(de.target)||p(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[b,p]),c.useEffect(()=>{if(!g)return;const se=de=>{var Ce;(Ce=H.current)!=null&&Ce.contains(de.target)||y(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[g,y]),c.useEffect(()=>{if(!g&&!b)return;const se=de=>{if(!de.altKey)return;const Ce=de.code.match(/^Digit([1-9])$/);if(!Ce)return;const pe=Number(Ce[1])-1,me=g?h[pe]:void 0,oe=b?Y[pe]:void 0;if(!(!me&&!oe)){if(de.preventDefault(),de.stopPropagation(),me){f==null||f(me),y(!1);return}oe&&(S(oe),p(!1))}};return window.addEventListener("keydown",se,!0),()=>window.removeEventListener("keydown",se,!0)},[h,g,b,Y,y,p,S,f]);const ye=se=>{if(!se)return;const de=n.find(Ce=>Ce.tabKey===se);de&&(u==null||u(de))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(cs,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?ft(e):"Dashboard"}),s.jsx("span",{title:ge.title,"aria-label":ge.title,className:"header-title-status-dot",style:{background:Z,boxShadow:xe}}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:Z,boxShadow:xe}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[ue&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ue]}),x&&s.jsx("button",{type:"button",onClick:x,className:"btn btn-secondary btn-sm ml-2",title:`${Qt}${w!=null&&w.openNewSession?` (${w.openNewSession})`:""}`,"aria-label":Qt,children:s.jsx(Hd,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[N&&s.jsxs("button",{type:"button",onClick:N,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:"Dashboard guide","aria-label":"Open dashboard guide",children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),j&&s.jsx("span",{children:"Guide"})]}),e&&(R||T||!nt(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:Gs(e)||ft(e),children:ft(e)}),I&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:()=>I(e.daemonId,e.workspacePath),children:s.jsx(br,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(br,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(R||T)&&o&&s.jsxs(s.Fragment,{children:[R&&d&&C&&s.jsx(tc,{mode:C,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>o(e),className:"btn btn-secondary btn-sm",title:T?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(It,{size:14})})]}),!nt(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx($o,{size:14})}),!R&&!nt(e)&&s.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Bt,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:D,children:[s.jsxs("div",{className:`dashboard-header-hidden${F?" is-drop-target":""}`,ref:H,onDragEnter:se=>{se.dataTransfer.types.includes("text/tab-key")&&(se.preventDefault(),L(!0))},onDragOver:se=>{se.dataTransfer.types.includes("text/tab-key")&&(se.preventDefault(),se.dataTransfer.dropEffect="move",L(!0))},onDragLeave:se=>{se.currentTarget.contains(se.relatedTarget)||L(!1)},onDrop:se=>{const de=se.dataTransfer.getData("text/tab-key");se.preventDefault(),L(!1),ye(de)},children:[s.jsxs("button",{type:"button",onClick:()=>y(!g),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${w!=null&&w.toggleHiddenTabs?` (${w.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(Bo,{size:16}),h.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:h.length})]}),g&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),s.jsx(yl,{value:w==null?void 0:w.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[v&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:v,children:"Reset panels"}),h.length>0&&m&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{m(),y(!1)},children:"Restore all"})]})]}),e&&u&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>u(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),s.jsx(yl,{value:w==null?void 0:w.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:ft(e)})]}),h.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:h.map(se=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{f==null||f(se),y(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:ft(se)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[h.indexOf(se)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",h.indexOf(se)+1]}):null,Gs(se)]})]},se.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!b),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Pa,{size:16}),he>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:he})]}),b&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[Se.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),Se.map(se=>s.jsx(vl,{notification:se,shortcutIndex:Y.indexOf(se)>=0?Y.indexOf(se)+1:void 0,onOpen:()=>S(se),onMarkRead:()=>k(se.id),onMarkUnread:()=>O(se.id),onDelete:()=>P(se.id)},se.id))]}),be.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),be.map(se=>s.jsx(vl,{notification:se,onOpen:()=>S(se),onMarkRead:()=>k(se.id),onMarkUnread:()=>O(se.id),onDelete:()=>P(se.id)},se.id))]}),A.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function Mt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Gb(e,t){return String(e||"")!==String(t||"")}function qb(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),i=!!t.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(o=>!(i&&!o.canResume||r&&![o.title,o.preview].map(d=>String(d||"").toLowerCase()).join(`
41
+ `).includes(r)||n&&!String(o.workspace||"").toLowerCase().includes(n)||a&&!su(o.summaryMetadata).map(d=>d.toLowerCase()).join(`
42
+ `).includes(a)))}function Xb(e,t="recent"){const r=e.slice();return r.sort((n,a)=>{if(t==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="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 Lu(e,t={}){return Xb(qb(e,t),t.sortMode||"recent")}function va(e){return e?"Resume saved history":"Start fresh"}function sc(e){return e?"Resuming saved history…":"Starting fresh…"}function Yb(){return"Start fresh"}function Eu(e,t=!1){return e==="cli"?va(t):e==="ide"?"Start IDE":"Start ACP session"}function Du(e,t=!1){return e==="cli"?sc(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Jb(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Qb(){return"Open saved history"}function Zb(){return"Saved History"}function rc(){return"Use saved history when you want continuity in the same provider conversation."}function ey(){return"No saved history found yet."}function ty(){return"Refresh saved history"}function sy(){return"Refreshing saved history…"}function Es(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function Ds(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 yr(e){return e==="start-fresh"?"Start fresh":"Restart"}function vr(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function nc(e){return`Resume saved history with ${e}?`}function ac(){return"Review or change the target workspace before resuming saved history."}function ry(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 ic({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:o=null,savedHistoryFilters:l,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:u,onClose:h,onNewChat:f,onSwitchSession:m,onRefreshHistory:v,onResumeSavedSession:b}){var P;const p=t.find(I=>I.id===e.routeId),g=(p==null?void 0:p.chats)||[],y=(P=p==null?void 0:p.activeChat)==null?void 0:P.id,x=it(e)&&!nt(e),[N,j]=c.useState(()=>Mt()),w=l||N,A=String(d||"").trim(),M=I=>{if(u){u(I);return}j(I)},S=c.useMemo(()=>a.map(I=>{const W=String(I.workspace||"").trim();return I.canResume||W||!A?I:{...I,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,a]),k=c.useMemo(()=>Lu(S,{textQuery:w.textQuery,workspaceQuery:w.workspaceQuery,modelQuery:w.modelQuery,resumableOnly:w.resumableOnly,sortMode:w.sortMode}),[S,w.modelQuery,w.resumableOnly,w.sortMode,w.textQuery,w.workspaceQuery]),O=s.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:[s.jsx("div",{onClick:h,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.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:[s.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:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:x?Zb():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Lb(e)}),x&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:rc()})]}),s.jsx("button",{onClick:h,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(It,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!x&&s.jsx("button",{onClick:f,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),x?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:w.textQuery,onChange:I=>M({...w,textQuery:I.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"}),s.jsx("input",{type:"text",value:w.workspaceQuery,onChange:I=>M({...w,workspaceQuery:I.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"}),s.jsx("input",{type:"text",value:w.modelQuery,onChange:I=>M({...w,modelQuery:I.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"}),s.jsxs("select",{value:w.sortMode,onChange:I=>M({...w,sortMode:I.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:w.resumableOnly,onChange:I=>M({...w,resumableOnly:I.target.checked})}),"Resume-ready only"]})]}),k.map(I=>{const W=e.providerSessionId===I.providerSessionId,K=W||!I.canResume||!!o,R=I.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{K||!b||b(I)},disabled:K,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${W?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${K?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${W?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:I.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:I.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:ry(I.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:I.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[I.workspace||"Workspace unknown",R?" · selected workspace":"",Vs(I.summaryMetadata)?` · ${Vs(I.summaryMetadata)}`:"",I.messageCount>0?` · ${I.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:W?"ACTIVE":I.canResume?R?"RESUME IN SELECTED WORKSPACE":o===I.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},I.id)})]}):g.map(I=>s.jsxs("div",{onClick:()=>{m(e.routeId,I.id),h()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${y===I.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${y===I.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:I.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[I.id.substring(0,12),"..."]}),y===I.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},I.id)),(x&&!i&&k.length===0||!x&&g.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Im,{size:32})}),s.jsx("div",{className:"text-[13px]",children:x?a.length>0?"No saved history matches these filters.":ey():"No recent chat sessions found."})]}),x&&i&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:sy()})})]}),s.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:s.jsx("button",{onClick:v,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(vn,{size:13})," ",x?ty():"Refresh History"]})})})]})]});return typeof document>"u"?O:hn.createPortal(O,document.body)}const wl={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 $u({toasts:e,onDismiss:t,onClickToast:r}){return s.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=wl[n.type]||wl.info;return s.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:[s.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))`}}),s.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(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(It,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.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})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,o)=>s.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(),t(n.id)},children:i.label},o))})]})]},n.id)})})}const ny=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function ay(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function iy(e){return e.sessionId||e.instanceId||e.agentType}function hi(e,t){return t||e||"unknown"}function Bu(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=$t(r,{fallbackId:r.id}));return t}function Ou(e,t={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=t.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:t.connectionStates?t.connectionStates[r]||t.defaultConnectionState||"new":t.defaultConnectionState}}function oc(e,t={}){return oy(e,Ou(e,t))}function oy(e,t={}){var f,m,v,b,p;const r=[],n=t.machineName,a=t.connectionState,i=ay(e),o=e.workspace||"",l=_x(e.type,{agentName:e.cliName}),d=it(e)||nt(e)?l:ht(e.type),u=Array.isArray(e.childSessions)?e.childSessions.map(g=>{var y,x;return{sessionId:g.id,instanceId:g.id,providerSessionId:g.providerSessionId,transport:g.transport,sessionCapabilities:g.capabilities,agentType:g.providerType,agentName:g.providerName||ht(g.providerType),status:g.status,title:g.title,lastMessagePreview:g.lastMessagePreview,lastMessageRole:g.lastMessageRole,lastMessageAt:g.lastMessageAt,lastMessageHash:g.lastMessageHash,messages:((y=g.activeChat)==null?void 0:y.messages)||[],activeModal:((x=g.activeChat)==null?void 0:x.activeModal)||void 0,unread:g.unread,lastSeenAt:g.lastSeenAt,lastUpdated:g.lastUpdated,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,surfaceHidden:g.surfaceHidden,git:g.git,settings:g.settings,messageInput:g.messageInput}}):[],h=ny(e);if(h){const g=e.sessionId||e.instanceId,y=(f=e.settings)==null?void 0:f.meshCoordinatorFor,x=(m=e.settings)==null?void 0:m.meshNodeFor,N=y?" (Coordinator)":x?" (Mesh Node)":"",j=l+N,w=(v=e.activeChat)==null?void 0:v.activeModal,A=w&&Array.isArray(w.buttons)&&w.buttons.length>0,M=Rx(e.activeChat,[{status:e.status,activeModal:(b=e.activeChat)==null?void 0:b.activeModal}],e.agents||[]),S=e.activeChat||{title:"",messages:[]};let k=S.title&&String(S.title).trim()?String(S.title).trim():"";const O=(p=e.activeChat)==null?void 0:p.id,P=e.chats;if(O&&Array.isArray(P)&&P.length>0){const R=P.find(T=>T.id===O||T.id&&String(T.id)===String(O));R!=null&&R.title&&String(R.title).trim()&&(k=String(R.title).trim())}const I=(it(e)||nt(e),e.type),W=(it(e)||nt(e))&&il(k,j,I)?"":k,K=S.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:it(e)?e.mode||"terminal":"chat",agentName:j,agentType:I,status:M,title:W,messages:K,resume:e.resume,hostIdeType:!it(e)&&!nt(e)?e.type:void 0,workspaceName:i,workspacePath:o,git:e.git,displayPrimary:W||i||(it(e)?e.mode==="chat"?j:`Terminal${N}`:j),displaySecondary:it(e)&&i?j:d,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:A?w.buttons:void 0,modalMessage:A?w.message:void 0,streamSource:"native",tabKey:hi(g,e.id),machineName:n,connectionState:a,settings:e.settings,messageInput:e.messageInput})}if(h&&(it(e)||nt(e)))return r;for(const g of u){const y=g.activeModal&&Array.isArray(g.activeModal.buttons)&&g.activeModal.buttons.length>0,x=Px(g),N=iy(g),j=`${e.id}:${N}`,w=g.title&&String(g.title).trim()||"",A=il(w,g.agentName,g.agentType)?"":w,M=g.messages||[];(g.transport==="cdp-webview"||g.sessionId||g.providerSessionId||M.length>0||y||A||!["idle","panel_hidden","disconnected","not_monitored"].includes(x))&&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:x,title:A,messages:M,hostIdeType:e.type,workspaceName:i,workspacePath:o,git:g.git||e.git,displayPrimary:A||i||g.agentName||d,displaySecondary:`${d} · ${g.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:g.lastMessagePreview,lastMessageRole:g.lastMessageRole,lastMessageAt:g.lastMessageAt,lastMessageHash:g.lastMessageHash,lastUpdated:g.lastUpdated||e.lastUpdated,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,modalButtons:y?g.activeModal.buttons:void 0,modalMessage:y?g.activeModal.message:void 0,streamSource:"agent-stream",tabKey:hi(g.sessionId||g.instanceId,j),machineName:n,connectionState:a,settings:g.settings,messageInput:g.messageInput})}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:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:i,workspacePath:o,git:e.git,displayPrimary:i||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:hi(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function Fu(e){return String(e.type||e.id||"").trim()}function cy(e){var t;return e.category!=="cli"||!Fu(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function ly(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!cy(a))continue;const i=Fu(a);if(!i||t.has(i))continue;t.add(i);const o=String(a.displayName||a.name||i),l=a.detectedPath||((n=a.lastDetection)==null?void 0:n.path)||null;r.push({type:i,label:o,icon:a.icon,statusLabel:l?`Detected at ${l}`:"Detected on this machine",detectedPath:l})}return r}function Oa(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],r=new Set,n=[];for(const a of t){const i=typeof a=="string"?a.trim():"";!i||r.has(i)||(r.add(i),n.push(i))}return n}function lo(e,t){const r=new Set(t.map(n=>n.type));return Oa(e).filter(n=>r.has(n))}function dy(e){return e.map(t=>t.type)}function uy(e,t){const r=Oa(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function hy(e,t){return Oa(e).filter(r=>r!==t)}function Sl(e,t,r){const n=Oa(e),a=n.indexOf(t);if(a<0)return n;const i=n.filter(l=>l!==t);if(r==="top")return[t,...i];if(r==="bottom")return[...i,t];const o=r==="up"?Math.max(0,a-1):Math.min(i.length,a+1);return i.splice(o,0,t),i}function kl({direction:e}){return s.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="up"?s.jsx("polyline",{points:"18 15 12 9 6 15"}):s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function jl({value:e,availableProviders:t,onChange:r,disabled:n=!1,saveButton:a}){const[i,o]=c.useState(""),l=c.useMemo(()=>new Map(t.map(m=>[m.type,m])),[t]),d=c.useMemo(()=>lo(e,t),[e,t]),u=e.length-d.length,h=t.filter(m=>!d.includes(m.type)),f=()=>{i&&(r(uy(d,i)),o(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:d.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):d.map((m,v)=>{const b=l.get(m);return s.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border-subtle bg-bg-primary px-3 py-2 sm:flex-row sm:items-center sm:justify-between",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",v+1]}),(b==null?void 0:b.icon)&&s.jsx("span",{"aria-hidden":"true",children:b.icon}),s.jsx("span",{className:"font-mono text-[12px] text-text-primary",children:m}),s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:"available"})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:b?`${b.label} · ${b.statusLabel}`:m})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:n||v===0,title:"Move up",onClick:()=>r(Sl(d,m,"up")),children:s.jsx(kl,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:n||v===d.length-1,title:"Move down",onClick:()=>r(Sl(d,m,"down")),children:s.jsx(kl,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(hy(d,m)),children:"Remove"})]})]},m)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:"Add available CLI provider"}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:i,onChange:m=>o(m.target.value),disabled:n||h.length===0,children:[s.jsx("option",{value:"",children:h.length?"Select provider…":"No additional detected CLI providers"}),h.map(m=>s.jsxs("option",{value:m.type,children:[m.label," (",m.type,")"]},m.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!i,onClick:f,children:"Add provider"}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Inventory is filtered to CLI providers detected on this machine. New launches use this order; existing running sessions may need restart.",u>0?` ${u} provider${u===1?"":"s"} from the saved policy are not detected now and will be omitted when saved.`:""]})]})}function py(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function Wu(e,t){const r=py(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Uu=[{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:"🏄"}],Ku=[{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:"🧩"}],Hu=[{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:"🟠"}],fy=Uu,my=Ku,xy=Hu;function ls(...e){return Af(Mf(e))}function gy({icon:e,title:t,subtitle:r,badge:n,actions:a,className:i}){return s.jsxs("div",{className:ls("dashboard-header",i),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&s.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&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function rn({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:i="max-w-6xl",contentClassName:o,children:l}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(gy,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:ls("mx-auto flex w-full flex-col gap-4",i,o),children:l})})]})}const uo="adhdev:themechange";function by(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function tr(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function sr(e){return e==="system"?by():e}function zu(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Zn(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(uo,{detail:{preference:e,theme:t}}))}function yy(){const e=tr(),t=sr(e);zu(t),Zn(e,t)}function cc(){const[e,t]=c.useState(tr),[r,n]=c.useState(()=>sr(tr()));c.useEffect(()=>{zu(r)},[r]),c.useEffect(()=>{const o=window.matchMedia("(prefers-color-scheme: light)"),l=d=>{if(e==="system"){const u=d.matches?"light":"dark";n(u),Zn("system",u)}};return o.addEventListener("change",l),()=>o.removeEventListener("change",l)},[e]),c.useEffect(()=>{const o=d=>{const u=d.detail||{},h=u.preference,f=u.theme;t(h==="dark"||h==="light"||h==="system"?h:tr()),n(f==="dark"||f==="light"?f:sr(tr()))},l=d=>{if(d.key!=="theme")return;const u=tr(),h=sr(u);t(u),n(h)};return window.addEventListener(uo,o),window.addEventListener("storage",l),()=>{window.removeEventListener(uo,o),window.removeEventListener("storage",l)}},[]);const a=c.useCallback(o=>{const l=sr(o);t(o),n(l);try{localStorage.setItem("theme",o)}catch{}Zn(o,l)},[]),i=c.useCallback(()=>{t(o=>{const l=o==="dark"?"light":o==="light"?"system":"dark",d=sr(l);n(d);try{localStorage.setItem("theme",l)}catch{}return Zn(l,d),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const Nl={dark:"Dark",light:"Light",system:"System"};function vy({collapsed:e}){const{preference:t,cycleTheme:r}=cc(),n=t==="dark"?s.jsx(Mm,{size:16}):t==="light"?s.jsx(Am,{size:16}):s.jsx(_m,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Nl[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:Nl[t]})]})}function pi(e,t){return e?typeof e=="function"?e(t):e:null}function wy({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:i,footerActions:o,preMainContent:l,collapsedStorageKey:d="sidebar-collapsed"}){const[u,h]=c.useState(!1),[f,m]=c.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),v=()=>h(!0),b=()=>h(!1),p=()=>{m(N=>{const j=!N;try{localStorage.setItem(d,j?"1":"0")}catch{}return j})},g=c.useMemo(()=>({collapsed:f,mobileMenuOpen:u,openMobileMenu:v,closeMobileMenu:b,toggleCollapsed:p}),[f,u]),y=N=>`nav-item${N.active?" active":""} cursor-pointer ${f?"justify-center py-2.5 px-0":""}${N.className?` ${N.className}`:""}`,x=N=>s.jsxs("div",{className:y(N),id:`nav-${N.id}`,onClick:()=>{N.onSelect(),b()},title:f?N.title??(typeof N.label=="string"?N.label:void 0):N.title,children:[s.jsx("span",{className:"nav-icon",children:N.icon}),!f&&N.label]},N.id);return s.jsxs("div",{className:`app-layout${u?" mobile-menu-open":""}${f?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:v,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),u&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:b,onKeyDown:N=>N.key==="Escape"&&b()}),s.jsxs("aside",{className:`sidebar ${u?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${f?"justify-center gap-0":""}`,children:pi(t,g)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:b,children:s.jsx(It,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(x)}),n.map(N=>s.jsxs("div",{className:N.className??"border-t border-border-subtle pt-2 mt-2",children:[!f&&N.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:N.title}):null,N.items.map(x)]},N.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(x),pi(i,g),s.jsx(vy,{collapsed:f}),pi(o,g)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function Tt({title:e,icon:t,description:r,accentColor:n,className:a,children:i}){return s.jsxs("div",{className:ls("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)&&s.jsxs("div",{className:"mb-4",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[t&&s.jsx("span",{className:"mr-1.5",children:t}),e]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function wa({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:ls("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const Sy={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"},ky={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function ir({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:ls("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Sy[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:ky[e]}),s.jsx("span",{children:t})]}),r&&s.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function Ft({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:ls("mb-5",n),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),r,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function fi(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:ls("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const jy={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"},Ny={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Cy({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:ls("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",jy[e],r),children:[s.jsx("span",{className:ls("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Ny[e])}),n]})}function _s({label:e,description:t,checked:r,disabled:n,onChange:a,extra:i}){return s.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,s.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:[s.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))"}}),s.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 Ty({onPrefChange:e}){const[t,r]=Kx(),[n,a]=c.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);c.useEffect(()=>{const o=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return o(),window.addEventListener("focus",o),document.addEventListener("visibilitychange",o),()=>{window.removeEventListener("focus",o),document.removeEventListener("visibilitychange",o)}},[]);const i=(o,l)=>{r({[o]:l}),e==null||e(o,l)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(_s,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Pa,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:o=>i("globalEnabled",o)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(_s,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Bt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:o=>i("browserNotifications",o)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.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"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{au().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"&&s.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"&&s.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."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(_s,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Rm,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:o=>i("completionAlert",o)}),s.jsx(_s,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Pm,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:o=>i("approvalAlert",o)}),s.jsx(_s,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(mr,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:o=>i("disconnectAlert",o)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function Sa(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Iy(e,t){const r=Sa(e),n=Sa(t);if(!r||!n)return e.localeCompare(t);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 Vu(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function nn(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Iy(r,t)>=0)return!1;const n=Sa(r),a=Sa(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Ay(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function mi(e,t){return e instanceof Error?e.message:t}function My({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const i=e.filter(o=>o.type==="adhdev-daemon");return i.length===0?s.jsx(wa,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:t||"Install ADHDev on a machine and sign in to connect it here."}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(o=>s.jsx(Ry,{ide:o,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},o.id))})}function Cl({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:i}){const o=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return hn.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:s.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:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.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"}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${o}`,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 _y(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...fy,...my,...xy].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function Ry({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var K,R;const[i,o]=c.useState("idle"),[l,d]=c.useState(""),[u,h]=c.useState(null),[f,m]=c.useState("idle"),[v,b]=c.useState(""),p=e.version||null,g=((K=e.machine)==null?void 0:K.platform)||((R=e.system)==null?void 0:R.platform)||"",y=$t(e,{fallbackId:e.id}),x=g==="win32"?"🪟":g==="darwin"?"🍎":"🐧",N=t.filter(T=>T.daemonId===e.id&&T.transport==="cdp-page"),j=t.filter(T=>T.daemonId===e.id&&T.transport==="pty"),w=t.filter(T=>T.daemonId===e.id&&T.transport==="acp"),A=e.p2p,M=async()=>{if(r){o("upgrading"),d("Starting upgrade...");try{const T=Ay(await r(e.id,"daemon_upgrade",{}));T.alreadyLatest?(o("done"),d(`Already on v${T.version||"latest"}.`)):T.upgraded||T.success?(o("done"),d(`Upgrade to v${T.version||"latest"} started. Daemon is restarting...`)):(o("error"),d(T.error||"Upgrade failed"))}catch(T){o("error"),d(mi(T,"Connection lost during upgrade"))}}},S=async()=>{if(h(null),!!n){m("loading");try{await n(e.id),m("done"),b("Machine disconnected.")}catch(T){m("error"),b(mi(T,"Failed to disconnect"))}}},k=async()=>{if(h(null),!!a){m("loading");try{await a(e.id),m("done"),b("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(T){m("error"),b(mi(T,"Failed to revoke token"))}}},O="0.9.76",P=Vu(e,O),I=nn(e,O),W=N.length+j.length+w.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:x}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:y}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),p&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${P?"":"bg-bg-secondary"}`,style:P?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!P&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&P&&s.jsx("button",{onClick:M,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${O}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${I?"↑ Update now":`↑ Update${` to v${O}`}`}`}),n&&s.jsx("button",{onClick:()=>h("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>h("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Cy,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[A&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${A.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${A.state==="connecting"||A.state==="new"?"animate-pulse":""}`,style:A.state==="connecting"||A.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",A.state==="connected"?"connected":A.state==="connecting"||A.state==="new"?"connecting...":A.state||"off"]}),A.peers!==void 0&&A.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",A.peers," peer",A.peers!==1?"s":"",")"]})]}),A&&W>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),W>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(T=>{const C=_y(T.type),F=T.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:C.icon}),s.jsx("span",{children:C.name}),F!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${F?"bg-green-400":"animate-pulse"}`,style:F?void 0:{background:"var(--status-warning)"},title:F?"CDP connected":"CDP connecting..."})]},T.id)}),j.map(T=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:T.cliName||"CLI"})]},T.id)),w.map(T=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:T.cliName||"ACP"})]},T.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||v)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-red-400":i==="done"||f==="done"?"text-green-400":"text-text-muted"}`,children:v||l})]}),u==="disconnect"&&s.jsx(Cl,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
43
+
44
+ This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
45
+
46
+ Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:S,onCancel:()=>h(null)}),u==="revoke"&&s.jsx(Cl,{title:"⚠️ Remove Machine",message:`Remove "${y}" from your dashboard?
47
+
48
+ This will:
49
+ • Immediately disconnect the machine
50
+ • Delete the machine registration
51
+ • Require restarting ADHDev on that machine
52
+
53
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:k,onCancel:()=>h(null)})]})}const Py=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Ly(){const{preference:e,setPreference:t}=cc();return s.jsx("div",{className:"flex gap-2",children:Py.map(r=>s.jsxs("button",{onClick:()=>t(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:[s.jsx("span",{children:r.icon}),r.label]},r.id))})}function Ey(e){const t=e.trim();return/^#[0-9a-fA-F]{6}$/.test(t)?t:/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:null}function Dy(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function xi(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Tl(e){const{r:t,g:r,b:n}=Dy(e);return .2126*xi(t)+.7152*xi(r)+.0722*xi(n)}function Il(e,t){const r=Tl(e),n=Tl(t),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function Gu(e){const t=Ey(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return Il(t,r)>=Il(t,n)?r:n}const ho={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},po={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},$y=[{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"}}}],qu="adhdev-chat-theme",Xu="adhdev-chat-theme-custom";function ea(){if(typeof window>"u")return"ember";try{return localStorage.getItem(qu)||"ember"}catch{return"ember"}}function qt(e){try{const t=localStorage.getItem(Xu);if(t){const r=JSON.parse(t);return{...e==="dark"?ho:po,...r[e]}}}catch{}return e==="dark"?ho:po}function Bn(e,t){try{localStorage.setItem(Xu,JSON.stringify({dark:e,light:t}))}catch{}}function Wt(e,t){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}, ${t})`}function ka(e,t){const r=Math.min(255,parseInt(e.slice(1,3),16)+t),n=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const By={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function an(e,t){var a;const r=(a=By[e])==null?void 0:a[t];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",ka(r,24)),n.style.setProperty("--accent-on-primary",Gu(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${ka(r,18)})`),n.style.setProperty("--border-accent",Wt(r,.35)),n.style.setProperty("--nav-active-bg",Wt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Wt(r,.06)}`)}function $s(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Wt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Wt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Wt(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",Wt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Wt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",ka(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Gu(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${ka(e.accentColor,40)})`),t.style.setProperty("--border-accent",Wt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Wt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Wt(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${Wt(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function lc(){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 Oy(e){try{localStorage.setItem(qu,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Bs()?"dark":"light";$s(qt(t))}else lc(),an(e,Bs()?"dark":"light")}function Fy(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=ea();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Bs()?"dark":"light";$s(qt(t))}else lc(),an(e,Bs()?"dark":"light")}function Bs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function _t({label:e,value:t,onChange:r}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,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 Wr({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.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}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function Wy({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=c.useState(()=>qt(r));c.useEffect(()=>{a(qt(r))},[r]);const i=c.useCallback((o,l)=>{a(d=>{const u={...d,[o]:l},f=qt(r==="dark"?"light":"dark");return r==="dark"?Bn(u,f):Bn(f,u),$s(u),t(u),u})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.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",s.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"]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(Wr,{title:"App Background",children:[s.jsx(_t,{label:"Background",value:n.bgPrimary,onChange:o=>i("bgPrimary",o)}),s.jsx(_t,{label:"Surface",value:n.bgSecondary,onChange:o=>i("bgSecondary",o)}),s.jsx(_t,{label:"Card",value:n.surfacePrimary,onChange:o=>i("surfacePrimary",o)})]}),s.jsxs(Wr,{title:"App Text",children:[s.jsx(_t,{label:"Primary",value:n.textPrimary,onChange:o=>i("textPrimary",o)}),s.jsx(_t,{label:"Secondary",value:n.textSecondary,onChange:o=>i("textSecondary",o)}),s.jsx(_t,{label:"Muted",value:n.textMuted,onChange:o=>i("textMuted",o)})]}),s.jsxs(Wr,{title:"Borders & Accent",children:[s.jsx(_t,{label:"Border subtle",value:n.borderSubtle,onChange:o=>i("borderSubtle",o)}),s.jsx(_t,{label:"Border default",value:n.borderDefault,onChange:o=>i("borderDefault",o)}),s.jsx(_t,{label:"Accent",value:n.accentColor,onChange:o=>i("accentColor",o)})]})]}),s.jsxs("div",{children:[s.jsxs(Wr,{title:"Chat Bubbles",children:[s.jsx(_t,{label:"User bubble",value:n.userBubble,onChange:o=>i("userBubble",o)}),s.jsx(_t,{label:"User text",value:n.userText,onChange:o=>i("userText",o)}),s.jsx(_t,{label:"Agent bubble",value:n.assistantBubble,onChange:o=>i("assistantBubble",o)}),s.jsx(_t,{label:"Agent text",value:n.assistantText,onChange:o=>i("assistantText",o)})]}),s.jsxs(Wr,{title:"Chat Layout",children:[s.jsx(_t,{label:"Chat BG",value:n.containerBg,onChange:o=>i("containerBg",o)}),s.jsx(_t,{label:"Send button",value:n.sendButton,onChange:o=>i("sendButton",o)}),s.jsx(_t,{label:"Input border",value:n.inputBorder,onChange:o=>i("inputBorder",o)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:o=>i("bubbleRadius",Number(o.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const o=e?ho:po,d=qt(e?"light":"dark");e?Bn(o,d):Bn(d,o),a(o),$s(o),t(o)},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 Uy(){const[e,t]=c.useState(ea),[r,n]=c.useState(!0),[a,i]=c.useState(()=>qt("dark"));c.useEffect(()=>{n(Bs());const d=new MutationObserver(()=>{const f=Bs();n(f);const m=ea();m==="custom"?$s(qt(f?"dark":"light")):an(m,f?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const u=window.matchMedia("(prefers-color-scheme: dark)"),h=()=>{const f=Bs();n(f);const m=ea();m==="custom"?$s(qt(f?"dark":"light")):an(m,f?"dark":"light")};return u.addEventListener("change",h),()=>{d.disconnect(),u.removeEventListener("change",h)}},[]),c.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?$s(qt(r?"dark":"light")):(lc(),an(e,r?"dark":"light"))},[e,r]),c.useEffect(()=>{i(qt(r?"dark":"light"))},[r]);const o=d=>{t(d),Oy(d)},l=[...$y,{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 s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(d=>{const u=e===d.id,h=r?d.preview.dark:d.preview.light,f=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>o(d.id),className:"text-left rounded-xl p-3 transition-all",style:{background:u?"var(--bg-glass-hover)":"var(--bg-glass)",border:u?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:u?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:h.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:h.assistantBubble,border:h.assistantBorder,color:h.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:h.userBubble,color:f},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:h.assistantBubble,border:h.assistantBorder,color:h.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[u&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:d.id==="custom"?"🎨 Custom":d.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:d.description})]})]})]},d.id)})}),e==="custom"&&s.jsx(Wy,{dark:r,onColorsChange:d=>i(d)})]})}const dc="adhdev_mobileDashboardMode_v1",fo="adhdev:mobile-dashboard-mode-change";function uc(){try{return localStorage.getItem(dc)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Ky(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??uc())},r=a=>{const i=a.detail;t(i)},n=a=>{a.key&&a.key!==dc||t()};return window.addEventListener(fo,r),window.addEventListener("storage",n),()=>{window.removeEventListener(fo,r),window.removeEventListener("storage",n)}}function Hy(e){try{localStorage.setItem(dc,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(fo,{detail:e}))}function zy(){const[e,t]=c.useState(!0);return c.useEffect(()=>{t(uc()==="chat")},[]),s.jsx(_s,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(cs,{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=>{t(r),Hy(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const gi=new Map,Al=new Map;function Vy(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t,n=r.machine;return!n||typeof n!="object"?null:{machine:n,timestamp:typeof r.timestamp=="number"?r.timestamp:void 0}}function Gy(e,t,r,n){return{...e||{},id:t,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 Yu(){const{sendCommand:e}=Ct(),{injectEntries:t,getIdes:r}=pn();return c.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??Kg,o=Al.get(n)||0;if(!(a!=null&&a.force)&&o>0&&Date.now()-o<i)return;const l=gi.get(n);if(l)return l;const d=(async()=>{const u=await e(n,"get_machine_runtime_stats"),h=Vy(u);if(!h)return;const f=r().find(v=>v.id===n),m=Gy(f,n,h.machine,h.timestamp||Date.now());t([m]),Al.set(n,Date.now())})().finally(()=>{gi.delete(n)});return gi.set(n,d),d},[r,t,e])}function qy(e,t,r){return{...e||{},id:t,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 Xy(e,t){const{sendData:r}=Ct(),{injectEntries:n,getIdes:a}=pn(),i=Array.from(new Set(e.filter(Boolean))).join("|");c.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const o=i?i.split("|"):[];if(o.length===0)return;const l=o.map(d=>os.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},h=>{const f=a().find(v=>v.id===d),m=qy(f,d,h);n([m])}));return()=>{l.forEach(d=>d())}},[i,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function Yy(e,t){const{sendData:r}=Ct(),[n,a]=c.useState(null),[i,o]=c.useState(!1);return c.useEffect(()=>{if(!e){a(null),o(!1);return}if(!(t!=null&&t.enabled)||!r){o(!1);return}a(null),o(!0);let l=null;const d=os.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},u=>{l&&(clearTimeout(l),l=null),a(u.diagnostics),o(!1)});return d.initialSendAccepted?l=setTimeout(()=>{o(!1)},Gg):o(!1),()=>{l&&clearTimeout(l),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:a}}function Jy(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Ju(e){const{sendData:t}=Ct(),[r,n]=c.useState({});return c.useEffect(()=>{const a=Jy(e);if(!a||!e.sessionId||!t){n({});return}const i=os.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},o=>{n({status:o.status,modalMessage:o.modalMessage,modalButtons:o.modalButtons}),pr.record({interactionId:o.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:o.status,modalButtonCount:Array.isArray(o.modalButtons)?o.modalButtons.length:0}})});return i.initialSendAccepted||n({}),()=>{i()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const Qu="adhdev_hiddenTabs",Zu="adhdev_autoHiddenMeshTabs";function Qy(){try{const e=localStorage.getItem(Qu);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function Cs(e){try{localStorage.setItem(Qu,JSON.stringify([...e]))}catch{}}function Zy(){try{const e=localStorage.getItem(Zu);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function Ml(e){try{localStorage.setItem(Zu,JSON.stringify([...e]))}catch{}}function Yr(e){return Zo(e)}function Fa(e,t){return lr(t).some(r=>e.has(r))}function ev(e){var t,r,n;return((t=e.settings)==null?void 0:t.launchedByCoordinator)===!0&&typeof((r=e.settings)==null?void 0:r.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0&&((n=e.settings)==null?void 0:n.spawnedSessionVisibility)==="hidden"}function tv(e,t,r=new Set){return e.filter(n=>{if(!ev(n))return!1;const a=Yr(n);return r.has(a)?!1:!Fa(t,n)})}function sv(){const[e,t]=c.useState(Qy),[r,n]=c.useState(Zy),a=c.useCallback(m=>{const v=Yr(m);t(b=>{const p=new Set(b);return p.has(v)?p.delete(v):p.add(v),Cs(p),p})},[]),i=c.useCallback(m=>{const v=Yr(m);t(b=>{if(b.has(v))return b;const p=new Set(b);return p.add(v),Cs(p),p})},[]),o=c.useCallback(m=>{const v=Yr(m);t(b=>{if(b.has(v))return b;const p=new Set(b);return p.add(v),Cs(p),p}),n(b=>{if(b.has(v))return b;const p=new Set(b);return p.add(v),Ml(p),p})},[]),l=c.useCallback(m=>{const v=Yr(m);t(b=>{if(!b.has(v))return b;const p=new Set(b);return p.delete(v),Cs(p),p}),n(b=>{if(b.has(v))return b;const p=new Set(b);return p.add(v),Ml(p),p})},[]),d=c.useCallback(()=>{t(m=>{if(m.size===0)return m;const v=new Set;return Cs(v),v})},[]),u=c.useCallback((m,v)=>{t(b=>{const p=new Set(b);for(const g of v)p.add(g);return Cs(p),p})},[]),h=c.useCallback((m,v)=>{t(b=>{const p=new Set(b);for(const g of v)p.delete(g);return Cs(p),p})},[]),f=c.useCallback(m=>Fa(e,m),[e]);return{hiddenTabs:e,autoHiddenTabs:r,toggleTarget:a,hideTarget:i,autoHideTarget:o,showTarget:l,showAllTabs:d,hideAllForDaemon:u,showAllForDaemon:h,isHidden:f}}function eh(e){return e instanceof Error?e.message:String(e||"")}function th(e){const t=eh(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function sh(e){const t=eh(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function rh({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!it(e)||nt(e))return;const i=Tr(e);if(i===t)return;const o=e.sessionId;o&&a(l=>({...l,[o]:t}));try{await n(Ys(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:ts(e),mode:t})}catch(l){const d=sh(l);o&&!d&&a(u=>{const h={...u};return i===nh(r,o)?delete h[o]:h[o]=i,h}),th(l)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",l instanceof Error?l.message:String(l)):console.error("Failed to switch CLI view mode:",l)}}function _l(e,t){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=t[r];return!n||e.mode===n?e:{...e,mode:n}}function rv(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let r=!1;const n=e.map(a=>{const i=_l(a,t),o=Array.isArray(a.childSessions)?a.childSessions.map(d=>_l(d,t)):a.childSessions,l=o!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:o}:{}}):a});return r?n:e}function nh(e,t){if(!t)return null;for(const r of e){if(r.sessionId===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function nv(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,i]of Object.entries(e))nh(t,a)===i&&(delete n[a],r=!0);return r?n:e}function av({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){c.useEffect(()=>{au()},[]);const a=c.useMemo(()=>e.map(i=>({id:i.tabKey,name:_u(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Gx(a),c.useEffect(()=>{if(Object.keys(t).length===0)return;const o=setTimeout(()=>{r(l=>{const d=Date.now(),u={};for(const[h,f]of Object.entries(l))d-f<5e3&&(u[h]=f);return Object.keys(u).length===Object.keys(l).length?l:u})},5500);return()=>clearTimeout(o)},[t,r]),c.useEffect(()=>{const i=setInterval(()=>{const o=Date.now()-3e5;n(l=>{const d=l.filter(u=>u.timestamp>o).slice(-100);return d.length===l.length?l:d})},6e4);return()=>clearInterval(i)},[n]),null}function Rl(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function Os(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],r=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,n=Rl(t==null?void 0:t.receivedAt)||Rl(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function mo(e,t=0){return Os(e)||e.lastUpdated||t||0}function ah(e){return Os(e)||e.lastUpdated||0}function ih(e,t,r=ah){const n=r(t)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const i=e.displayPrimary.localeCompare(t.displayPrimary);if(i!==0)return i;const o=e.displaySecondary.localeCompare(t.displaySecondary);return o!==0?o:e.tabKey.localeCompare(t.tabKey)}function xo(e){var r;const t=kt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function iv(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!xo(e)&&!e.title.trim()}function ov(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(xo(r))-Number(xo(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:ih(t,r)})[0]||null}function Xt(e,t){const r=e.filter(o=>o.routeId===t);if(r.length===0)return null;const n=r.find(o=>o.streamSource==="native")||null,a=r.filter(o=>o.streamSource==="agent-stream"),i=ov(a);return n?i&&iv(n)?i:n:i||r[0]||null}function cv(e){const t=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return!t||r.startsWith(`${t}:`)?r:`${t}:${r}`}function lv(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=cv(n),i=r.get(a);if(!i){r.set(a,n);continue}const o=(i.workspace?1:0)+(i.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>o||(n.timestamp||0)>(i.timestamp||0))&&r.set(a,n)}return Array.from(r.values())}function bi(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function dv(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function Pl(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?dv(fr(r.content)):"";return[e.id||"",e.title||"",e.status||"",t.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 uv(e){const t=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.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),Pl(e.activeChat),...t.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastMessageAt||""),r.lastMessagePreview||"",r.lastMessageRole||"",String(r.lastUpdated||""),Pl(r.activeChat)].join(":"))].join("|")}function hv(e,t){const r=Date.now();return e.map(n=>{const a=t[n.tabKey];return a&&r-a<5e3?{...n,messages:[],title:""}:n})}function pv(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const i of lr({routeId:n.routeId}))r.set(i,a);for(const i of lr({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of lr({tabKey:n.tabKey}))r.set(i,n)}return r}function fv(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function mv(e){const t=fv(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const r=String(t.role||""),n=fr(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function xv({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=c.useMemo(()=>lv(e),[e]),i=c.useMemo(()=>Bu(e),[e]),o=c.useRef([]),l=c.useRef([]),d=c.useRef([]),u=c.useRef(new Map),h=c.useRef(new Map),f=c.useMemo(()=>{const j=new Map,w=[];for(const k of a){const{connectionState:O="new",machineName:P}=Ou(k,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),I=uv(k),W=u.current.get(k.id);if(W&&W.ide===k&&W.sourceSignature===I&&W.connectionState===O&&W.machineName===P){j.set(k.id,W),w.push(...W.conversations);continue}const K=oc(k,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),R={ide:k,sourceSignature:I,connectionState:O,machineName:P,conversations:K};j.set(k.id,R),w.push(...K)}u.current=j;const A=new Map,M=k=>{const O=mv(k),P=h.current.get(k.tabKey);if(P&&P.signature===O)return A.set(k.tabKey,P),P.timestamp;const I={signature:O,timestamp:ah(k)||(P==null?void 0:P.timestamp)||0};return A.set(k.tabKey,I),I.timestamp},S=[...w].sort((k,O)=>ih(k,O,M));return h.current=A,S},[a,t,i]),m=c.useMemo(()=>{const j=hv(f,r);return bi(o.current,j)?o.current:(o.current=j,j)},[f,r]),v=c.useMemo(()=>{const j=new Map,w=Array.from(new Set(m.map(A=>A.routeId)));for(const A of w){const M=Xt(m,A);M&&j.set(A,M)}return j},[m]),b=c.useMemo(()=>{const j=new Map;for(const w of m){const A=v.get(w.routeId),M=w.streamSource==="native"&&A?A:w;for(const S of lr({providerSessionId:w.providerSessionId,sessionId:w.sessionId,tabKey:w.tabKey}))j.set(S,M)}return j},[m,v]),p=c.useMemo(()=>pv(m,v),[m,v]),g=c.useCallback(j=>{if(j)return b.get(j)},[b]),y=c.useCallback(j=>{if(j)return p.get(j)},[p]),x=c.useMemo(()=>{const j=m.filter(w=>!Fa(n,w));return bi(l.current,j)?l.current:(l.current=j,j)},[m,n]),N=c.useMemo(()=>{const j=x.map(w=>w.tabKey);return bi(d.current,j)?d.current:(d.current=j,j)},[x]);return{chatIdes:a,conversations:m,visibleConversations:x,visibleTabKeys:N,resolveConversationBySessionId:g,resolveConversationByTarget:y}}function gv({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=c.useMemo(()=>{var l;return e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),i=c.useMemo(()=>{var l;return!e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),o=c.useCallback(()=>{t&&n(l=>{const d=new URLSearchParams(l);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:o}}function bv({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){c.useEffect(()=>{ct.setIdes(e)},[e]),c.useEffect(()=>{ct.setResolveAction((a,i,o)=>{t(a,i,o).catch(()=>{})})},[t]),c.useEffect(()=>{const a=ct.onToast(i=>{r(l=>l.some(u=>u.message===i.message&&i.timestamp-u.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 o=i.duration||5e3;setTimeout(()=>r(l=>l.filter(d=>d.id!==i.id)),o)});return()=>{a()}},[r]),c.useEffect(()=>{const a=Iu.on("status_event",i=>{ct.handleRawEvent(i,"ws")});return()=>{a()}},[]),c.useEffect(()=>{var i;const a=o=>{var p;const l=o.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 d=l.targetSessionId||l.targetKey||l.daemonId,u=n(d),h=(u==null?void 0:u.routeId)||l.daemonId;if(!h)return;const f=Number(l.buttonIndex),m=l.button||((p=u==null?void 0:u.modalButtons)==null?void 0:p[f])||"Approve",v=String(m).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),b=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(v);t(h,"resolve_action",{action:b?"approve":"reject",button:m,...Number.isFinite(f)&&{buttonIndex:f},...(u==null?void 0:u.sessionId)&&{targetSessionId:u.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 o;return(o=navigator.serviceWorker)==null?void 0:o.removeEventListener("message",a)}},[n,t])}const yv="adhdev_dashboardLayout_v1",vv="adhdev_dashboardDockview_v1",wv="adhdev_dashboardDockviewHiddenRestore_v1",Ur={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function hc(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Sv(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function oh(e){return`${yv}:${e}`}function kv(e){const t=oh(e);return hc(t,null)}function jv(e,t){try{const r=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,n=oh(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function ch(e){return`${vv}:${e}`}function Nv(e){const t=ch(e);return hc(t,null)}function Cv(e,t){try{const r=ch(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function lh(e){return`${wv}:${e}`}function Tv(e){const t=lh(e);return hc(t,{})}function Iv(e,t){try{const r=lh(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Av(){return{groupAssignments:[...Ur.groupAssignments],focusedGroup:Ur.focusedGroup,groupActiveTabIds:{...Ur.groupActiveTabIds},groupTabOrders:{...Ur.groupTabOrders},groupSizes:[...Ur.groupSizes]}}function Mv(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function _v(){const[e]=c.useState(()=>Sv(typeof window<"u"?window.innerWidth:1280)),[t,r]=c.useState(()=>new Map),[n,a]=c.useState(0),[i,o]=c.useState({}),[l,d]=c.useState({}),[u,h]=c.useState([]),[f,m]=c.useState(()=>typeof window<"u"&&window.innerWidth<768),[v,b]=c.useState(!1),p=c.useCallback(()=>{if(v)return;const k=kv(e)??Av();r(new Map(k.groupAssignments)),a(k.focusedGroup),o(k.groupActiveTabIds),d(k.groupTabOrders),h(k.groupSizes),b(!0)},[v,e]);c.useEffect(()=>{v&&jv(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:u})},[v,e,t,n,i,l,u]),c.useEffect(()=>{const k=window.matchMedia("(max-width: 767px)"),O=P=>m(P.matches);return k.addEventListener("change",O),()=>k.removeEventListener("change",O)},[]);const g=c.useCallback(k=>{r(k)},[]),y=c.useCallback(k=>{a(k)},[]),x=c.useCallback(k=>{o(k)},[]),N=c.useCallback(k=>{d(k)},[]),j=c.useCallback(k=>{h(k)},[]),w=c.useCallback(k=>{y(k)},[y]),A=c.useCallback((k,O)=>{o(P=>(P[k]??null)===(O??null)?P:{...P,[k]:O})},[]),M=c.useCallback((k,O)=>{d(P=>{const I=P[k];return Mv(I,O)?P:{...P,[k]:O}})},[]),S=c.useCallback((k,O)=>{const P=O.get(k)??0;return A(P,k),w(P),P},[w,A]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:g,focusedGroup:n,updateFocusedGroup:y,focusGroup:w,groupActiveTabIds:i,updateGroupActiveTabIds:x,setGroupActiveTab:A,groupTabOrders:l,updateGroupTabOrders:N,setGroupTabOrder:M,groupSizes:u,updateGroupSizes:j,isMobile:f,hasHydratedStoredLayout:v,hydrateStoredLayout:p,focusConversationTab:S}}function Rv(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Qo(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Pv({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,focusConversationTab:o,setSearchParams:l,historyModalOpen:d,activeConv:u,isRefreshingHistory:h,ides:f,handleRefreshHistory:m}){const v=c.useRef(!1),b=c.useRef(!1),p=c.useRef(null),g=c.useRef(!1);c.useEffect(()=>{if(!e||v.current||t.length===0)return;if(!a){i();return}const y=r(e);y&&(o(y.tabKey,n),v.current=!0,b.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(x=>{const N=new URLSearchParams(x);return N.delete("activeTab"),N},{replace:!0}))},[e,t,r,n,a,i,o,l]),c.useEffect(()=>{if(!(b.current||a)&&t.length!==0){if(!e){i(),b.current=!0;return}if(v.current){b.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(b.current||a)&&(i(),b.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,i]),c.useEffect(()=>{if(!d){g.current=!1;return}if(!u||g.current||h)return;const y=f.find(x=>x.id===u.routeId);y&&(!y.chats||y.chats.length===0||Rv(y.chats,u))&&(g.current=!0,m())},[d,u,h,f,m])}function yi(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=Qo(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function dh({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:i}){const[o,l]=c.useState(!1),[d,u]=c.useState(!1),h=c.useCallback(async b=>{try{await e("standalone","launch_ide",{ideType:b,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),f=c.useCallback(async(b,p)=>{try{const g=b||(t==null?void 0:t.daemonId)||"",y=await e(g,"switch_chat",{id:p,sessionId:p,...Ps(t)}),x=y==null?void 0:y.result;if((y==null?void 0:y.success)===!0||x==="switched"||x==="switched-by-title")return;x===!1||x==="not_found"?Br(a,"⚠️ Session tab not found — try refreshing history"):typeof x=="string"&&x.startsWith("error:")?Br(a,`⚠️ Switch error: ${x}`):Br(a,"⚠️ Session switch failed")}catch(g){console.error("Switch failed",g),Br(a,`❌ Switch failed: ${g.message||"connection error"}`)}},[t,e,a]),m=c.useCallback(async()=>{if(!(!t||o)){l(!0);try{const b=gr(t);await e(b,"new_chat",{...Ps(t)}),i(p=>({...p,[t.tabKey]:Date.now()}))}catch(b){console.error("New chat failed",b)}finally{l(!1)}}},[t,o,e,i]),v=c.useCallback(async()=>{var b,p;if(!(!t||d)){u(!0);try{const g=gr(t),y=async()=>e(g,"list_chats",{forceExpand:!0,...Ps(t)});let x=await y(),N=(x==null?void 0:x.chats)||((b=x==null?void 0:x.result)==null?void 0:b.chats);yi(N,t)&&(await new Promise(j=>setTimeout(j,450)),x=await y(),N=(x==null?void 0:x.chats)||((p=x==null?void 0:x.result)==null?void 0:p.chats)),x!=null&&x.success&&Array.isArray(N)&&(n(t.routeId,N),yi(N,t)&&!yi(r,t)&&Br(a,"⚠️ History dialog did not fully open — try once more"))}catch(g){console.error("Refresh history failed",g)}finally{u(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:o,isRefreshingHistory:d,handleLaunchIde:h,handleSwitchSession:f,handleNewChat:m,handleRefreshHistory:v}}function Lv(e,t){if(e.size!==t.size)return!1;for(const[r,n]of e)if(t.get(r)!==n)return!1;return!0}function Ev(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Ll(e,t){const r=Object.keys(e),n=Object.keys(t);return r.length!==n.length?!1:r.every(a=>t[Number(a)]===e[Number(a)])}function On(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[o,l]of e)!r.has(o)||l<=0||n.includes(l)||n.push(l);n.sort((o,l)=>o-l);const a={};n.forEach((o,l)=>{a[o]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[o,l]of e){if(!r.has(o)||l<=0)continue;const d=a[l];typeof d=="number"&&d>0&&i.set(o,d)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function El(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=t[Number(n)];typeof i=="number"&&(r[i]=a)}return r}function Dv(e,t,r){if(t.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...t].reverse().find(a=>a<e)??t[0];return r[n]??0}function $v(e,t,r){if(t.length<=1)return[];const n=t.map(o=>e[o]).filter(o=>Number.isFinite(o)),a=n.length===t.length?n:Array(r).fill(100/r),i=a.reduce((o,l)=>o+l,0);return i>0?a.map(o=>o/i*100):Array(r).fill(100/r)}function Dl(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=Number(n);r[i>=t?i+1:i]=a}return r}function $l(e){return Array(e).fill(100/e)}function Bv({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:i,updateGroupSizes:o,isMobile:l,visibleConversations:d,visibleTabKeys:u}){const h=c.useRef(null),f=c.useMemo(()=>On(e,u),[e,u]),m=f.assignments,v=c.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),b=v>1,p=c.useCallback((w,A)=>{t(M=>{const S=new Map(On(M,u).assignments);return A===0?S.delete(w):S.set(w,A),S}),n(M=>({...M,[A]:w})),r(A)},[t,u,n,r]),g=c.useCallback(w=>{t(A=>{const M=On(A,u).assignments,S=new Map;for(const[k,O]of M)O!==w&&(O>w?S.set(k,O-1):S.set(k,O));return S}),o(A=>{if(A.length<=1)return[];const M=[...A];M.splice(w,1);const S=M.reduce((k,O)=>k+O,0);return S>0?M.map(k=>k/S*100):[]}),r(0)},[t,u,o,r]),y=c.useCallback((w,A)=>{A.preventDefault();const M=h.current;if(!M)return;const S=A.clientX,k=M.offsetWidth,O=i.length===v?[...i]:$l(v),P=W=>{const R=(W.clientX-S)/k*100,T=[...O];T[w]=Math.max(15,O[w]+R),T[w+1]=Math.max(15,O[w+1]-R),o(T)},I=()=>{document.removeEventListener("mousemove",P),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",P),document.addEventListener("mouseup",I)},[i,v,o]),x=c.useCallback((w,A,M)=>{if(v>=4)return;const S=M==="left"?A:A+1;t(k=>{const O=On(k,u).assignments,P=new Map;for(const I of d){const W=O.get(I.tabKey)??0,K=W>=S?W+1:W;K>0&&P.set(I.tabKey,K)}return S>0&&P.set(w,S),P}),o(k=>{const O=k.length===v?[...k]:$l(v),P=O[A]??100/v,I=Math.max(15,P/2),W=Math.max(15,P/2),K=[...O];K[A]=I,K.splice(S,0,W);const R=K.reduce((T,C)=>T+C,0);return K.map(T=>T/R*100)}),n(k=>{const O=Dl(k,S);return O[S]=w,O}),a(k=>{const O=Dl(k,S);return O[S]=[w],O}),r(S)},[v,t,u,d,o,n,a,r]);c.useEffect(()=>{Lv(e,m)||t(m)},[e,m,t]),c.useEffect(()=>{const{mapping:w,usedGroups:A}=f;n(M=>{const S=El(M,w);return Ll(M,S)?M:S}),a(M=>{const S=El(M,w);return Ll(M,S)?M:S}),r(M=>{const S=l?0:Dv(M,A,w);return M===S?M:S}),o(M=>{const S=l?[]:$v(M,A,f.groupCount);return Ev(M,S)?M:S})},[f,l,n,a,r,o]);const N=c.useMemo(()=>{const w=Array.from({length:v},()=>[]);for(const A of d){const M=m.get(A.tabKey)??0,S=Math.min(M,v-1);w[S].push(A)}return w},[d,m,v]),j=c.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:h,normalizedGroupAssignments:m,numGroups:v,isSplitMode:b,groupedConvs:N,moveTabToGroup:p,closeGroup:g,handleResizeStart:y,splitTabRelative:x,clearAllSplits:j}}function vi(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="stable"||t==="latest"?"stable":t==="preview"||t==="next"?"preview":null}function Ov(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="latest"||t==="stable"?"latest":t==="next"||t==="preview"?"next":null}function Fn(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function pc(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=vi(t.channel)||vi(e.updateChannel)||vi(e.releaseChannel)||void 0,n=Ov(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=Fn(t.targetVersion)||Fn(e.serverVersion)||void 0,i=Fn(t.minVersion)||void 0,o=Fn(t.updateCommand)||(r?`adhdev update --channel ${r}`:void 0);return{...r?{channel:r}:{},...n?{npmTag:n}:{},...a?{targetVersion:a}:{},...i?{minVersion:i}:{},...o?{updateCommand:o}:{}}}function rr(e,t=null){return pc(e).targetVersion||t}function uh(e){return pc(e).channel||null}function hh(e){const t=pc(e);return{...t.channel?{channel:t.channel}:{},...t.npmTag?{npmTag:t.npmTag}:{},...t.targetVersion?{targetVersion:t.targetVersion}:{},...Object.keys(t).length>0?{updatePolicy:t}:{}}}function Fv({ides:e,sendDaemonCommand:t}){const r="0.9.76",n=c.useMemo(()=>e.filter(f=>f.type!=="adhdev-daemon"?!1:Vu(f,rr(f,r))).sort((f,m)=>Number(nn(m,rr(m,r)))-Number(nn(f,rr(f,r)))),[r,e]),a=c.useMemo(()=>n.some(f=>nn(f,rr(f,r))),[r,n]),i=c.useMemo(()=>n.map(f=>rr(f,r)).find(f=>typeof f=="string"&&f.trim().length>0)||r,[r,n]),[o,l]=c.useState(!1),[d,u]=c.useState({}),h=c.useCallback(async f=>{var v,b;const m=e.find(p=>p.id===f);if(m){u(p=>({...p,[f]:"upgrading"}));try{const p=await t(f,"daemon_upgrade",hh(m));(v=p==null?void 0:p.result)!=null&&v.upgraded||(b=p==null?void 0:p.result)!=null&&b.success?u(g=>({...g,[f]:"done"})):u(g=>({...g,[f]:"error"}))}catch{u(p=>({...p,[f]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:i,versionBannerDismissed:o,setVersionBannerDismissed:l,upgradingDaemons:d,handleBannerUpgrade:h}}const ph=80;function ta(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function Wv(e){return{...e,createdAt:ta(e.createdAt),updatedAt:ta(e.updatedAt,e.createdAt),lastEventAt:ta(e.lastEventAt,e.updatedAt||e.createdAt)}}function Uv(e){const t=Zo(e);return t==="unknown:"?e.id:t}function Kv(e){return[e.type,wu(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Hv(e,t=ph){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Uv(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,t))}function zv(e,t){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?t.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const o=Ea(a,t),l=o.inboxBucket==="needs_attention"?"needs_attention":o.inboxBucket==="task_complete"&&o.unread?"task_complete":null;if(!l)continue;const d=ta(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),u=Kv({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(Wv({id:u,dedupKey:u,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:uu(a),preview:wg(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return Hv(n)}function Vv(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function Gv(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=ph}=e,a=c.useMemo(()=>zv(t,r).slice(0,Math.max(0,n)),[t,r,n]),i=c.useMemo(()=>Vv(a),[a]);return{notifications:a,unreadCount:i}}function qv({notifications:e,sendDaemonCommand:t}){const r=c.useCallback(i=>{const o=e.find(d=>d.id===i),l=Math.max(Date.now(),(o==null?void 0:o.updatedAt)||0);o!=null&&o.sessionId&&t(o.machineId||o.routeId,"mark_session_seen",{sessionId:o.sessionId,seenAt:l}).catch(()=>{})},[e,t]),n=c.useCallback(i=>{const o=e.find(l=>l.id===i);o!=null&&o.sessionId&&t(o.machineId||o.routeId,"mark_notification_unread",{sessionId:o.sessionId,notificationId:o.id}).catch(()=>{})},[e,t]),a=c.useCallback(i=>{const o=e.find(l=>l.id===i);o!=null&&o.sessionId&&t(o.machineId||o.routeId,"delete_notification",{sessionId:o.sessionId,notificationId:o.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}const Xv=c.createContext(null);function Yv(){return c.useContext(Xv)}function Wa(...e){const t=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const o=i.toLowerCase();t.has(o)||(t.add(o),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 Jv(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const r=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function Ua(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=Jv(r);if(n)return n}return"C:\\"}for(const r of t){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function Qv(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const r=t.includes("\\")?"\\":"/",n=t.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 Zv(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Ka(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=Zv(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,o=i.includes("\\")?"\\":"/",l=(u,h)=>/^[A-Za-z]:\\?$/.test(u)?`${u.replace(/\\?$/,"\\")}${h}`:u==="/"||u==="\\"?`${o}${h}`:`${u.replace(/[\\/]+$/,"")}${o}${h}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(u=>(u==null?void 0:u.type)==="directory"&&typeof(u==null?void 0:u.name)=="string").map(u=>({name:u.name,path:typeof(u==null?void 0:u.path)=="string"&&u.path.trim()?u.path:l(i,u.name)})).sort((u,h)=>u.name.localeCompare(h.name)):[];return{path:i,directories:d}}function e0(e,t){const r={meshId:t.meshId||"",workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp"};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand)\s*\}\}/g,(n,a)=>r[a]||"")}function fh(e,t={}){const r=e==null?void 0:e.mcpConfig;return(r==null?void 0:r.mode)!=="manual"?null:{serverName:r.serverName||"adhdev-mesh",configFormat:r.format,configPathCommand:r.configPathCommand,requiresRestart:r.requiresRestart===!0,instructions:r.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:e0(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function t0(e){if(!e||typeof e!="object")return null;const t=e,r=typeof t.instructions=="string"?t.instructions:"",n=typeof t.template=="string"?t.template:"";return!r&&!n?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:r||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:n}}function ws(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function mh(e){return jn(e)||e.tabKey||e.routeId||null}function xh(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",a=e.conversations.find(i=>{if(n&&i.routeId!==n)return!1;const o=[i.providerSessionId,i.sessionId,i.nativeSessionId,i.tabKey].map(l=>typeof l=="string"?l.trim():"").filter(Boolean);return!!(t&&o.includes(t)||r&&o.includes(r)||n&&i.routeId===n)});if(a!=null&&a.tabKey)return a.tabKey;if(n){const i=Xt(e.conversations,n)||e.conversations.find(o=>o.routeId===n);if(i!=null&&i.tabKey)return i.tabKey}return t||r||n||null}function ms(e){return String(e||"").trim()}function gh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ja(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function s0(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function r0(e,t){const r=ms(e.providerSessionId),n=ms(e.targetSessionId),a=t.find(i=>{const o=[i.providerSessionId,i.sessionId,i.nativeSessionId,i.tabKey,i.routeId].map(ms).filter(Boolean);return!!(r&&o.includes(r)||n&&o.includes(n))});return a?a.tabKey:n||r||null}function n0(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=gh(t.daemonId);if(n&&n!==e.machineId)return null;const a=ms(t.providerType);if(e.providerType&&a!==e.providerType)return null;const i=ms(e.resumeSessionId),o=ms(e.launchedSessionId),l=ms(t.providerSessionId),d=ms(t.targetSessionId);if(i&&i!==l&&i!==d||o&&o!==l&&o!==d)return null;const u=ja(e.workspacePath);if(u){const h=ja(t.workspaceName);if(h&&!s0(h,u))return null}return r0(t,r)}function Bl(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function a0({ides:e,conversations:t,onOpenSession:r}){const[n,a]=c.useState(null),i=c.useRef(null),o=c.useCallback(()=>{i.current=null,a(null)},[]),l=c.useCallback(d=>{i.current=d,a(d)},[]);return c.useEffect(()=>{if(!n)return;const d=ja(n.workspacePath),u=e.find(f=>{var g,y,x,N;if(!f||f.type==="adhdev-daemon"||gh(f.daemonId||f.id)!==n.machineId||(mn(f)?"cli":or(f)?"acp":"ide")!==n.kind)return!1;const b=String(f.agentType||f.type||"");if(n.providerType&&b!==n.providerType)return!1;if(n.resumeSessionId)return String(f.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const j=String(n.launchedSessionId||"");return[f.providerSessionId,f.sessionId,f.instanceId,f.id].map(A=>String(A||"")).filter(Boolean).includes(j)}if(d){const j=ja(f.workspace||f.runtimeWorkspaceLabel);return j?j===d:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((N=(x=(y=(g=f.activeChat)==null?void 0:g.messages)==null?void 0:y.at)==null?void 0:x.call(y,-1))==null?void 0:N.timestamp)||0)>=n.startedAt-5e3});if(!u)return;const h=xh({entrySessionId:u.sessionId,entryInstanceId:u.instanceId,entryRouteId:u.id,conversations:t});h&&(o(),r(h))},[o,t,e,r,n]),c.useEffect(()=>ct.onStatusEvent(d=>{const u=i.current;if(!u)return;const h=n0(u,d,t);h&&(o(),r(h))}),[o,t,r]),c.useEffect(()=>{if(!n)return;const d=window.setTimeout(()=>{a(u=>!u||u.startedAt!==n.startedAt?u:(i.current=null,null))},45e3);return()=>window.clearTimeout(d)},[n]),{trackPendingLaunch:l}}function i0({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const o=Yv(),l=c.useCallback(async(p,g)=>Ka(e,p,g),[e]),d=c.useCallback(async(p,g)=>{if(!g.trim())return{ok:!1,error:"Choose a workspace path first."};try{const y=await e(p,"workspace_add",{path:g.trim()});return y!=null&&y.success?{ok:!0}:{ok:!1,error:(y==null?void 0:y.error)||"Could not save workspace"}}catch(y){return{ok:!1,error:y instanceof Error?y.message:"Could not save workspace"}}},[e]),u=c.useCallback(async(p,g,y)=>{var x;try{const N={ideType:g,enableCdp:!0};(x=y==null?void 0:y.workspacePath)!=null&&x.trim()&&(N.workspace=y.workspacePath.trim());const j=await e(p,"launch_ide",N);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"}:(t({machineId:p,kind:"ide",providerType:g,workspacePath:(y==null?void 0:y.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(N){return{ok:!1,error:N instanceof Error?N.message:"Could not launch IDE"}}},[e,t]),h=c.useCallback(async(p,g,y,x)=>{var j,w,A;const N=Date.now();try{const M={cliType:y};(j=x==null?void 0:x.workspacePath)!=null&&j.trim()?M.dir=x.workspacePath.trim():x!=null&&x.workspaceId&&(M.workspaceId=x.workspaceId),(w=x==null?void 0:x.resumeSessionId)!=null&&w.trim()&&(M.resumeSessionId=x.resumeSessionId.trim()),Array.isArray(x==null?void 0:x.cliArgs)&&x.cliArgs.length>0&&(M.cliArgs=x.cliArgs),(A=x==null?void 0:x.initialModel)!=null&&A.trim()&&(M.initialModel=x.initialModel.trim());const S=await e(p,"launch_cli",M),k=(S==null?void 0:S.result)||S,O=(k==null?void 0:k.sessionId)||(k==null?void 0:k.id);return S!=null&&S.success&&O?(t({machineId:p,kind:g,providerType:y,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,launchedSessionId:O,startedAt:N}),{ok:!0}):S!=null&&S.success?(t({machineId:p,kind:g,providerType:y,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,startedAt:N}),{ok:!0}):{ok:!1,error:(S==null?void 0:S.error)||(k==null?void 0:k.error)||`Could not launch ${g.toUpperCase()} session`}}catch(M){return Bl(M)?(t({machineId:p,kind:g,providerType:y,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,startedAt:N}),{ok:!0}):{ok:!1,error:M instanceof Error?M.message:`Could not launch ${g.toUpperCase()} session`}}},[r,e,t]),f=c.useCallback(async p=>{var g;if(o!=null&&o.listMeshes)return o.listMeshes(p);if(!p)return[];try{const y=await e(p,"list_meshes",{}),x=(y==null?void 0:y.result)??y;if((x==null?void 0:x.success)===!1)throw new Error((x==null?void 0:x.error)||"Could not load meshes");return(Array.isArray(x==null?void 0:x.meshes)?x.meshes:Array.isArray((g=x==null?void 0:x.result)==null?void 0:g.meshes)?x.result.meshes:[]).map(j=>{var w;return{id:String((j==null?void 0:j.id)||""),name:String((j==null?void 0:j.name)||(j==null?void 0:j.id)||"Untitled mesh"),repoIdentity:(j==null?void 0:j.repoIdentity)||(j==null?void 0:j.repo_identity)||null,workspace:Array.isArray(j==null?void 0:j.nodes)&&j.nodes.length>0?String(((w=j.nodes[0])==null?void 0:w.workspace)||""):null,nodesCount:Array.isArray(j==null?void 0:j.nodes)?j.nodes.length:void 0,status:(j==null?void 0:j.status)||null}}).filter(j=>j.id)}catch(y){throw console.error("List meshes failed",y),y}},[o,e]),m=c.useCallback(async(p,g,y)=>{if(!g.trim())return{ok:!1,error:"Choose a mesh first."};if(o!=null&&o.launchMeshCoordinator)return o.launchMeshCoordinator(p,g,y);const x=Date.now();try{const N={meshId:g.trim()};y.trim()&&(N.cliType=y.trim());const j=await e(p,"launch_mesh_coordinator",N),w=(j==null?void 0:j.result)??j;if((w==null?void 0:w.success)===!1||(j==null?void 0:j.success)===!1){const M=String((w==null?void 0:w.code)||(j==null?void 0:j.code)||""),S=t0((w==null?void 0:w.meshCoordinatorSetup)||(w==null?void 0:w.manualSetup)||(j==null?void 0:j.meshCoordinatorSetup)||(j==null?void 0:j.manualSetup));return{ok:!1,error:(w==null?void 0:w.error)||(j==null?void 0:j.error)||"Could not launch mesh coordinator",code:M||void 0,manualSetup:S}}const A=(w==null?void 0:w.sessionId)||(w==null?void 0:w.id);return A?r(A):t({machineId:p,kind:"cli",providerType:(w==null?void 0:w.cliType)||y.trim()||void 0,workspacePath:(w==null?void 0:w.workspace)||null,startedAt:x}),{ok:!0}}catch(N){return Bl(N)?(t({machineId:p,kind:"cli",providerType:y.trim()||void 0,startedAt:x}),{ok:!0}):{ok:!1,error:N instanceof Error?N.message:"Could not launch mesh coordinator"}}},[o,r,e,t]),v=c.useCallback(async(p,g)=>{if(!p||!g)return[];try{const y=await e(p,"list_saved_sessions",{providerType:g,kind:"cli",limit:30}),x=(y==null?void 0:y.result)??y;return Array.isArray(x==null?void 0:x.sessions)?x.sessions:[]}catch(y){return console.error("List saved sessions failed",y),[]}},[e]),b=c.useCallback(async p=>{await rh({conversation:n,mode:p,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:i})},[n,a,e,i]);return{handleBrowseMachineDirectory:l,handleSaveMachineWorkspace:d,handleLaunchMachineIde:u,handleLaunchMachineProvider:h,handleListMachineMeshes:f,handleLaunchMeshCoordinator:m,handleListMachineSavedSessions:v,setActiveCliViewMode:b}}function o0(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":return!0;case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function c0(e,t,r=Date.now()){return!e||!o0(t)?null:{tabKey:e,nonce:r}}function l0({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:i,setSearchParams:o}){const[l,d]=c.useState(null),[u,h]=c.useState(null),f=c.useMemo(()=>{var g,y;if(!e){if(l){const x=t.find(N=>N.tabKey===l);if(x)return x}return r[0]}const p=n[a];if(p){const x=t.find(N=>N.tabKey===p);if(x)return x}return((g=i[a])==null?void 0:g[0])||((y=i[0])==null?void 0:y[0])},[t,l,a,n,i,e,r]),m=c.useCallback(p=>{d(p)},[]),v=c.useCallback(p=>{d(p.tabKey),o(g=>{const y=new URLSearchParams(g),x=kg(p);return x?y.set("activeTab",x):y.delete("activeTab"),y},{replace:!0})},[o]),b=c.useCallback((p,g)=>{const y=c0(p,g);y&&h(y)},[]);return{activeConv:f,openDesktopConversation:v,requestScrollToBottom:b,scrollToBottomRequest:u,setDesktopActiveTab:m}}function d0(e){const t=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?t===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 u0(e){const t=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,i=[e.tabKey,e.historySessionId||"",t,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&t&&t!==r),autoReadKey:i,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function h0({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=c.useRef(null),i=c.useRef(null),o=c.useRef(null),l=c.useRef(null),d=c.useRef(null);c.useEffect(()=>{const u=()=>{o.current&&(clearTimeout(o.current),o.current=null),l.current&&(clearTimeout(l.current),l.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),i.current=null};if(t){u(),a.current=null;return}if(!(e!=null&&e.sessionId)){u(),a.current=null;return}const h=fa(e,r),f=u0({tabKey:e.tabKey,historySessionId:jn(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Os(e),liveState:h}),m=f.autoReadKey,v=d0({autoReadKey:m,shouldMarkSeen:f.shouldMarkSeen,completedKey:a.current,pendingKey:i.current});if(!f.shouldMarkSeen){v.shouldCancelPending&&u(),a.current=m;return}if(!v.shouldSchedule)return;v.shouldCancelPending&&u();const b=()=>{if(document.visibilityState!=="visible"||a.current===m)return;a.current=m,i.current=null,o.current=null,l.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const g=f.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:g,completionMarker:f.completionMarker}).catch(()=>{})};if(i.current=v.nextPendingKey,document.visibilityState==="visible"){o.current=setTimeout(b,1500);const g=()=>{document.visibilityState!=="visible"&&o.current&&(clearTimeout(o.current),o.current=null)};d.current=g,document.addEventListener("visibilitychange",g);return}const p=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(b,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=p,document.addEventListener("visibilitychange",p)},[e,t,r,n]),c.useEffect(()=>()=>{o.current&&clearTimeout(o.current),l.current&&clearTimeout(l.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function wi(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const r=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(r)?r:""}function p0({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:o,setClearedTabs:l,setSearchParams:d}){var C;const[u,h]=c.useState(!1),[f,m]=c.useState([]),[v,b]=c.useState(()=>Mt()),[p,g]=c.useState(!1),[y,x]=c.useState(null),N=c.useRef(null),j=c.useMemo(()=>r||t||e,[e,r,t]),w=!!j&&it(j)&&!nt(j),A=c.useMemo(()=>{if(!j||!w)return null;const F=j.daemonId||j.routeId||"",L=ts(j),D=wi(j);return`${F}:${L}:${j.providerSessionId||""}:${D}`},[j,w]),M=c.useMemo(()=>!j||!w?"":wi(j),[j,w]),{isCreatingChat:S,isRefreshingHistory:k,handleSwitchSession:O,handleNewChat:P,handleRefreshHistory:I}=dh({sendDaemonCommand:a,activeConv:j,chats:(C=n.find(F=>F.id===(j==null?void 0:j.routeId)))==null?void 0:C.chats,updateRouteChats:i,setToasts:o,setClearedTabs:l}),W=c.useCallback(()=>{h(!0)},[]),K=c.useCallback(()=>{h(!1)},[]),R=c.useCallback(async()=>{if(!(!j||!w||p)){g(!0);try{const F=j.daemonId||j.routeId,L=ts(j),D=wi(j),H=await a(F,"list_saved_sessions",{agentType:L,providerType:L,kind:"cli",limit:50,...j.providerSessionId?{providerSessionId:j.providerSessionId}:{},...D?{workspace:D}:{}}),Q=(H==null?void 0:H.result)??H;m(Array.isArray(Q==null?void 0:Q.sessions)?Q.sessions:[])}catch(F){console.error("Refresh saved sessions failed",F),m([])}finally{g(!1)}}},[j,p,w,a]);c.useEffect(()=>{if(!u){N.current=null;return}if(!w){N.current=null,m([]),g(!1);return}!A||p||N.current!==A&&(N.current=A,R())},[R,u,p,w,A]);const T=c.useCallback(async F=>{if(!j||!w||!F.providerSessionId||!F.workspace)return;const L=j.daemonId||j.routeId,D=ts(j);try{x(F.providerSessionId);const H=await a(L,"launch_cli",{cliType:D,dir:F.workspace,resumeSessionId:F.providerSessionId,initialModel:ru(F.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Q=(H==null?void 0:H.result)??H,ge=typeof(Q==null?void 0:Q.sessionId)=="string"?Q.sessionId:typeof(Q==null?void 0:Q.id)=="string"?Q.id:"";ge&&d(ue=>{const Z=new URLSearchParams(ue);return Z.set("activeTab",ge),Z},{replace:!0}),K()}catch(H){console.error("Resume saved session failed",H)}finally{x(null)}},[K,j,w,a,d]);return{historyModalOpen:u,openHistoryModal:W,closeHistoryModal:K,historyTargetConv:j,isSavedSessionHistoryTarget:w,isHistoryCreatingChat:S,isHistoryRefreshingHistory:k,handleHistorySwitchSession:O,handleHistoryNewChat:P,handleHistoryRefresh:I,savedHistorySessions:f,savedHistoryFilters:v,setSavedHistoryFilters:b,missingWorkspaceResumePath:M,isSavedHistoryLoading:p,resumingSavedHistorySessionId:y,handleRefreshSavedHistory:R,handleResumeSavedHistorySession:T}}function f0({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:o,resolveConversationByTarget:l}){const[d,u]=c.useState(null),[h,f]=c.useState(null),m=c.useMemo(()=>{if(e||!n)return null;const y=l(n);return y&&!it(y)&&!nt(y)?y:null},[e,n,l]),v=c.useMemo(()=>{const y=d==null?void 0:d.routeId;if(!y)return null;const x=d!=null&&d.tabKey?i.find(N=>N.tabKey===d.tabKey):a?i.find(N=>N.tabKey===a):null;return(x==null?void 0:x.routeId)===y?x:Xt(i,y)},[i,d,a]),b=c.useMemo(()=>{if(v)return o.find(y=>y.id===v.routeId)},[o,v]);c.useEffect(()=>{m&&(u({routeId:m.routeId,tabKey:ll(m)}),f(m),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,m]);const p=c.useCallback(y=>{y&&(u({routeId:y.routeId,tabKey:ll(y)}),f(y))},[]),g=c.useCallback(()=>{u(null),f(null)},[]);return{remoteDialogConv:v,remoteDialogIdeEntry:b,remoteDialogActiveConv:h,setRemoteDialogActiveConv:f,openRemoteDialog:p,closeRemoteDialog:g}}function m0({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:o,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:u}){const{remoteDialogConv:h,remoteDialogIdeEntry:f,remoteDialogActiveConv:m,setRemoteDialogActiveConv:v,openRemoteDialog:b,closeRemoteDialog:p}=f0({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:o,resolveConversationByTarget:l}),[g,y]=c.useState(!1),[x,N]=c.useState(null),j=c.useCallback(async M=>{const S=M||d;!S||!it(S)&&!nt(S)||(N(S),y(!0))},[d]),w=c.useCallback(()=>{y(!1),N(null)},[]),A=c.useCallback(async M=>{const S=x||d;if(!S||!it(S)&&!nt(S)){w();return}y(!1);try{const k=ts(S),O=S.routeId||S.daemonId||"";await u(O,"stop_cli",{cliType:k,targetSessionId:S.sessionId,mode:M})}catch(k){console.error("Stop CLI failed:",k)}finally{N(null)}},[d,w,x,u]);return{remoteDialogConv:h,remoteDialogIdeEntry:f,remoteDialogActiveConv:m,setRemoteDialogActiveConv:v,openRemoteDialog:b,closeRemoteDialog:p,cliStopDialogOpen:g,cliStopTargetConv:x,requestCliStop:j,cancelCliStop:w,confirmCliStop:A}}function bh({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:i=!1}){var N,j;const o=Nr(),l=Ys(e),d=i?null:du(e),u=!i&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),h=!i&&e.streamSource==="agent-stream"&&!!e.agentName,f=!i&&!h&&(e.transport==="pty"||e.transport==="acp"),m=xr(e),v=Sg(e),b=(N=e.settings)==null?void 0:N.meshNodeFor,p=e.meshQueueStats,g=(j=e.settings)==null?void 0:j.meshCoordinatorFor;if(!u&&!h&&!f&&!d&&!b&&!p)return null;const y=c.useCallback(()=>{if(n){n();return}l&&o("/dashboard",{state:{openMachineId:l}})},[l,o,n]),x=c.useCallback(()=>{if(r){r();return}const w=mh(e);w&&o(ws(w))},[e,o,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:x,title:v,children:[s.jsx(Bt,{size:12}),s.jsx("span",{children:v})]}):s.jsxs("span",{className:"conversation-meta-chip",title:v,children:[s.jsx(Bt,{size:12}),s.jsx("span",{children:v})]})),h&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:m,children:[s.jsx(mr,{size:12}),s.jsx("span",{children:m})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:m,children:[s.jsx(mr,{size:12}),s.jsx("span",{children:m})]}),d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:y,title:d,children:[s.jsx(ys,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(ys,{size:12}),s.jsx("span",{children:d})]})),b&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(ys,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),g&&p&&s.jsxs("span",{className:`conversation-meta-chip ${p.pending>0?"is-active":""}`,style:p.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${p.pending} pending, ${p.assigned} assigned, ${p.completed} completed, ${p.failed} failed`,children:[s.jsx(Sm,{size:12}),s.jsxs("span",{children:[p.pending," Pending"]})]})]})}function Si(e,t=!0){return(e??!0)&&t}const fc=c.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:o,handleRelaunch:l,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:h=null,handleFocusAgent:f,isFocusingAgent:m,actionLogs:v,userName:b,scrollToBottomRequestNonce:p,isInputActive:g=!0,isVisible:y=!0}){const x=n,N=!n,j=Si(y,x),w=Si(y,N),A=Si(y),M=Ju(t),S=M.status||M.modalMessage||M.modalButtons?{...t,...M.status?{status:M.status}:{},...M.modalMessage!==void 0?{modalMessage:M.modalMessage}:{},...M.modalButtons!==void 0?{modalButtons:M.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(eu,{activeConv:S,onModalButton:o}),s.jsx(bh,{conversation:S,className:"chat-pane-meta-row mx-3 mt-1",meshOnly:!0}),S.transport!=="pty"&&S.transport!=="acp"&&S.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.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:[s.jsx("span",{className:"text-sm",children:s.jsx(fn,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:l,children:"Relaunch with CDP"})]})}):null,S.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:x?"visible":"hidden",pointerEvents:x?"auto":"none"},children:s.jsx(Db,{activeConv:S,clearToken:r,terminalRef:i,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:h,isVisible:j,isInputActive:g&&j})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:N?"visible":"hidden",pointerEvents:N?"auto":"none"},children:s.jsx(co,{activeConv:S,ideEntry:a,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:h,handleFocusAgent:f,isFocusingAgent:m,actionLogs:v,userName:b,scrollToBottomRequestNonce:p,isInputActive:g&&w,isVisible:w})})]}):s.jsx(co,{activeConv:S,ideEntry:a,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:h,handleFocusAgent:f,isFocusingAgent:m,actionLogs:v,userName:b,scrollToBottomRequestNonce:p,isInputActive:g&&A,isVisible:A})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function x0({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:o,sendFeedbackMessage:l=null,isFocusingAgent:d,onBack:u,onOpenNativeConversation:h,onOpenMachine:f,onOpenHistory:m,onOpenRemote:v,onStopCli:b,cliViewMode:p,onSetCliViewMode:g,handleSendChat:y,handleFocusAgent:x,handleModalButton:N,handleRelaunch:j}){const w=c.useRef(null),A=it(e)&&!t,M=A&&p==="terminal",S=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${S} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:u,type:"button","aria-label":"Back",children:s.jsx(Do,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:ft(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(bh,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>h(e),onOpenMachine:()=>f(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[A&&p&&s.jsx(tc,{mode:p,onChange:g,compact:!0}),A&&b&&s.jsx("button",{onClick:()=>{b(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:s.jsx(It,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(e),type:"button",children:s.jsx($o,{size:14})}),!t&&!A&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>v(e),type:"button",children:s.jsx(Bt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(fc,{activeConv:e,clearToken:0,isCliTerminal:M,ideEntry:n,terminalRef:w,handleModalButton:N,handleRelaunch:j,handleSendChat:y,isSendingChat:o,sendFeedbackMessage:l,handleFocusAgent:x,isFocusingAgent:d,actionLogs:a,userName:i})})]})}const ki={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 g0(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function yh(){const[e,t]=c.useState("unix"),[r,n]=c.useState("powershell"),[a,i]=c.useState(!1),o=e==="unix"?"unix":r;c.useEffect(()=>{t(g0())},[]);const l=c.useCallback(()=>{navigator.clipboard.writeText(ki[o].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[o]);return s.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:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.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:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.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:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.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"}),s.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"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:ki[o].prompt}),s.jsx("span",{className:"flex-1 break-all",children:ki[o].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function vh({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Bt},{key:"chats",label:"Chats",icon:cs}];return s.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:s.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 o=e===n;return s.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 ${o?"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:o?{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:()=>t(n),type:"button","aria-pressed":o,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${o?"text-accent-primary":"bg-transparent text-current"}`,style:o?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(i,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function Wn({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function Qs({children:e,className:t=""}){return s.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)] ${t}`,children:e})}function Kr({icon:e,title:t,subtitle:r,children:n}){return s.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:[s.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}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function b0({conversation:e,onCancel:t,onConfirm:r}){const n=ft(e),a=Gs(e);return s.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:[s.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"fade-in relative w-full sm:w-[min(92vw,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] border border-border-subtle bg-bg-primary shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border-subtle bg-[var(--surface-primary)] px-4 py-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base font-extrabold text-text-primary",children:"Hide this chat from the inbox?"}),s.jsx("div",{className:"mt-1 text-[13px] leading-relaxed text-text-muted",children:"This only collapses the chat locally. You can restore it from Hidden tabs."})]}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary text-text-secondary transition-colors hover:bg-surface-primary hover:text-text-primary",onClick:t,"aria-label":"Cancel hide chat",children:s.jsx(It,{size:16})})]}),s.jsx("div",{className:"px-4 py-4",children:s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary/60 px-3.5 py-3",children:[s.jsx("div",{className:"truncate text-sm font-bold text-text-primary",children:n}),s.jsx("div",{className:"mt-1 truncate text-xs text-text-muted",children:a})]})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-border-subtle bg-bg-secondary px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))]",children:[s.jsx("button",{type:"button",className:"btn btn-secondary min-h-[40px] px-4 text-sm",onClick:t,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary min-h-[40px] px-4 text-sm",onClick:r,children:"Hide tab"})]})]})]})}function Un({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onCollectChatDebugBundle:i}){const o=t==="needs_attention"||t==="task_complete",l=t==="working",d=t==="earlier",u=t==="task_complete",{isReconnecting:h,isConnecting:f}=Cr(e.conversation),m=ft(e.conversation),v=Gs(e.conversation),b=Mu(e.conversation,{requiresAction:t==="needs_attention"}),p=o?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":l?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":d?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",g=o?"bg-accent-primary shadow-glow":l?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":d?"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",y=d?"text-text-secondary":"text-text-primary",x=d?"text-text-muted":"text-text-secondary",N=d?"text-text-secondary opacity-80":"text-text-muted",j=d?"text-text-muted opacity-80":"text-text-muted",w=!l&&!u,A="text-[color:var(--status-warning)]",M=S=>{if(!i)return;S.preventDefault(),S.stopPropagation();const k=i==null?void 0:i(e.conversation);Promise.resolve(k).catch(O=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",O)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${p}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[o||l?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${g}`,style:o?{color:"var(--accent-on-primary)"}:void 0,children:r(m)}),a&&s.jsxs("button",{type:"button",className:"mobile-inbox-hide-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-border-subtle bg-bg-primary/70 px-2 text-[10px] font-semibold text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:S=>{S.preventDefault(),S.stopPropagation(),a()},"aria-label":`Hide ${m}`,title:"Hide conversation",children:[s.jsx(Bo,{size:11}),s.jsx("span",{children:"Hide"})]})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:M,type:"button",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${y}`,children:m}),w&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${j}`,children:Zd(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${x}`,children:[s.jsx("span",{className:"truncate",children:v}),s.jsx(br,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),h?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${A} animate-pulse`,children:"Reconnecting…"})]}):f?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):b==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:A,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${N}`,children:e.preview})]}),o&&!u&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),u&&s.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"}),l&&s.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 Ol({size:e=32}){return s.jsx("div",{className:"flex flex-col items-center gap-2.5",children:s.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}})})}function y0({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:o,getAvatarText:l,actionLogs:d,sendDaemonCommand:u,onOpenConversation:h,onShowAllHidden:f,onHideConversation:m,onOpenNewSession:v,onOpenMachine:b,onOpenSettings:p,onSectionChange:g,wsStatus:y="connected",isStandalone:x=!1,onCollectChatDebugBundle:N}){const[j,w]=c.useState(null),A=y==="disconnected"||y==="reconnecting"||y==="offline"||y==="auth_failed",M=o.length>0,S=t.length>0||r.length>0||n.length>0||a.length>0,k=e==="machines"?"Machines":"Chats",O=x?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",P=x?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",I=c.useCallback(async R=>{const T=gr(R);if(!T)return;const C=Array.isArray(R.messages)?R.messages:[],F=xu({activeConv:R,visibleMessages:C,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:C.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),L=await u(T,"get_chat_debug_bundle",{...Ps(R),delivery:"daemon_file",frontendSnapshot:F}),D=ba(L),H=yu(D),Q=await bu(H);Q==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ct.showToast(gu(D,{locatorCopyStatus:Q}),Q==="failed"?"warning":"success")},[d,u]),W=N||I,K=c.useCallback(()=>{j&&(m==null||m(j),w(null))},[j,m]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${O}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:k}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||r.length>0)&&s.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:[s.jsx(Pa,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:p,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:s.jsx(Ra,{size:18})})]})]})}),s.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] ${P}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:A?s.jsx(Kr,{icon:s.jsx(Ol,{}),title:y==="offline"?"Network offline":y==="auth_failed"?"Session expired":"Reconnecting",subtitle:y==="offline"?"Waiting for network…":y==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):o.length===0?s.jsx(Kr,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:x?"Waiting for your daemon":"Connect your machines",subtitle:x?"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:!x&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(yh,{})})}):s.jsx(Qs,{children:o.map((R,T)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${T>0?"border-t border-border-subtle/70":""}`,onClick:()=>b(R.id),type:"button",children:[s.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(R.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:R.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:R.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[R.unread," new"]}):R.total>0?`${R.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:R.subtitle}),R.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[R.total," chat",R.total!==1?"s":"",R.unread>0?` · ${R.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},R.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Wn,{title:"Needs attention",className:"mb-0"}),s.jsx(Qs,{children:t.map((R,T)=>s.jsx("div",{className:T>0?"border-t border-border-subtle/70":"",children:s.jsx(Un,{item:R,type:"needs_attention",getAvatarText:l,onOpenConversation:h,onRequestHideConversation:m?()=>w(R.conversation):void 0,onCollectChatDebugBundle:W})},R.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Wn,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(Qs,{children:r.map((R,T)=>s.jsx("div",{className:T>0?"border-t border-border-subtle/70":"",children:s.jsx(Un,{item:R,type:"task_complete",getAvatarText:l,onOpenConversation:h,onRequestHideConversation:m?()=>w(R.conversation):void 0,onCollectChatDebugBundle:W})},R.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Wn,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(Qs,{children:n.map((R,T)=>s.jsx("div",{className:T>0?"border-t border-border-subtle/70":"",children:s.jsx(Un,{item:R,type:"working",getAvatarText:l,onOpenConversation:h,onRequestHideConversation:m?()=>w(R.conversation):void 0,onCollectChatDebugBundle:W})},R.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(Wn,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(Qs,{children:a.map((R,T)=>s.jsx("div",{className:T>0?"border-t border-border-subtle/70":"",children:s.jsx(Un,{item:R,type:"earlier",getAvatarText:l,onOpenConversation:h,onRequestHideConversation:m?()=>w(R.conversation):void 0,onCollectChatDebugBundle:W})},R.conversation.tabKey))}):S?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):A?s.jsx(Kr,{icon:s.jsx(Ol,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):M?s.jsx(Kr,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(cs,{size:20})}),title:"No conversations yet",subtitle:Pu,children:v&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:v,"aria-label":Qt,title:Qt,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:Qt})]})}):s.jsx(Kr,{icon:s.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&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(Qs,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[i.length," collapsed ",i.length===1?"conversation":"conversations"]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:f,children:"Restore all"})]})})})]}),e==="chats"&&v&&S&&s.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:v,"aria-label":Qt,title:Qt,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),j&&s.jsx(b0,{conversation:j,onCancel:()=>w(null),onConfirm:K}),s.jsx(vh,{section:e,onSectionChange:g})]})}function v0(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 wh(e){const t=[e.workspace||"Workspace unknown"],r=Vs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=v0(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Ha({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:o="Use this folder",onClose:l,onNavigate:d,onConfirm:u}){const[h,f]=c.useState(r);c.useEffect(()=>{f(r)},[r]);const m=Qv(r),v=h.trim();return s.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:s.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:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.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:s.jsx(It,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.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:()=>{!m||a||d(m)},disabled:!m||a,children:[s.jsx(Do,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:h,onChange:b=>f(b.target.value),onKeyDown:b=>{b.key!=="Enter"||!v||a||(b.preventDefault(),d(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"}),s.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||d(v)},disabled:!v||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:n.map(b=>s.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:()=>d(b.path),children:[s.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:s.jsx(zs,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:b.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:b.path})]})]},b.path))})}),s.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:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>u(v||r),disabled:!v&&!r||a,children:o})]})]})})}function mc({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:o="Launch",busyLabel:l="Launching…",busy:d=!1,showArgsInput:u,argsValue:h,onArgsChange:f,showModelInput:m,modelValue:v,onModelChange:b,historyProviderNode:p,onConfirm:g,onCancel:y}){const x=n==null?void 0:n.find(N=>N.key===a);return s.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:s.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:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.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:y,"aria-label":"Close launch confirmation",children:s.jsx(It,{size:16})})]}),s.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&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:N=>i(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:n.map(N=>s.jsx("option",{value:N.key,children:N.label},N.key))}),(x==null?void 0:x.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:x.description})]}),p,r.map(N=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:N.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:N.value})]},`${N.label}:${N.value}`)),m&&b&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:v||"",onChange:N=>b(N.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),u&&f&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:h||"",onChange:N=>f(N.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.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:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:y,disabled:d,children:"Cancel"}),s.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:d,children:[s.jsx(Fo,{size:14}),d?l:o]})]})]})})}function Fl(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Fs(e){const{machine:t,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 d of t.workspaces||[])i.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${Fl(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const o=(r==null?void 0:r.trim())||"",l=o?(t.workspaces||[]).find(d=>d.path===o):null;if(o&&!l&&i.push({key:`custom:${o}`,label:Fl(o),description:o,workspaceId:null,workspacePath:o}),n){const d=`saved:${n}`;if(i.some(u=>u.key===d))return{options:i,selectedKey:d}}return l?{options:i,selectedKey:`saved:${l.id}`}:o?{options:i,selectedKey:`custom:${o}`}:{options:i,selectedKey:"__home__"}}function w0(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function S0(e){return[w0(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function k0(e){return e.lastLaunchedAt?La(e.lastLaunchedAt):""}function Sh(e){return{metaText:S0(e),updatedLabel:k0(e)}}function ji(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function j0({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var at,gt,St,jt;const o=kn(),[l,d]=c.useState(!1),u=(((at=e.detectedIdes)==null?void 0:at.length)||0)>0,h=c.useMemo(()=>(e.workspaces||[]).map(Me=>({id:Me.id,path:Me.path,label:Me.label})),[e]),f=e.defaultWorkspaceId||null,[m,v]=c.useState(f||((gt=h[0])==null?void 0:gt.id)||""),[b,p]=c.useState(""),[g,y]=c.useState(""),[x,N]=c.useState([]),[j,w]=c.useState(!1),[A,M]=c.useState(""),[S,k]=c.useState(!1),[O,P]=c.useState(ji(u,t.length,r.length)),I=c.useRef(null),[W,K]=c.useState(null),R=c.useRef("__home__"),[T,C]=c.useState("__home__"),[F,L]=c.useState(""),[D,H]=c.useState(""),[Q,ge]=c.useState(""),[ue,Z]=c.useState([]),[xe,Se]=c.useState(()=>Mt().textQuery),[be,Y]=c.useState(()=>Mt().workspaceQuery),[he,ye]=c.useState(()=>Mt().modelQuery),[se,de]=c.useState(()=>Mt().resumableOnly),[Ce,pe]=c.useState(()=>Mt().sortMode),[me,oe]=c.useState(!1),[fe,ce]=c.useState(!1),E=c.useRef(null),z=c.useRef(null);c.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&o(e.id,{minFreshMs:3e4}).catch(()=>{})},[o,e]);const le=m==="__custom__"?b.trim():((St=h.find(Me=>Me.id===m))==null?void 0:St.path)||"",re=m==="__custom__"&&!!le&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),q=m!=="__custom__"&&((jt=h.find(Me=>Me.id===m))==null?void 0:jt.path)||"",je=c.useMemo(()=>(e.recentLaunches||[]).map(Me=>Me.workspace),[e]),we=c.useCallback(async Me=>{w(!0),M("");try{const qe=await a(Me);y(qe.path),p(qe.path),N(qe.directories)}catch(qe){M(qe instanceof Error?qe.message:"Could not load folder")}finally{w(!1)}},[a]),Pe=c.useCallback(()=>{var qe;v("__custom__"),k(!0);const Me=Ua(e.platform,Wa(b.trim(),q,je,e.defaultWorkspacePath,(qe=h.find(st=>st.id===f))==null?void 0:qe.path,h.map(st=>st.path)));we(Me)},[b,f,we,je,q,e.platform,h]),Re=c.useCallback(Me=>{if(Me!=null&&Me.workspaceId){v(Me.workspaceId),p("");return}if(Me!=null&&Me.workspacePath){v("__custom__"),p(Me.workspacePath);return}v(""),p("")},[]),B=c.useCallback(Me=>{if(v(Me),Me==="__custom__"){Pe();return}p("")},[Pe]),Ae=c.useCallback(Me=>{v("__custom__"),p(Me)},[]),Ee=c.useCallback((Me,qe)=>{I.current=qe,R.current=Me.selectedWorkspaceKey||"__home__",C(Me.selectedWorkspaceKey||"__home__"),L(Me.initialArgs||""),H(Me.initialModel||""),ge(""),Z([]);const st=Me.providerType?`${e.id}:${Me.providerType}`:null;if(Gb(z.current,st)){const Xe=Mt();Se(Xe.textQuery),Y(Xe.workspaceQuery),ye(Xe.modelQuery),de(Xe.resumableOnly),pe(Xe.sortMode)}z.current=st,K(Me),Me.providerType&&i&&(oe(!0),i(Me.providerType).then(Xe=>Z(Xe||[])).catch(Xe=>console.warn("Failed to load saved sessions",Xe)).finally(()=>oe(!1)))},[i,e.id]),Ve=c.useMemo(()=>Lu(ue,{textQuery:xe,workspaceQuery:be,modelQuery:he,resumableOnly:se,sortMode:Ce}),[he,se,ue,Ce,xe,be]);c.useEffect(()=>{Q&&(Ve.some(Me=>Me.providerSessionId===Q)||ge(""))},[Ve,Q]);const Ge=c.useCallback(()=>{I.current&&(ce(!0),I.current().finally(()=>{I.current=null,ce(!1),K(null)}))},[]),Ze=c.useCallback(()=>{I.current=null,K(null)},[]),et=c.useCallback(Me=>{R.current=Me,C(Me)},[]);return c.useEffect(()=>{var Me;E.current!==e.id&&(E.current=e.id,v(f||((Me=h[0])==null?void 0:Me.id)||"__custom__"),p(""),y(""),N([]),M(""),k(!1),Se(Mt().textQuery),Y(Mt().workspaceQuery),ye(Mt().modelQuery),de(Mt().resumableOnly),pe(Mt().sortMode),z.current=null,P(ji(u,t.length,r.length)))},[r.length,t.length,f,u,e.id,h]),c.useEffect(()=>{var Me;m!=="__custom__"&&(m&&h.some(qe=>qe.id===m)||v(f||((Me=h[0])==null?void 0:Me.id)||"__custom__"))},[f,m,h]),c.useEffect(()=>{O==="ide"&&u||O==="cli"&&t.length>0||O==="acp"&&r.length>0||P(ji(u,t.length,r.length))},[O,r.length,t.length,u]),{showAllRecent:l,setShowAllRecent:d,hasIdeOptions:u,workspaceRows:h,defaultWorkspaceId:f,workspaceChoice:m,customWorkspacePath:b,browseCurrentPath:g,browseDirectories:x,browseBusy:j,browseError:A,browseDialogOpen:S,activeLauncherKind:O,launchConfirm:W,launchConfirmWorkspaceKeyRef:R,launchConfirmWorkspaceKey:T,launchConfirmArgs:F,launchConfirmModel:D,launchConfirmResumeId:Q,launchConfirmSavedSessions:ue,launchConfirmTextFilter:xe,launchConfirmWorkspaceFilter:be,launchConfirmModelFilter:he,launchConfirmResumableOnly:se,launchConfirmSortMode:Ce,filteredLaunchConfirmSavedSessions:Ve,launchConfirmSessionsLoading:me,launchConfirmBusy:fe,resolvedWorkspacePath:le,canCreateMissingWorkspace:re,openBrowseDialog:Pe,loadBrowsePath:we,handleWorkspaceChoiceChange:B,chooseCustomWorkspacePath:Ae,setCustomWorkspacePath:p,setBrowseDialogOpen:k,setActiveLauncherKind:P,openLaunchConfirm:Ee,handleConfirmLaunch:Ge,closeLaunchConfirm:Ze,setWorkspaceSelectionFromOption:Re,setLaunchConfirmWorkspaceKeyAndSync:et,setLaunchConfirmArgs:L,setLaunchConfirmModel:H,setLaunchConfirmResumeId:ge,setLaunchConfirmTextFilter:Se,setLaunchConfirmWorkspaceFilter:Y,setLaunchConfirmModelFilter:ye,setLaunchConfirmResumableOnly:de,setLaunchConfirmSortMode:pe}}function N0({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:o,machineAction:l,isStandalone:d,section:u,showBottomNav:h,onBack:f,onSectionChange:m,onOpenConversation:v,onOpenRecent:b,onOpenMachineDetails:p,onMachineUpgrade:g,onLaunchDetectedIde:y,onAddWorkspace:x,onBrowseDirectory:N,onLaunchWorkspaceProvider:j,onListSavedSessions:w}){const A=T=>T==="ide"?"IDE":T==="cli"?"CLI":"ACP",M=r.slice(0,4),S=t.slice(0,3),k=j0({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:N,onListSavedSessions:w}),O=c.useMemo(()=>M.map(T=>{const{metaText:C,updatedLabel:F}=Sh(T);return{key:`recent-launch:${T.id}`,primary:T.label,secondary:C,updatedLabel:F,onClick:()=>{const{options:L,selectedKey:D}=Fs({machine:{workspaces:k.workspaceRows,defaultWorkspaceId:k.defaultWorkspaceId},currentWorkspacePath:T.workspace});k.openLaunchConfirm({title:T.kind==="ide"?Es("restart-ide",T.label):T.providerSessionId?nc(T.label):Es("start-fresh",T.label),description:T.kind==="ide"?Ds("restart-ide"):T.providerSessionId?ac():Ds("start-fresh"),confirmLabel:T.kind==="ide"?yr("restart-ide"):T.providerSessionId?va(!0):yr("start-fresh"),busyLabel:T.kind==="ide"?vr("restart-ide"):T.providerSessionId?sc(!0):vr("start-fresh"),workspaceOptions:L,selectedWorkspaceKey:D,details:[{label:"Mode",value:A(T.kind)},...T.providerType?[{label:"Provider",value:T.providerType}]:[]]},async()=>{const H=L.find(Q=>Q.key===k.launchConfirmWorkspaceKeyRef.current);k.setWorkspaceSelectionFromOption(H),await b({...T,workspace:(H==null?void 0:H.workspacePath)??null})})}}}),[k,b,M]),P=c.useMemo(()=>S.map(T=>({key:`recent-chat:${T.conversation.tabKey}`,primary:ft(T.conversation),secondary:Rb(T.conversation,{timestampLabel:T.timestamp?Zd(T.timestamp):null}),unread:T.unread,onClick:()=>v(T.conversation)})),[v,S]),I=k.showAllRecent?O:O.slice(0,4),W=O.length>0,K=P.length>0,R=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${R} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:f,type:"button","aria-label":"Back",children:s.jsx(Do,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:$t(e,{fallbackId:e.id})}),s.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}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[K&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:P.map(T=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${T.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:T.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:T.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:T.secondary})]},T.key))})]}),W&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:I.map(T=>s.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:T.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:T.primary}),T.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:T.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:T.secondary})]},T.key))}),O.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.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:()=>k.setShowAllRecent(T=>!T),children:k.showAllRecent?"Show fewer":`Show ${O.length-4} more`})})]}),(k.hasIdeOptions||n.length>0||a.length>0)&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:s.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:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),s.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),s.jsx("select",{value:k.workspaceChoice,onChange:T=>k.handleWorkspaceChoiceChange(T.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:k.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[k.workspaceRows.map(T=>s.jsxs("option",{value:T.id,children:[T.id===k.defaultWorkspaceId?"⭐ ":"",Da(T.path,T.label)||T.path]},T.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),k.workspaceChoice==="__custom__"&&s.jsxs("div",{className:"flex flex-col gap-2.5",children:[s.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.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:s.jsx(zs,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),s.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:k.resolvedWorkspacePath||k.browseCurrentPath||"No folder selected yet."})]})]})}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.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:k.openBrowseDialog,children:"Select workspace…"}),s.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:()=>{k.resolvedWorkspacePath&&x(k.resolvedWorkspacePath)},disabled:!k.resolvedWorkspacePath||k.browseBusy,children:"Save as workspace"})]})]}),k.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:k.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[k.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${k.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:()=>k.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${k.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:()=>k.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${k.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:()=>k.setActiveLauncherKind("acp"),children:"ACP"})]}),k.activeLauncherKind&&s.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[s.jsx("div",{className:"text-xs font-bold text-text-secondary",children:k.activeLauncherKind==="ide"?"Choose an IDE":k.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:k.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(T=>s.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:C,selectedKey:F}=Fs({machine:{workspaces:k.workspaceRows,defaultWorkspaceId:k.defaultWorkspaceId},currentWorkspaceId:k.workspaceChoice!=="__custom__"?k.workspaceChoice:null,currentWorkspacePath:k.resolvedWorkspacePath});k.openLaunchConfirm({title:`Launch ${T.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:C,selectedWorkspaceKey:F,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:T.name}]},async()=>{const L=C.find(D=>D.key===k.launchConfirmWorkspaceKeyRef.current);k.setWorkspaceSelectionFromOption(L),y(T.type,{workspacePath:(L==null?void 0:L.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:T.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:k.resolvedWorkspacePath||"Use selected workspace"})]},T.type)):(k.activeLauncherKind==="cli"?n:a).map(T=>s.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 C=k.activeLauncherKind==="cli"?"cli":"acp",{options:F,selectedKey:L}=Fs({machine:{workspaces:k.workspaceRows,defaultWorkspaceId:k.defaultWorkspaceId},currentWorkspaceId:k.workspaceChoice!=="__custom__"?k.workspaceChoice:null,currentWorkspacePath:k.resolvedWorkspacePath});k.openLaunchConfirm({title:`Launch ${T.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${C.toUpperCase()}`,workspaceOptions:F,selectedWorkspaceKey:L,details:[{label:"Mode",value:C.toUpperCase()},{label:"Provider",value:T.displayName}],showArgsInput:!0,showModelInput:C==="acp",initialArgs:"",initialModel:"",providerType:T.type},async()=>{const D=F.find(H=>H.key===k.launchConfirmWorkspaceKeyRef.current);k.setWorkspaceSelectionFromOption(D),j(C,T.type,{workspaceId:(D==null?void 0:D.workspaceId)??null,workspacePath:(D==null?void 0:D.workspacePath)??null,args:k.launchConfirmArgs,model:k.launchConfirmModel,resumeSessionId:k.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[T.icon?`${T.icon} `:"",T.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:k.resolvedWorkspacePath||"Use selected workspace"})]},T.type))})]}),l.message&&s.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,k.canCreateMissingWorkspace&&s.jsx("div",{className:"mt-2",children:s.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:()=>x(k.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&s.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:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",o]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.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:p,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),k.browseDialogOpen&&s.jsx(Ha,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:k.browseCurrentPath,directories:k.browseDirectories,busy:k.browseBusy,error:k.browseError,confirmLabel:"Use this folder",onClose:()=>k.setBrowseDialogOpen(!1),onNavigate:T=>{k.loadBrowsePath(T)},onConfirm:T=>{k.chooseCustomWorkspacePath(T),k.setBrowseDialogOpen(!1)}}),k.launchConfirm&&s.jsx(mc,{title:k.launchConfirm.title,description:k.launchConfirm.description,details:k.launchConfirm.details,workspaceOptions:k.launchConfirm.workspaceOptions,selectedWorkspaceKey:k.launchConfirmWorkspaceKey,onWorkspaceChange:k.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:k.launchConfirm.providerType?va(!!k.launchConfirmResumeId):k.launchConfirm.confirmLabel,busyLabel:k.launchConfirm.providerType?void 0:k.launchConfirm.busyLabel,busy:k.launchConfirmBusy,showArgsInput:k.launchConfirm.showArgsInput,argsValue:k.launchConfirmArgs,onArgsChange:k.setLaunchConfirmArgs,showModelInput:k.launchConfirm.showModelInput,modelValue:k.launchConfirmModel,onModelChange:k.setLaunchConfirmModel,historyProviderNode:k.launchConfirm.providerType&&(k.launchConfirmSessionsLoading||k.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),k.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:rc()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:k.launchConfirmTextFilter,onChange:T=>k.setLaunchConfirmTextFilter(T.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:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:k.launchConfirmWorkspaceFilter,onChange:T=>k.setLaunchConfirmWorkspaceFilter(T.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:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:k.launchConfirmModelFilter,onChange:T=>k.setLaunchConfirmModelFilter(T.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:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),s.jsxs("select",{value:k.launchConfirmSortMode,onChange:T=>k.setLaunchConfirmSortMode(T.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:k.launchConfirmBusy||k.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:k.launchConfirmResumableOnly,onChange:T=>k.setLaunchConfirmResumableOnly(T.target.checked),disabled:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:k.launchConfirmResumeId,onChange:T=>k.setLaunchConfirmResumeId(T.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:k.launchConfirmBusy||k.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Yb()}),k.filteredLaunchConfirmSavedSessions.map(T=>s.jsxs("option",{value:T.providerSessionId,disabled:!T.canResume,children:[T.title||T.providerSessionId," ",T.canResume?"":"(workspace missing)"]},T.providerSessionId))]}),!k.launchConfirmSessionsLoading&&k.launchConfirmSavedSessions.length>0&&k.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),k.launchConfirmResumeId&&(()=>{const T=k.filteredLaunchConfirmSavedSessions.find(F=>F.providerSessionId===k.launchConfirmResumeId);if(!T)return null;const C=wh(T);return s.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:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:C.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:C.providerSessionId}),s.jsx("div",{className:"mt-1",children:C.metaLine}),C.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:C.updatedLabel}),C.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:C.preview})]})})()]}),onConfirm:k.handleConfirmLaunch,onCancel:k.closeLaunchConfirm}),h&&s.jsx(vh,{section:u,onSectionChange:m})]})}function sa(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function C0(e,t=[]){const r=new Map(e.map(a=>[a.conversation.tabKey,a])),n=t.map(a=>r.get(a)).filter(a=>!!a);return n.length===e.length?n:sa(e)}function T0(e){var r;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":"Offline"}function I0(e,t){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:Vs(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var o;const a=mn(n)?"cli":or(n)?"acp":"ide",i=Vs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((o=n.activeChat)==null?void 0:o.title)||(mn(n)?n.cliName||n.type:or(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:or(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:n.lastMessageAt||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function A0(e,t){const r=new Map;for(const n of t){const a=Ys(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((f,m)=>m.timestamp-f.timestamp)[0]||null,o=(i==null?void 0:i.conversation)||null,l=ro(n),d=a.filter(f=>f.unread||f.requiresAction).length,u=T0(n),h=[n.platform||"machine",u].filter(Boolean);return{id:n.id,label:$t(n,{fallbackId:n.id}),subtitle:h.join(" · "),unread:d,total:a.length,latestConversation:o,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:o?Pb(o):"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,o=a.latestTimestamp||a.fallbackActivityAt||0;return o!==i?o-i:n.label.localeCompare(a.label)})}function M0(e){return e==="chat"}function Kn(e,t){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}`,t)}catch{}}function _0({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:o,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:u,requestedMachineId:h,onRequestedMachineConsumed:f,requestedMobileSection:m,onRequestedMobileSectionConsumed:v,setSelectedTabKey:b,setScreen:p,setSelectedMachineId:g,setSection:y,setMachineBackTarget:x,resetMachineAction:N}){const j=c.useRef(null),w=c.useCallback(A=>{if(!(A!=null&&A.sessionId))return;const M=fa(A,o),S=Math.max(Date.now(),Os(A),M.lastUpdated||0);Kn("mark_read:start",{tabKey:A.tabKey,sessionId:A.sessionId,displayPrimary:ft(A),inboxBucket:M.inboxBucket,unread:M.unread,lastSeenAt:M.lastSeenAt,lastUpdated:M.lastUpdated,activityAt:Os(A),readAt:S}),l(Ys(A)||A.routeId,"mark_session_seen",{sessionId:A.sessionId,providerSessionId:A.providerSessionId,seenAt:S,completionMarker:M.completionMarker}).then(k=>{Kn("mark_read:result",{tabKey:A.tabKey,sessionId:A.sessionId,result:k})}).catch(k=>{Kn("mark_read:error",{tabKey:A.tabKey,sessionId:A.sessionId,error:k instanceof Error?k.message:String(k)})})},[o,l]);return c.useEffect(()=>{var M;if(!n){M0(i)&&p("inbox"),b(((M=e[0])==null?void 0:M.tabKey)||null),j.current=null;return}if(i!=="chat"){j.current=null;return}const A=`${n.tabKey}:${n.sessionId||""}`;j.current!==A&&(j.current=A,w(n))},[e,w,i,n,p,b]),c.useEffect(()=>{if(!d)return;const A=e.find(M=>M.tabKey===d);A&&(b(A.tabKey),p("chat"),u==null||u())},[e,u,d,p,b]),c.useEffect(()=>{if(!h)return;const A=t.find(M=>M.id===h);A&&(g(A.id),N(),y("machines"),x("inbox"),p("machine"),f==null||f())},[t,f,h,N,x,p,y,g]),c.useEffect(()=>{m&&(y(m),p("inbox"),v==null||v())},[v,m,p,y]),c.useEffect(()=>{const A=r.filter(M=>M.inboxBucket==="task_complete"||M.unread);A.length!==0&&Kn("inbox_state",{screen:i,selectedTabKey:a,items:A.map(M=>{const S=fa(M.conversation,o);return{liveState:S,tabKey:M.conversation.tabKey,sessionId:M.conversation.sessionId,displayPrimary:ft(M.conversation),serverBucket:S.inboxBucket,computedBucket:M.inboxBucket,serverUnread:S.unread,computedUnread:M.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:Os(M.conversation)}})})},[r,o,i,a]),{markConversationRead:w}}function R0(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Wl(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function P0(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function L0({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,i]=c.useState("idle"),[o,l]=c.useState(""),[d,u]=c.useState(null),h=c.useCallback(()=>{i("idle"),l(""),u(null)},[]),f=c.useCallback(async(x,N,j)=>{var w;try{i("loading"),l(`Launching ${N}…`);const A={ideType:N,enableCdp:!0};(w=j==null?void 0:j.workspacePath)!=null&&w.trim()&&(A.workspace=j.workspacePath.trim()),await e(x,"launch_ide",A),i("done"),l(`${N} launch requested`)}catch(A){i("error"),l(A instanceof Error?A.message:"Launch IDE failed"),console.error("Launch IDE failed",A)}},[e]),m=c.useCallback(async(x,N,j)=>{if(N.trim())try{i("loading"),l(j!=null&&j.createIfMissing?"Creating folder…":"Saving workspace…");const w=await e(x,"workspace_add",{path:N.trim(),createIfMissing:(j==null?void 0:j.createIfMissing)===!0});if(w!=null&&w.success){i("done"),l(j!=null&&j.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=c.useCallback(async x=>{var N,j,w,A,M,S;try{i("loading"),l("Starting daemon upgrade…");const k=await e(x,"daemon_upgrade",{});if((N=k==null?void 0:k.result)!=null&&N.alreadyLatest){i("done"),l(`Already on v${((j=k==null?void 0:k.result)==null?void 0:j.version)||"latest"}.`);return}if((w=k==null?void 0:k.result)!=null&&w.upgraded||(A=k==null?void 0:k.result)!=null&&A.success){i("done"),l(`Upgrade to v${((M=k==null?void 0:k.result)==null?void 0:M.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((S=k==null?void 0:k.result)==null?void 0:S.error)||"Upgrade failed")}catch(k){i("error"),l(k instanceof Error?k.message:"Upgrade failed")}},[e]),b=c.useCallback(async(x,N,j,w)=>{var S,k,O;const A=Date.now(),M={machineId:x,kind:N,providerType:j,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:A};try{i("loading"),l(`Launching ${j}…`),u(M);const P={cliType:j};(S=w==null?void 0:w.workspacePath)!=null&&S.trim()?P.dir=w.workspacePath.trim():w!=null&&w.workspaceId&&(P.workspaceId=w.workspaceId),w!=null&&w.resumeSessionId&&(P.resumeSessionId=w.resumeSessionId),(k=w==null?void 0:w.args)!=null&&k.trim()&&(P.cliArgs=w.args.trim().split(/\s+/).filter(Boolean)),(O=w==null?void 0:w.model)!=null&&O.trim()&&(P.initialModel=w.model.trim());const I=await e(x,"launch_cli",P),W=(I==null?void 0:I.result)||I,K=(W==null?void 0:W.sessionId)||(W==null?void 0:W.id);if(I!=null&&I.success&&K){u(null),i("done"),l(`${j} launched`),t(ws(K));return}if(I!=null&&I.success){i("loading"),l(`${j} launch requested — waiting for session…`);return}u(null),i("error"),l((I==null?void 0:I.error)||(W==null?void 0:W.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(P){if(P0(P)){i("loading"),l(`${j} launch requested — waiting for session…`);return}u(null),i("error"),l(P instanceof Error?P.message:`Could not launch ${N.toUpperCase()} workspace`)}},[t,e]),p=c.useCallback(async(x,N)=>{try{const j=await e(x,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),w=(j==null?void 0:j.result)??j;return Array.isArray(w==null?void 0:w.sessions)?w.sessions:[]}catch(j){return console.error("Failed to list saved sessions on mobile:",j),[]}},[e]),g=c.useCallback(async(x,N)=>Ka(e,x,N),[e]);c.useEffect(()=>{if(!d)return;const x=Wl(d.workspacePath),N=r.find(w=>{var P,I,W,K;if(!w||w.type==="adhdev-daemon"||R0(w.daemonId||w.id)!==d.machineId||(w.transport==="acp"?"acp":w.transport==="pty"?"cli":null)!==d.kind||String(w.agentType||w.type||"")!==d.providerType)return!1;const k=String(w.providerSessionId||"");if(d.resumeSessionId&&k)return k===d.resumeSessionId;if(x){const R=Wl(w.workspace||w.runtimeWorkspaceLabel);return R?R===x:!1}return Number(w.lastUpdated||w._lastUpdate||w.timestamp||((K=(W=(I=(P=w.activeChat)==null?void 0:P.messages)==null?void 0:I.at)==null?void 0:W.call(I,-1))==null?void 0:K.timestamp)||0)>=d.startedAt-5e3});if(!N)return;const j=xh({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});j&&(u(null),i("done"),l(`${d.providerType} launched`),t(ws(j)))},[n,r,t,d]),c.useEffect(()=>{if(!d)return;const x=window.setTimeout(()=>{u(N=>!N||N.startedAt!==d.startedAt?N:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(x)},[d]);const y=c.useCallback(async(x,N)=>{if(N.kind==="ide"&&N.providerType){await f(x,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await b(x,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[f,b]);return{machineAction:{state:a,message:o},resetMachineAction:h,handleLaunchDetectedIde:f,handleAddWorkspace:m,handleMachineUpgrade:v,handleLaunchWorkspaceProvider:b,handleListSavedSessions:p,handleBrowseDirectory:g,handleOpenRecent:y}}function E0({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:o,setSelectedMachineId:l,setSection:d,setMachineBackTarget:u}){const h=c.useCallback(y=>{i(y.tabKey),o("chat"),n(y)},[n,o,i]),f=c.useCallback(y=>{const x=e.find(N=>N.routeId===y.routeId&&N.streamSource==="native");x&&(i(x.tabKey),o("chat"),n(x))},[e,n,o,i]),m=c.useCallback(()=>{n(t),o("inbox")},[n,t,o]),v=c.useCallback((y,x="inbox")=>{l(y),a(),d("machines"),u(x),o("machine")},[a,u,o,d,l]),b=c.useCallback(y=>{const x=Ys(y);x&&v(x,"chat")},[v]),p=c.useCallback(()=>{a(),o(r)},[r,a,o]),g=c.useCallback(y=>{d(y),o("inbox")},[o,d]);return{openConversation:h,openNativeConversation:f,backFromConversation:m,openMachine:v,openConversationMachine:b,backFromMachine:p,changeMachineSection:g}}function qs(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function D0(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function $0({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:o,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:u,requestedMachineId:h,onRequestedMachineConsumed:f,requestedMobileSection:m,onRequestedMobileSectionConsumed:v,onOpenHistory:b,onOpenRemote:p,onStopCli:g,wsStatus:y,isConnected:x,onShowAllHiddenConversations:N,onHideConversation:j,onOpenNewSession:w,liveSessionInboxState:A,setCliViewModeOverrides:M}){const[S,k]=c.useState(()=>{var q;return((q=e[0])==null?void 0:q.tabKey)||null}),[O,P]=c.useState(()=>e[0]?"chat":"inbox"),[I,W]=c.useState("chats"),[K,R]=c.useState(null),[T,C]=c.useState("inbox"),F=c.useRef([]),L=Nr(),D="0.9.76",H=c.useMemo(()=>e.find(q=>q.tabKey===S)||e[0]||null,[e,S]),Q=c.useMemo(()=>H?r.find(q=>q.id===H.routeId):void 0,[r,H]),ge=c.useMemo(()=>!H||nt(H)||!it(H)?null:Tr(H),[H]),ue=c.useMemo(()=>r.filter(q=>q.type==="adhdev-daemon").sort(Vo),[r]),Z=c.useMemo(()=>ue.find(q=>q.id===K)||null,[ue,K]),xe=Ba({sendDaemonCommand:a,activeConv:H||void 0,setActionLogs:i,isStandalone:o}),Se=L0({sendDaemonCommand:a,navigate:L,ides:r,conversations:e}),be=c.useMemo(()=>e.map(q=>{const je=O==="chat"&&(H==null?void 0:H.tabKey)===q.tabKey,we=Ea(q,A,{hideOpenTaskCompleteUnread:!0,isOpenConversation:je}),Pe=Os(q),Re=Au(q);return{conversation:q,timestamp:Pe,preview:Re,unread:we.unread,requiresAction:we.requiresAction,isWorking:we.isWorking,inboxBucket:we.inboxBucket}}),[e,A,O,H]),{markConversationRead:Y}=_0({conversations:e,machineEntries:ue,items:be,selectedConversation:H,selectedTabKey:S,screen:O,liveSessionInboxState:A,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:u,requestedMachineId:h,onRequestedMachineConsumed:f,requestedMobileSection:m,onRequestedMobileSectionConsumed:v,setSelectedTabKey:k,setScreen:P,setSelectedMachineId:R,setSection:W,setMachineBackTarget:C,resetMachineAction:Se.resetMachineAction}),he=E0({conversations:e,selectedConversation:H,machineBackTarget:T,markConversationRead:Y,resetMachineAction:Se.resetMachineAction,setSelectedTabKey:k,setScreen:P,setSelectedMachineId:R,setSection:W,setMachineBackTarget:C}),ye=c.useMemo(()=>sa(be.filter(q=>q.requiresAction)),[be]),se=c.useMemo(()=>sa(be.filter(q=>q.unread&&!q.requiresAction)),[be]),de=c.useMemo(()=>C0(be.filter(q=>!q.unread&&!q.requiresAction&&q.isWorking),F.current),[be]);c.useEffect(()=>{F.current=de.map(q=>q.conversation.tabKey)},[de]);const Ce=c.useMemo(()=>sa(be.filter(q=>!q.unread&&!q.requiresAction&&!q.isWorking)),[be]),pe=c.useMemo(()=>Z?be.filter(q=>Ys(q.conversation)===Z.id):[],[be,Z]),me=c.useMemo(()=>I0(Z,r),[r,Z]),oe=(Z==null?void 0:Z.version)||null,fe=!!Z&&!!oe&&!0&&oe!==D,ce=c.useMemo(()=>(Z==null?void 0:Z.availableProviders)||[],[Z]),E=c.useMemo(()=>ce.filter(q=>qs(q,"cli")).map(q=>({type:q.type,displayName:q.displayName||q.type,icon:q.icon})),[ce]),z=c.useMemo(()=>ce.filter(q=>qs(q,"acp")).map(q=>({type:q.type,displayName:q.displayName||q.type,icon:q.icon})),[ce]),le=c.useMemo(()=>A0(ue,be),[be,ue]),re=c.useCallback(async q=>{Z&&await Se.handleOpenRecent(Z.id,q)},[Se,Z]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:O==="chat"&&H?s.jsx(x0,{selectedConversation:H,isAcp:nt(H),isStandalone:o,selectedIdeEntry:Q,actionLogs:n,userName:l,isSendingChat:xe.isSendingChat,sendFeedbackMessage:xe.sendFeedbackMessage,isFocusingAgent:xe.isFocusingAgent,handleModalButton:xe.handleModalButton,handleRelaunch:xe.handleRelaunch,onBack:he.backFromConversation,onOpenNativeConversation:he.openNativeConversation,onOpenMachine:he.openConversationMachine,onOpenHistory:b,onOpenRemote:p,onStopCli:g,cliViewMode:ge,onSetCliViewMode:async q=>{await rh({conversation:H,mode:q,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:M})},handleSendChat:xe.handleSendChat,handleFocusAgent:xe.handleFocusAgent}):O==="machine"&&Z?s.jsx(N0,{selectedMachineEntry:Z,selectedMachineConversations:pe,selectedMachineRecentLaunches:me,cliProviders:E,acpProviders:z,selectedMachineNeedsUpgrade:fe,appVersion:D,machineAction:Se.machineAction,isStandalone:o,section:I,showBottomNav:T==="inbox",onBack:he.backFromMachine,onSectionChange:he.changeMachineSection,onOpenConversation:he.openConversation,onOpenRecent:re,onOpenMachineDetails:()=>L(`/machines/${Z.id}`),onMachineUpgrade:()=>Se.handleMachineUpgrade(Z.id),onLaunchDetectedIde:(q,je)=>Se.handleLaunchDetectedIde(Z.id,q,je),onAddWorkspace:(q,je)=>Se.handleAddWorkspace(Z.id,q,je),onBrowseDirectory:q=>Se.handleBrowseDirectory(Z.id,q),onLaunchWorkspaceProvider:(q,je,we)=>Se.handleLaunchWorkspaceProvider(Z.id,q,je,we),onListSavedSessions:q=>Se.handleListSavedSessions(Z.id,q)}):s.jsx(y0,{section:I,attentionItems:ye,unreadItems:se,workingItems:de,completedItems:Ce,hiddenConversations:t,machineCards:le,getAvatarText:D0,actionLogs:n,sendDaemonCommand:a,onOpenConversation:he.openConversation,onShowAllHidden:N,onHideConversation:j,onOpenNewSession:w,onOpenMachine:he.openMachine,onOpenSettings:()=>L("/settings"),onSectionChange:W,wsStatus:y,isConnected:x,isStandalone:o})})}function Ni(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function B0({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const o=c.useRef(0),[l,d]=c.useState(!1),[u,h]=c.useState(null),f=c.useCallback(()=>{o.current=0,d(!1),h(null)},[]);c.useEffect(()=>(window.addEventListener("dragend",f),window.addEventListener("drop",f),()=>{window.removeEventListener("dragend",f),window.removeEventListener("drop",f)}),[f]);const m=c.useCallback(g=>{g.dataTransfer.types.includes("text/tab-key")&&(o.current+=1,d(!0))},[]),v=c.useCallback(g=>{if(!g.dataTransfer.types.includes("text/tab-key"))return;if(g.preventDefault(),!Ni(t,r)){h("merge");return}const y=g.currentTarget.getBoundingClientRect(),x=g.clientX-y.left,N=y.width/3;x<N?h("split-left"):x>N*2?h("split-right"):h("merge")},[t,r]),b=c.useCallback(()=>{o.current-=1,!(o.current>0)&&(o.current=0,d(!1),h(null))},[]),p=c.useCallback(g=>{o.current=0,d(!1);const y=g.dataTransfer.getData("text/tab-key"),x=y?e.some(j=>j.tabKey===y):!1,N=u;if(h(null),i(),!!y){if(g.preventDefault(),N==="split-left"&&Ni(t,r)){r==null||r(y,"split-left");return}if(N==="split-right"&&Ni(t,r)){r==null||r(y,"split-right");return}if(x){a(y);return}n==null||n(y)}},[e,u,t,r,n,a,i]);return{dragOver:l,dropAction:u,resetDragState:f,handleDragEnter:m,handleDragOver:v,handleDragLeave:b,handleDrop:p}}function O0(e,t){const r=new Set(t.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),a=t.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...a]}function F0({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,o]=c.useState(t??null),[l,d]=c.useState(r??[]),[u,h]=c.useState(null),f=c.useRef(null),m=c.useRef(null),v=c.useRef(n),b=c.useRef(a);c.useEffect(()=>{v.current=n},[n]),c.useEffect(()=>{b.current=a},[a]),c.useEffect(()=>{t&&t!==i&&o(t)},[t,i]),c.useEffect(()=>{d(M=>{const S=O0(M,e);return S.length===M.length&&S.every((k,O)=>k===M[O])?M:S})},[e]);const p=c.useMemo(()=>{const M=u??l;if(M.length===0)return e;const S=new Map(M.map((k,O)=>[k,O]));return[...e].sort((k,O)=>{const P=S.get(k.tabKey)??999,I=S.get(O.tabKey)??999;return P-I})},[e,u,l]);c.useEffect(()=>{var S,k;if(p.length===0){i!==null&&(o(null),(S=v.current)==null||S.call(v,null));return}if(i&&p.some(O=>O.tabKey===i))return;const M=p[0].tabKey;M!==i&&(o(M),(k=v.current)==null||k.call(v,M))},[p,i]);const g=c.useMemo(()=>p.find(M=>M.tabKey===i),[p,i]),y=c.useCallback(M=>{var S;o(M),(S=v.current)==null||S.call(v,M)},[]),x=c.useCallback((M,S,k)=>{d(O=>{var K;const P=O.filter(R=>R!==M),I=P.indexOf(S);if(I<0)return O;const W=k==="left"?I:I+1;return P.splice(W,0,M),(K=b.current)==null||K.call(b,P),P}),h(null)},[]),N=c.useCallback((M,S,k)=>{const P=(l.length>0?l:e.map(K=>K.tabKey)).filter(K=>K!==M),I=P.indexOf(S);if(I<0)return;const W=k==="left"?I:I+1;P.splice(W,0,M),f.current=P,h(P)},[l,e]),j=c.useCallback(()=>{var S;const M=f.current;M&&(d(M),(S=b.current)==null||S.call(b,M))},[]),w=c.useCallback(()=>{f.current=null,h(null)},[]),A=c.useCallback(M=>{d(S=>{var O;const k=S.filter(P=>P!==M);return k.push(M),(O=b.current)==null||O.call(b,k),k})},[]);return{activeTabId:i,activeConv:g,sortedConversations:p,previewOrderRef:f,draggingTabRef:m,selectTab:y,handleTabReorder:x,updatePreviewOrder:N,commitPreviewOrder:j,clearPreviewOrder:w,moveTabToEnd:A,setDraggingTabKey:M=>{m.current=M}}}function W0({dropAction:e,canSplit:t}){return s.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[s.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:t?1:.45},children:s.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"})}),s.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:s.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"})}),s.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:t?1:.45},children:s.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 xc({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:i}){if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const o=!r&&!n,l=n&&!!i,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",u=n?Pu: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&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:u}),l&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:i,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Qt,"aria-label":Qt,children:[s.jsx(Hd,{size:14}),s.jsx("span",{children:Qt})]})}),o&&s.jsx(yh,{}),o&&s.jsx("div",{className:"mt-8",children:s.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 →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const kh="adhdev-tab-shortcuts";function jh(){try{return JSON.parse(localStorage.getItem(kh)||"{}")}catch{return{}}}function Nh({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,o]=c.useState(()=>jh()),[l,d]=c.useState(null),u=c.useCallback(f=>{const m=[];return f.metaKey&&m.push(a?"⌘":"Meta"),f.ctrlKey&&m.push("Ctrl"),f.altKey&&m.push(a?"⌥":"Alt"),f.shiftKey&&m.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(m.push(f.key.length===1?f.key.toUpperCase():f.key),m.join("+"))},[a]),h=c.useCallback(f=>{o(f);try{localStorage.setItem(kh,JSON.stringify(f))}catch{}},[]);return c.useEffect(()=>{if(!e||!l)return;const f=m=>{if(m.preventDefault(),m.stopPropagation(),m.key==="Escape"){d(null);return}const v=u(m);if(!v)return;const b={...i};for(const[p,g]of Object.entries(b))g===v&&delete b[p];b[l]=v,h(b),d(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[e,l,i,h,u]),c.useEffect(()=>{if(!e)return;const f=m=>{if(!(!m.ctrlKey&&!m.metaKey&&!m.altKey)){for(const[v,b]of Object.entries(i))if(t.includes(v)&&u(m)===b){m.preventDefault(),r(),n(v);return}}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,i,t,r,n,u]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:d,saveShortcuts:h}}const Ci=e=>{e.preventDefault()},U0=c.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:o,draggingTabRef:l,onFocus:d,onSelectTab:u,onConversationActivated:h,onPreviewReorder:f,onReorderTab:m,onCommitPreviewOrder:v,onClearPreviewOrder:b,onDragStateReset:p,onDragTabKeyChange:g,onReceiveTab:y,onOpenContextMenu:x,longPressTimer:N,isGroupActive:j}){const w=Cr(t),A=w.isGenerating?"agent-tab-generating":w.isWaiting?"agent-tab-waiting":"",M=w.isReconnecting,S=c.useCallback(C=>{l.current=t.tabKey,g(t.tabKey),C.dataTransfer.setData("text/tab-key",t.tabKey),C.dataTransfer.effectAllowed="move"},[t.tabKey,l,g]),k=c.useCallback(()=>{l.current=null,g(null),v(),b(),p()},[l,g,v,b,p]),O=c.useCallback(C=>{const F=l.current;if(!(!F||F===t.tabKey)&&C.dataTransfer.types.includes("text/tab-key")){C.preventDefault(),C.stopPropagation();const L=C.currentTarget.getBoundingClientRect(),D=C.clientX<L.left+L.width/2?"left":"right";f(F,t.tabKey,D)}},[t.tabKey,l,f]),P=c.useCallback(C=>{C.preventDefault(),C.stopPropagation();const F=C.dataTransfer.getData("text/tab-key");if(F&&F!==t.tabKey){const L=C.currentTarget.getBoundingClientRect(),D=C.clientX<L.left+L.width/2?"left":"right";o.includes(F)?m(F,t.tabKey,D):y&&y(F)}b()},[t.tabKey,o,m,y,b]),I=c.useCallback(C=>{C.stopPropagation(),d(),u(t.tabKey),h(t)},[t,h,d,u]),W=c.useCallback(C=>{C.preventDefault(),x(C.clientX,C.clientY,t.tabKey)},[t.tabKey,x]),K=c.useCallback(C=>{const F=C.touches[0];N.current=setTimeout(()=>{x(F.clientX,F.clientY,t.tabKey)},600)},[t.tabKey,N,x]),R=c.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),T=["adhdev-dockview-tab",A,r&&"is-active",j&&"is-group-active",M&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:T,draggable:!0,onDragStart:S,onDragEnd:k,onDragOver:O,onDrop:P,onClick:I,onContextMenu:W,onTouchStart:K,onTouchEnd:R,onTouchMove:R,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:w.isGenerating?s.jsx("div",{className:"tab-spinner"}):w.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):M?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):w.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:ft(t),children:ft(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[M?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Ls(t)}):w.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Ls(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:Ls(t)}),s.jsx(br,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),i&&s.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,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function K0({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:o,onConversationActivated:l,onPreviewReorder:d,onReorderTab:u,onCommitPreviewOrder:h,onClearPreviewOrder:f,onDragStateReset:m,onDragTabKeyChange:v,onReceiveTab:b,onHideTab:p,isGroupActive:g,allowTabShortcuts:y=!0}){const[x,N]=c.useState(null),j=c.useRef(null),w=c.useRef(null),A=c.useMemo(()=>e.map(W=>W.tabKey),[e]);wn("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(x==null?void 0:x.tabKey)||null});const{isMac:M,tabShortcuts:S,shortcutListening:k,setShortcutListening:O,saveShortcuts:P}=Nh({enabled:y,sortedTabKeys:e.map(W=>W.tabKey),onFocus:i,onSelectTab:o});c.useEffect(()=>{if(!x)return;const W=K=>{const R=document.querySelector("[data-pane-context-menu]");R&&R.contains(K.target)||N(null)};return window.addEventListener("mousedown",W,!0),()=>window.removeEventListener("mousedown",W,!0)},[x]),c.useEffect(()=>{const W=w.current;if(!W)return;const K=R=>{Math.abs(R.deltaY)<=Math.abs(R.deltaX)||(R.preventDefault(),W.scrollLeft+=R.deltaY)};return W.addEventListener("wheel",K,{passive:!1}),()=>W.removeEventListener("wheel",K)},[]);const I=c.useCallback((W,K,R)=>{N({x:W,y:K,tabKey:R})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.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(W=>s.jsx(U0,{conv:W,isActive:t===W.tabKey,isDraggedTab:a.current===W.tabKey,isTaskCompleteUnread:n.has(W.tabKey),shortcut:y?S[W.tabKey]:void 0,conversationKeys:A,draggingTabRef:a,onFocus:i,onSelectTab:o,onConversationActivated:l,onPreviewReorder:d,onReorderTab:u,onCommitPreviewOrder:h,onClearPreviewOrder:f,onDragStateReset:m,onDragTabKeyChange:v,onReceiveTab:b,onOpenContextMenu:I,longPressTimer:j,isGroupActive:g},W.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),x&&s.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:x.x,top:x.y},children:[y&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:Ci,onClick:W=>{W.stopPropagation(),O(x.tabKey),N(null)},children:["⌨ ",S[x.tabKey]?`Change shortcut (${S[x.tabKey]})`:"Set shortcut"]}),S[x.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:Ci,onClick:()=>{const W={...S};delete W[x.tabKey],P(W),N(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[y&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:Ci,onClick:()=>{p(x.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&k&&s.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:()=>O(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:W=>W.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",M?"⌘+1":"Ctrl+1",", ",M?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function H0({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:o,hasRegisteredMachines:l,userName:d,groupIndex:u,onFocus:h,isSplitMode:f,numGroups:m,onMoveTab:v,onReceiveTab:b,style:p,onActiveTabChange:g,initialActiveTabId:y,initialTabOrder:x,onTabOrderChange:N,onHideTab:j,isFocused:w,allowTabShortcuts:A=!0,onOpenNewSession:M,liveSessionInboxState:S}){const{sendCommand:k}=Ct(),O=c.useRef(null),{activeTabId:P,activeConv:I,sortedConversations:W,draggingTabRef:K,selectTab:R,handleTabReorder:T,updatePreviewOrder:C,commitPreviewOrder:F,clearPreviewOrder:L,moveTabToEnd:D,setDraggingTabKey:H}=F0({conversations:e,initialActiveTabId:y,initialTabOrder:x,onActiveTabChange:g,onTabOrderChange:N}),Q=Ba({sendDaemonCommand:a,activeConv:I,setActionLogs:i,isStandalone:o}),{dragOver:ge,dropAction:ue,resetDragState:Z,handleDragEnter:xe,handleDragOver:Se,handleDragLeave:be,handleDrop:Y}=B0({conversations:e,numGroups:m,onMoveTab:v,onReceiveTab:b,onOwnTabDrop:D,onClearPreviewOrder:L}),he=I&&!nt(I)&&Tr(I)==="terminal",ye=c.useMemo(()=>I?t.find(pe=>pe.id===I.routeId):void 0,[t,I]),se=c.useMemo(()=>I?n.filter(pe=>pe.routeId===I.tabKey):[],[n,I]),de=c.useMemo(()=>new Set(W.filter(pe=>wx(pe,S,{isOpenConversation:pe.tabKey===P})).map(pe=>pe.tabKey)),[P,S,W]);wn("PaneGroup",{groupIndex:u,conversationCount:e.length,activeTabId:P,dragOver:ge});const Ce=c.useCallback(pe=>{pe.streamSource==="agent-stream"&&pe.agentType&&k(pe.routeId,mu(),{agentType:pe.agentType,...pe.sessionId&&{targetSessionId:pe.sessionId}}).catch(()=>{})},[k]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:h,style:{...p,outline:ge?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(K0,{conversations:W,activeTabId:P,groupIndex:u,numGroups:m,unreadTabKeys:de,draggingTabRef:K,onFocus:h,onSelectTab:R,onConversationActivated:Ce,onPreviewReorder:C,onReorderTab:T,onCommitPreviewOrder:F,onClearPreviewOrder:L,onDragStateReset:Z,onDragTabKeyChange:H,onMoveTab:v,onReceiveTab:b,onHideTab:j,isGroupActive:w??!1,allowTabShortcuts:A}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:xe,onDragOver:Se,onDragLeave:be,onDrop:Y,children:[ge&&s.jsx(W0,{dropAction:ue,canSplit:!!(m<4&&v)}),I?s.jsx(fc,{activeConv:I,clearToken:r[I.tabKey]||0,isCliTerminal:!!he,ideEntry:ye,terminalRef:O,handleModalButton:Q.handleModalButton,handleRelaunch:Q.handleRelaunch,handleSendChat:Q.handleSendChat,isSendingChat:Q.isSendingChat,sendFeedbackMessage:Q.sendFeedbackMessage,handleFocusAgent:Q.handleFocusAgent,isFocusingAgent:Q.isFocusingAgent,actionLogs:se,userName:d,isInputActive:!f||!!w}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(xc,{conversationsCount:e.length,isSplitMode:f,isStandalone:o,hasRegisteredMachines:l,onOpenNewSession:M})})]})]})}function z0({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:o,actionLogs:l,sendDaemonCommand:d,setActionLogs:u,isStandalone:h,hasRegisteredMachines:f,userName:m,focusedGroup:v,focusGroup:b,moveTabToGroup:p,splitTabRelative:g,closeGroup:y,handleResizeStart:x,groupActiveTabIds:N,setGroupActiveTab:j,groupTabOrders:w,setGroupTabOrder:A,toggleHiddenTab:M,onOpenNewSession:S,allowTabShortcuts:k=!0,liveSessionInboxState:O}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((P,I)=>{const W=t&&n.length===r?`${n[I]}%`:void 0;return s.jsxs(Et.Fragment,{children:[t&&I>0&&s.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=>x(I-1,K),onDoubleClick:()=>y(I),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(H0,{style:t?{flexBasis:W??`${100/r}%`,flexGrow:W?0:1,flexShrink:W?0:1}:void 0,conversations:P,clearedTabs:i,ides:o,actionLogs:l,sendDaemonCommand:d,setActionLogs:u,isStandalone:h,hasRegisteredMachines:f,userName:m,groupIndex:I,isFocused:t&&v===I,onFocus:()=>b(I),isSplitMode:t,numGroups:r,onMoveTab:(K,R)=>{R==="left"&&I>0?p(K,I-1):R==="right"&&I<r-1?p(K,I+1):R==="split-left"&&r<4?g(K,I,"left"):R==="split-right"&&r<4&&g(K,I,"right")},onReceiveTab:K=>p(K,I),onActiveTabChange:K=>j(I,K),initialActiveTabId:N[I],initialTabOrder:w[I],onTabOrderChange:K=>A(I,K),onHideTab:M,onOpenNewSession:S,allowTabShortcuts:k,liveSessionInboxState:O})]},I)})})}function Ch({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,i]=c.useState(null),[o,l]=c.useState(null);c.useEffect(()=>e?xt.onScreenshot("ide-page",(h,f)=>{if(h!==e)return;const m=new FileReader;m.onload=()=>i(m.result),m.readAsDataURL(f)}):void 0,[e]),c.useEffect(()=>{r!=="connected"&&i(null)},[r]),c.useEffect(()=>{var h;return e?((h=xt.onStatus)==null?void 0:h.call(xt,(f,m)=>{f===e&&m!=null&&m.screenshotUsage&&l(m.screenshotUsage)}))||(()=>{}):void 0},[e]),c.useEffect(()=>{i(null)},[e,t]),c.useEffect(()=>{const u=e?xt.get(e):null;if(!(!u||r!=="connected"))return n!=="chat"&&t?u.startScreenshots(t):u.stopScreenshots(t),()=>{u.stopScreenshots(t)}},[n,r,t,e]);const d=c.useCallback(async(u,h)=>{const f=e?xt.get(e):null;return!f||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):f.sendInput(u,h,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:o,handleRemoteAction:d}}const Th="adhdev-dashboard-action-shortcuts",V0=1200,G0=[["toggleHiddenTabs","G H"],["openNewSession","N"],["setActiveTabShortcut","G S"],["selectPreviousGroupTab","G K"],["selectPreviousGroupTab","T ←"],["selectPreviousGroupTab","⌥+["],["selectPreviousGroupTab","Ctrl+Alt+["],["selectNextGroupTab","G J"],["selectNextGroupTab","T →"],["selectNextGroupTab","⌥+]"],["selectNextGroupTab","Ctrl+Alt+]"],["splitActiveTabDown","S ↓"],["splitActiveTabDown","⌘+⌥+-"],["splitActiveTabDown","Ctrl+Alt+-"],["splitActiveTabRight","S →"],["splitActiveTabRight","⌘+⌥+\\"],["splitActiveTabRight","⌘+⌥+="],["splitActiveTabRight","Ctrl+Alt+\\"],["focusLeftPane","F ←"],["focusLeftPane","⌘+⌥+←"],["focusLeftPane","⌘+⌥+["],["focusLeftPane","Ctrl+Alt+←"],["focusRightPane","F →"],["focusRightPane","⌘+⌥+→"],["focusRightPane","⌘+⌥+]"],["focusRightPane","Ctrl+Alt+→"],["focusUpPane","F ↑"],["focusUpPane","⌘+⌥+U"],["focusUpPane","Ctrl+Alt+↑"],["focusDownPane","F ↓"],["focusDownPane","⌘+⌥+J"],["focusDownPane","Ctrl+Alt+↓"],["moveActiveTabToLeftPane","M ←"],["moveActiveTabToLeftPane","⌘+⌥+⇧+←"],["moveActiveTabToLeftPane","⌘+⌥+,"],["moveActiveTabToLeftPane","Ctrl+Alt+Shift+←"],["moveActiveTabToRightPane","M →"],["moveActiveTabToRightPane","⌘+⌥+⇧+→"],["moveActiveTabToRightPane","⌘+⌥+."],["moveActiveTabToRightPane","Ctrl+Alt+Shift+→"],["moveActiveTabToUpPane","M ↑"],["moveActiveTabToUpPane","⌘+⌥+I"],["moveActiveTabToUpPane","Ctrl+Alt+Shift+↑"],["moveActiveTabToDownPane","M ↓"],["moveActiveTabToDownPane","⌘+⌥+K"],["moveActiveTabToDownPane","Ctrl+Alt+Shift+↓"],["triggerPrimaryApprovalAction","⌥+A"],["triggerSecondaryApprovalAction","⌥+D"],["toggleCliView","T"]];function q0(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function lt(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function Ih(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:lt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:lt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:lt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:lt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:lt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:lt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:lt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:lt("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:lt("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:lt("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:lt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:lt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:lt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:lt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:lt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:lt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:lt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:lt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:lt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:lt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:lt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:lt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:lt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:lt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:lt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:lt("toggleCliView",e)}]}function go(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Na(e){const t=Object.fromEntries(Ih(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Th)||"{}"),n={...t,...r};for(const[a,i]of G0)n[a]===i&&(n[a]=t[a]);return n}catch{return t}}function Ah(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function X0({enabled:e=!0,onTrigger:t}){const r=q0(),[n,a]=c.useState(()=>Na(r)),[i,o]=c.useState(null),[l,d]=c.useState([]),u=c.useRef({parts:[],timer:null}),h=c.useCallback(p=>{const g=[];return p.metaKey&&g.push(r?"⌘":"Meta"),p.ctrlKey&&g.push("Ctrl"),p.altKey&&g.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&g.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(g.push(Ah(p.key)),g.join("+"))},[r]),f=c.useCallback(p=>{a(p);try{localStorage.setItem(Th,JSON.stringify(p))}catch{}},[]);c.useEffect(()=>{const p=Na(r),g=Object.entries(n),y=Object.entries(p);g.length===y.length&&g.every(([x,N])=>p[x]===N)||f(p)},[n,r,f]);const m=c.useCallback(()=>{typeof window<"u"&&u.current.timer!=null&&window.clearTimeout(u.current.timer),u.current={parts:[],timer:null}},[]),v=c.useCallback(()=>{typeof window>"u"||(u.current.timer!=null&&window.clearTimeout(u.current.timer),u.current.timer=window.setTimeout(()=>{u.current={parts:[],timer:null}},V0))},[]);c.useEffect(()=>{if(!i)return;const p=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){o(null),d([]);return}const y=h(g);if(!y)return;const N=!(g.metaKey||g.ctrlKey||g.altKey)&&/^[A-Z0-9]$/.test(y);if(l.length===0&&N){d([y]);return}const w=[...l,y].slice(0,2).join(" "),A={...n};for(const[M,S]of Object.entries(A))S===w&&delete A[M];A[i]=w,f(A),o(null),d([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,h,f,i,l]),c.useEffect(()=>{if(!e||i)return;const p=g=>{if(g.defaultPrevented)return;const y=h(g);if(!y)return;const x=g.metaKey||g.ctrlKey||g.altKey;if(go(g.target))return;const N=u.current.parts,j=x?[y]:[...N.slice(-1),y].slice(-2),w=j.join(" "),A=j[j.length-1],M=Object.entries(n).filter(([,I])=>!!I),S=M.find(([,I])=>I===w);if(S){g.preventDefault(),m(),t(S[0]);return}if(M.some(([,I])=>I.startsWith(`${w} `))){g.preventDefault(),u.current.parts=j,v();return}const O=M.find(([,I])=>I===A);if(O){g.preventDefault(),m(),t(O[0]);return}if(M.some(([,I])=>I.startsWith(`${A} `))){g.preventDefault(),u.current.parts=[A],v();return}m()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,v,e,h,t,m,i]),c.useEffect(()=>()=>m(),[m]);const b=c.useMemo(()=>Ih(r),[r]);return{isMac:r,actionDefinitions:b,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:o,setShortcutListeningDraft:d,saveShortcuts:f}}function Y0({isTabInPopout:e,isTabFloating:t,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(t&&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})):t?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 Mh(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Ul({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!Mh(n):!0}function J0({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:Mh(r)}const _h=1e3,Q0=4;function Kl(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Hl(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function Z0({detachDelayMs:e=_h,stillnessThresholdPx:t=Q0,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let i=null,o=null,l=null,d=null,u=null,h=!1;const f=()=>{u!=null&&(a(u),u=null)},m=()=>{f(),l=null},v=()=>{f(),i=null,o=null,l=null,d=null,h=!1},b=()=>{!i||!l||!d||h||u!=null||(u=n(()=>{u=null,!(!i||!l||!d||h)&&Kl(d,o)&&(Hl(l,d,t)||(h=!0,r({panelId:i,clientX:d.clientX,clientY:d.clientY})))},e))},p=y=>{if(!(!i||h)){if(!Kl(y,o)){d={clientX:y.clientX,clientY:y.clientY},m();return}(!l||Hl(l,y,t))&&(f(),l={clientX:y.clientX,clientY:y.clientY}),d={clientX:y.clientX,clientY:y.clientY},b()}},g=y=>{!i||h||(y&&(d={clientX:y.clientX,clientY:y.clientY}),m())};return{startDrag:y=>{f(),i=y.panelId,o=y.selfPanelBounds??null,l=null,d={clientX:y.clientX,clientY:y.clientY},h=!1},markSelfPanel:p,markNonSelfPanel:g,markNoDropTarget:g,markDockTarget:g,endDrag:v,isDragging:()=>i!=null,hasDetached:()=>h,dispose:v}}function ew(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Hn(e){return e.isActive}function zl(e){return e.isVisible}const Rh=c.createContext(null);function za(){const e=c.useContext(Rh);if(!e)throw new Error("DashboardDockviewContext missing");return e}function ra(e){return ft(e)||e.tabKey}function tw(e){return`remote:${e}`}function Vt(e){return e.startsWith("remote:")}function Vl(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function sw(e){e.preventDefault()}function Ti(e){var n;const t=e==null?void 0:e.defaultView;if(!t)return;const r=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),r(e==null?void 0:e.body),r(e==null?void 0:e.documentElement),(n=t.requestAnimationFrame)==null||n.call(t,()=>{try{t.focus(),r(e==null?void 0:e.body)}catch{}})}catch{}}function Ii(e,t){e.classList.remove(Yi.className,Ji.className),e.classList.add(t==="light"?Yi.className:Ji.className)}function Gl(e){return e?Array.from(new Set(e.groups.map(t=>{var r,n;return(n=(r=t.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(t=>!!t&&t!==window))):[]}function rw(e){const[,t]=c.useState(0);c.useEffect(()=>{const r=()=>t(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 nw(e,t,r){var o;const n=[t];let a;for(const l of n){let d;for(const u of l){const h=e.addPanel({id:u.tabKey,component:"conversation",title:ra(u),params:{kind:"conversation",tabKey:u.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=h.id)}a=d??a}return r??((o=t[0])==null?void 0:o.tabKey)??null}function ql(e,t){const r=new Set(t.map(a=>a.tabKey)),n=new Map;for(const a of t)n.set(a.tabKey,(n.get(a.tabKey)||0)+1);for(const a of[...e.panels])Vt(a.id)||r.has(a.id)||e.removePanel(a);for(const a of t){const i=e.getPanel(a.tabKey);if(i){(n.get(a.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:a.tabKey,daemonId:a.daemonId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,panelId:i.id}),i.update({params:{tabKey:a.tabKey}}),i.title!==ra(a)&&i.api.setTitle(ra(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:ra(a),params:{kind:"conversation",tabKey:a.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 Xl(e,t,r){var d,u;const n=r?tw(r):null;for(const h of[...e.panels])Vt(h.id)&&(!n||h.id!==n)&&e.removePanel(h);if(!r||!n)return;const a=Xt(t,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),o=Ru(a);if(i){i.title!==o&&i.api.setTitle(o);return}const l=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((u=e.panels.find(h=>!Vt(h.id)))==null?void 0:u.id);e.addPanel({id:n,component:"remote",title:o,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function aw({params:e,api:t}){var v;const r=za(),n=c.useRef(null),[a,i]=c.useState(()=>Hn(t)),[o,l]=c.useState(()=>zl(t)),d=r.conversationsByTabKey.get(e.tabKey),u=Ba({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});c.useEffect(()=>{i(Hn(t)),l(zl(t));const b=[t.onDidActiveChange(p=>i(p.isActive)),t.onDidActiveGroupChange(p=>{if(!Hn(t)&&!p.isActive){i(!1);return}i(Hn(t))}),t.onDidVisibilityChange(p=>l(p.isVisible))];return()=>{for(const p of b)p.dispose()}},[t]);const h=c.useMemo(()=>d?r.ides.find(b=>b.id===d.routeId):void 0,[r.ides,d]),f=c.useMemo(()=>d?r.actionLogs.filter(b=>b.routeId===d.tabKey):[],[r.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(xc,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const m=!nt(d)&&Tr(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(fc,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:m,ideEntry:h,terminalRef:n,handleModalButton:u.handleModalButton,handleRelaunch:u.handleRelaunch,handleSendChat:u.handleSendChat,isSendingChat:u.isSendingChat,handleFocusAgent:u.handleFocusAgent,isFocusingAgent:u.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((v=r.scrollToBottomRequest)==null?void 0:v.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:o})})}function iw({params:e}){var d;const t=za(),r=c.useMemo(()=>Xt([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=c.useMemo(()=>t.ides.find(u=>u.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((d=r==null?void 0:r.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:o,handleRemoteAction:l}=Ch({doId:a,targetSessionId:r?fu(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?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(Qd,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:o,transportType:r.transport,onAction:l})}):s.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 ow(){const e=za();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(xc,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function cw(e){var v,b;rw(e);const t=za(),r=c.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=Xt([...t.conversationsByTabKey.values()],e.params.routeId),g=((v=e.api.group.activePanel)==null?void 0:v.id)===e.api.id,y=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${g?" is-active":""}${y?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:p!=null&&p.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:p.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const n=t.conversationsByTabKey.get(e.params.tabKey);if(!n)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,i=e.api.isGroupActive,o=Ea(n,t.liveSessionInboxState,{isOpenConversation:a}),l=o.isReconnecting,d=o.isConnecting,u=o.isGenerating,h=o.isWaiting,f=o.unread,m=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:ft(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var g;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((g=p.target)==null?void 0:g.ownerDocument)??document})},children:[f&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:u?s.jsx("div",{className:"tab-spinner"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):d?s.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:ft(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Ls(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Ls(n)}):s.jsx("span",{children:Ls(n)})})]}),m&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:m,children:m})]})}function lw({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:o,hasRegisteredMachines:l,initialDataLoaded:d,userName:u,toggleHiddenTab:h,actionShortcuts:f,registerActionHandlers:m,onActiveTabChange:v,onOpenNewSession:b,onRequestScrollToBottom:p,requestedActiveTabKey:g,requestedRemoteIdeId:y,onRequestedActiveTabConsumed:x,scrollToBottomRequest:N,liveSessionInboxState:j,layoutProfile:w}){var st,Xe,ot;const{theme:A}=cc(),{sendCommand:M}=Ct(),S=c.useRef(null),k=c.useRef(null),O=c.useRef(null),P=c.useRef(!1),I=c.useRef(!1),W=c.useRef(!1),K=c.useRef(null),R=c.useRef([]),[T,C]=c.useState(null),[F,L]=c.useState(0),D=c.useRef(typeof window>"u"?{}:Tv(w)),H=c.useMemo(()=>new Map(e.map(U=>[U.tabKey,U])),[e]),Q=c.useMemo(()=>{const U=S.current;return U?U.groups.some(V=>{try{const J=V.model.location.type;return J!=="floating"&&J!=="popout"?!1:V.panels.some(ne=>H.has(ne.id))}catch{return!1}}):!1},[H,F,e]),ge=c.useCallback(()=>{var U;(U=S.current)==null||U.focus()},[]),ue=c.useCallback((U,V)=>{p==null||p(U,V)},[p]),Z=c.useCallback(U=>{const V=document,J=U.document;for(const ae of V.querySelectorAll('link[rel="stylesheet"]')){const Ne=J.createElement("link");Ne.rel="stylesheet",Ne.href=ae.href,ae.crossOrigin&&(Ne.crossOrigin=ae.crossOrigin),J.head.appendChild(Ne)}for(const ae of V.querySelectorAll("style")){const Ne=J.createElement("style");Ne.textContent=ae.textContent,J.head.appendChild(Ne)}const ne=[];for(const ae of V.styleSheets)try{for(const Ne of ae.cssRules)Ne instanceof CSSStyleRule&&(Ne.selectorText===":root"||Ne.selectorText==="html")&&ne.push(Ne.cssText)}catch{}if(ne.length>0){const ae=J.createElement("style");ae.textContent=ne.join(`
54
+ `),J.head.appendChild(ae)}const $=V.documentElement.getAttribute("data-theme");$&&J.documentElement.setAttribute("data-theme",$),J.documentElement.style.colorScheme=$==="light"?"light":"dark",J.body.className=V.body.className;const X=V.documentElement.getAttribute("style");X&&J.documentElement.setAttribute("style",X);const te=J.getElementById("dv-popout-window");te instanceof HTMLElement&&(te.classList.add("adhdev-dockview"),Ii(te,A))},[A]),xe=c.useCallback(()=>{var V;const U=S.current;if(U)for(const J of U.groups)try{const ne=(V=J.element)==null?void 0:V.ownerDocument;if(!ne||ne===document)continue;const $=ne.getElementById("dv-popout-window");$ instanceof HTMLElement&&($.classList.add("adhdev-dockview"),Ii($,A));const X=document.documentElement.getAttribute("data-theme");X&&ne.documentElement.setAttribute("data-theme",X),ne.documentElement.style.colorScheme=X==="light"?"light":"dark",ne.body.className=document.body.className;const te=document.documentElement.getAttribute("style");te?ne.documentElement.setAttribute("style",te):ne.documentElement.removeAttribute("style")}catch{}},[A]),Se=c.useCallback(U=>{const V=S.current;if(!V)return;const J=V.getPanel(U);J&&V.addPopoutGroup(J,{popoutUrl:"/popout.html",onDidOpen:({window:ne})=>{Z(ne),me();const $=H.get(U);ne.document.title=$?`${ft($)} — ADHDev`:"ADHDev — Popout"}})},[H,Z]),be=c.useCallback(U=>{const V=S.current,J=V==null?void 0:V.getPanel(U);if(!V||!J)return;const ne=V.groups.filter($=>{var X;try{return((X=$.element)==null?void 0:X.ownerDocument)===document}catch{return!0}});ne.length>0?J.api.moveTo({group:ne[0],position:"center"}):J.api.moveTo({position:"center"}),J.api.setActive()},[]),Y=c.useCallback(U=>{var ne;const V=S.current;if(!V)return!1;const J=V.getPanel(U);if(!J)return!1;try{return((ne=J.group.element)==null?void 0:ne.ownerDocument)!==document}catch{return!1}},[]),he=c.useCallback(U=>{Y(U)&&be(U),h(U)},[Y,be,h]),ye=c.useCallback(U=>{const V=S.current,J=V==null?void 0:V.getPanel(U);!V||!J||V.addFloatingGroup(J,{width:600,height:500})},[]),se=c.useCallback(U=>{var J;const V=(J=S.current)==null?void 0:J.getPanel(U);if(!V)return!1;try{return V.group.model.location.type==="floating"}catch{return!1}},[]),de=c.useCallback(()=>{var V,J;const U=(J=(V=S.current)==null?void 0:V.activePanel)==null?void 0:J.id;return!U||Vt(U)?null:H.has(U)?U:null},[H]),Ce=c.useCallback(U=>{const V=S.current,J=V==null?void 0:V.getPanel(U);if(!V||!J)return;const ne=V.groups.filter($=>{try{return $.model.location.type==="grid"}catch{return!0}});ne.length>0?J.api.moveTo({group:ne[0],position:"center"}):J.api.moveTo({position:"center"}),J.api.setActive()},[]),pe=c.useCallback(()=>{var X;const U=S.current;if(!U)return;const J=U.groups.filter(te=>{var ae;try{return((ae=te.element)==null?void 0:ae.ownerDocument)===document&&te.model.location.type==="grid"}catch{return!1}})[0]||null,ne=[...U.panels];for(const te of ne){const ae=(X=te.group.element)==null?void 0:X.ownerDocument,Ne=te.group.model.location.type;ae===document&&Ne==="grid"||(J&&J.id!==te.group.id?te.api.moveTo({group:J,position:"center"}):te.api.moveTo({position:"center"}))}const $=U.activePanel;$&&($.group.model.openPanel($),$.api.setActive()),Ti(document)},[]),me=c.useCallback(()=>{var V,J;const U=S.current;if(U)for(const ne of U.groups){const $=(V=ne.element)==null?void 0:V.ownerDocument;if(!$||$===document)continue;const X=$.getElementById("dv-popout-window");if(!(X instanceof HTMLElement))continue;let te=null,ae=$.title||"ADHDev",Ne="Popout workspace";const $e=ne.activePanel;if($e)if(te=$e.id,Vt($e.id)){const Le=((J=$e.params)==null?void 0:J.routeId)||$e.id.slice(7),tt=Xt([...H.values()],Le);ae=Ru(tt),Ne=tt!=null&&tt.machineName?`Remote view · ${tt.machineName}`:"Remote view"}else{const Le=H.get($e.id);ae=Le?ft(Le):$e.title||$e.id,Ne=Le?Ls(Le):"Dockview panel"}$.title=`${ae} — ADHDev`;const Be=Array.from($.querySelectorAll("#adhdev-popout-header"));for(const Le of Be)Le.remove();const Ie=$.createElement("div");Ie.id="adhdev-popout-header",$.body.appendChild(Ie),Ie.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(";")),Ie.innerHTML=`
55
+ <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
56
+ <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
57
+ <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Vl(ae)}</div>
58
+ <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Vl(Ne)}</div>
59
+ </div>
60
+ <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
61
+ <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>
62
+ <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>
63
+ </div>
64
+ `,X.style.top="52px",X.style.height="calc(100% - 52px)";const Oe=Ie.querySelector("[data-adhdev-popout-focus]");Oe&&(Oe.onclick=()=>{window.focus()});const We=Ie.querySelector("[data-adhdev-popout-dock]");We&&(We.disabled=!te,We.style.opacity=te?"1":"0.5",We.style.cursor=te?"pointer":"default",We.onclick=()=>{var Le;te&&be(te),(Le=$.defaultView)==null||Le.focus()})}},[H,be]),oe=c.useCallback(U=>{var ne;const V=S.current,J=V==null?void 0:V.getPanel(U);if(!(!V||!J)){J.group.model.openPanel(J),J.api.setActive(),ue(U,"dockview-shortcut");try{const $=J.group.model.location;$.type==="popout"?$.getWindow().focus():Ti((ne=J.group.element)==null?void 0:ne.ownerDocument)}catch{}}},[ue]),fe=c.useCallback(U=>{const V=S.current,J=V==null?void 0:V.activePanel,ne=(V==null?void 0:V.activeGroup)||(J==null?void 0:J.group);if(!V||!J||!ne)return;const $=ne.panels||[];if($.length<=1)return;const X=$.findIndex(Ne=>Ne.id===J.id);if(X<0)return;const te=(X+U+$.length)%$.length,ae=$[te];ae&&(ae.group.model.openPanel(ae),ae.api.setActive(),Vt(ae.id)||ue(ae.id,"dockview-shortcut"))},[ue]),ce=c.useCallback(U=>{var Oe;const V=S.current,J=(V==null?void 0:V.activeGroup)||((Oe=V==null?void 0:V.activePanel)==null?void 0:Oe.group);if(!V||!J)return;const ne=V.groups||[],$=ne.find(We=>We.id===J.id);if(!$)return;const X=$.element.getBoundingClientRect(),te=X.left+X.width/2,ae=X.top+X.height/2,Ne=(We,Le,tt,rt)=>Math.max(0,Math.min(Le,rt)-Math.max(We,tt)),$e=We=>{const Le=We.element.getBoundingClientRect(),tt=Le.left+Le.width/2,rt=Le.top+Le.height/2;let pt=0,bt=0,mt=0,At=!1;if(U==="left"?(At=tt<te,pt=Math.max(0,X.left-Le.right),bt=Math.abs(rt-ae),mt=Ne(X.top,X.bottom,Le.top,Le.bottom)):U==="right"?(At=tt>te,pt=Math.max(0,Le.left-X.right),bt=Math.abs(rt-ae),mt=Ne(X.top,X.bottom,Le.top,Le.bottom)):U==="above"?(At=rt<ae,pt=Math.max(0,X.top-Le.bottom),bt=Math.abs(tt-te),mt=Ne(X.left,X.right,Le.left,Le.right)):(At=rt>ae,pt=Math.max(0,Le.top-X.bottom),bt=Math.abs(tt-te),mt=Ne(X.left,X.right,Le.left,Le.right)),!At)return Number.POSITIVE_INFINITY;const Ye=mt>0?0:120;return pt*3+bt+Ye};let Be=null,Ie=Number.POSITIVE_INFINITY;for(const We of ne){if(We.id===$.id)continue;const Le=$e(We);Number.isFinite(Le)&&(Le>=Ie||(Ie=Le,Be=We))}return Be||void 0},[]),E=c.useCallback(U=>{var ne;const V=ce(U);if(!V)return;const J=V.activePanel||V.panels[0];J&&(V.model.openPanel(J),J.api.setActive(),Vt(J.id)||ue(J.id,"dockview-focus"),Ti((ne=V.element)==null?void 0:ne.ownerDocument))},[ce,ue]),z=c.useCallback((U,V)=>{const J=S.current,ne=J==null?void 0:J.activePanel,$=(J==null?void 0:J.activeGroup)||(ne==null?void 0:ne.group);if(!J||!ne||!$)return;let X=ce(U);!X&&(V!=null&&V.createGroupIfMissing)&&(X=J.addGroup({referenceGroup:$,direction:U})),X&&(ne.api.moveTo({group:X,position:"center"}),ne.group.model.openPanel(ne),ne.api.setActive(),Vt(ne.id)||ue(ne.id,V!=null&&V.createGroupIfMissing?"dockview-split":"dockview-move"))},[ce,ue]),{isMac:le,tabShortcuts:re,shortcutListening:q,setShortcutListening:je,saveShortcuts:we}=Nh({sortedTabKeys:e.map(U=>U.tabKey),onFocus:ge,onSelectTab:oe}),Pe=c.useCallback(()=>{var J;const U=S.current;if(!U)return;const V=U.activePanel;if(V){if(Vt(V.id)){const ne=((J=V.params)==null?void 0:J.routeId)||V.id.slice(7),$=Xt(e,ne);$!=null&&$.tabKey&&je($.tabKey);return}H.has(V.id)&&je(V.id)}},[H,oe,je,e]),Re=c.useCallback(U=>{const V=[];return U.metaKey&&V.push(le?"⌘":"Meta"),U.ctrlKey&&V.push("Ctrl"),U.altKey&&V.push(le?"⌥":"Alt"),U.shiftKey&&U.key.length!==1&&V.push(le?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(U.key)?null:(V.push(Ah(U.key)),V.join("+"))},[le]),B=c.useCallback(U=>{var V,J;switch(U){case"splitActiveTabRight":z("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":z("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const ne=de();ne&&ye(ne);return}case"popoutActiveTab":{const ne=de();ne&&Se(ne);return}case"dockActiveTab":{const ne=de();if(!ne)return;Y(ne)?be(ne):se(ne)&&Ce(ne);return}case"focusLeftPane":E("left");return;case"focusRightPane":E("right");return;case"focusUpPane":E("above");return;case"focusDownPane":E("below");return;case"moveActiveTabToLeftPane":z("left");return;case"moveActiveTabToRightPane":z("right");return;case"moveActiveTabToUpPane":z("above");return;case"moveActiveTabToDownPane":z("below");return;case"selectPreviousGroupTab":fe(-1);return;case"selectNextGroupTab":fe(1);return;case"setActiveTabShortcut":Pe();return;case"hideCurrentTab":{const ne=(J=(V=S.current)==null?void 0:V.activePanel)==null?void 0:J.id;ne&&!Vt(ne)&&he(ne);return}default:return}},[fe,Ce,E,ye,de,he,se,Y,be,z,Se,Pe]);c.useEffect(()=>{if(!T)return;const U=T.sourceDocument,V=U.defaultView??window,J=ne=>{const $=U.querySelector("[data-dockview-tab-context-menu]");$&&$.contains(ne.target)||C(null)};return V.addEventListener("mousedown",J,!0),V!==window&&window.addEventListener("mousedown",()=>C(null),!0),()=>{V.removeEventListener("mousedown",J,!0),V!==window&&window.removeEventListener("mousedown",()=>C(null),!0)}},[T]);const Ae=c.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:H,hasDetachedConversationPanels:Q,ides:r,isStandalone:o,hasRegisteredMachines:l,onOpenNewSession:b,liveSessionInboxState:j,sendDaemonCommand:a,setActionLogs:i,toggleHiddenTab:he,userName:u,scrollToBottomRequest:N,tabShortcuts:re,openTabContextMenu:({x:U,y:V,tabKey:J,sourceDocument:ne})=>C({x:U,y:V,tabKey:J,sourceDocument:ne??document}),popoutTab:Se,moveTabBackToMain:be,isTabInPopout:Y,floatTab:ye,isTabFloating:se}),[n,t,H,Q,r,o,l,b,j,a,i,he,u,N,re,Se,be,Y,ye,se]),Ee=T?Y0({isTabInPopout:Y(T.tabKey),isTabFloating:se(T.tabKey),tabShortcut:re[T.tabKey],actionShortcuts:f}):[],Ve=c.useCallback(U=>{var ne;const V=S.current;if((((ne=V==null?void 0:V.activePanel)==null?void 0:ne.id)??null)===U.id){U.group.model.openPanel(U);return}U.group.model.openPanel(U),U.api.setActive()},[]),Ge=c.useCallback((U,V="requested-tab")=>{if(!U)return!1;const J=S.current;if(!J)return!1;const ne=J.getPanel(U);return ne?(Ve(ne),ue(U,V),x==null||x(),!0):!1},[Ve,x,ue]),Ze=c.useCallback(()=>{if(W.current)return!1;const U=Ge(K.current,"stored-layout-restore");return U&&(W.current=!0),U},[Ge]),et=c.useCallback(()=>{var V;const U=S.current;U&&Cv(w,{activeTabId:((V=U.activePanel)==null?void 0:V.id)??null,layout:U.toJSON()})},[w]),at=c.useCallback(()=>{Iv(w,D.current)},[w]),gt=c.useCallback(U=>{var ne,$,X,te;const V=S.current;if(!V)return{kind:"grid"};const J=V.toJSON();for(const ae of J.floatingGroups||[])if(($=(ne=ae.data)==null?void 0:ne.views)!=null&&$.includes(U)&&ae.position)return{kind:"floating",position:ae.position};for(const ae of J.popoutGroups||[])if((te=(X=ae.data)==null?void 0:X.views)!=null&&te.includes(U))return{kind:"popout",position:ae.position,popoutUrl:ae.url};return{kind:"grid"}},[]),St=c.useCallback(U=>{const V=S.current;if(!V)return;const J=V.getPanel(U),ne=D.current[U];if(!J||!ne||ne.kind==="grid")return;if(J.group.model.location.type===ne.kind){delete D.current[U],at();return}if(ne.kind==="floating"){V.addFloatingGroup(J,{x:ne.position.left??24,y:ne.position.top??24,width:ne.position.width,height:ne.position.height}),delete D.current[U],at();return}delete D.current[U],at()},[at]);c.useEffect(()=>(m==null||m({setShortcutForActiveTab:Pe,restoreHiddenTabToSavedLocation:St,activateConversationTab:oe,resetAllPanelsToMain:pe,activatePreviousTabInGroup:()=>fe(-1),activateNextTabInGroup:()=>fe(1),floatActiveTab:()=>{const U=de();U&&ye(U)},popoutActiveTab:()=>{const U=de();U&&Se(U)},dockActiveTab:()=>{const U=de();U&&(Y(U)?be(U):se(U)&&Ce(U))},splitActiveTabRight:()=>z("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>z("below",{createGroupIfMissing:!0}),focusLeftPane:()=>E("left"),focusRightPane:()=>E("right"),focusUpPane:()=>E("above"),focusDownPane:()=>E("below"),moveActiveTabToLeftPane:()=>z("left"),moveActiveTabToRightPane:()=>z("right"),moveActiveTabToUpPane:()=>z("above"),moveActiveTabToDownPane:()=>z("below")}),()=>m==null?void 0:m(null)),[fe,Ce,ye,E,de,se,Y,z,be,Se,m,pe,St,oe,Pe]),c.useEffect(()=>()=>{var U;(U=O.current)==null||U.call(O),O.current=null},[]);const jt=c.useCallback(U=>{var J,ne;S.current=U.api,(J=O.current)==null||J.call(O),O.current=null;const V=Nv(w);if(K.current=(V==null?void 0:V.activeTabId)??null,V!=null&&V.layout&&U.api.fromJSON(V.layout,{reuseExistingPanels:!1}),I.current=Ul({hasStoredLayout:!!(V!=null&&V.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),I.current||(ql(U.api,e),Xl(U.api,e,y)),U.api.totalPanels===0&&e.length>0){const $=nw(U.api,e,g);if($){const X=U.api.getPanel($);X&&Ve(X)}}else!I.current&&!Ge(g)&&Ze();if(P.current=!0,U.api.onDidActivePanelChange($=>{var te;if(K.current=($==null?void 0:$.id)??null,W.current=!0,me(),$&&Vt($.id)){const ae=((te=$.params)==null?void 0:te.routeId)||$.id.slice(7),Ne=Xt(e,ae);v((Ne==null?void 0:Ne.tabKey)??null),et();return}if(v(($==null?void 0:$.id)??null),et(),!$)return;const X=H.get($.id);(X==null?void 0:X.streamSource)==="agent-stream"&&X.agentType&&M(X.routeId,mu(),{agentType:X.agentType,...X.sessionId&&{targetSessionId:X.sessionId}}).catch(()=>{})}),U.api.onDidLayoutChange(()=>{et(),me(),L($=>$+1)}),ew()){const $=Ie=>({clientX:Ie.clientX,clientY:Ie.clientY}),X=Ie=>{const Oe=Ie==null?void 0:Ie.getBoundingClientRect();return Oe?{left:Oe.left,right:Oe.right,top:Oe.top,bottom:Oe.bottom}:null},te=Ie=>{var We;const Oe=(We=k.current)==null?void 0:We.getBoundingClientRect();return Oe?Ie.clientX<Oe.left||Ie.clientX>Oe.right||Ie.clientY<Oe.top||Ie.clientY>Oe.bottom:!1},ae=Z0({detachDelayMs:_h,onDetach:({panelId:Ie,clientX:Oe,clientY:We})=>{var mt,At;const Le=U.api.getPanel(Ie);if(!Le)return;try{if(Le.group.model.location.type!=="grid")return}catch{return}const tt=(mt=k.current)==null?void 0:mt.getBoundingClientRect(),rt=(At=Le.group.element)==null?void 0:At.getBoundingClientRect(),pt=Math.round(Math.min(Math.max((rt==null?void 0:rt.width)??600,360),720)),bt=Math.round(Math.min(Math.max((rt==null?void 0:rt.height)??500,260),640));U.api.addFloatingGroup(Le,{x:tt?Math.max(0,Oe-tt.left-32):void 0,y:tt?Math.max(0,We-tt.top-18):void 0,width:pt,height:bt}),Le.api.setActive(),et(),me(),L(Ye=>Ye+1)}}),Ne=[U.api.onWillDragPanel(Ie=>{if(!(Ie.nativeEvent.defaultPrevented||Ie.nativeEvent.shiftKey)){try{if(Ie.panel.group.model.location.type!=="grid")return}catch{return}ae.startDrag({panelId:Ie.panel.id,selfPanelBounds:X(Ie.panel.group.element),...$(Ie.nativeEvent)})}}),U.api.onWillShowOverlay(Ie=>{if(ae.hasDetached()){Ie.preventDefault();return}ae.markDockTarget($(Ie.nativeEvent))}),U.api.onWillDrop(Ie=>{if(ae.hasDetached()){Ie.preventDefault(),ae.endDrag();return}ae.markDockTarget($(Ie.nativeEvent))}),U.api.onDidDrop(()=>ae.endDrag()),U.api.onUnhandledDragOverEvent(Ie=>{ae.isDragging()&&ae.markSelfPanel($(Ie.nativeEvent))})],$e=Ie=>{if(!ae.isDragging())return;const Oe=$(Ie);te(Oe)&&ae.markNonSelfPanel(Oe)},Be=()=>ae.endDrag();window.addEventListener("dragover",$e,!0),window.addEventListener("drop",Be,!0),window.addEventListener("dragend",Be,!0),O.current=()=>{ae.dispose();for(const Ie of Ne)Ie.dispose();window.removeEventListener("dragover",$e,!0),window.removeEventListener("drop",Be,!0),window.removeEventListener("dragend",Be,!0)}}U.api.onDidAddGroup($=>{requestAnimationFrame(()=>{var X,te;try{const ae=(X=$.element)==null?void 0:X.ownerDocument;if(!ae||ae===document)return;(te=ae.getElementById("dv-popout-window"))==null||te.classList.add("adhdev-dockview");const Ne=document.documentElement.getAttribute("data-theme");Ne&&ae.documentElement.setAttribute("data-theme",Ne),ae.body.className=document.body.className;const $e=document.documentElement.getAttribute("style");$e&&ae.documentElement.setAttribute("style",$e)}catch{}me(),L(ae=>ae+1)})}),v(((ne=U.api.activePanel)==null?void 0:ne.id)??null)},[Ve,Ge,H,r,d,w,v,et,g,y,M,me,e]);c.useLayoutEffect(()=>{const U=S.current;if(!U||!P.current||I.current&&Ul({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;I.current&&(I.current=!1);const V=R.current,J=new Set(V),ne=e.map(Be=>Be.tabKey),$=new Set(ne),X=J0({previousVisibleConversationCount:V.length,visibleConversationCount:e.length,ides:r});let te=!1;for(const Be of V)$.has(Be)||X||(D.current[Be]=gt(Be),te=!0);te&&at(),X||(ql(U,e),Xl(U,e,y));const ae=ne.filter(Be=>!J.has(Be));let Ne=!1;for(const Be of ae){const Ie=U.getPanel(Be),Oe=D.current[Be];if(!Ie||!Oe||Oe.kind==="grid")continue;if(Ie.group.model.location.type===Oe.kind){delete D.current[Be],Ne=!0;continue}if(Oe.kind==="floating"){U.addFloatingGroup(Ie,{x:Oe.position.left??24,y:Oe.position.top??24,width:Oe.position.width,height:Oe.position.height}),delete D.current[Be],Ne=!0;continue}}if(Ne&&at(),R.current=ne,g&&Ge(g))return;!U.activePanel&&U.panels[0]&&Ve(U.panels[0]),!!(U.activePanel&&U.getPanel(U.activePanel.id))||Ze()},[Ve,Ge,Ze,r,d,at,gt,g,y,e]),c.useEffect(()=>{P.current&&Ge(g)},[Ge,g]),c.useEffect(()=>{const U=J=>{const ne=J.target;if(!ne)return;const $=ne.querySelector("[data-tab-key]")||ne.closest("[data-tab-key]");if($){const X=$.getAttribute("data-tab-key");if(X&&J.dataTransfer){const te=ne.closest(".dv-tab")||$.closest(".dv-tab")||$;J.dataTransfer.effectAllowed="move",J.dataTransfer.setData("text/tab-key",X),te instanceof HTMLElement&&J.dataTransfer.setDragImage(te,Math.max(12,Math.round(te.clientWidth/2)),Math.max(10,Math.round(te.clientHeight/2)))}}};window.addEventListener("dragstart",U);const V=Gl(S.current);for(const J of V)J.addEventListener("dragstart",U);return()=>{window.removeEventListener("dragstart",U);for(const J of V)J.removeEventListener("dragstart",U)}},[F]),c.useEffect(()=>{var V;const U=(V=k.current)==null?void 0:V.querySelector(".adhdev-dockview");U instanceof HTMLElement&&Ii(U,A),xe(),me()},[me,xe,A]),c.useEffect(()=>{me()},[me]),c.useEffect(()=>{const U=V=>{if(V.defaultPrevented||q)return;const J=Re(V);if(!J)return;const ne=V.metaKey||V.ctrlKey||V.altKey;go(V.target)&&!ne||Na(le).setActiveTabShortcut!==J||(V.preventDefault(),V.stopPropagation(),Pe())};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[Re,le,q,Pe]),c.useEffect(()=>{const U=k.current;if(!U)return;const V=J=>{var ae,Ne;if(!J.isTrusted)return;const ne=(Ne=(ae=J.target)==null?void 0:ae.closest)==null?void 0:Ne.call(ae,".dv-scrollable");if(!ne)return;J.preventDefault(),J.stopPropagation();const $=Math.abs(J.deltaX),X=Math.abs(J.deltaY),te=$>X?J.deltaX:J.deltaY;ne.dispatchEvent(new WheelEvent("wheel",{deltaY:te,deltaMode:J.deltaMode,bubbles:!1,cancelable:!0}))};return U.addEventListener("wheel",V,{passive:!1,capture:!0}),()=>U.removeEventListener("wheel",V,{capture:!0})},[]),c.useEffect(()=>{const U=Gl(S.current);if(U.length===0)return;const V=U.map(J=>{let ne=[],$=null;const X=()=>{$!=null&&J.clearTimeout($),$=null,ne=[]},te=()=>{$!=null&&J.clearTimeout($),$=J.setTimeout(()=>{$=null,ne=[]},1200)},ae=$e=>{if(!$e.ctrlKey&&!$e.metaKey&&!$e.altKey)return;const Be=Re($e);if(!Be)return;const Ie=jh();for(const[Oe,We]of Object.entries(Ie))if(e.some(Le=>Le.tabKey===Oe)&&We===Be){$e.preventDefault(),oe(Oe);return}},Ne=$e=>{if($e.defaultPrevented||q)return;const Be=Re($e);if(!Be)return;const Ie=$e.metaKey||$e.ctrlKey||$e.altKey;if(go($e.target))return;const Oe=Na(le),We=Object.entries(Oe).filter(([Ye,ke])=>!!ke&&(Ye==="splitActiveTabRight"||Ye==="splitActiveTabDown"||Ye==="floatActiveTab"||Ye==="popoutActiveTab"||Ye==="dockActiveTab"||Ye==="focusLeftPane"||Ye==="focusRightPane"||Ye==="focusUpPane"||Ye==="focusDownPane"||Ye==="moveActiveTabToLeftPane"||Ye==="moveActiveTabToRightPane"||Ye==="moveActiveTabToUpPane"||Ye==="moveActiveTabToDownPane"||Ye==="selectPreviousGroupTab"||Ye==="selectNextGroupTab"||Ye==="setActiveTabShortcut"||Ye==="hideCurrentTab")),Le=Ie?[Be]:[...ne.slice(-1),Be].slice(-2),tt=Le.join(" "),rt=Le[Le.length-1],pt=We.find(([,Ye])=>Ye===tt);if(pt){$e.preventDefault(),X(),B(pt[0]);return}if(We.some(([,Ye])=>Ye.startsWith(`${tt} `))){$e.preventDefault(),ne=Le,te();return}const mt=We.find(([,Ye])=>Ye===rt);if(mt){$e.preventDefault(),X(),B(mt[0]);return}if(We.some(([,Ye])=>Ye.startsWith(`${rt} `))){$e.preventDefault(),ne=[rt],te();return}X()};return J.addEventListener("keydown",ae),J.addEventListener("keydown",Ne),()=>{X(),J.removeEventListener("keydown",ae),J.removeEventListener("keydown",Ne)}});return()=>{for(const J of V)J()}},[Re,le,F,oe,q,B,e]);const Me=A==="light"?Yi:Ji,qe=((ot=(Xe=(st=S.current)==null?void 0:st.activePanel)==null?void 0:Xe.group.element)==null?void 0:ot.ownerDocument)??document;return s.jsxs(Rh.Provider,{value:Ae,children:[s.jsx("div",{ref:k,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(_f,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:aw,remote:iw},defaultTabComponent:cw,watermarkComponent:ow,onReady:jt,singleTabMode:"default",tabAnimation:"smooth",theme:Me,popoutUrl:"/popout.html"})}),T&&hn.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:T.x,top:T.y},children:Ee.map(U=>{if(U.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},U.id);let V=s.jsx(Bm,{size:13,className:"shrink-0 opacity-70"}),J=()=>{};switch(U.id){case"dockInWindow":case"dockBackToGrid":V=s.jsx(Fm,{size:13,className:"shrink-0 opacity-70"}),J=()=>{Ce(T.tabKey),C(null)};break;case"moveBackToMain":V=s.jsx($m,{size:13,className:"shrink-0 opacity-70"}),J=()=>{be(T.tabKey),C(null)};break;case"floatAsPanel":V=s.jsx(Om,{size:13,className:"shrink-0 opacity-70"}),J=()=>{ye(T.tabKey),C(null)};break;case"openInNewWindow":V=s.jsx(Dm,{size:13,className:"shrink-0 opacity-70"}),J=()=>{Se(T.tabKey),C(null)};break;case"setShortcut":J=ne=>{ne.stopPropagation(),je(T.tabKey),C(null)};break;case"removeShortcut":V=s.jsx(It,{size:13,className:"shrink-0 opacity-70"}),J=()=>{const ne={...re};delete ne[T.tabKey],we(ne),C(null)};break;case"hideTab":V=s.jsx(Bo,{size:13,className:"shrink-0 opacity-70"}),J=()=>{he(T.tabKey),C(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${U.tone==="muted"?"text-text-muted":""}`,onMouseDown:sw,onClick:J,children:[V,s.jsx("span",{className:"flex-1 min-w-0",children:U.label}),U.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:U.shortcut}):null]},U.id)})}),T.sourceDocument.body),q&&hn.createPortal(s.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:()=>je(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:U=>U.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",le?"⌘+1":"Ctrl+1",", ",le?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),qe.body)]})}const Ph="adhdev-recent-launch-args-v1",dw=8;function Lh(e){return String(e||"").trim().replace(/\s+/g," ")}function gc(e,t){return`${e.trim()}::${t.trim()}`}function bc(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Ph)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function Eh(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Ph,JSON.stringify(e))}catch{}}function bo(e,t){var i;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((i=bc().byKey[gc(r,n)])==null?void 0:i.items)||[]}function Dh(e,t,r){var h;const n=String(e||"").trim(),a=String(t||"").trim(),i=Lh(r);if(!n||!a||!i)return;const o=bc(),l=gc(n,a),d=((h=o.byKey[l])==null?void 0:h.items)||[],u=[i,...d.filter(f=>f!==i)].slice(0,dw);o.byKey[l]={items:u},Eh(o)}function uw(e,t,r){var h;const n=String(e||"").trim(),a=String(t||"").trim(),i=Lh(r);if(!n||!a||!i)return;const o=bc(),l=gc(n,a),u=(((h=o.byKey[l])==null?void 0:h.items)||[]).filter(f=>f!==i);u.length>0?o.byKey[l]={items:u}:delete o.byKey[l],Eh(o)}function $h(e){return!e.hasLoadedInitialResults&&!e.isLoading}function na({title:e,description:t,action:r,children:n,className:a="",contentClassName:i=""}){return s.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),t&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:t})]}),r?s.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?s.jsx("div",{className:t||r?`mt-3 ${i}`.trim():i,children:n}):null]})}function hw({savedSessionsLoading:e,savedSessionsLoaded:t,savedSessionsCount:r=0}){return e?"Refreshing saved history…":t?r>0?`${r} saved ${r===1?"history":"histories"} loaded. Open saved history to choose one.`:"No saved history found yet. New Hermes CLI conversations will appear here after ADHDev captures provider history.":"Start fresh, or open saved history when you want continuity."}function Bh({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:i,onRefresh:o,onOpenHistory:l,onClearSelection:d}){const u=i?wh(i):null,h=hw({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(na,{title:"Saved history",description:rc(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:o,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:l,children:Qb()})]}),children:[u?s.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:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),s.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:u.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:u.providerSessionId}),s.jsx("div",{className:"mt-1",children:u.metaLine}),u.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:u.updatedLabel}),u.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:u.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:d,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:h}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function Oh({setup:e,providerName:t,className:r=""}){return e?s.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${r}`,children:[s.jsxs("div",{className:"font-semibold",children:["Manual MCP setup required",t?` for ${t}`:""]}),e.instructions&&s.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-text-muted",children:[e.serverName&&s.jsxs("span",{children:["Server: ",s.jsx("code",{children:e.serverName})]}),e.configFormat&&s.jsxs("span",{children:["Format: ",s.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&s.jsxs("span",{children:["Config path: ",s.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&s.jsx("span",{children:"Start a fresh CLI session after editing config."})]}),e.template&&s.jsx("pre",{className:"mt-3 max-h-72 overflow-auto rounded-lg border border-border-subtle bg-bg-primary p-3 text-xs font-mono leading-relaxed text-text-primary select-all whitespace-pre-wrap",children:e.template})]}):null}function pw({workspaceMode:e,activeKind:t,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:i,onSelect:o}){return e==="mesh"?null:s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:r},{id:"ide",label:"IDE",enabled:n},{id:"acp",label:"ACP",enabled:a}].map(l=>s.jsx("button",{type:"button",className:`btn btn-sm ${t===l.id?"btn-primary":"btn-secondary"}`,onClick:()=>o(l.id),disabled:!l.enabled||i,children:l.label},l.id))})]})}function Ai(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>qs(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>qs(a,"acp"))?"acp":null}function zn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function fw({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:i,onLaunchProvider:o,onListMeshes:l,onLaunchMeshCoordinator:d,onListSavedSessions:u}){var Ye,ke;const h=kn(),f=c.useMemo(()=>[...e].sort(Vo),[e]),[m,v]=c.useState(((Ye=f[0])==null?void 0:Ye.id)||""),b=c.useMemo(()=>f.find(G=>G.id===m)||f[0],[m,f]),p=c.useMemo(()=>((b==null?void 0:b.workspaces)||[]).map(G=>({id:G.id,path:G.path,label:G.label})),[b]),g=(b==null?void 0:b.defaultWorkspaceId)||null,[y,x]=c.useState("workspace"),[N,j]=c.useState(""),[w,A]=c.useState(""),[M,S]=c.useState([]),[k,O]=c.useState(""),[P,I]=c.useState(!1),[W,K]=c.useState(null),[R,T]=c.useState(""),[C,F]=c.useState(Ai(f[0])),[L,D]=c.useState(""),[H,Q]=c.useState(""),[ge,ue]=c.useState([]),[Z,xe]=c.useState(""),[Se,be]=c.useState([]),[Y,he]=c.useState(!1),[ye,se]=c.useState(!1),[de,Ce]=c.useState(""),[pe,me]=c.useState(!1),[oe,fe]=c.useState(()=>Mt()),[ce,E]=c.useState(null),[z,le]=c.useState(!1),[re,q]=c.useState(""),[je,we]=c.useState(null),[Pe,Re]=c.useState(!1),[B,Ae]=c.useState(""),[Ee,Ve]=c.useState([]),[Ge,Ze]=c.useState(!1),[et,at]=c.useState(""),[gt,St]=c.useState(!1),jt=c.useRef(null),Me=c.useRef(0);c.useEffect(()=>{var G;!m&&((G=f[0])!=null&&G.id)&&v(f[0].id)},[m,f]),c.useEffect(()=>{!b||!(!b.workspaces||!b.availableProviders||!b.detectedIdes||!b.recentLaunches)||h(b.id,{minFreshMs:3e4}).catch(()=>{})},[h,b]);const qe=c.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(G=>qs(G,"cli")),[b]),st=c.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(G=>qs(G,"acp")),[b]),Xe=c.useMemo(()=>((b==null?void 0:b.detectedIdes)||[]).map(G=>({id:G.type,label:G.name||G.type,meta:G.running?"Detected locally":"Available to open"})),[b]),ot=c.useMemo(()=>C==="cli"?qe.map(G=>({id:G.type,label:G.displayName||G.type,meta:"CLI provider"})):C==="acp"?st.map(G=>({id:G.type,label:G.displayName||G.type,meta:"ACP provider"})):Xe,[st,C,qe,Xe]),U=c.useMemo(()=>M.find(G=>G.id===k)||null,[M,k]),V=c.useMemo(()=>qe.find(G=>G.type===L)||null,[qe,L]),J=c.useMemo(()=>fh(V==null?void 0:V.meshCoordinator,{meshId:(U==null?void 0:U.id)||"",workspace:(U==null?void 0:U.workspace)||""}),[V,U]),ne=je||J,$=c.useCallback(async G=>{I(!0),T("");try{const _e=await l(G);S(_e),O(_=>{var ie;return _e.some(ve=>ve.id===_)?_:((ie=_e[0])==null?void 0:ie.id)||""}),K(G)}catch(_e){S([]),O(""),K(G),T(_e instanceof Error?_e.message:"Could not load meshes")}finally{I(!1)}},[l]);c.useEffect(()=>{var _e;if(!b)return;if(jt.current!==b.id){jt.current=b.id,x("workspace"),j(g||((_e=p[0])==null?void 0:_e.id)||"__home__"),A(""),S([]),O(""),K(null),T(""),F(Ai(b)),D(""),Q(""),xe(""),be([]),se(!1),Ce(""),fe(Mt()),q(""),we(null);return}j(_=>{var ie;return _==="__custom__"||_==="__home__"||p.some(ve=>ve.id===_)?_:g||((ie=p[0])==null?void 0:ie.id)||"__home__"}),F(_=>_==="ide"&&Xe.length>0||_==="cli"&&qe.length>0||_==="acp"&&st.length>0?_:Ai(b))},[st.length,qe.length,g,Xe.length,b,p]),c.useEffect(()=>{!b||y!=="mesh"||W===b.id||P||$(b.id)},[$,W,P,b,y]),c.useEffect(()=>{y==="mesh"&&C!=="cli"&&qe.length>0&&F("cli")},[C,qe.length,y]),c.useEffect(()=>{var G;C&&(ot.some(_e=>_e.id===L)||D(((G=ot[0])==null?void 0:G.id)||""))},[C,ot,L]),c.useEffect(()=>{we(null)},[b==null?void 0:b.id,k,L,y]);const X=c.useCallback(async(G,_e)=>{const _=Me.current+1;return Me.current=_,he(!0),Ce(""),u(G,_e).then(ie=>{Me.current===_&&be(ie)}).catch(ie=>{Me.current===_&&(be([]),Ce(ie instanceof Error?ie.message:"Could not load saved sessions"))}).finally(()=>{Me.current===_&&(he(!1),se(!0))})},[u]),te=c.useCallback((G,_e)=>{ue(bo(G,_e))},[]);c.useEffect(()=>{Me.current+=1,xe(""),fe(Mt()),!b||!L||C==="ide"?ue([]):te(b.id,L),se(!1),be([]),Ce(""),he(!1)},[C,te,X,b,L]),c.useEffect(()=>{if(!Z)return;const G=Se.find(_e=>_e.providerSessionId===Z);G!=null&&G.canResume||xe("")},[Se,Z]);const ae=N==="__custom__"?w.trim():N==="__home__"?"":((ke=p.find(G=>G.id===N))==null?void 0:ke.path)||"",Ne=c.useMemo(()=>b?t.filter(G=>G.id!==b.id&&G.daemonId===b.id).map(G=>G.workspace):[],[t,b]),$e=c.useMemo(()=>((b==null?void 0:b.recentLaunches)||[]).map(G=>G.workspace),[b]),Be=c.useCallback(G=>{const _e=String(G.workspace||"").trim();if(!_e)return;const _=p.find(ie=>zn(ie.path)===zn(_e));if(_){j(_.id),A("");return}j("__custom__"),A(_e)},[p]),Ie=c.useCallback(G=>{const _e=String(G.workspace||"").trim();if(!_e)return{workspaceId:null,workspacePath:null};const _=p.find(ie=>zn(ie.path)===zn(_e));return _?{workspaceId:_.id,workspacePath:null}:{workspaceId:null,workspacePath:_e}},[p]),Oe=c.useMemo(()=>Se.find(G=>G.providerSessionId===Z)||null,[Se,Z]),We=c.useMemo(()=>{var _e;if(C!=="cli"||!b||!L)return null;const G=((_e=qe.find(_=>_.type===L))==null?void 0:_e.displayName)||L;return{routeId:b.id,daemonId:b.id,providerSessionId:Z||void 0,transport:"pty",mode:"chat",agentName:G,agentType:L,status:"idle",title:G,messages:[],ideType:L,workspaceName:ae,workspacePath:ae,displayPrimary:G,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${b.id}:${L}`,machineName:$t(b,{fallbackId:b.id})}},[C,qe,ae,b,Z,L]),Le=c.useCallback(()=>{var _e;if(!b)return;j("__custom__"),Re(!0),at("");const G=Ua(b.platform,Wa(w.trim(),ae,Ne,$e,b.defaultWorkspacePath,(_e=p.find(_=>_.id===g))==null?void 0:_e.path,p.map(_=>_.path)));Ze(!0),n(b.id,G).then(_=>{Ae(_.path),A(_.path),Ve(_.directories)}).catch(_=>{at(_ instanceof Error?_.message:"Could not load folder")}).finally(()=>Ze(!1))},[w,g,$e,Ne,n,ae,b,p]),tt=c.useCallback(G=>{b&&(Ze(!0),at(""),n(b.id,G).then(_e=>{Ae(_e.path),A(_e.path),Ve(_e.directories)}).catch(_e=>{at(_e instanceof Error?_e.message:"Could not load folder")}).finally(()=>Ze(!1)))},[n,b]),rt=c.useCallback(async()=>{if(!b||!ae)return;St(!0),q("");const G=await a(b.id,ae);if(St(!1),!G.ok){q(G.error||"Could not save workspace");return}q("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,ae,b]),pt=c.useCallback(async()=>{if(!b)return;if(y==="mesh"){if(!k||!L)return;le(!0),q(""),we(null);const _=await d(b.id,k,L);if(le(!1),!_.ok){if(_.code==="mesh_coordinator_manual_mcp_setup_required"&&_.manualSetup){we(_.manualSetup),q("Manual MCP setup required before this provider can act as mesh coordinator.");return}q(_.error||"Could not start mesh coordinator");return}r();return}if(!C||!L)return;le(!0),q("");const G=H.trim()?H.trim().split(/\s+/).filter(Boolean):[],_e=C==="ide"?await i(b.id,L,{workspacePath:ae||null}):await o(b.id,C,L,{workspaceId:N!=="__home__"&&N!=="__custom__"?N:null,workspacePath:N==="__custom__"&&ae||null,resumeSessionId:C==="cli"&&Z?Z:null,cliArgs:G});if(le(!1),!_e.ok){q(_e.error||"Could not start session");return}C!=="ide"&&H.trim()&&(Dh(b.id,L,H),te(b.id,L)),r()},[C,H,te,r,i,d,o,ae,b,k,Z,L,N,y]),bt=y==="mesh"?"Start mesh coordinator":C?Eu(C,C==="cli"&&!!Z):"Start",mt=y==="mesh"?"Starting coordinator…":C?Du(C,C==="cli"&&!!Z):"Starting…",At=f.length>5;return b?s.jsxs(s.Fragment,{children:[s.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:s.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:[s.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:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.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."})]}),s.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:s.jsx(It,{size:16})})]}),s.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:[s.jsx(na,{title:"Machine",children:At?s.jsx("select",{"aria-label":"Machine",value:b.id,onChange:G=>v(G.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:z,children:f.map(G=>s.jsx("option",{value:G.id,children:$t(G,{fallbackId:G.id})},G.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:f.map(G=>{const _e=$t(G,{fallbackId:G.id}),_=b.id===G.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${_e}`,"aria-pressed":_,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${_?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/60 text-text-secondary hover:bg-bg-secondary hover:text-text-primary"}`,onClick:()=>v(G.id),disabled:z,title:_e,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${G.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:_e})]},G.id)})})}),s.jsxs(na,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:y==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Le,disabled:z,children:"Browse…"}):void 0,children:[s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":"Launch target type",children:[{id:"workspace",label:"Workspace",desc:"Normal session"},{id:"mesh",label:"Mesh",desc:"Coordinator session"}].map(G=>s.jsxs("button",{type:"button",role:"radio","aria-checked":y===G.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${y===G.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{x(G.id),q(""),G.id==="mesh"&&b&&W!==b.id&&!P&&$(b.id)},disabled:z,children:[s.jsx("div",{className:"text-sm font-semibold",children:G.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:G.desc})]},G.id))}),y==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:N,onChange:G=>{const _e=G.target.value;j(_e),_e==="__custom__"?Le():q("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:z,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),p.map(G=>s.jsxs("option",{value:G.id,children:[G.id===g?"⭐ ":"",Da(G.path,G.label)||G.path]},G.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:N==="__home__"?"Launch without a workspace.":ae||"Select a workspace folder."}),N==="__custom__"&&ae&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Le,disabled:z,children:[s.jsx(zs,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:rt,disabled:z||gt,children:gt?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[P&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!P&&R&&s.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:R}),!P&&!R&&M.length===0&&s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker."}),M.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:M.map(G=>s.jsxs("button",{type:"button",role:"radio","aria-checked":k===G.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${k===G.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>O(G.id),disabled:z,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:G.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[G.repoIdentity||"Repo mesh",typeof G.nodesCount=="number"?` · ${G.nodesCount} node${G.nodesCount===1?"":"s"}`:""]}),G.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",G.workspace]})]},G.id))}),U&&s.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),s.jsx(pw,{workspaceMode:y,activeKind:C,cliEnabled:qe.length>0,ideEnabled:Xe.length>0,acpEnabled:st.length>0,busy:z,onSelect:F}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.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"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[ot.map(G=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${L===G.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>D(G.id),disabled:z,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:G.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:G.meta})]},G.id)),ot.length===0&&s.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."})]})]}),y==="mesh"&&ne&&s.jsx(Oh,{setup:ne,providerName:(V==null?void 0:V.displayName)||(V==null?void 0:V.name)||L}),y!=="mesh"&&C!=="ide"&&s.jsxs(na,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:H,onChange:G=>Q(G.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:z}),ge.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:ge.map(G=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>Q(G),disabled:z,title:G,children:G},G))})]}),y!=="mesh"&&C==="cli"&&s.jsx(Bh,{busy:z,savedSessionsLoading:Y,savedSessionsError:de,selectedSession:Oe,onRefresh:()=>{!b||!L||X(b.id,L)},onOpenHistory:()=>{!b||!L||(me(!0),$h({hasLoadedInitialResults:ye,isLoading:Y})&&X(b.id,L))},onClearSelection:()=>xe("")}),re&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${re.includes("saved")||re.includes("requested")||re.includes("Manual MCP setup")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:re})]}),s.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:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:r,disabled:z,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:pt,disabled:z||(y==="mesh"?!k||!L||C!=="cli"||P:!C||!L||N==="__custom__"&&!ae),children:[s.jsx(Fo,{size:14}),z?mt:bt]})]})]})}),Pe&&s.jsx(Ha,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:B,directories:Ee,busy:Ge,error:et,onClose:()=>Re(!1),onNavigate:tt,onConfirm:G=>{A(G),Ae(G),j("__custom__"),Re(!1)}}),pe&&We&&s.jsx(ic,{activeConv:We,ides:[],isCreatingChat:!1,isRefreshingHistory:Y,savedSessions:Se,isSavedSessionsLoading:Y,isResumingSavedSessionId:ce,savedHistoryFilters:oe,missingWorkspaceResumePath:ae||null,onSavedHistoryFiltersChange:fe,onClose:()=>me(!1),onNewChat:()=>{xe(""),me(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!b||!L||X(b.id,L)},onResumeSavedSession:G=>{if(!b||!L||ce||!G.canResume)return;const _e=Ie(G);xe(G.providerSessionId),Be(G),E(G.providerSessionId),me(!1),le(!0),q(""),o(b.id,"cli",L,{workspaceId:_e.workspaceId,workspacePath:_e.workspacePath,resumeSessionId:G.providerSessionId}).then(_=>{if(!_.ok){q(_.error||"Could not resume session");return}r()}).finally(()=>{le(!1),E(_=>_===G.providerSessionId?null:_)})}})]}):null}function mw(e,t){const{sendCommand:r}=Ct(),[n,a]=c.useState(null),[i,o]=c.useState(!1);c.useEffect(()=>{if(!e||!t){a(null);return}o(!0),r(e,"git_remote_url",{workspace:t}).then(d=>{const u=(d==null?void 0:d.result)??d;a(typeof(u==null?void 0:u.remoteUrl)=="string"?u.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>o(!1))},[e,t,r]);const l=xw(n);return{remoteUrl:n,githubUrl:l,loading:i}}function xw(e){if(!e)return null;const t=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(t)return`https://github.com/${t[1]}`;const r=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return r?`https://github.com/${r[1]}`:null}const Fh=5e3;function gw(e){return`git:${e}`}function bw({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Fh}){return{type:"subscribe",topic:"workspace.git",key:gw(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function yc(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Xs(e,t){if(e instanceof Error)return e.message;if(e&&typeof e=="object"){const r=e;if(typeof r.error=="string"&&r.error.trim())return r.error;if(typeof r.message=="string"&&r.message.trim())return r.message}return t}function yw(e){const t=yc(e);return(t==null?void 0:t.success)===!1?{status:null,error:Xs(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Xs(t,"Git status response did not include status")}}function vw(e){const t=yc(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Xs(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Xs(t,"Git diff summary response did not include diffSummary")}}function Mi(e){return e===void 0||typeof e=="boolean"}function ww(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Mi(t.binary)&&Mi(t.truncated)&&Mi(t.staged)}function Sw(e){const t=yc(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Xs(t,"Git file diff request failed")}:ww(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Xs(t,"Git file diff response did not include a valid diff object")}}function kw({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Fh}){const{sendCommand:i,sendData:o}=Ct(),l=typeof t=="string"?t.trim():"",d=!!(r&&e&&l),[u,h]=c.useState(null),[f,m]=c.useState(null),[v,b]=c.useState(!1),[p,g]=c.useState(null),y=c.useCallback(async()=>{if(!(!d||!e||!l)){b(!0),g(null);try{const N=yw(await i(e,"git_status",{workspace:l}));if(N.error){h(null),m(null),g(N.error);return}if(h(N.status),!n){m(null);return}const j=vw(await i(e,"git_diff_summary",{workspace:l}));if(j.error){m(null),g(j.error);return}m(j.diffSummary)}catch(N){g(Xs(N,"Git status request failed"))}finally{b(!1)}}},[d,e,n,i,l]),x=c.useMemo(()=>l?bw({workspace:l,includeDiffSummary:n,intervalMs:a}):null,[n,a,l]);return c.useEffect(()=>{if(!d||!e||!l||!x){h(null),m(null),b(!1),g(null);return}const N=o?os.subscribe({sendData:o},e,x,j=>{var w,A;j.workspace===l&&(h(j.status),m(j.diffSummary??null),g(((w=j.status)==null?void 0:w.error)||((A=j.diffSummary)==null?void 0:A.error)||null),b(!1))},{retryIntervalMs:1e3}):null;return y(),()=>{N==null||N()}},[d,e,y,x,o,l]),{status:u,diffSummary:f,loading:v,error:p,refresh:y}}const jw={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},Nw={added:"text-emerald-400",modified:"text-orange-400",deleted:"text-red-400",renamed:"text-sky-400",copied:"text-sky-400",untracked:"text-zinc-400",conflict:"text-red-400 font-bold"};function Yl(e){return e.split("/").pop()??e}function Cw(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function Tw({files:e,truncated:t,onFileClick:r,selectedPath:n,className:a=""}){return e.length===0?s.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:"No changed files."}):s.jsxs("div",{className:`flex flex-col ${a}`,children:[s.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(i=>{const o=n===i.path,l=jw[i.status]??"?",d=Nw[i.status]??"text-zinc-400",u=Cw(i.path),h=Yl(i.path),f=i.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${o?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(i),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:i.status,children:l}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[u&&s.jsxs("span",{className:"text-text-secondary",children:[u,"/"]}),s.jsx("span",{className:"text-text-primary",children:h}),i.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",Yl(i.oldPath)]}),f]}),!i.binary&&(i.insertions>0||i.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[i.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",i.insertions]}),i.insertions>0&&i.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),i.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",i.deletions]})]}),i.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${i.path}-${i.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function Iw(e,t){let r="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?r="bg-emerald-500/10 text-emerald-300":e.startsWith("-")&&!e.startsWith("---")?r="bg-red-500/10 text-red-300":e.startsWith("@@")?r="text-sky-400":(e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ "))&&(r="text-text-secondary"),s.jsx("div",{className:`px-3 ${r}`,children:s.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},t)}function Aw({diff:e,binary:t,truncated:r,loading:n,error:a,className:i=""}){const o=c.useRef(null);if(c.useEffect(()=>{o.current&&(o.current.scrollTop=0)},[e]),n)return s.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${i}`,children:"Loading diff…"});if(a)return s.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${i}`,children:a});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${i}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${i}`,children:"No diff available."});const l=e.split(`
65
+ `);return s.jsxs("div",{ref:o,className:`overflow-auto ${i}`,children:[s.jsx("div",{className:"py-1",children:l.map((d,u)=>Iw(d,u))}),r&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary border-t border-border/30",children:["Diff truncated — run ",s.jsx("code",{className:"font-mono",children:"git diff"})," locally for full output."]})]})}function Mw(e,t){const r=[`Branch: ${e||"unknown"}`];r.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const n={};for(const a of t.files)n[a.status]||(n[a.status]=[]),n[a.status].push(a.path);for(const[a,i]of Object.entries(n))r.push(`${a}: ${i.slice(0,5).join(", ")}${i.length>5?` (+${i.length-5} more)`:""}`);return r.join(`
66
+ `)}function Wh({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=Ct(),{status:a,diffSummary:i,loading:o,error:l,refresh:d}=kw({daemonId:e,workspace:t,includeDiffSummary:!0}),[u,h]=c.useState(null),[f,m]=c.useState(null),[v,b]=c.useState(""),[p,g]=c.useState(!1),[y,x]=c.useState(!1),[N,j]=c.useState(null),[w,A]=c.useState(null),{githubUrl:M}=mw(e,t),S=c.useCallback(async K=>{if(!((u==null?void 0:u.path)===K.path&&!u.loading)){h({path:K.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const R=await n(e,"git_diff_file",{workspace:t,path:K.path,staged:K.staged}),T=Sw(R);if(T.error||!T.diff){h({path:K.path,diff:"",binary:!1,truncated:!1,loading:!1,error:T.error??"Failed to load diff"});return}h({path:K.path,diff:T.diff.diff,binary:T.diff.binary??!1,truncated:T.diff.truncated??!1,loading:!1,error:null})}catch(R){const T=R instanceof Error?R.message:"Failed to load diff";h({path:K.path,diff:"",binary:!1,truncated:!1,loading:!1,error:T})}}},[e,n,u,t]),k=c.useCallback(K=>{b(""),g(!1),j(null),A(null),m(K)},[]),O=c.useCallback(()=>{m(null),j(null),x(!1)},[]),P=c.useCallback(async()=>{var K,R,T;if(f){x(!0),j(null);try{let C;f==="checkpoint"?C=await n(e,"git_checkpoint",{workspace:t,message:v,includeUntracked:p}):f==="stash"?C=await n(e,"git_stash_push",{workspace:t,message:v,includeUntracked:p}):f==="stash_pop"?C=await n(e,"git_stash_pop",{workspace:t}):f==="checkout_files"&&u&&(C=await n(e,"git_checkout_files",{workspace:t,paths:[u.path]}));const F=(C==null?void 0:C.result)??C;if((F==null?void 0:F.success)===!1||F!=null&&F.error){j((F==null?void 0:F.error)??"Action failed"),x(!1);return}f==="checkpoint"?A(`Checkpoint created: ${((R=(K=F==null?void 0:F.checkpoint)==null?void 0:K.commit)==null?void 0:R.slice(0,7))??"done"}`):f==="stash"?A(`Stashed as ${((T=F==null?void 0:F.stash)==null?void 0:T.stashRef)??"stash@{0}"}`):f==="stash_pop"?A("Stash restored"):(A("File reverted"),h(null)),m(null),await d()}catch(C){j(C instanceof Error?C.message:"Action failed")}finally{x(!1)}}},[f,n,e,t,v,p,u,d]),I=!!(a!=null&&a.hasConflicts),W=a?a.staged+a.modified+a.untracked+a.deleted+a.renamed:null;return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:K=>{K.target===K.currentTarget&&r()},children:s.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),M&&s.jsx("a",{href:`${M}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-sky-400 underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:d,disabled:o,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),s.jsx("button",{onClick:r,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(It,{className:"h-4 w-4"})})]}),a&&s.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[a.headCommit&&s.jsxs("span",{title:a.headMessage??void 0,children:[s.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&s.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&s.jsxs("span",{className:"text-orange-400",children:["↑",a.ahead," ahead"]}),a.behind>0&&s.jsxs("span",{className:"text-orange-400",children:["↓",a.behind," behind"]}),a.staged>0&&s.jsxs("span",{className:"text-emerald-400",children:[a.staged," staged"]}),a.modified>0&&s.jsxs("span",{children:[a.modified," modified"]}),a.untracked>0&&s.jsxs("span",{children:[a.untracked," untracked"]}),a.deleted>0&&s.jsxs("span",{className:"text-red-400",children:[a.deleted," deleted"]}),a.stashCount>0&&s.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&s.jsx("span",{className:"font-bold text-red-400",children:"conflicts"}),W===0&&!a.error&&s.jsx("span",{className:"text-emerald-500",children:"clean"}),i&&i.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[i.files.length," file",i.files.length!==1?"s":"",i.totalInsertions>0&&s.jsxs("span",{className:"text-emerald-500",children:[" +",i.totalInsertions]}),i.totalDeletions>0&&s.jsxs("span",{className:"text-red-400",children:[" -",i.totalDeletions]})]})]}),l&&s.jsx("div",{className:"shrink-0 border-b border-border/50 bg-red-500/10 px-4 py-2 text-xs text-red-400",children:l}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[o&&!i&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),i&&s.jsx(Tw,{files:i.files,truncated:i.truncated,selectedPath:(u==null?void 0:u.path)??null,onFileClick:S}),!o&&!i&&!l&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:u?s.jsx(Aw,{diff:u.diff,binary:u.binary,truncated:u.truncated,loading:u.loading,error:u.error,className:"h-full"}):s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),w&&s.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-emerald-500/10 px-4 py-2 text-xs text-emerald-400 flex items-center justify-between",children:[s.jsx("span",{children:w}),s.jsx("button",{onClick:()=>A(null),className:"ml-2 text-emerald-400 hover:text-text-primary",children:"×"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[s.jsx("button",{onClick:()=>k("checkpoint"),disabled:I,title:I?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),s.jsx("button",{onClick:()=>k("stash"),disabled:I,title:I?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),s.jsx("button",{onClick:()=>k("stash_pop"),disabled:I||!(a!=null&&a.stashCount),title:I?"Resolve conflicts before restoring a stash":a!=null&&a.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),s.jsx("button",{onClick:()=>k("checkout_files"),disabled:!u,title:u?`Revert changes to ${u.path}`:"Select a file to revert",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkout selected"}),i&&i.files.length>0&&s.jsx("button",{onClick:()=>{const K=Mw((a==null?void 0:a.branch)??null,i);navigator.clipboard.writeText(K),A("Copied to clipboard"),setTimeout(()=>A(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),f&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[f==="checkpoint"&&"Create checkpoint commit",f==="stash"&&"Stash changes",f==="stash_pop"&&"Restore latest stash?",f==="checkout_files"&&`Revert changes to ${(u==null?void 0:u.path)??"file"}?`]}),(f==="checkpoint"||f==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:v,onChange:K=>b(K.target.value),maxLength:200,placeholder:"Message (required)",className:"rounded border border-border bg-surface-alt px-2 py-1 text-xs text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-border",autoFocus:!0}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:p,onChange:K=>g(K.target.checked)}),"Include untracked files"]})]}),N&&s.jsx("p",{className:"text-xs text-red-400",children:N}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:O,disabled:y,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),s.jsx("button",{onClick:P,disabled:y||(f==="checkpoint"||f==="stash")&&!v.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:y?"Working…":"Confirm"})]})]})})]})})}function _w({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=c.useState(!1),[i,o]=c.useState(!1),[l,d]=c.useState(!1),[u,h]=c.useState(!1),[f,m]=c.useState(!1),[v,b]=c.useState("quickstart"),[p,g]=c.useState("workspace"),y=c.useMemo(()=>!t&&!e,[t,e]),x=c.useCallback(S=>{a(S),S&&o(!1)},[]),N=c.useCallback(S=>{o(S),S&&a(!1)},[]),j=c.useCallback(()=>{b(r===0?"quickstart":"shortcuts"),g("workspace"),d(!0),a(!1),o(!1)},[r]),w=c.useCallback(()=>{d(!1)},[]),A=c.useCallback(()=>{h(!0)},[]),M=c.useCallback(()=>{h(!1)},[]);return c.useEffect(()=>{if(!y){m(!1);return}m(!0);const S=window.setTimeout(()=>{m(!1)},1e4);return()=>window.clearTimeout(S)},[y]),{inboxOpen:n,hiddenOpen:i,shortcutHelpOpen:l,newSessionOpen:u,guideNudgeVisible:f,guideTab:v,shortcutSection:p,isDesktopDashboard:y,setGuideTab:b,setShortcutSection:g,handleInboxOpenChange:x,handleHiddenOpenChange:N,handleOpenShortcutHelp:j,closeShortcutHelp:w,openNewSession:A,closeNewSession:M}}function Rw(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 Pw(e){return e instanceof Error?e.message:String(e||"")}function Lw(e){const t=Pw(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Ew({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:i,onOpenRemote:o,onStopCli:l,activeCliViewMode:d,onSetActiveCliViewMode:u,mobileChatConversations:h,hiddenConversations:f,ides:m,actionLogs:v,sendDaemonCommand:b,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:y,initialDataLoaded:x,userName:N,requestedMobileTabKey:j,onRequestedMobileTabConsumed:w,requestedMachineId:A,onRequestedMachineConsumed:M,requestedMobileSection:S,onRequestedMobileSectionConsumed:k,containerRef:O,isSplitMode:P,numGroups:I,groupSizes:W,groupedConvs:K,clearedTabs:R,focusedGroup:T,focusGroup:C,moveTabToGroup:F,splitTabRelative:L,closeGroup:D,handleResizeStart:H,groupActiveTabIds:Q,setGroupActiveTab:ge,groupTabOrders:ue,setGroupTabOrder:Z,toggleHiddenTab:xe,visibleConversations:Se,requestedDesktopTabKey:be,onRequestedDesktopTabConsumed:Y,onDesktopActiveTabChange:he,onRequestScrollToBottom:ye,onHideConversation:se,onShowHiddenConversation:de,onShowAllHiddenConversations:Ce,scrollToBottomRequest:pe,machineEntries:me,layoutProfile:oe,onBrowseMachineDirectory:fe,onSaveMachineWorkspace:ce,onLaunchMachineIde:E,onLaunchMachineProvider:z,onListMachineMeshes:le,onLaunchMeshCoordinator:re,onListMachineSavedSessions:q,notifications:je,notificationUnreadCount:we,liveSessionInboxState:Pe,onMarkNotificationRead:Re,onMarkNotificationUnread:B,onDeleteNotification:Ae}){const Ee=Et.useRef(null),{inboxOpen:Ve,hiddenOpen:Ge,shortcutHelpOpen:Ze,newSessionOpen:et,guideNudgeVisible:at,guideTab:gt,shortcutSection:St,isDesktopDashboard:jt,setGuideTab:Me,setShortcutSection:qe,handleInboxOpenChange:st,handleHiddenOpenChange:Xe,handleOpenShortcutHelp:ot,closeShortcutHelp:U,openNewSession:V,closeNewSession:J}=_w({isMobile:t,showMobileChatMode:e,visibleConversationCount:Se.length}),[ne,$]=Et.useState(null),X=Et.useCallback((ke,G)=>{$({daemonId:ke,workspace:G})},[]),te=Et.useCallback(ke=>{var G;hn.flushSync(()=>{de(ke)}),(G=Ee.current)==null||G.restoreHiddenTabToSavedLocation(ke.tabKey)},[de]),ae=Et.useCallback(ke=>{var _e;const G=h.find(_=>io(_,ke))||f.find(_=>io(_,ke));G&&(f.some(_=>_.tabKey===G.tabKey)&&te(G),he(G.tabKey),(_e=Ee.current)==null||_e.activateConversationTab(G.tabKey),ye(G.tabKey,"notification-open")),Re(ke.id),st(!1)},[te,f,h,he,Re,ye]),Ne=Et.useCallback(()=>{var G;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((G=Ee.current)==null||G.resetAllPanelsToMain(),Xe(!1))},[Xe]),$e=Et.useCallback(async ke=>{var ve;if(!r)return;const G=(ve=r.modalButtons)==null?void 0:ve[ke];if(!G)return;const _e=gr(r);if(!_e)return;const _=G.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),ie=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(_);try{await b(_e,"resolve_action",{button:G,action:ie?"approve":"reject",buttonIndex:ke,...Ps(r)})}catch(Ue){Lw(Ue)||console.error("[Shortcut approval] Failed:",Ue)}},[r,b]),{isMac:Be,actionDefinitions:Ie,actionShortcuts:Oe,shortcutListening:We,shortcutListeningDraft:Le,setShortcutListening:tt,setShortcutListeningDraft:rt,saveShortcuts:pt}=X0({enabled:jt&&!Ze,onTrigger:ke=>{var G,_e,_,ie,ve,Ue,De,Ke,ut,Lt,yt,hs,Tn,In,An,Mn;if(ke==="openShortcutHelp"){ot();return}if(ke==="openNewSession"){V();return}if(ke==="hideCurrentTab"){r&&se(r);return}if(ke==="toggleHiddenTabs"){Xe(!Ge);return}if(ke==="openHistoryForActiveTab"){r&&!nt(r)&&i(r);return}if(ke==="openRemoteForActiveTab"){r&&!it(r)&&!nt(r)&&o(r);return}if(ke==="splitActiveTabRight"){(G=Ee.current)==null||G.splitActiveTabRight();return}if(ke==="splitActiveTabDown"){(_e=Ee.current)==null||_e.splitActiveTabDown();return}if(ke==="floatActiveTab"){(_=Ee.current)==null||_.floatActiveTab();return}if(ke==="popoutActiveTab"){(ie=Ee.current)==null||ie.popoutActiveTab();return}if(ke==="dockActiveTab"){(ve=Ee.current)==null||ve.dockActiveTab();return}if(ke==="focusLeftPane"){(Ue=Ee.current)==null||Ue.focusLeftPane();return}if(ke==="focusRightPane"){(De=Ee.current)==null||De.focusRightPane();return}if(ke==="focusUpPane"){(Ke=Ee.current)==null||Ke.focusUpPane();return}if(ke==="focusDownPane"){(ut=Ee.current)==null||ut.focusDownPane();return}if(ke==="moveActiveTabToLeftPane"){(Lt=Ee.current)==null||Lt.moveActiveTabToLeftPane();return}if(ke==="moveActiveTabToRightPane"){(yt=Ee.current)==null||yt.moveActiveTabToRightPane();return}if(ke==="moveActiveTabToUpPane"){(hs=Ee.current)==null||hs.moveActiveTabToUpPane();return}if(ke==="moveActiveTabToDownPane"){(Tn=Ee.current)==null||Tn.moveActiveTabToDownPane();return}if(ke==="triggerPrimaryApprovalAction"){$e(0);return}if(ke==="triggerSecondaryApprovalAction"){$e(1);return}if(ke==="triggerTertiaryApprovalAction"){$e(2);return}if(ke==="setActiveTabShortcut"){(In=Ee.current)==null||In.setShortcutForActiveTab();return}if(ke==="selectPreviousGroupTab"){(An=Ee.current)==null||An.activatePreviousTabInGroup();return}if(ke==="selectNextGroupTab"){(Mn=Ee.current)==null||Mn.activateNextTabInGroup();return}!r||!it(r)||nt(r)||ke==="toggleCliView"&&u(d==="chat"?"terminal":"chat")}}),bt=Et.useCallback(()=>{U(),tt(null),rt([])},[U,tt,rt]),mt=Et.useMemo(()=>St==="all"?Ie:Ie.filter(ke=>Rw(ke)===St),[Ie,St]),At=Et.useCallback(()=>{const ke=Object.fromEntries(Ie.map(G=>[G.id,""]));pt(ke)},[Ie,pt]),Ye=Et.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const ke=Object.fromEntries(Ie.map(G=>[G.id,G.defaultShortcut]));pt(ke)},[Ie,pt]);return Et.useEffect(()=>{const ke=G=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?G.metaKey&&G.key.toLowerCase()==="w":G.ctrlKey&&G.key.toLowerCase()==="w")&&(G.preventDefault(),r&&se&&se(r))};return window.addEventListener("keydown",ke),()=>window.removeEventListener("keydown",ke)},[r,se]),Et.useEffect(()=>{if(!Ze||We)return;const ke=G=>{G.key==="Escape"&&(G.preventDefault(),bt())};return window.addEventListener("keydown",ke,!0),()=>window.removeEventListener("keydown",ke,!0)},[bt,Ze,We]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(Vb,{activeConv:r,wsStatus:n,isConnected:a,conversations:Se,hiddenConversations:f,onOpenHistory:i,onHideConversation:se,onShowConversation:te,onShowAllHidden:Ce,onResetPanelsToMain:Ne,notifications:je,notificationUnreadCount:we,onOpenNotification:ae,onMarkNotificationRead:Re,onMarkNotificationUnread:B,onDeleteNotification:Ae,inboxOpen:Ve,onInboxOpenChange:st,hiddenOpen:Ge,onHiddenOpenChange:Xe,onOpenNewSession:t?void 0:V,onOpenDashboardGuide:ot,guideNudgeVisible:at,actionShortcuts:Oe,onOpenRemote:()=>{!r||it(r)||nt(r)||o(r)},onStopCli:l,activeCliViewMode:d,onSetCliViewMode:u,onOpenGitDialog:X}),e?s.jsx($0,{conversations:h,hiddenConversations:f,ides:m,actionLogs:v,sendDaemonCommand:b,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:y,userName:N,requestedActiveTabKey:j,onRequestedActiveTabConsumed:w,requestedMachineId:A,onRequestedMachineConsumed:M,requestedMobileSection:S,onRequestedMobileSectionConsumed:k,onOpenHistory:i,onOpenRemote:o,onStopCli:l,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Ce,onHideConversation:se,onOpenNewSession:V,liveSessionInboxState:Pe}):t?s.jsx(z0,{containerRef:O,isSplitMode:P,numGroups:I,groupSizes:W,groupedConvs:K,clearedTabs:R,ides:m,actionLogs:v,sendDaemonCommand:b,setActionLogs:p,isStandalone:y,hasRegisteredMachines:me.length>0,userName:N,focusedGroup:T,focusGroup:C,moveTabToGroup:F,splitTabRelative:L,closeGroup:D,handleResizeStart:H,groupActiveTabIds:Q,setGroupActiveTab:ge,groupTabOrders:ue,setGroupTabOrder:Z,toggleHiddenTab:xe,onOpenNewSession:V,allowTabShortcuts:!1,liveSessionInboxState:Pe}):s.jsx(lw,{visibleConversations:Se,clearedTabs:R,ides:m,actionLogs:v,sendDaemonCommand:b,setActionLogs:p,isStandalone:y,hasRegisteredMachines:me.length>0,initialDataLoaded:x,userName:N,toggleHiddenTab:xe,actionShortcuts:Oe,registerActionHandlers:ke=>{Ee.current=ke},onActiveTabChange:he,requestedActiveTabKey:be,onRequestedActiveTabConsumed:Y,onRequestScrollToBottom:ye,scrollToBottomRequest:pe,onOpenNewSession:V,liveSessionInboxState:Pe,layoutProfile:oe}),et&&s.jsx(fw,{machines:me,ides:m,onClose:J,onBrowseDirectory:fe,onSaveWorkspace:ce,onLaunchIde:E,onLaunchProvider:z,onListMeshes:le,onLaunchMeshCoordinator:re,onListSavedSessions:q}),ne&&s.jsx(Wh,{daemonId:ne.daemonId,workspace:ne.workspace,onClose:()=>$(null)}),Ze&&s.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:bt,children:s.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:ke=>ke.stopPropagation(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),s.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."})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:bt,"aria-label":"Close dashboard guide",children:s.jsx(It,{size:14})})]}),s.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(ke=>s.jsx("button",{type:"button",className:`btn btn-sm ${gt===ke.id?"btn-primary":"btn-secondary"}`,onClick:()=>Me(ke.id),children:ke.label},ke.id))}),gt==="overview"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Be?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),gt==="quickstart"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),s.jsxs("div",{children:[s.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."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.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."]})]})]})]}),gt==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.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(ke=>s.jsx("button",{type:"button",className:`btn btn-sm ${St===ke.id?"btn-primary":"btn-secondary"}`,onClick:()=>qe(ke.id),children:ke.label},ke.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:At,children:"Disable all"}),s.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:Ye,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:mt.map(ke=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${We===ke.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:ke.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ke.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:ke.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.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===ke.id?Le.length>0?`${Le.join(" ")} ...`:"Listening...":Oe[ke.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{tt(ke.id),rt([])},children:We===ke.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const G={...Oe};G[ke.id]="",pt(G)},children:"Disable"})]})]})},ke.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Be?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",", or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs."]})]})]})})]})}const _i=[{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 Dw({onClose:e}){const[t,r]=c.useState(0),n=_i[t],a=t===_i.length-1;return s.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:[s.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:[s.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:s.jsx(It,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:_i.map((i,o)=>s.jsx("div",{style:{width:o===t?24:8,height:8,borderRadius:4,background:o===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},o))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx("span",{children:n.icon})," ",n.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&s.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:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&s.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 →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>a?e():r(i=>i+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
67
+ @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
68
+ @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
69
+ `})]})}function $w({hasExtensions:e,ideName:t,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?s.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[s.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:t}),n.map(i=>{const o=r===i.tabKey,l=i.status==="waiting_approval",d=i.status==="generating";return s.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 ${o?"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:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),i.title,l&&s.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 Bw({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[i,o]=c.useState(()=>a||"native"),l=c.useMemo(()=>Bu(t),[t]),d=c.useMemo(()=>e?oc(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),u=c.useMemo(()=>d.find(p=>p.streamSource==="native"),[d]),h=c.useMemo(()=>d.filter(p=>p.streamSource==="agent-stream"),[d]),f=c.useMemo(()=>e?Xt(d,e.id):null,[d,e]);c.useEffect(()=>{a&&o(a)},[a]),c.useEffect(()=>{if(a||!f)return;const p=f.streamSource==="native"?"native":f.tabKey;!p||i===p||i==="native"&&o(p)},[i,f,a]),c.useEffect(()=>{var p;i!=="native"&&(h.some(g=>g.tabKey===i)||o(((p=h[0])==null?void 0:p.tabKey)||"native"))},[i,h]),c.useEffect(()=>{i==="native"&&(u||h[0]&&o(h[0].tabKey))},[i,u,h]);const m=c.useMemo(()=>i==="native"&&u?u:h.find(p=>p.tabKey===i)||f||u||h[0],[i,u,f,h]),v=c.useMemo(()=>h.map(p=>({tabKey:p.tabKey,title:_u(p)||n,status:p.status})),[h,n]),b=c.useCallback(p=>{if(p)return d.find(g=>io(g,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[d]);return{activeChatTab:i,setActiveChatTab:o,activeConv:m,conversations:d,extensionTabs:v,hasExtensions:v.length>0,resolveConversationByTarget:b}}function Ow({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:i,setActionLogs:o,isStandalone:l,userName:d,onOpenHistory:u,onConversationChange:h,onClose:f}){const[m,v]=c.useState("split"),[b,p]=c.useState(()=>vs(e)?"native":e.tabKey),g=c.useRef(null),y=c.useMemo(()=>t||r.find(C=>C.id===e.routeId),[e.routeId,t,r]),x=c.useMemo(()=>ht((y==null?void 0:y.type)||""),[y==null?void 0:y.type]),{conversations:N,extensionTabs:j,hasExtensions:w}=Bw({ideData:y,allIdes:r,connectionStates:n,ideName:x||"IDE",preferredTabKey:vs(e)?void 0:e.tabKey}),A=c.useMemo(()=>y?Xt(N,y.id):null,[y,N]);c.useEffect(()=>{const C=g.current,F={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(g.current=F,!(C&&C.routeId===F.routeId&&C.tabKey===F.tabKey&&C.streamSource===F.streamSource)){if(vs(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),c.useEffect(()=>{if(b==="native"){if(N.some(C=>C.streamSource==="native"))return;(A==null?void 0:A.streamSource)==="agent-stream"&&p(A.tabKey);return}if(!N.some(C=>C.tabKey===b)){if((A==null?void 0:A.streamSource)==="agent-stream"){p(A.tabKey);return}p("native")}},[N,b,A]);const M=c.useMemo(()=>b==="native"?N.find(C=>C.streamSource==="native")||e:N.find(C=>C.tabKey===b)||e,[e,N,b]),S=Ju(M),k=c.useMemo(()=>S.status||S.modalMessage||S.modalButtons?{...M,...S.status?{status:S.status}:{},...S.modalMessage!==void 0?{modalMessage:S.modalMessage}:{},...S.modalButtons!==void 0?{modalButtons:S.modalButtons}:{}}:M,[M,S]),O=Sn(k),P=Ba({sendDaemonCommand:i,activeConv:k,setActionLogs:o,isStandalone:l}),{connScreenshot:I,screenshotUsage:W,handleRemoteAction:K}=Ch({doId:O,targetSessionId:fu(k),connState:k.connectionState||"new",viewMode:m}),R=c.useMemo(()=>a.filter(C=>C.routeId===k.tabKey),[a,k.tabKey]);c.useEffect(()=>{h==null||h(k)},[k,h]),c.useEffect(()=>{const C=F=>{F.key==="Escape"&&f()};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[f]);const T=c.useCallback(C=>{C.stopPropagation()},[]);return s.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:f,children:s.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:T,children:[s.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:[s.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:s.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:[s.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Bt,{size:16})}),s.jsx("span",{className:"truncate",children:Xo(M)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:f,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(C=>{const F=m===C;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${F?"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(C),title:C==="split"?"Split view":"Remote only",children:C==="split"?s.jsx(jm,{size:15}):s.jsx(Bt,{size:15})},C)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>u(M),title:"Chat History",children:[s.jsx($o,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:f,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${m==="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:[m!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${m==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx($w,{hasExtensions:w,ideName:x||"IDE",activeChatTab:b,extensionTabs:j,onSelectTab:p}),s.jsx(eu,{activeConv:k,onModalButton:P.handleModalButton}),s.jsx(co,{activeConv:k,ideEntry:y,showMetaChips:!1,handleSendChat:P.handleSendChat,isSendingChat:P.isSendingChat,sendFeedbackMessage:P.sendFeedbackMessage,handleFocusAgent:P.handleFocusAgent,isFocusingAgent:P.isFocusingAgent,actionLogs:R,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${m==="split"?"order-1 md:order-2":""}`,children:s.jsx(Qd,{addLog:()=>{},connState:k.connectionState||"new",connScreenshot:I,screenshotUsage:W,transportType:k.transport,onAction:K})})]})]})})}function Fw({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=Eb(e);return s.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:[s.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.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:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[s.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",i,"?"]}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:t?"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."})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&s.jsx("button",{onClick:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),s.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"}),s.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function Ww({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:i}){var o;return s.jsxs(s.Fragment,{children:[s.jsx(Fb,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(ic,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,missingWorkspaceResumePath:e.missingWorkspaceResumePath,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),t.conversation&&s.jsx(Ow,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose}),r.open&&r.targetConv&&(it(r.targetConv)||nt(r.targetConv))&&s.jsx(Fw,{activeConv:r.targetConv,canSaveAndStop:it(r.targetConv)&&!nt(r.targetConv)&&!!((o=r.targetConv.resume)!=null&&o.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx($u,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),i.open&&s.jsx(Dw,{onClose:i.onClose})]})}function Uw({daemons:e,targetVersion:t,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:i}){return e.length===0?null:s.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:[s.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:s.jsx(vn,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[r?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(o=>{const l=$t(o,{fallbackId:o.id}),d=n[o.id],u=o.version||o.daemonVersion||"unknown",h=o.versionUpdateRequired===!0,m=uh(o)==="preview"?"Update to preview":h?"Update now":"Upgrade";return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:h?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${h?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:l}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",u]}),h&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),d==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:h?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):d==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(o.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:h?"var(--status-danger)":"var(--status-warning)",background:h?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${h?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(o.id),children:m})]},o.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:s.jsx(It,{size:16})})]})}function Kw(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function Hw(e){const t=e.machine;return typeof(t==null?void 0:t.cpus)!="number"||typeof(t==null?void 0:t.totalMem)!="number"||typeof(t==null?void 0:t.arch)!="string"||typeof(t==null?void 0:t.release)!="string"}function zw(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>Hw(t)).map(t=>t.id)}}function Vw(){var Fc,Wc,Uc,Kc;const{sendCommand:e}=Ct(),t=kn(),r=Yu(),n=Po(),a=Nr(),[i,o]=Rf(),l=i.get("activeTab"),d=((Fc=n.state)==null?void 0:Fc.openRemoteForTabKey)||null,u=((Wc=n.state)==null?void 0:Wc.openMachineId)||null,h=((Uc=n.state)==null?void 0:Uc.mobileSection)||null,f=Tu(),m=f.ides||[],v=f.initialLoaded??!0,{updateRouteChats:b,setToasts:p}=f,[g,y]=c.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),x=f.toasts||[],N=f.wsStatus||"connected",j=f.isConnected??!0,w=f.connectionStates||{},A=f.showReconnected||!1,{layoutProfile:M,groupAssignments:S,updateGroupAssignments:k,focusedGroup:O,updateFocusedGroup:P,focusGroup:I,groupActiveTabIds:W,updateGroupActiveTabIds:K,setGroupActiveTab:R,groupTabOrders:T,updateGroupTabOrders:C,setGroupTabOrder:F,groupSizes:L,updateGroupSizes:D,isMobile:H,hasHydratedStoredLayout:Q,hydrateStoredLayout:ge,focusConversationTab:ue}=_v(),[Z,xe]=c.useState(()=>uc());c.useEffect(()=>Ky(xe),[]);const Se=c.useMemo(()=>Kw({isMobile:H,mobileViewMode:Z}),[H,Z]),[be,Y]=c.useState([]),[he,ye]=c.useState({}),[se,de]=c.useState({});wn("Dashboard",{ideCount:m.length,toastCount:x.length,focusedGroup:O,groupCount:Object.keys(S).length,actionLogCount:be.length});const Ce=c.useMemo(()=>m.filter(Qe=>Qe.type==="adhdev-daemon").sort(Vo),[m]),pe=Ce[0],me=!!pe;c.useEffect(()=>{const{metadataDaemonIds:Qe,runtimeDaemonIds:zt}=zw(Ce);for(const Rr of Qe)t(Rr,{minFreshMs:3e4}).catch(()=>{});for(const Rr of zt)r(Rr,{minFreshMs:3e4}).catch(()=>{})},[t,r,Ce]);const oe=(pe==null?void 0:pe.terminalBackend)||null,fe=pe?$t(pe,{fallbackId:pe.id}):null,ce=(pe==null?void 0:pe.id)||null,E=c.useMemo(()=>rv(m,he),[m,he]),{hiddenTabs:z,autoHiddenTabs:le,autoHideTarget:re,hideTarget:q,toggleTarget:je,showTarget:we,showAllTabs:Pe}=sv(),{conversations:Re,visibleConversations:B,visibleTabKeys:Ae,resolveConversationBySessionId:Ee,resolveConversationByTarget:Ve}=xv({ides:E,connectionStates:w,clearedTabs:se,hiddenTabs:z}),Ge=c.useMemo(()=>new Map(Re.map(Qe=>[Qe.tabKey,Qe])),[Re]),Ze=c.useMemo(()=>tv(Re,z,le),[Re,z,le]);c.useEffect(()=>{for(const Qe of Ze)re(Qe)},[Ze,re]),hb(B,Se),c.useEffect(()=>{Object.keys(he).length!==0&&ye(Qe=>nv(Qe,m))},[m,he]);const et=c.useMemo(()=>vx(m),[m]),{notifications:at,unreadCount:gt}=Gv({conversations:Re,liveSessionInboxState:et}),{handleMarkDashboardNotificationRead:St,handleMarkDashboardNotificationUnread:jt,handleDeleteDashboardNotification:Me}=qv({notifications:at,sendDaemonCommand:e}),{containerRef:qe,normalizedGroupAssignments:st,numGroups:Xe,isSplitMode:ot,groupedConvs:U,moveTabToGroup:V,closeGroup:J,handleResizeStart:ne,splitTabRelative:$}=Bv({groupAssignments:S,updateGroupAssignments:k,updateFocusedGroup:P,updateGroupActiveTabIds:K,updateGroupTabOrders:C,groupSizes:L,updateGroupSizes:D,isMobile:H,visibleConversations:B,visibleTabKeys:Ae}),{activeConv:X,openDesktopConversation:te,requestScrollToBottom:ae,scrollToBottomRequest:Ne,setDesktopActiveTab:$e}=l0({isMobile:H,conversations:Re,visibleConversations:B,groupActiveTabIds:W,focusedGroup:O,groupedConvs:U,setSearchParams:o});h0({activeConv:X,isMobile:H,liveSessionInboxState:et,sendDaemonCommand:e});const{requestedDesktopTabKey:Be,requestedMobileTabKey:Ie,consumeRequestedActiveTab:Oe}=gv({isMobile:H,urlActiveTab:l,resolveConversationBySessionId:Ee,setSearchParams:o}),{remoteDialogConv:We,remoteDialogIdeEntry:Le,remoteDialogActiveConv:tt,setRemoteDialogActiveConv:rt,openRemoteDialog:pt,closeRemoteDialog:bt,cliStopDialogOpen:mt,cliStopTargetConv:At,requestCliStop:Ye,cancelCliStop:ke,confirmCliStop:G}=m0({isMobile:H,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:Be,conversations:Re,ides:m,resolveConversationByTarget:Ve,activeConv:X,sendDaemonCommand:e}),{historyModalOpen:_e,openHistoryModal:_,closeHistoryModal:ie,historyTargetConv:ve,isSavedSessionHistoryTarget:Ue,isHistoryCreatingChat:De,isHistoryRefreshingHistory:Ke,handleHistorySwitchSession:ut,handleHistoryNewChat:Lt,handleHistoryRefresh:yt,savedHistorySessions:hs,savedHistoryFilters:Tn,setSavedHistoryFilters:In,missingWorkspaceResumePath:An,isSavedHistoryLoading:Mn,resumingSavedHistorySessionId:Zp,handleRefreshSavedHistory:ef,handleResumeSavedHistorySession:tf}=p0({activeConv:X,remoteDialogConv:We,remoteDialogActiveConv:tt,ides:m,sendDaemonCommand:e,updateRouteChats:b,setToasts:p,setClearedTabs:de,setSearchParams:o}),sf=c.useMemo(()=>B,[B]),_n=H&&Z==="chat",rf=c.useMemo(()=>Re.filter(Qe=>Fa(z,Qe)),[Re,z]),$c=c.useCallback(Qe=>{const zt=new URLSearchParams(i);zt.set("activeTab",Qe),o(zt,{replace:!0})},[i,o]),{trackPendingLaunch:nf}=a0({ides:m,conversations:Re,onOpenSession:$c}),{handleBrowseMachineDirectory:af,handleSaveMachineWorkspace:of,handleLaunchMachineIde:cf,handleLaunchMachineProvider:lf,handleListMachineMeshes:df,handleLaunchMeshCoordinator:uf,handleListMachineSavedSessions:hf,setActiveCliViewMode:pf}=i0({sendDaemonCommand:e,trackPendingLaunch:nf,onOpenSession:$c,activeConv:X,ides:m,setCliViewModeOverrides:ye});av({visibleConversations:B,clearedTabs:se,setClearedTabs:de,setActionLogs:Y}),bv({ides:m,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Ve});const{isRefreshingHistory:ff,handleRefreshHistory:mf}=dh({sendDaemonCommand:e,activeConv:X,chats:(Kc=m.find(Qe=>Qe.id===(X==null?void 0:X.routeId)))==null?void 0:Kc.chats,updateRouteChats:b,setToasts:p,setClearedTabs:de});Pv({urlActiveTab:H&&!_n?l:null,conversations:Re,resolveConversationBySessionId:Ee,normalizedGroupAssignments:st,hasHydratedStoredLayout:H&&!_n?Q:!0,hydrateStoredLayout:H&&!_n?ge:()=>{},focusConversationTab:ue,setSearchParams:o,historyModalOpen:_e,activeConv:X,isRefreshingHistory:ff,ides:m,handleRefreshHistory:mf});const xf=c.useMemo(()=>!X||!it(X)||nt(X)?null:Tr(X),[X]),{versionMismatchDaemons:gf,hasRequiredVersionDaemons:Bc,targetVersion:bf,versionBannerDismissed:yf,setVersionBannerDismissed:vf,upgradingDaemons:wf,handleBannerUpgrade:Sf}=Fv({ides:m,sendDaemonCommand:e}),Oc=c.useCallback(Qe=>{we(Qe),te(Qe)},[te,we]),kf=c.useCallback(Qe=>{q(Qe)},[q]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[s.jsx(Wb,{terminalBackend:oe,isStandalone:me,machineLabel:fe,machineKey:ce}),(!yf||Bc)&&s.jsx(Uw,{daemons:gf,targetVersion:bf,required:Bc,upgradingDaemons:wf,onUpgrade:Sf,onDismiss:()=>vf(!0)}),s.jsx(Ew,{showMobileChatMode:_n,isMobile:H,activeConv:X,wsStatus:N,isConnected:j,onOpenHistory:Qe=>{Qe&&rt(Qe),_()},onOpenRemote:pt,onStopCli:Ye,activeCliViewMode:xf,onSetActiveCliViewMode:pf,mobileChatConversations:sf,ides:m,actionLogs:be,sendDaemonCommand:e,setActionLogs:Y,setCliViewModeOverrides:ye,isStandalone:me,initialDataLoaded:v,userName:f.userName,requestedMobileTabKey:Ie,onRequestedMobileTabConsumed:Oe,requestedMachineId:u,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:h,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:qe,isSplitMode:ot,numGroups:Xe,groupSizes:L,groupedConvs:U,clearedTabs:se,focusedGroup:O,focusGroup:I,moveTabToGroup:V,splitTabRelative:$,closeGroup:J,handleResizeStart:ne,groupActiveTabIds:W,setGroupActiveTab:R,groupTabOrders:T,setGroupTabOrder:F,toggleHiddenTab:Qe=>je(Ge.get(Qe)||{tabKey:Qe}),visibleConversations:B,hiddenConversations:rf,requestedDesktopTabKey:Be,onRequestedDesktopTabConsumed:Oe,onDesktopActiveTabChange:$e,onRequestScrollToBottom:ae,onHideConversation:kf,onShowHiddenConversation:Oc,onShowAllHiddenConversations:Pe,scrollToBottomRequest:Ne,machineEntries:Ce,layoutProfile:M,onBrowseMachineDirectory:af,onSaveMachineWorkspace:of,onLaunchMachineIde:cf,onLaunchMachineProvider:lf,onListMachineMeshes:df,onLaunchMeshCoordinator:uf,onListMachineSavedSessions:hf,notifications:at,notificationUnreadCount:gt,liveSessionInboxState:et,onMarkNotificationRead:St,onMarkNotificationUnread:jt,onDeleteNotification:Me}),s.jsx("style",{children:`
70
+ body { overflow: hidden; overscroll-behavior: none; }
71
+ `}),s.jsx(Ww,{historyModal:{open:_e,targetConv:ve,ides:m,isCreatingChat:De,isRefreshingHistory:Ue?!1:Ke,savedSessions:hs,savedHistoryFilters:Tn,missingWorkspaceResumePath:An||null,onSavedHistoryFiltersChange:In,isSavedSessionsLoading:Mn,isResumingSavedSessionId:Zp,onClose:ie,onNewChat:Lt,onSwitchSession:ut,onRefreshHistory:Ue?ef:yt,onResumeSavedSession:tf},remoteDialog:{conversation:We,ideEntry:Le,ides:m,connectionStates:w,actionLogs:be,sendDaemonCommand:e,setActionLogs:Y,isStandalone:me,userName:f.userName,onOpenHistory:Qe=>{Qe&&rt(Qe),_()},onConversationChange:rt,onClose:bt},cliStopDialog:{open:mt,targetConv:At,onCancel:ke,onStopNow:async()=>{await G("hard")},onSaveAndStop:async()=>{await G("save")}},connectionBanner:{wsStatus:N,showReconnected:A,loginUrl:f.connectionLoginUrl,onReconnect:f.retryServerConnection},toastOverlay:{toasts:x,onDismiss:Qe=>p(zt=>zt.filter(Rr=>Rr.id!==Qe)),onClick:Qe=>{if(Qe.targetKey){const zt=Ve(Qe.targetKey);zt&&(ue(zt.tabKey,st),Oc(zt),ae(zt.tabKey,"toast-open"))}}},onboarding:{open:g,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}y(!1)}}})]})}function Gw({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,o]=c.useState([]),[l,d]=c.useState(null),[u,h]=c.useState(null),[f,m]=c.useState(!1),[v,b]=c.useState(null),[p,g]=c.useState(!1),[y,x]=c.useState(""),N=c.useRef(null),j=c.useCallback(L=>{N.current=L},[]),w=c.useCallback((L,D,H=!1)=>{o(Q=>[...Q.slice(-100),{timestamp:Date.now(),level:L,message:D}]),setTimeout(()=>{var Q;return(Q=a.current)==null?void 0:Q.scrollIntoView({behavior:"smooth"})},100),H&&ct.showToast(D,L==="error"||L==="warn"?"warning":"success")},[a]),A=c.useCallback(L=>{const D=L instanceof Error?L.message:String(L||"");return D.includes("P2P command timeout")||D.includes("P2P not connected")||D.includes("P2P not available")},[]),M=c.useCallback(async(L,D)=>{var H;if(!e||l)return!1;d(L),w("info",`Launching ${ht(L)}${D!=null&&D.workspace?` in ${D.workspace}`:""}...`);try{const Q={ideType:L,enableCdp:!0};(H=D==null?void 0:D.workspace)!=null&&H.trim()?Q.workspace=D.workspace.trim():D!=null&&D.useDefaultWorkspace&&(Q.useDefaultWorkspace=!0);const ge=await r(e,"launch_ide",Q);return w(ge!=null&&ge.success?"info":"error",ge!=null&&ge.success?`${ht(L)} launched`:`Failed: ${ge==null?void 0:ge.error}`,!0),!!(ge!=null&&ge.success)}catch(Q){return w("error",`Launch error: ${Q.message}`,!0),!1}finally{d(null)}},[e,l,w,r]),S=c.useCallback(async L=>{if(!e)return{success:!1};const{cliType:D,dir:H,workspaceId:Q,useDefaultWorkspace:ge,useHome:ue,argsStr:Z,model:xe,resumeSessionId:Se}=L;if(!D)return w("warn","Select a CLI or ACP provider first",!0),{success:!1};const be=Z?Z.split(/\s+/).filter(Boolean):void 0,Y=(H==null?void 0:H.trim())||(Q?"(saved id)":ge?"(default workspace)":ue?"(home)":"");w("info",`Launching ${D}${Y?` in ${Y}`:""}${xe?` (model: ${xe})`:""}...`),h(D);try{const he={cliType:D,cliArgs:be,initialModel:xe||void 0};H!=null&&H.trim()?he.dir=H.trim():Q?he.workspaceId=Q:ge?he.useDefaultWorkspace=!0:ue&&(he.useHome=!0),Se&&(he.resumeSessionId=Se);const ye=await r(e,"launch_cli",he),se=(ye==null?void 0:ye.result)||ye;return ye!=null&&ye.success?(w("info",`${D} launched`,!0),(se==null?void 0:se.launchSource)==="home"?w("info","📂 Running in home directory (explicit choice)"):(se==null?void 0:se.launchSource)==="defaultWorkspace"&&w("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:se==null?void 0:se.sessionId}):(w("error",`Failed: ${(ye==null?void 0:ye.error)||(se==null?void 0:se.error)}`,!0),(ye==null?void 0:ye.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&b({cliType:D,argsStr:Z,model:xe}),{success:!1,sessionId:se==null?void 0:se.sessionId})}catch(he){return A(he)?(w("warn",`${D} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(w("error",`Launch error: ${he.message}`,!0),{success:!1})}finally{h(null)}},[e,w,A,r]),k=c.useCallback(async(L,D,H,Q)=>e?L?D.trim()?S({cliType:L,dir:D,argsStr:H,model:Q}):(b({cliType:L,argsStr:H,model:Q}),{success:!1}):(w("warn","Select a provider",!0),{success:!1}):{success:!1},[e,w,S]),O=c.useCallback(async(L,D,H)=>{if(e&&window.confirm(`Stop ${L}?
72
+ This will terminate the process.`))try{const Q=await r(e,"stop_cli",{cliType:L,dir:D,targetSessionId:H});Q!=null&&Q.success?w("info",`${L} stopped`,!0):w("error",`Stop failed: ${(Q==null?void 0:Q.error)||"Unknown error"}`,!0)}catch(Q){w("error",`Stop failed: ${Q.message}`,!0)}},[e,w,r]),P=c.useCallback(async L=>{try{await r(L.daemonId,"restart_ide",{ideType:L.type}),w("info",`${ht(L.type)} restart initiated`,!0)}catch(D){w("error",`Restart failed: ${D.message}`,!0)}},[w,r]),I=c.useCallback(async L=>{if(window.confirm(`Stop ${ht(L.type)}?
73
+ This will disconnect CDP and optionally kill the process.`))try{const D=await r(L.daemonId,"stop_ide",{ideType:L.type,killProcess:!0});D!=null&&D.success?w("info",`${ht(L.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]),W=c.useCallback(async()=>{if(e)try{const L=await r(e,"detect_ides",{});w("info",`Found ${((L==null?void 0:L.result)||[]).length} IDE(s)`,!0)}catch(L){w("error",`Detection failed: ${L.message}`,!0)}},[e,w,r]),K=c.useCallback(async L=>{if(!e||!L.trim())return!1;m(!0);try{const D=await r(e,"workspace_add",{path:L.trim()});return D!=null&&D.success?(w("info",`Workspace added: ${L.trim()}`),!0):(w("error",(D==null?void 0:D.error)||"workspace_add failed"),!1)}catch(D){return w("error",D.message),!1}finally{m(!1)}},[e,w,r]),R=c.useCallback(async L=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){m(!0);try{const D=await r(e,"workspace_remove",{id:L});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{m(!1)}}},[e,w,r]),T=c.useCallback(async L=>{var D;if(e){m(!0);try{const H=await r(e,"workspace_set_default",L===null?{clear:!0}:{id:L});if(H!=null&&H.success){w("info",L?"Default workspace updated":"Default workspace cleared",!0);const Q=typeof H.defaultWorkspacePath=="string"?H.defaultWorkspacePath:"";Q&&((D=N.current)==null||D.call(N,Q))}else w("error",(H==null?void 0:H.error)||"workspace_set_default failed",!0)}catch(H){w("error",H.message,!0)}finally{m(!1)}}},[e,w,r]),C=c.useCallback(async L=>{var H;if(!e||!L.trim())return;const D=L.trim();m(!0);try{const Q=await r(e,"workspace_set_default",{path:D});Q!=null&&Q.success?(w("info","Default workspace set from history"),(H=N.current)==null||H.call(N,D)):w("error",(Q==null?void 0:Q.error)||"Could not set default (path missing on disk?)")}catch(Q){w("error",Q.message)}finally{m(!1)}},[e,w,r]),F=c.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:y}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:y})}catch(L){w("warn",`Live nickname updated, but account sync failed: ${L.message}`)}w("info",`Nickname set to "${y||"(cleared)"}"`),g(!1)}catch(L){w("error",`Failed: ${L.message}`)}},[e,y,t,w,n,r]);return{logs:i,launchingIde:l,launchingAgentType:u,workspaceBusy:f,launchPick:v,setLaunchPick:b,editingNickname:p,setEditingNickname:g,nicknameInput:y,setNicknameInput:x,addLog:w,handleLaunchIde:M,runLaunchCliCore:S,handleLaunchCli:k,handleStopCli:O,handleRestartIde:P,handleStopIde:I,handleDetectIdes:W,handleWorkspaceAdd:K,handleWorkspaceRemove:R,handleWorkspaceSetDefault:T,handleWorkspaceResumePath:C,handleSaveNickname:F,setOnDefaultWorkspaceChanged:j}}function qw({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:o}){var P;const{workspaceBusy:l,handleWorkspaceAdd:d,handleWorkspaceRemove:u,handleWorkspaceSetDefault:h}=i,[f,m]=c.useState(!1),[v,b]=c.useState(""),[p,g]=c.useState([]),[y,x]=c.useState(!1),[N,j]=c.useState(""),w=c.useCallback(async I=>{x(!0),j("");try{const W=await Ka(o,e,I);b(W.path),g(W.directories)}catch(W){j(W instanceof Error?W.message:"Could not load folder")}finally{x(!1)}},[e,o]),A=c.useCallback(()=>{m(!0);const I=[...r.map(K=>K.workspace),...n.map(K=>K.workspace),...a.map(K=>K.workspace)],W=Ua(t.platform,Wa(I,t.defaultWorkspacePath,(t.workspaces||[]).map(K=>K.path)));w(W)},[a,n,r,w,t.defaultWorkspacePath,t.platform,t.workspaces]),M=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,S=t.availableMem??t.freeMem??t.totalMem,k=M&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-S)/t.totalMem*100))):0,O=((P=t.loadavg)==null?void 0:P[0])||0;return s.jsxs("div",{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[s.jsx(Ln,{icon:s.jsx(Kd,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?Cx(t.uptime):"Waiting…"}),s.jsx(Ln,{icon:s.jsx(Bt,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(Ln,{icon:s.jsx(Oo,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(Ln,{icon:s.jsx(Cm,{size:16}),label:"ACPs",value:`${a.length}`})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),s.jsxs("div",{className:"flex gap-6",children:[s.jsx(rl,{value:M?Math.min(Math.round(O/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:M?`${O.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(rl,{value:k,max:100,label:"Memory",color:"#3b82f6",detail:M?`${ii(t.totalMem-S)} / ${ii(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${ii(t.totalMem)} total`})]})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[s.jsx(zs,{size:14})," Workspaces"]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[s.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),s.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:t.defaultWorkspaceId||"",onChange:I=>void h(I.target.value===""?null:I.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(I=>s.jsx("option",{value:I.id,children:I.label||I.path},I.id))]}),t.defaultWorkspacePath&&s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:t.defaultWorkspacePath,children:t.defaultWorkspacePath})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.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:A,children:"Select workspace…"}),s.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(t.workspaces||[]).length>0&&s.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(t.workspaces||[]).map(I=>s.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:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[I.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:Da(I.path,I.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:I.path,children:I.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void u(I.id),children:"Remove"})]},I.id))})]}),f&&s.jsx(Ha,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:v,directories:p,busy:y,error:N,confirmLabel:"Add workspace",onClose:()=>m(!1),onNavigate:I=>{w(I)},onConfirm:I=>{(async()=>{if(!I)return;await d(I)&&m(!1)})()}})]})}function Xw(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t;return!r.settings||typeof r.settings!="object"?null:{settings:r.settings,values:r.values&&typeof r.values=="object"?r.values:{}}}function Yw(e,t,r){const n=[];for(const[a,i]of Object.entries(e.settings)){const o=r!=null&&r.filterSchema?r.filterSchema(i):i;if(o.length===0)continue;const l=t.find(d=>d.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:o,values:e.values[a]||{}})}return n}function Ri(e){if(!e||typeof e!="object")return!1;const t=e;return(t.sourceMode==="normal"||t.sourceMode==="no-upstream")&&typeof t.disableUpstream=="boolean"&&(t.explicitProviderDir===null||typeof t.explicitProviderDir=="string")&&typeof t.userDir=="string"&&typeof t.upstreamDir=="string"&&Array.isArray(t.providerRoots)}function Jl(e){if(!e||typeof e!="object")return null;if(Ri(e))return e;const t=e,r=t.result;return Ri(r)?r:Ri(t.sourceConfig)?t.sourceConfig:null}function Jw(e){const t=e.trim();return t||null}const Ql=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Qw=[{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 Zw({machineId:e,provider:t,sendDaemonCommand:r,onClose:n}){const[a,i]=c.useState("config"),[o,l]=c.useState("codex-cli"),[d,u]=c.useState([]),[h,f]=c.useState(""),[m,v]=c.useState([]),[b,p]=c.useState(""),g=c.useRef(null),y=c.useRef(null),x=S=>{u(k=>k.includes(S)?k.filter(O=>O!==S):[...k,S])},N=()=>u([...Ql]),j=()=>u([]);c.useEffect(()=>{var S;(S=g.current)==null||S.scrollIntoView({behavior:"smooth"})},[m]),c.useEffect(()=>()=>{y.current&&clearInterval(y.current)},[]);const w=c.useCallback(()=>{y.current&&clearInterval(y.current),y.current=setInterval(async()=>{try{const S=await r(e,"provider_auto_fix_status",{providerType:t.type});(S==null?void 0:S.running)===!1&&a==="running"&&(i("done"),v(k=>[...k,`
74
+ ✅ Auto-fix completed!`]),y.current&&clearInterval(y.current))}catch{}},3e3)},[e,t.type,r,a]),A=async()=>{if(d.length!==0){i("running"),v(["🚀 Starting auto-fix...",`Agent: ${o}`,`Scripts: ${d.join(", ")}`,h?`💬 Comment: ${h}`:"",""]),p("");try{const S=await r(e,"provider_auto_fix",{providerType:t.type,functions:d,agent:o,...h?{comment:h}:{}});S!=null&&S.success&&(S!=null&&S.started||S!=null&&S.running)?(v(k=>[...k,"✅ Agent started. Monitoring progress..."]),w()):(i("error"),p((S==null?void 0:S.error)||"Failed to start auto-fix"))}catch(S){i("error"),p((S==null?void 0:S.message)||"Connection failed")}}},M=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:t.type}),v(S=>[...S,`
75
+ ⚠️ Auto-fix cancelled.`]),i("done"),y.current&&clearInterval(y.current)}catch{}};return s.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:s.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:S=>S.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:t.icon||"🔧"}),s.jsxs("div",{children:[s.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",t.displayName]}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),s.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),s.jsx("div",{className:"flex gap-2",children:Qw.map(S=>s.jsxs("button",{onClick:()=>l(S.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:o===S.value?S.color+"66":"var(--border-subtle)",background:o===S.value?S.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:o===S.value?S.color:"var(--text-primary)"},children:S.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:S.desc})]},S.value))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:N,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),s.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),s.jsx("button",{onClick:j,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Ql.map(S=>s.jsxs("button",{onClick:()=>x(S),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(S)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(S)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(S)?"#a78bfa":"var(--text-secondary)"},children:[d.includes(S)?"☑ ":"☐ ",S]},S))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",s.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),s.jsx("textarea",{value:h,onChange:S=>f(S.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")&&s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),s.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:[m.map((S,k)=>s.jsx("div",{className:S.startsWith("✅")?"text-green-400":"",style:S.startsWith("❌")||S.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:S},k)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:g})]}),b&&s.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:b})]})]}),s.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[s.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&d.length>0&&`${d.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),s.jsxs("div",{className:"flex gap-2",children:[a==="config"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:A,disabled:d.length===0,className:"machine-btn",style:{background:d.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:d.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:d.length>0?"#a78bfa":void 0,opacity:d.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&s.jsx("button",{onClick:M,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{i("config"),v([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function eS({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var w;const i=t.filter(A=>A.category==="ide"),[o,l]=c.useState(((w=i[0])==null?void 0:w.type)||""),[d,u]=c.useState(""),[h,f]=c.useState(""),[m,v]=c.useState(!1),[b,p]=c.useState(""),[g,y]=c.useState(!1),x=A=>{const M=A.toLowerCase().replace(/[^a-z0-9-]/g,"");u(M),(!h||h===N(d))&&f(N(M))},N=A=>A.split("-").map(M=>M.charAt(0).toUpperCase()+M.slice(1)).join(" "),j=async()=>{if(!(!d||!h||!o)){v(!0),p("");try{const A=await r(e,"provider_clone",{type:d,name:h,category:"ide",location:"user",cloneFrom:o});A!=null&&A.success||A!=null&&A.created?(y(!0),a==null||a(d)):p((A==null?void 0:A.error)||"Failed to create provider")}catch(A){p((A==null?void 0:A.message)||"Connection failed")}v(!1)}};return s.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:s.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:A=>A.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),s.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?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:d})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(A=>s.jsxs("button",{onClick:()=>l(A.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:o===A.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:o===A.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:A.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:o===A.type?"#a78bfa":"var(--text-secondary)"},children:A.displayName})]},A.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:d,onChange:A=>x(A.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"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",d||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:h,onChange:A=>f(A.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"})]}),b&&s.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:b})]})}),s.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?s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:j,disabled:!d||!h||m,className:"machine-btn",style:{background:d&&h?"rgba(34,197,94,0.12)":void 0,borderColor:d&&h?"rgba(34,197,94,0.3)":void 0,color:d&&h?"#86efac":void 0,opacity:!d||!h||m?.4:1},children:m?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Zl(e){return e==="cli"||e==="acp"}function tS(e){switch(e){case"detected":return"Detected";case"not_detected":return"Not detected";case"enabled_unchecked":return"Enabled, not checked";case"disabled":return"Disabled";default:return"Disabled"}}function sS(e){switch(e){case"detected":return"bg-green-500/[0.10] border-green-500/25 text-green-400";case"not_detected":return"bg-red-500/[0.10] border-red-500/25 text-red-400";case"enabled_unchecked":return"bg-yellow-500/[0.10] border-yellow-500/25 text-yellow-400";case"disabled":default:return"bg-white/[0.04] border-white/[0.10] text-text-muted"}}function ed(e){if(!e)return"No result yet";const t=e.stage||"check",r=e.ok?"OK":"Failed",n=e.message||e.path||e.command||"";return n?`${t}: ${r} — ${n}`:`${t}: ${r}`}function rS({machineId:e,providers:t,sendDaemonCommand:r}){var K;const[n,a]=c.useState([]),[i,o]=c.useState(!1),[l,d]=c.useState(null),[u,h]=c.useState("all"),[f,m]=c.useState(null),[v,b]=c.useState(!1),[p,g]=c.useState(null),[y,x]=c.useState("normal"),[N,j]=c.useState(""),[w,A]=c.useState(!1),M=c.useCallback(async()=>{if(e)try{const R=await r(e,"get_provider_source_config",{}),T=Jl(R);T&&(g(T),x(T.sourceMode),j(T.explicitProviderDir||""))}catch{}},[e,r]),S=c.useCallback(async()=>{if(e){o(!0);try{const R=await r(e,"get_provider_settings",{}),T=Xw(R);if(T){const C=Yw(T,t,{filterSchema:F=>F.filter(L=>L.key!=="enabled")});C.sort((F,L)=>F.category.localeCompare(L.category)||F.displayName.localeCompare(L.displayName)),a(C)}}catch{}o(!1)}},[e,t,r]);c.useEffect(()=>{n.length===0&&S(),p||M()},[]);const k=async(R,T,C)=>{d(`${R}.${T}`),a(F=>F.map(L=>L.type===R?{...L,values:{...L.values,[T]:C}}:L));try{const F=await r(e,"set_provider_setting",{providerType:R,key:T,value:C});F!=null&&F.success||S()}catch{S()}d(null)},O=async(R,T)=>{await k(R,"enabled",T),await S()},P=async R=>{d(`${R}.detect`);try{await r(e,"detect_provider",{providerType:R})}finally{await S(),d(null)}},I=async R=>{await k(R,"executablePath",""),await k(R,"executableArgs",""),await S()},W=async()=>{A(!0);try{const R=await r(e,"set_provider_source_config",{providerSourceMode:y,providerDir:Jw(N)}),T=Jl(R);T?(g(T),x(T.sourceMode),j(T.explicitProviderDir||"")):await M(),await S()}catch{await M()}A(!1)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex justify-between items-center mb-4",children:[s.jsxs("div",{className:"flex gap-1 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(R=>s.jsx("button",{onClick:()=>h(R),className:`machine-btn text-[10px] px-2 py-0.5 ${u===R?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:R.toUpperCase()},R))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>b(!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"}),s.jsx("button",{onClick:S,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Running CLI sessions refresh provider scripts/config; process binary changes still apply on next launch."})]}),s.jsx("button",{onClick:M,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),s.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),s.jsxs("select",{value:y,onChange:R=>x(R.target.value),className:"machine-input text-[11px]",children:[s.jsx("option",{value:"normal",children:"normal"}),s.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),s.jsx("input",{type:"text",value:N,onChange:R=>j(R.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void W(),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"})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(p==null?void 0:p.userDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(p==null?void 0:p.upstreamDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((K=p==null?void 0:p.providerRoots)==null?void 0:K.join(" → "))||"loading…"]})]})]}),u!=="all"&&n.filter(R=>R.category===u).length>1&&(()=>{const R=n.filter(L=>L.category===u),T=new Map;for(const L of R)for(const D of L.schema){if(D.type!=="boolean")continue;const H=T.get(D.key),Q=!!(L.values[D.key]??D.default);H?(H.onCount+=Q?1:0,H.total+=1):T.set(D.key,{label:D.label||D.key,onCount:Q?1:0,total:1})}const C=[...T.entries()].filter(([,L])=>L.total===R.length);if(C.length===0)return null;const F=async(L,D)=>{for(const H of R)await k(H.type,L,D)};return s.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[s.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",u.toUpperCase()," providers (",R.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:C.map(([L,D])=>{const H=D.onCount===D.total,Q=D.onCount===0;return s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:"text-text-secondary font-medium",children:D.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",D.onCount,"/",D.total,")"]}),s.jsx("button",{onClick:()=>void F(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"}),s.jsx("button",{onClick:()=>void F(L,!1),disabled:Q,className:`machine-btn text-[9px] px-1.5 py-px ${Q?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},L)})})]})})(),i&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):s.jsx("div",{className:"flex flex-col gap-2",children:n.filter(R=>u==="all"||R.category===u).map(R=>s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[s.jsx("span",{className:"text-lg",children:R.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:R.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:R.category==="acp"?"rgba(139,92,246,0.08)":R.category==="cli"?"rgba(59,130,246,0.08)":R.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:R.category==="acp"?"#a78bfa":R.category==="cli"?"#60a5fa":R.category==="ide"?"#86efac":"var(--status-warning)"},children:R.category}),Zl(R.category)&&(()=>{const T=t.find(L=>L.type===R.type),C=(T==null?void 0:T.enabled)===!0||R.values.enabled===!0,F=(T==null?void 0:T.machineStatus)||(C?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${sS(F)}`,children:tS(F)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void O(R.type,!C),disabled:l===`${R.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${C?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:C?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void P(R.type),disabled:!C||l===`${R.type}.detect`,title:C?"Run detection for the configured executable":"Enable this provider before detection",className:`machine-btn text-[9px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${C?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void I(R.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),R.category==="ide"&&s.jsx("button",{onClick:()=>m(t.find(T=>T.type===R.type)||{type:R.type,name:R.displayName,displayName:R.displayName,icon:R.icon,category:R.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"})]}),Zl(R.category)&&(()=>{const T=t.find(C=>C.type===R.type);return s.jsxs("div",{className:"mb-2.5 grid gap-1 rounded-lg border border-white/[0.06] bg-bg-primary/40 px-3 py-2 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Detection:"})," ",ed(T==null?void 0:T.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",ed(T==null?void 0:T.lastVerification)]}),s.jsx("div",{className:"text-[9px] text-text-muted",children:"Supported catalog entry only becomes launchable after Enable + Detect succeeds. Custom executable path/args below are machine-local overrides."})]})})(),s.jsx("div",{className:"flex flex-col gap-2",children:R.schema.map(T=>s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[T.label||T.key,l===`${R.type}.${T.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),T.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:T.description})]}),s.jsx("div",{className:"shrink-0",children:T.type==="boolean"?s.jsx("button",{onClick:()=>k(R.type,T.key,!(R.values[T.key]??T.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:R.values[T.key]??T.default?"#8b5cf6":"var(--border-subtle)"},children:s.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:R.values[T.key]??T.default?21:3}})}):T.type==="number"?s.jsx("input",{type:"number",value:Number(R.values[T.key]??T.default??0)||0,min:T.min,max:T.max,onChange:C=>{const F=parseInt(C.target.value)||0;T.min!==void 0&&F<T.min||T.max!==void 0&&F>T.max||k(R.type,T.key,F)},className:"machine-input w-20 text-center text-[11px]"}):T.type==="select"&&T.options?s.jsx("select",{value:String(R.values[T.key]??T.default??""),onChange:C=>k(R.type,T.key,C.target.value),className:"machine-input text-[11px]",children:T.options.map(C=>s.jsx("option",{value:C,children:C},C))}):s.jsx("input",{type:"text",value:String(R.values[T.key]??T.default??""),onBlur:C=>k(R.type,T.key,C.target.value),className:"machine-input w-[120px] text-[11px]"})})]},T.key))})]},R.type))}),f&&s.jsx(Zw,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>m(null)}),v&&s.jsx(eS,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>b(!1),onCreated:()=>{b(!1),S()}})]})}const nS=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function aS({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function iS(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function oS(e){return e.trim().toLowerCase()}function Va(e,t){const r=oS(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function vc(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function wr(e,t=220){const r=vc(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function cS(e){const t=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(t))return{kind:t.length>0?"structured":"empty",entries:t.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 t=="string"){const r=t.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function lS(e,t){return e.filter(r=>Va([r.level,r.message],t))}function td(e){return`${e.timestamp}:${e.level}:${e.message}`}function dS(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const o of e.entries)n.set(td(o),o);for(const o of t.entries)n.set(td(o),o);const a=Array.from(n.values()).sort((o,l)=>o.timestamp-l.timestamp).slice(-r),i=a.reduce((o,l)=>Math.max(o,Number(l.timestamp||0)),e.lastTs);return{entries:a,kind:"structured",rawText:"",lastTs:i}}return t.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:t.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function uS(e,t,r=120){if(t.length===0)return e;const n=new Map;for(const a of e)n.set(a.id,a);for(const a of t)n.set(a.id,a);return Array.from(n.values()).sort((a,i)=>a.ts-i.ts).slice(-r)}function hS(e,t){return e.split(`
76
+ `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>Va([r],t))}function pS(e,t){return e.filter(r=>Va([r.level,r.category,r.stage,r.interactionId,vc(r.payload)],t))}function fS(e,t){return e.filter(r=>Va([r.kind,r.topic,r.interactionId,vc(r.payload)],t))}function sd(e){return e==="warn"||e==="error"}function mS({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){return{all:e.length+t.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=>sd(a.level)).length+r.filter(a=>sd(a.level)).length}}function xS({daemonLogs:e,daemonRawLines:t,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(`
77
+ `)):t.length>0&&a.push(["[daemon logs]",...t].join(`
78
+ `)),r.length>0&&a.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${wr(i.payload,500)}`.trim())].join(`
79
+ `)),n.length>0&&a.push(["[browser events]",...n.map(i=>`${new Date(i.ts).toISOString()} ${i.kind}${i.topic?` topic=${i.topic}`:""} ${wr(i.payload,500)}`.trim())].join(`
80
+ `)),a.join(`
81
+
82
+ `)}function gS({machineId:e,sendDaemonCommand:t}){const[r,n]=c.useState([]),[a,i]=c.useState("empty"),[o,l]=c.useState(""),[d,u]=c.useState([]),[h,f]=c.useState([]),[m,v]=c.useState(null),[b,p]=c.useState(!0),[g,y]=c.useState("info"),[x,N]=c.useState("all"),[j,w]=c.useState(!0),[A,M]=c.useState(!0),[S,k]=c.useState(""),[O,P]=c.useState(""),[I,W]=c.useState(0),K=c.useRef(0),R=c.useRef(0),T=c.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),C=c.useRef([]),F=c.useCallback(()=>{const Z={entries:[],kind:"empty",rawText:"",lastTs:0};T.current=Z,K.current=0,n([]),l(""),i("empty"),w(!0)},[]),L=c.useCallback(()=>{C.current=[],R.current=0,u([]),M(!0)},[]),D=c.useCallback(Z=>{Z!==g&&(F(),y(Z))},[g,F]),H=c.useCallback(Z=>{N(xe=>xe===Z?xe:Z)},[]),Q=c.useCallback(()=>{F(),L(),f([]),v(null),k(""),P(""),pr.clear()},[F,L]),ge=c.useCallback(()=>{W(Z=>Z+1)},[]),ue=c.useCallback(async()=>{if(!e)return;const Z=K.current,xe=R.current,[Se,be]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:g,since:Z}),t(e,"get_debug_trace",aS({count:120,since:xe,category:x}))]);if(Se.status==="fulfilled"){const Y=Se.value,he=(Y==null?void 0:Y.result)||Y,ye=cS(he),se=dS(T.current,ye,300);T.current=se,K.current=se.lastTs,w(!1),k((Y==null?void 0:Y.success)===!1?String((Y==null?void 0:Y.error)||"Could not load daemon logs"):""),i(se.kind),l(se.rawText),n(se.entries)}else w(!1),k(Se.reason instanceof Error?Se.reason.message:"Could not load daemon logs");if(be.status==="fulfilled"){const Y=be.value,he=(Y==null?void 0:Y.result)||Y;if((Y==null?void 0:Y.success)===!1)P(String((Y==null?void 0:Y.error)||"Could not load daemon trace"));else if(Array.isArray(he==null?void 0:he.trace)){const ye=he.trace,se=uS(C.current,ye,120),de=ye.reduce((Ce,pe)=>Math.max(Ce,Number(pe.ts||0)),xe);C.current=se,de>xe&&(R.current=de),P(""),u(se)}else P("");M(!1)}else M(!1),P(be.reason instanceof Error?be.reason.message:"Could not load daemon trace");f(pr.list({limit:120})),v(Date.now())},[g,e,t,x]);return c.useEffect(()=>{L()},[L,x]),c.useEffect(()=>{if(!e||(ue(),!b))return;const Z=setInterval(()=>{ue()},3e3);return()=>clearInterval(Z)},[b,ue,e,I]),{daemonLogs:r,daemonLogKind:a,daemonRawText:o,debugTrace:d,webEvents:h,lastUpdatedAt:m,autoRefresh:b,logLevel:g,traceCategory:x,daemonLoading:j,traceLoading:A,daemonFetchError:S,traceFetchError:O,setAutoRefresh:p,setLogLevel:D,setTraceCategory:H,refresh:ge,clear:Q}}function bS({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:i,daemonRawLineCount:o,traceCount:l,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":i>0||o>0?"ok":"empty",detail:r||(a==="text"?`${o} raw file-fallback line(s)`:`${i} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:n?"error":t?"loading":l>0?"ok":"empty",detail:n||`${l} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:d>0?"ok":"empty",detail:d>0?`${d} local browser event(s)`:"No browser events captured"}]}function rd(e){return e==="warn"||e==="error"}function yS(e){const t=e.toLowerCase();return/\[(err|error)\]/i.test(e)||t.includes(" error ")||t.includes(" failed")?"error":/\[(wrn|warn|warning)\]/i.test(e)||t.includes(" warning ")||t.includes(" timeout")?"warn":/\[(dbg|debug)\]/i.test(e)?"debug":"info"}function vS(e,t){const r=e.match(/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\b/);if(r){const n=Date.parse(r[0]);if(Number.isFinite(n))return n}return Number.MAX_SAFE_INTEGER-1e5+t}function nd(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function wS(e){const t=wr(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function SS(e){const t=wr(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function kS({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.forEach((i,o)=>{a.push({id:`daemon-log-${i.timestamp}-${o}`,source:"daemon_log",ts:Number(i.timestamp||0),severity:i.level,message:i.message,raw:i.message})}),n.forEach(i=>{a.push({id:`browser-event-${i.id}`,source:"browser_event",ts:Number(i.ts||0),severity:"info",message:SS(i),topic:i.topic,interactionId:i.interactionId,payload:i.payload})}),r.forEach(i=>{a.push({id:`daemon-trace-${i.id}`,source:"daemon_trace",ts:Number(i.ts||0),severity:i.level,message:wS(i),category:i.category,stage:i.stage,interactionId:i.interactionId,payload:i.payload})}),t.forEach((i,o)=>{a.push({id:`raw-file-${o}`,source:"raw_file",ts:vS(i,o),severity:yS(i),message:i,raw:i})}),a.sort((i,o)=>i.ts!==o.ts?i.ts-o.ts:nd(i.source)-nd(o.source))}function jS(e){return`${e.source}:${e.severity}:${e.message}`}function NS(e){const t=e.filter(n=>rd(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!rd(n.severity))continue;const a=jS(n),i=r.get(a);i?(i.count+=1,i.firstTs=Math.min(i.firstTs,n.ts),i.lastTs=Math.max(i.lastTs,n.ts)):r.set(a,{key:a,source:n.source,severity:n.severity,message:n.message,count:1,firstTs:n.ts,lastTs:n.ts})}return{totalCount:e.length,issueCount:t.length,latestIssue:t[0]||null,repeatedPatterns:Array.from(r.values()).filter(n=>n.count>1).sort((n,a)=>a.count!==n.count?a.count-n.count:a.lastTs-n.lastTs).slice(0,5)}}function CS(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function ad(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${CS(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function TS({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
83
+ `)),a.push(["[source status]",...r.map(o=>`${o.label}: ${o.status} - ${o.detail}`)].join(`
84
+ `)),t.latestIssue&&a.push(["[latest issue]",ad(t.latestIssue)].join(`
85
+ `)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(o=>`${o.count}x ${o.severity.toUpperCase()} ${o.source} ${o.message}`)].join(`
86
+ `));const i=e.slice(-n);return a.push(["[timeline]",...i.length>0?i.map(ad):["No diagnostic events captured."]].join(`
87
+ `)),a.join(`
88
+
89
+ `)}function IS(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function AS(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function MS({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:i,quickFilter:o,searchQuery:l,daemonLoading:d,traceLoading:u,daemonFetchError:h,traceFetchError:f}){const m=iS(n,i),v=lS(e,l),b=hS(t,l),p=pS(m,l),g=fS(a,l),y=IS(v,o),x=o==="all"?b:[],N=AS(p,o),j=o==="issues"?[]:g,w=mS({daemonLogs:v,daemonRawLines:b,trace:p,webEvents:g}),A=kS({daemonLogs:y,daemonRawLines:x,trace:N,webEvents:j}),M=NS(A),S=bS({daemonLoading:d,traceLoading:u,daemonFetchError:h,traceFetchError:f,daemonLogKind:r,daemonLogsCount:v.length,daemonRawLineCount:b.length,traceCount:p.length,webEventCount:g.length});return{filteredDaemonLogs:v,filteredDaemonRawLines:b,filteredTraceEntries:p,filteredWebEvents:g,visibleDaemonLogs:y,visibleDaemonRawLines:x,visibleTraceEntries:N,visibleWebEvents:j,quickFilterCounts:w,diagnosticEvents:A,diagnosticsSummary:M,sourceStates:S}}function _S(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Uh(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function yo(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 Pi(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 wc(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function RS({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${yo(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Uh(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:wc(e.source)}),e.category&&e.stage&&s.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&s.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&s.jsxs("span",{children:["ix=",e.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function PS({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:o,onCopyVisible:l,onToggleAutoRefresh:d,onRefresh:u,onClear:h}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(f=>s.jsx("button",{type:"button",onClick:()=>a(f.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===f.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:f.label},f.id))}),s.jsx("input",{value:r,onChange:f=>i(f.target.value),placeholder:"Search diagnostics…",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"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:o,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:l,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:d,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:h,className:"machine-btn",children:"Clear"})]})]})}function LS({logLevel:e,traceCategory:t,onLogLevelChange:r,onTraceCategoryChange:n}){return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-3",children:s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(a=>s.jsxs("button",{onClick:()=>r(a),className:`machine-btn text-[10px] px-2 py-0.5 ${e===a?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",a.toUpperCase(),"+"]},a))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:nS.map(a=>s.jsx("button",{onClick:()=>n(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function ES({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:i,daemonFetchError:o,traceFetchError:l}){var h,f;const d=((h=e.latestIssue)==null?void 0:h.severity)==="error"?"danger":((f=e.latestIssue)==null?void 0:f.severity)==="warn"?"warning":"good",u=o||l?"danger":i?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Pi(e.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:n.trim()?`Filtered by “${n.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Pi(d)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[wc(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:Uh(e.latestIssue.ts)})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Pi(u)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:o||l?"Needs attention":i?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",_S(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(m=>s.jsxs("div",{children:[m.label,": ",m.status]},m.id))})]})]})}function DS({patterns:e}){return e.length===0?null:s.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(t=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[s.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[t.count,"× ",t.severity.toUpperCase()," · ",wc(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function $S({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:i,visibleTraceEntries:o,visibleWebEvents:l,quickFilter:d,searchQuery:u}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(h=>({...h,timeline:!h.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(h=>s.jsx(RS,{event:h},h.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(h=>({...h,daemon:!h.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${i.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.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:[e.daemonLoading&&a.length===0&&i.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&i.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:d==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&i.map((h,f)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:h},`raw-${f}`)),e.daemonLogKind!=="text"&&a.map((h,f)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${yo(h.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(h.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:h.level==="error"?"ERR":h.level==="warn"?"WRN":h.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:h.message})]},`log-${f}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(h=>({...h,trace:!h.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[o.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.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:[e.traceLoading&&o.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&o.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&o.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:u.trim()?"No trace entries match the current search.":e.traceCategory==="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."}),o.map(h=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${yo(h.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(h.ts).toLocaleTimeString()}),s.jsx("span",{children:h.level.toUpperCase()}),s.jsxs("span",{children:[h.category,".",h.stage]}),h.interactionId&&s.jsxs("span",{children:["ix=",h.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:wr(h.payload,360)||"No payload"})]},h.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(h=>({...h,web:!h.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[l.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.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:[l.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:u.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),l.map(h=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(h.ts).toLocaleTimeString()}),s.jsx("span",{children:h.kind}),h.topic&&s.jsxs("span",{children:["topic=",h.topic]}),h.interactionId&&s.jsxs("span",{children:["ix=",h.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:wr(h.payload,360)||"No payload"})]},h.id))]})]})]})}function BS({machineId:e,sendDaemonCommand:t}){const r=gS({machineId:e,sendDaemonCommand:t}),[n,a]=c.useState("info"),[i,o]=c.useState(""),[l,d]=c.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),u=c.useRef(null),h=c.useRef(!1),f=c.useMemo(()=>MS({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:i,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,i,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);c.useEffect(()=>{if(r.autoRefresh&&f.diagnosticEvents.length>0){const b=h.current?"smooth":"instant";setTimeout(()=>{var p;(p=u.current)==null||p.scrollIntoView({behavior:b}),h.current=!0},50)}},[f.diagnosticEvents.length,r.autoRefresh]);const m=c.useCallback(async()=>{var p;const b=xS({daemonLogs:f.visibleDaemonLogs,daemonRawLines:f.visibleDaemonRawLines,trace:f.visibleTraceEntries,webEvents:f.visibleWebEvents});if(!b.trim()){ct.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(b)),ct.showToast("Copied visible logs to clipboard.","success")}catch(g){ct.showToast(g instanceof Error?g.message:"Could not copy visible logs","warning")}},[f.visibleDaemonLogs,f.visibleDaemonRawLines,f.visibleTraceEntries,f.visibleWebEvents]),v=c.useCallback(async()=>{var p;const b=TS({events:f.diagnosticEvents,summary:f.diagnosticsSummary,sources:f.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(b)),ct.showToast("Copied diagnostic bundle to clipboard.","success")}catch(g){ct.showToast(g instanceof Error?g.message:"Could not copy diagnostic bundle","warning")}},[f.diagnosticEvents,f.diagnosticsSummary,f.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(PS,{quickFilter:n,quickFilterCounts:f.quickFilterCounts,searchQuery:i,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:()=>{v()},onCopyVisible:()=>{m()},onToggleAutoRefresh:()=>r.setAutoRefresh(b=>!b),onRefresh:r.refresh,onClear:r.clear}),s.jsx(LS,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(ES,{diagnosticsSummary:f.diagnosticsSummary,diagnosticEventsCount:f.diagnosticEvents.length,sourceStates:f.sourceStates,searchQuery:i,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(DS,{patterns:f.diagnosticsSummary.repeatedPatterns}),s.jsx($S,{streams:r,sectionsOpen:l,setSectionsOpen:d,diagnosticEvents:f.diagnosticEvents,visibleDaemonLogs:f.visibleDaemonLogs,visibleDaemonRawLines:f.visibleDaemonRawLines,visibleTraceEntries:f.visibleTraceEntries,visibleWebEvents:f.visibleWebEvents,quickFilter:n,searchQuery:i}),s.jsx("div",{ref:u})]})}function OS(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 Kh(e){const t=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return t?t==="auto_resumed"?"restored after restart":t==="resume_failed"?"restore failed":t==="host_restart_interrupted"?"host restart interrupted":t==="orphan_snapshot"?"snapshot recovered":t.replace(/_/g," "):null}function FS(e){var a;const t=[],r=[],n=[];for(const i of e||[]){const o=String((i==null?void 0:i.lifecycle)||"").trim(),l=Kh((i==null?void 0:i.meta)||void 0),d=((a=i==null?void 0:i.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(o)?t.push(i):(o==="stopped"||o==="failed")&&(d||l)?r.push(i):n.push(i)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function WS(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Li(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 Ei(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Di(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function id(e){if(!e)return"unknown";const t=Date.now()-e,r=Math.max(0,Math.round(t/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 US(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function KS(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 HS(e){var r;const t=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}`;t.set(i,(t.get(i)||0)+1)}return Array.from(t.values()).filter(n=>n>1).length}function zS({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=c.useState(""),[i,o]=c.useState(null),[l,d]=c.useState(!1),u=Yy(e,{enabled:!!e,includeSessions:!0,limit:pl,intervalMs:Vg}),h=u.diagnostics,f=u.loading,m=u.applyDiagnostics,v=c.useMemo(()=>OS({diagnostics:h,loading:f,refreshing:l,error:n}),[h,f,l,n]),b=c.useMemo(()=>new Map(t.map(P=>[P.sessionId||P.id,P])),[t]),p=c.useCallback(async()=>{if(e){d(!0);try{const P=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:pl}),I=Ei(P);if(!(I!=null&&I.success))throw new Error((I==null?void 0:I.error)||"Could not load hosted runtime diagnostics");m(I.diagnostics||I.result||null),a("")}catch(P){const I=P instanceof Error?P.message:"Could not load hosted runtime diagnostics";a(I)}finally{d(!1)}}},[m,e,r]);c.useEffect(()=>{!e||h||f||l||p()},[h,f,e,p,l]);const g=c.useCallback(async(P,I)=>{const W=`${P}:${I.sessionId}`;if(!(P==="session_host_stop_session"&&!window.confirm(`Stop ${I.displayName}?
90
+ This will terminate the hosted runtime.`))){o(W);try{const K=await r(e,P,{sessionId:I.sessionId}),R=Ei(K);if(!(R!=null&&R.success))throw new Error((R==null?void 0:R.error)||"Session host action failed");const T=P==="session_host_resume_session"?"resumed":P==="session_host_restart_session"?"restarted":"stopped";ct.showToast(`Session host ${T}: ${I.displayName}`,"success"),await p()}catch(K){const R=K instanceof Error?K.message:"Session host action failed";ct.showToast(R,"warning"),a(R)}finally{o(K=>K===W?null:K)}}},[e,p,r]),y=c.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
91
+ The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){o("session_host_prune_duplicate_sessions");try{const I=await r(e,"session_host_prune_duplicate_sessions",{}),W=Ei(I);if(!(W!=null&&W.success))throw new Error((W==null?void 0:W.error)||"Duplicate prune failed");const K=W.result||{},R=Array.isArray(K.prunedSessionIds)?K.prunedSessionIds.length:0,T=typeof K.duplicateGroupCount=="number"?K.duplicateGroupCount:0;ct.showToast(`Pruned ${R} duplicate runtime(s) across ${T} group(s)`,"success"),await p()}catch(I){const W=I instanceof Error?I.message:"Duplicate prune failed";ct.showToast(W,"warning"),a(W)}finally{o(I=>I==="session_host_prune_duplicate_sessions"?null:I)}}},[e,p,r]),x=c.useMemo(()=>[...(h==null?void 0:h.sessions)||[]].sort((P,I)=>(I.lastActivityAt||0)-(P.lastActivityAt||0)),[h==null?void 0:h.sessions]),N=c.useMemo(()=>h!=null&&h.liveRuntimes||h!=null&&h.recoverySnapshots||h!=null&&h.inactiveRecords?{liveRuntimes:(h==null?void 0:h.liveRuntimes)||[],recoverySnapshots:(h==null?void 0:h.recoverySnapshots)||[],inactiveRecords:(h==null?void 0:h.inactiveRecords)||[]}:FS(x),[h==null?void 0:h.inactiveRecords,h==null?void 0:h.liveRuntimes,h==null?void 0:h.recoverySnapshots,x]),j=N.liveRuntimes,w=N.recoverySnapshots,A=N.inactiveRecords,M=c.useMemo(()=>HS(j),[j]),S=c.useMemo(()=>[...(h==null?void 0:h.recentTransitions)||[]].slice(-6).reverse(),[h==null?void 0:h.recentTransitions]),k=c.useMemo(()=>[...(h==null?void 0:h.recentLogs)||[]].reverse().find(P=>P.level==="warn"||P.level==="error")||null,[h==null?void 0:h.recentLogs]),O=(P,I)=>{var H;const W=i===`session_host_resume_session:${P.sessionId}`,K=i===`session_host_restart_session:${P.sessionId}`,R=i===`session_host_stop_session:${P.sessionId}`,T=Kh(P.meta),C=b.get(P.sessionId),F=P.attachedClients.length===1?"1 client":`${P.attachedClients.length} clients`,L=I==="recovery"?"Recover":"Resume",D=WS(I);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:P.displayName||(C==null?void 0:C.cliName)||P.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${KS(P.lifecycle)}`,children:P.lifecycle}),T&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:T})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:P.workspaceLabel||(C==null?void 0:C.runtimeWorkspaceLabel)||P.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:P.runtimeKey}),P.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",P.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((H=P.writeOwner)==null?void 0:H.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:US(P.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(Od,{size:11})," ",F]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",id(P.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",D]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[I==="recovery"&&(P.lifecycle==="interrupted"||P.lifecycle==="failed"||P.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{g("session_host_resume_session",P)},children:W?`${L}ing…`:L}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{g("session_host_restart_session",P)},children:K?"Restarting…":"Restart"}),I==="live"&&(P.lifecycle==="running"||P.lifecycle==="starting"||P.lifecycle==="interrupted")&&s.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",P)},children:R?"Stopping…":"Stop"})]})]})},P.sessionId)};return s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(ys,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Jb()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[M>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{y()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${M})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${v.toneClass}`,children:v.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:f||l,children:[s.jsx(vn,{size:13}),f||l?"Refreshing…":"Refresh"]})]})]}),n&&!h&&s.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:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(fn,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),h&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:h.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:w.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:h.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:id(h.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Di(h.hostStartedAt)})]})]}),k&&s.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:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(fn,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:k.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Di(k.timestamp),k.sessionId?` · ${k.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Oo,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Li("live")}),j.length===0?s.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."}):s.jsx("div",{className:"space-y-2",children:j.map(P=>O(P,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(ys,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Li("recovery")}),w.length===0?s.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."}):s.jsx("div",{className:"space-y-2",children:w.map(P=>O(P,"recovery"))})]}),A.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Li("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:A.map(P=>O(P,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),S.length===0?s.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."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:S.map(P=>{var W;const I=x.find(K=>K.sessionId===P.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(I==null?void 0:I.displayName)||((W=b.get(P.sessionId))==null?void 0:W.cliName)||P.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[P.action,P.lifecycle?` · ${P.lifecycle}`:"",P.detail?` · ${P.detail}`:"",P.error?` · ${P.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${P.success===!1?"text-red-300":"text-text-secondary"}`,children:Di(P.timestamp)})]},`${P.sessionId}:${P.timestamp}:${P.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:h.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function VS({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.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:s.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:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.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."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.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=>s.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:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function $i({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function Bi({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function GS({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:o}){const l=n.slice(0,6),d=r.slice(0,4),u="0.9.76",h=uh(e),f=rr(e,u),m=nn(e,f),v=h==="preview"?"Update to preview":"Update daemon";return s.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&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx($i,{icon:s.jsx(cs,{size:13}),children:"Current Chats"}),s.jsx(Bi,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(b=>{const p=mo(b);return s.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:()=>o(b),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:ft(b)}),p>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:La(p)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Gs(b)})]},b.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx($i,{icon:s.jsx(Kd,{size:13}),children:"Recent Launches"}),s.jsx(Bi,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(b=>{const{metaText:p,updatedLabel:g}=Sh(b);return s.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(b),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:b.label}),g&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:g})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:p})]},b.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx($i,{icon:s.jsx(fn,{size:13}),children:"Daemon Update"}),s.jsx(Bi,{className:"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m?"Daemon update required":"Version mismatch detected"}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[m?"This machine is on an incompatible daemon version. Update it before starting more sessions.":h==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",f&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",f,h?` (${h})`:""]})]}),s.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:[s.jsx(vn,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:v})]})]})})]})]})}function qS(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function XS({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:i,onCustomPathChange:o,onOpenBrowseDialog:l}){return s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:t,onChange:d=>{const u=d.target.value;if(i(u),u==="__custom__"&&a){l();return}u!=="__custom__"&&o("")},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:(e.workspaces||[]).length>0?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(d=>s.jsxs("option",{value:d.id,children:[d.id===e.defaultWorkspaceId?"⭐ ":"",Da(d.path,d.label)]},d.id)),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),t==="__custom__"&&(a?s.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:l,children:"Select workspace…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:d=>o(d.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:t==="__custom__"?r?s.jsx("span",{className:"font-mono truncate block",title:r,children:r}):a?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":r?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:t===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const YS={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 Vn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Oi({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:o,sendDaemonCommand:l,initialWorkspaceId:d,initialWorkspacePath:u,onOpenGitDialog:h}){const f=Nr(),{handleLaunchIde:m,handleStopCli:v,handleRestartIde:b,handleStopIde:p,handleDetectIdes:g,launchingIde:y,launchingAgentType:x,addLog:N}=o,[j,w]=c.useState(null),A=c.useCallback(_=>{_&&f(ws(_))},[f]),M=YS[e],S=e==="ide",k=e==="acp",O=c.useMemo(()=>n.filter(_=>qs(_,e)),[e,n]),P=c.useMemo(()=>new Map(O.map(_=>[_.type,_.displayName||_.type])),[O]),[I,W]=c.useState(""),[K,R]=c.useState(""),[T,C]=c.useState([]),[F,L]=c.useState(""),[D,H]=c.useState(""),[Q,ge]=c.useState([]),[ue,Z]=c.useState(!1),[xe,Se]=c.useState(!1),[be,Y]=c.useState(""),[he,ye]=c.useState(!1),[se,de]=c.useState(()=>Mt()),[Ce,pe]=c.useState(null),[me,oe]=c.useState(u?"__custom__":d||t.defaultWorkspaceId||""),[fe,ce]=c.useState(u||""),[E,z]=c.useState([]),[le,re]=c.useState(!1),[q,je]=c.useState(""),[we,Pe]=c.useState([]),[Re,B]=c.useState(!1),[Ae,Ee]=c.useState(""),Ve=c.useRef(null),[Ge,Ze]=c.useState(null),et=c.useRef("__home__"),[at,gt]=c.useState("__home__"),[St,jt]=c.useState(!1),Me=c.useRef(0),qe=E.filter(_=>!a.some(ie=>ie.type===_&&kt(ie.status)!=="stopped")),st=c.useRef({});c.useEffect(()=>{t.defaultWorkspaceId&&!me&&oe(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),c.useEffect(()=>{if(u){oe("__custom__"),ce(u);return}d&&(oe(d),ce(""))},[d,u]),c.useEffect(()=>{S||I&&(O.some(_=>_.type===I)||(W(""),H("")))},[O,S,I]);const Xe=(()=>{if(me==="__custom__")return fe.trim();if(!me)return"";const _=(t.workspaces||[]).find(ie=>ie.id===me);return(_==null?void 0:_.path)||""})(),ot=c.useCallback(_=>{const ie=st.current[_];ie&&(clearTimeout(ie),delete st.current[_]),z(ve=>ve.includes(_)?ve.filter(Ue=>Ue!==_):ve)},[]),U=c.useRef(new Set),V=c.useCallback(async _=>{if(l){B(!0),Ee("");try{const ie=await Ka(l,r,_);je(ie.path),ce(ie.path),Pe(ie.directories)}catch(ie){Ee(ie instanceof Error?ie.message:"Could not load folder")}finally{B(!1)}}},[r,l]),J=c.useCallback(()=>{if(!l)return;oe("__custom__"),re(!0);const _=a.map(ve=>ve.workspace),ie=Ua(t.platform,Wa(fe.trim(),Xe,u,_,t.defaultWorkspacePath,(t.workspaces||[]).map(ve=>ve.path)));V(ie)},[fe,u,V,t.defaultWorkspacePath,t.platform,t.workspaces,a,Xe,l]),ne=c.useCallback(_=>{const ie=String(_.workspace||"").trim();if(!ie)return;const ve=(t.workspaces||[]).find(Ue=>Vn(Ue.path)===Vn(ie));if(ve){oe(ve.id),ce("");return}oe("__custom__"),ce(ie)},[t.workspaces]),$=c.useCallback(_=>{const ie=String(_.workspace||"").trim();if(!ie)return{workspaceId:null,workspacePath:"",useHome:!0};const ve=(t.workspaces||[]).find(Ue=>Vn(Ue.path)===Vn(ie));return ve?{workspaceId:ve.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ie,useHome:!1}},[t.workspaces]),X=c.useCallback(async _=>{if(!l||!_||e!=="cli"){ge([]),Z(!1),Se(!1),Y("");return}const ie=Me.current+1;Me.current=ie,Z(!0),Y("");try{const ve=await l(r,"list_saved_sessions",{providerType:_,kind:"cli",limit:30});if(Me.current!==ie)return;const Ue=(ve==null?void 0:ve.result)??ve;ge(Array.isArray(Ue==null?void 0:Ue.sessions)?Ue.sessions:[])}catch(ve){if(Me.current!==ie)return;ge([]),Y(ve instanceof Error?ve.message:"Could not load saved sessions")}finally{Me.current===ie&&(Z(!1),Se(!0))}},[e,r,l]),te=c.useMemo(()=>{if(e!=="cli"||!I)return null;const _=P.get(I)||I;return{routeId:r,daemonId:r,providerSessionId:D||void 0,transport:"pty",mode:"chat",agentName:_,agentType:I,status:"idle",title:_,messages:[],ideType:I,workspaceName:Xe,workspacePath:Xe,displayPrimary:_,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${I}`}},[e,r,P,Xe,D,I]),ae=c.useCallback(_=>{if(e==="ide"||!_){C([]);return}C(bo(r,_))},[e,r]),Ne=c.useCallback((_,ie)=>{e==="ide"||!_||(uw(r,_,ie),C(bo(r,_)))},[e,r]);c.useEffect(()=>{Me.current+=1,H(""),ae(I),Se(!1),ge([]),Y(""),Z(!1)},[e,ae,X,I]);const $e=c.useMemo(()=>Q.find(_=>_.providerSessionId===D)||null,[Q,D]);c.useEffect(()=>{if(!D)return;const _=Q.find(ie=>ie.providerSessionId===D);_!=null&&_.canResume||H("")},[Q,D]);const Be=c.useCallback((_,ie)=>{Ve.current=ie,et.current=_.selectedWorkspaceKey||"__home__",gt(_.selectedWorkspaceKey||"__home__"),Ze(_)},[]),Ie=c.useCallback(()=>{Ve.current&&(jt(!0),Ve.current().finally(()=>{Ve.current=null,jt(!1),Ze(null)}))},[]),Oe=c.useCallback(_=>{if(!_)return;z(ve=>ve.includes(_)?ve:[...ve,_]);const ie=st.current[_];ie&&clearTimeout(ie),st.current[_]=setTimeout(()=>{z(ve=>ve.includes(_)?ve.filter(Ue=>Ue!==_):ve),delete st.current[_]},2e4)},[]);c.useEffect(()=>{for(const ie of a)kt(ie.status)!=="stopped"&&(E.includes(ie.type)&&!U.current.has(ie.type)&&(U.current.add(ie.type),N("info",`${P.get(ie.type)||ie.type} launched`,!0)),ot(ie.type));const _=new Set(a.filter(ie=>kt(ie.status)!=="stopped").map(ie=>ie.type));U.current.forEach(ie=>{!E.includes(ie)&&!_.has(ie)&&U.current.delete(ie)})},[N,ot,a,E,P]),c.useEffect(()=>()=>{Object.values(st.current).forEach(clearTimeout),st.current={}},[]);const[We,Le]=c.useState({}),[tt,rt]=c.useState(null);c.useEffect(()=>{if(!S||!r||!l)return;(async()=>{try{const ie=await l(r,"get_ide_extensions",{}),ve=(ie==null?void 0:ie.result)||ie;ve!=null&&ve.success&&(ve!=null&&ve.ideExtensions)&&Le(ve.ideExtensions)}catch{}})()},[S,r,l]);const pt=_=>S?ht(_.type):e==="cli"?_.cliName:_.acpName,bt=S?t.detectedIdes||[]:[],mt=c.useCallback(async _=>{const ie=(_==null?void 0:_.type)||I,ve=(_==null?void 0:_.workspacePath)??Xe;if(S){await m(ie,ve?{workspace:ve}:void 0)&&Oe(ie);return}const Ue=await o.runLaunchCliCore({cliType:ie,dir:_!=null&&_.workspaceId?void 0:ve||void 0,workspaceId:(_==null?void 0:_.workspaceId)||void 0,useHome:(_==null?void 0:_.useHome)||!(_!=null&&_.workspaceId)&&!ve,argsStr:(_==null?void 0:_.argsStr)??(K||void 0),model:(_==null?void 0:_.model)??(k&&F||void 0),resumeSessionId:(_==null?void 0:_.resumeSessionId)||!k&&e==="cli"&&ie===I&&D||void 0});if(Ue.success||Ue.pending){const De=(_==null?void 0:_.argsStr)??K;!S&&(De!=null&&De.trim())&&(Dh(r,ie,De),ae(ie)),Oe(ie),Ue.success&&Ue.sessionId&&A(Ue.sessionId)}},[o,m,k,S,K,F,ae,Oe,r,A,Xe,D,I]),At=Eu(S?"ide":k?"acp":"cli",!S&&!k&&!!D),Ye=Du(S?"ide":k?"acp":"cli",!S&&!k&&!!D),ke=()=>{var De;const _=S?ht(I):P.get(I)||I,ie=!S&&!k&&!!D,{options:ve,selectedKey:Ue}=Fs({machine:t,currentWorkspaceId:me&&me!=="__custom__"?me:null,currentWorkspacePath:Xe});Be({title:ie?nc(_):Es("start-fresh",_),description:ie?ac():Ds("start-fresh"),confirmLabel:At,busyLabel:Ye,workspaceOptions:ve,selectedWorkspaceKey:Ue,details:[{label:"Mode",value:M.label},{label:"Provider",value:_},...!S&&e==="cli"&&D?[{label:"Resume",value:((De=Q.find(Ke=>Ke.providerSessionId===D))==null?void 0:De.title)||D}]:[],...!S&&K.trim()?[{label:"Arguments",value:K.trim()}]:[],...k&&F.trim()?[{label:"Model",value:F.trim()}]:[]]},async()=>{const Ke=ve.find(ut=>ut.key===et.current);Ke!=null&&Ke.workspaceId?(oe(Ke.workspaceId),ce("")):Ke!=null&&Ke.workspacePath?(oe("__custom__"),ce(Ke.workspacePath)):(oe(""),ce("")),await mt({workspaceId:(Ke==null?void 0:Ke.workspaceId)??null,workspacePath:(Ke==null?void 0:Ke.workspacePath)??"",useHome:!(Ke!=null&&Ke.workspaceId)&&!(Ke!=null&&Ke.workspacePath)})})},G=_=>{S?p(_):v(_.type,_.workspace,_.id)},_e=c.useCallback(async(_,ie,ve=!1)=>{if(_.mode===ie){ve&&_.sessionId&&A(_.sessionId);return}if(!l||!_.sessionId){ve&&_.sessionId&&A(_.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:_.sessionId,cliType:_.type,mode:ie}),ve&&A(_.sessionId)}catch(Ue){const De=sh(Ue);th(Ue)?console.warn(De?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Ue instanceof Error?Ue.message:String(Ue)):console.error("Failed to switch CLI view mode:",Ue)}},[r,A,l]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${M.accent} relative overflow-hidden`,children:[s.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",M.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:S?bt.length>0?bt.map(_=>{const ie=a.find(ut=>(ut.type||"").toLowerCase()===(_.type||"").toLowerCase()&&kt(ut.status)!=="stopped"),ve=_.running||!!ie,Ue=!!ie&&ie.cdpConnected,De=E.includes(_.type||_.id||""),Ke=I===(_.type||"");return s.jsxs("button",{onClick:()=>{if(Ue&&ie){const ut=ie.sessionId;ut?f(ws(ut),{state:{openRemoteForTabKey:ut}}):f("/dashboard",{state:{openRemoteForTabKey:ie.id}});return}De||W(ut=>ut===(_.type||"")?"":_.type||"")},disabled:!!y||De,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Ue?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ke?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:y&&y!==_.type?.4:1},children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(_.type)}),ve&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Ue?"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"}`})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.name||ht(_.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Ue?"text-green-400":De?"text-orange-400":Ke?"text-accent-primary":"text-text-muted"}`,children:Ue?"Open Session":De?"Starting...":Ke?"Configure":"Select"})]})]},_.type)}):s.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.",s.jsxs("button",{onClick:g,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:[s.jsx(wm,{size:14})," Scan System"]})]}):O.length>0?O.map(_=>{const ie=I===_.type,ve=E.includes(_.type),De=!!a.find(Ke=>Ke.type===_.type&&kt(Ke.status)!=="stopped");return s.jsxs("button",{onClick:()=>W(Ke=>Ke===_.type?"":_.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ie?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:_.icon}),De&&s.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)]"})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ve?"text-orange-400":ie?"text-accent-primary":"text-text-muted"}`,children:ve?"Starting...":ie?"Configure":"Select"})]})]},_.type)}):s.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.",s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),I&&(S?bt.find(_=>_.type===I):O.find(_=>_.type===I))&&s.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:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:S?ht(I):P.get(I)||I})]}),s.jsx(XS,{machine:t,selectedWorkspace:me,resolvedWorkspacePath:Xe,customPath:fe,canBrowse:!!l,onWorkspaceChange:oe,onCustomPathChange:ce,onOpenBrowseDialog:J}),!S&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!k&&e==="cli"&&s.jsx(Bh,{busy:!!x||!!y||E.includes(I),savedSessionsLoading:ue,savedSessionsError:be,savedSessionsLoaded:xe,savedSessionsCount:Q.length,selectedSession:$e,onRefresh:()=>void X(I),onOpenHistory:()=>{I&&(ye(!0),$h({hasLoadedInitialResults:xe,isLoading:ue})&&X(I))},onClearSelection:()=>H("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[k&&s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),s.jsx("input",{type:"text",placeholder:"Leave empty for default",value:F,onChange:_=>L(_.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"})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),s.jsx("input",{type:"text",placeholder:"Optional flags...",value:K,onChange:_=>R(_.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.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:T.map(_=>s.jsxs("div",{className:"inline-flex max-w-full items-stretch overflow-hidden rounded-md border border-[#ffffff1a] bg-bg-tertiary text-xs text-text-secondary transition-colors hover:border-accent-primary/40 hover:text-text-primary",title:_,children:[s.jsx("button",{type:"button",className:"min-w-0 max-w-[220px] truncate px-2.5 py-1.5 text-left",onClick:()=>R(_),children:_}),s.jsx("button",{type:"button",className:"flex items-center justify-center border-l border-[#ffffff1a] px-1.5 text-text-muted transition-colors hover:bg-status-error/10 hover:text-status-error focus:outline-none focus:ring-1 focus:ring-status-error/50",onClick:()=>Ne(I,_),"aria-label":`Remove startup arguments: ${_}`,title:"Remove startup arguments",children:s.jsx(It,{size:12})})]},_))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:ke,disabled:!!x||!!y||E.includes(I),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:x===I||y===I?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+E.filter(_=>!a.some(ie=>ie.type===_&&kt(ie.status)!=="stopped")).length,")"]}),a.length===0&&qe.length===0?s.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"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[qe.map(_=>s.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:s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(_)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:S?ht(_):P.get(_)||_}),s.jsx("div",{className:"text-[11px] text-text-muted",children:x===_?"Launching process...":"Waiting for process and session to register..."})]})]}),s.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 ie=S?_:null,ve=!S&&!k?_:null,Ue=kt(_.status);return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(_.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[pt(_),(ie==null?void 0:ie.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",ie.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex min-w-0 flex-wrap items-center gap-2",children:[s.jsx("span",{className:"truncate",children:_.workspace||"—"}),h&&_.git&&_.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:De=>{De.stopPropagation(),h(_.daemonId??r,_.workspace)},children:s.jsx(br,{git:_.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(br,{git:_.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(ve==null?void 0:ve.mode)&&s.jsx("span",{className:ve.mode==="chat"?"text-violet-400":"text-text-secondary",children:ve.mode==="chat"?"Chat view":"Terminal view"})]}),ve&&(ve.runtimeKey||ve.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ve.runtimeKey&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),s.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",ve.runtimeKey]}),s.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 De;(De=navigator.clipboard)==null||De.writeText(`adhdev attach ${ve.runtimeKey}`),w(ve.runtimeKey||null),window.setTimeout(()=>{w(Ke=>Ke===ve.runtimeKey?null:Ke)},1200)},children:j===ve.runtimeKey?"Copied":"Copy"})]}),ve.runtimeWriteOwner&&s.jsx("span",{style:{color:ve.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ve.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:qS(ve.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Ue==="stopped"?"bg-red-500/[0.08] text-red-500":Ue==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Ue}),S&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const De=_.sessionId;if(De){f(ws(De),{state:{openRemoteForTabKey:De}});return}f("/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:s.jsx(Bt,{size:13})}),s.jsx("button",{onClick:()=>{const De=_.workspace||"",{options:Ke,selectedKey:ut}=Fs({machine:t,currentWorkspacePath:De});Be({title:Es("restart-ide",ht(_.type)),description:Ds("restart-ide"),confirmLabel:yr("restart-ide"),busyLabel:vr("restart-ide"),workspaceOptions:Ke,selectedWorkspaceKey:ut,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:ht(_.type)}]},async()=>{const Lt=Ke.find(hs=>hs.key===et.current),yt=(Lt==null?void 0:Lt.workspacePath)??"";if(yt&&yt!==De){await mt({type:_.type,workspacePath:yt});return}await b(_)})},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:s.jsx(vn,{size:14})})]}),k&&s.jsx("button",{onClick:()=>{const De=_.sessionId;De&&A(De)},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:s.jsx(cs,{size:14})}),ve&&Ue!=="stopped"&&s.jsxs(s.Fragment,{children:[ve.mode&&s.jsx(tc,{mode:ve.mode,onChange:De=>void _e(ve,De,!1),compact:!0}),s.jsx("button",{onClick:()=>{const De=_.sessionId;De&&A(De)},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:ve.mode==="chat"?s.jsx(cs,{size:14}):s.jsx(Bt,{size:13})})]}),Ue==="stopped"?s.jsx("button",{onClick:()=>{const De=_.workspace||"",Ke=S?ht(_.type):pt(_),{options:ut,selectedKey:Lt}=Fs({machine:t,currentWorkspacePath:De});Be({title:Es("restart-stopped",Ke),description:Ds("restart-stopped"),confirmLabel:yr("restart-stopped"),busyLabel:vr("restart-stopped"),workspaceOptions:ut,selectedWorkspaceKey:Lt,details:[{label:"Mode",value:M.label},{label:"Provider",value:Ke}]},async()=>{const yt=ut.find(hs=>hs.key===et.current);await mt({type:_.type,workspaceId:(yt==null?void 0:yt.workspaceId)??null,workspacePath:(yt==null?void 0:yt.workspacePath)??"",useHome:!(yt!=null&&yt.workspaceId)&&!(yt!=null&&yt.workspacePath)})})},disabled:E.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:E.includes(_.type)?"⏳":s.jsx(Fo,{size:14})}):s.jsx("button",{onClick:()=>G(_),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:s.jsx(It,{size:14})})]})]}),ie&&ie.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ie.aiAgents.map(De=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${ma(De.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[De.name," · ",kt(De.status)]},De.id))}),ie&&(We[ie.type]||[]).length>0&&l&&s.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[s.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:(We[ie.type]||[]).map(De=>s.jsxs("button",{disabled:tt===`${ie.type}.${De.type}`,onClick:async()=>{const Ke=`${ie.type}.${De.type}`;rt(Ke);try{await l(r,"set_ide_extension",{ideType:ie.type,extensionType:De.type,enabled:!De.enabled}),Le(ut=>({...ut,[ie.type]:(ut[ie.type]||[]).map(Lt=>Lt.type===De.type?{...Lt,enabled:!Lt.enabled}:Lt)}))}catch(ut){console.error("Extension toggle failed:",ut)}finally{rt(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 ${De.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${De.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),De.name,s.jsx("span",{className:"text-[9px] font-normal",children:De.enabled?"ON":"OFF"})]},De.type))})]})]},_.id)})]}),le&&l&&s.jsx(Ha,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:q,directories:we,busy:Re,error:Ae,confirmLabel:"Use this folder",onClose:()=>re(!1),onNavigate:_=>{V(_)},onConfirm:_=>{ce(_),oe("__custom__"),re(!1)}}),Ge&&s.jsx(mc,{title:Ge.title,description:Ge.description,details:Ge.details,workspaceOptions:Ge.workspaceOptions,selectedWorkspaceKey:at,onWorkspaceChange:_=>{et.current=_,gt(_)},confirmLabel:Ge.confirmLabel,busyLabel:Ge.busyLabel,busy:St,onConfirm:Ie,onCancel:()=>{Ve.current=null,Ze(null)}}),he&&te&&s.jsx(ic,{activeConv:te,ides:[],isCreatingChat:!1,isRefreshingHistory:ue,savedSessions:Q,isSavedSessionsLoading:ue,isResumingSavedSessionId:Ce,savedHistoryFilters:se,missingWorkspaceResumePath:Xe||null,onSavedHistoryFiltersChange:de,onClose:()=>ye(!1),onNewChat:()=>{H(""),ye(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{X(I)},onResumeSavedSession:_=>{if(!_.canResume||Ce)return;const ie=$(_);H(_.providerSessionId),ne(_),pe(_.providerSessionId),ye(!1),mt({type:_.providerType,workspaceId:ie.workspaceId,workspacePath:ie.workspacePath,useHome:ie.useHome,resumeSessionId:_.providerSessionId}).finally(()=>{pe(ve=>ve===_.providerSessionId?null:ve)})}})]})}const od=[{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 JS({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:o,getIcon:l,initialCategory:d="ide",initialWorkspaceId:u,initialWorkspacePath:h,sendDaemonCommand:f,onOpenGitDialog:m}){var g;const[v,b]=c.useState(d);c.useEffect(()=>{b(d)},[d]);const p=c.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.length]);return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[s.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:od.map(y=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${v===y.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>b(y.id),children:[s.jsx("span",{children:y.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${v===y.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:p[y.id]})]},y.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(g=od.find(y=>y.id===v))==null?void 0:g.helper})]}),v==="ide"&&s.jsx(Oi,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:o,sendDaemonCommand:f,initialWorkspaceId:u,initialWorkspacePath:h,onOpenGitDialog:m}),v==="cli"&&s.jsx(Oi,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:o,sendDaemonCommand:f,initialWorkspaceId:u,initialWorkspacePath:h,onOpenGitDialog:m}),v==="acp"&&s.jsx(Oi,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:i,getIcon:l,actions:o,sendDaemonCommand:f,initialWorkspaceId:u,initialWorkspacePath:h,onOpenGitDialog:m})]})}function QS({onNicknameSynced:e}={}){var ce,E,z,le,re,q,je,we,Pe,Re;const{id:t}=Pf(),r=Nr(),n=Po(),{sendCommand:a}=Ct(),i=kn(),o=Yu(),l=Tu(),d=l.ides||[],u=l.initialLoaded??!0,h=d.find(B=>B.id===t&&B.type==="adhdev-daemon"),f=d.some(B=>B.type==="adhdev-daemon"),m=t?(ce=l.connectionRetryStatuses)==null?void 0:ce[t]:void 0,v=!!(m!=null&&m.blocked),[b,p]=c.useState("workspace"),[g,y]=c.useState(null),x=c.useCallback((B,Ae)=>{y({daemonId:B,workspace:Ae})},[]),[N,j]=c.useState("ide"),w=c.useRef(null),[A,M]=c.useState(null),S=c.useRef("__home__"),[k,O]=c.useState("__home__"),[P,I]=c.useState(!1),W=c.useRef(null);c.useEffect(()=>{!t||!h||!(!h.workspaces||!h.availableProviders||!h.detectedIdes||!h.recentLaunches)||i(t,{minFreshMs:3e4}).catch(()=>{})},[i,h,t]),c.useEffect(()=>{if(!t||!h||b!=="overview")return;const B=h.machine;(typeof(B==null?void 0:B.cpus)!="number"||typeof(B==null?void 0:B.totalMem)!="number"||typeof(B==null?void 0:B.arch)!="string"||typeof(B==null?void 0:B.release)!="string")&&o(t,{minFreshMs:3e4}).catch(()=>{})},[b,o,h,t]),Xy(t&&b==="overview"?[t]:[],{enabled:b==="overview",intervalMs:Ug});const K=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},R=Gw({machineId:t,registeredMachineId:(h==null?void 0:h.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:W});c.useEffect(()=>ct.onToast(Ae=>{l.setToasts(Ve=>{if(Ve.some(et=>et.message===Ae.message&&Ae.timestamp-et.timestamp<3e3))return Ve;const Ze={id:Ae.id,message:Ae.message,type:Ae.type,timestamp:Ae.timestamp,targetKey:Ae.targetKey,actions:Ae.actions};return[...Ve.slice(-4),Ze]});const Ee=Ae.duration||5e3;setTimeout(()=>l.setToasts(Ve=>Ve.filter(Ge=>Ge.id!==Ae.id)),Ee)}),[l]);const T=(h==null?void 0:h.availableProviders)||[],C={};for(const B of T)C[B.type]=B.icon;const F=B=>C[B]||"",L=h?{id:h.id,hostname:tu(h,{fallbackId:h.id}),platform:((E=h.machine)==null?void 0:E.platform)||"unknown",arch:((z=h.machine)==null?void 0:z.arch)||"",cpus:((le=h.machine)==null?void 0:le.cpus)||0,totalMem:((re=h.machine)==null?void 0:re.totalMem)||0,freeMem:(q=h.machine)==null?void 0:q.freeMem,availableMem:(je=h.machine)==null?void 0:je.availableMem,loadavg:(we=h.machine)==null?void 0:we.loadavg,uptime:(Pe=h.machine)==null?void 0:Pe.uptime,release:((Re=h.machine)==null?void 0:Re.release)||"",cdpConnected:!!h.cdpConnected,machineNickname:h.machineNickname||null,p2p:h.p2p?{screenshotActive:!1,...h.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:h.detectedIdes||[],workspaces:h.workspaces||[],defaultWorkspaceId:h.defaultWorkspaceId??h.activeWorkspaceId??null,defaultWorkspacePath:h.defaultWorkspacePath??h.activeWorkspacePath??null}:null,D=d.filter(B=>B.daemonId===t&&B.type!=="adhdev-daemon").filter(B=>!mn(B)&&!or(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,version:B.version||"",instanceId:B.instanceId||"",status:B.status,workspace:B.workspace||null,terminals:B.terminals||0,aiAgents:Lx(B.aiAgents||(B.agents||[]).map(Ae=>({id:Ae.name,name:Ae.name,status:Ae.status,version:Ae.version}))),activeChat:B.activeChat||null,chats:B.chats||[],childSessions:B.childSessions||[],cdpConnected:B.cdpConnected||!1,daemonId:t,lastMessageAt:B.lastMessageAt})),H=d.filter(B=>B.daemonId===t&&mn(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,cliName:B.cliName||B.type,status:B.status,workspace:B.workspace||"",activeChat:B.activeChat||null,providerSessionId:B.providerSessionId,mode:B.mode,runtimeKey:B.runtimeKey,runtimeDisplayName:B.runtimeDisplayName,runtimeWorkspaceLabel:B.runtimeWorkspaceLabel,runtimeWriteOwner:B.runtimeWriteOwner||null,runtimeAttachedClients:B.runtimeAttachedClients||[],daemonId:t,lastMessageAt:B.lastMessageAt})),Q=d.filter(B=>B.daemonId===t&&or(B)).map(B=>({id:B.id,sessionId:B.sessionId,type:B.type,acpName:B.cliName||B.type,status:B.status,workspace:B.workspace||"",activeChat:B.activeChat||null,providerSessionId:B.providerSessionId,daemonId:t,lastMessageAt:B.lastMessageAt})),ge=h?$t(h,{fallbackId:t}):"",ue="workspace",Z=n.state,xe=Z==null?void 0:Z.initialMachineTab,Se=Z==null?void 0:Z.initialWorkspaceCategory,be=Z==null?void 0:Z.initialWorkspaceId,Y=Z==null?void 0:Z.initialWorkspacePath,he=xe==="ides"||xe==="clis"||xe==="acps"?"workspace":xe||ue,ye=xe==="ides"?"ide":xe==="clis"?"cli":xe==="acps"?"acp":Se,se=[...D.map(B=>{var Ae;return{id:`ide:${B.type}:${B.workspace||""}`,label:((Ae=B.activeChat)==null?void 0:Ae.title)||B.type,kind:"ide",providerType:B.type,subtitle:B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:B.lastMessageAt||0}}),...H.map(B=>{var Ae;return{id:`cli:${B.type}:${B.workspace||""}`,label:((Ae=B.activeChat)==null?void 0:Ae.title)||B.cliName,kind:"cli",providerType:B.type,providerSessionId:B.providerSessionId,subtitle:B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:B.lastMessageAt||0}}),...Q.map(B=>{var Ae;return{id:`acp:${B.type}:${B.workspace||""}`,label:((Ae=B.activeChat)==null?void 0:Ae.title)||B.acpName,kind:"acp",providerType:B.type,providerSessionId:B.providerSessionId,subtitle:Vs(B.summaryMetadata)||B.workspace||void 0,workspace:B.workspace||void 0,lastLaunchedAt:B.lastMessageAt||0}})].sort((B,Ae)=>(Ae.lastLaunchedAt||0)-(B.lastLaunchedAt||0)),de=((h==null?void 0:h.recentLaunches)||[]).length>0?((h==null?void 0:h.recentLaunches)||[]).map(B=>({id:B.id,label:B.title||B.providerName||B.providerType,kind:B.kind,providerType:B.providerType,providerSessionId:B.providerSessionId,subtitle:Vs(B.summaryMetadata)||B.workspace||void 0,workspace:B.workspace,summaryMetadata:B.summaryMetadata,lastLaunchedAt:B.lastLaunchedAt})):se,Ce=c.useMemo(()=>{var Ae;const B=((Ae=l.connectionStates)==null?void 0:Ae[t||""])||void 0;return d.filter(Ee=>Ee.daemonId===t&&Ee.type!=="adhdev-daemon").flatMap(Ee=>oc(Ee,{connectionStates:t&&B?{[t]:B}:void 0,defaultConnectionState:B})).filter(Ee=>!(Ee.transport==="pty"&&Ee.mode==="terminal")).sort((Ee,Ve)=>mo(Ve)-mo(Ee))},[d,l.connectionStates,t]),pe=c.useCallback(B=>{const Ae=mh(B);Ae&&r(ws(Ae))},[r]),me=c.useCallback(()=>{w.current&&(I(!0),w.current().finally(()=>{w.current=null,I(!1),M(null)}))},[]),oe=c.useCallback(B=>{if(!L)return;const{options:Ae,selectedKey:Ee}=Fs({machine:L,currentWorkspacePath:B.workspace}),Ve=async()=>{j(B.kind),p("workspace")};w.current=async()=>{const Ge=Ae.find(at=>at.key===S.current),Ze=(Ge==null?void 0:Ge.workspacePath)??null,et=(Ge==null?void 0:Ge.workspaceId)??null;if(B.kind==="ide"&&B.providerType){await R.handleLaunchIde(B.providerType,Ze?{workspace:Ze}:void 0);return}if((B.kind==="cli"||B.kind==="acp")&&B.providerType){await R.runLaunchCliCore({cliType:B.providerType,dir:et?void 0:Ze||"",workspaceId:et||void 0,model:B.kind==="acp"&&ru(B.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:B.providerSessionId});return}await Ve()},S.current=Ee,O(Ee),M({title:B.kind==="ide"?Es("restart-ide",B.label):B.providerSessionId?nc(B.label):Es("start-fresh",B.label),description:B.kind==="ide"?Ds("restart-ide"):B.providerSessionId?ac():Ds("start-fresh"),confirmLabel:B.kind==="ide"?yr("restart-ide"):B.providerSessionId?va(!0):yr("start-fresh"),busyLabel:B.kind==="ide"?vr("restart-ide"):B.providerSessionId?sc(!0):vr("start-fresh"),workspaceOptions:Ae,details:[{label:"Mode",value:B.kind.toUpperCase()},...B.providerType?[{label:"Provider",value:B.providerType}]:[]]})},[R,L]);if(c.useEffect(()=>{p(he)},[ue,he,t]),c.useEffect(()=>{ye&&j(ye)},[ye,t]),!L)return u?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:K,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const fe=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Bt,{size:14})," Workspace"]}),count:D.length+H.length+Q.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ys,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ra,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(km,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ym,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.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:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:K,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:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[R.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:R.nicknameInput,onChange:B=>R.setNicknameInput(B.target.value),onKeyDown:B=>{B.key==="Enter"&&R.handleSaveNickname(),B.key==="Escape"&&R.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]"}),s.jsx("button",{onClick:R.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"}),s.jsx("button",{onClick:()=>R.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"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{R.setEditingNickname(!0),R.setNicknameInput(L.machineNickname||"")},title:"Click to set nickname",children:ge}),v?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),l.retryConnection&&t&&s.jsx("button",{onClick:()=>l.retryConnection(t),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:"Reconnect"})]}):s.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"})]}),s.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:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[L.platform," · ",L.arch]}),s.jsxs("span",{children:[L.cpus," cores"]}),(h==null?void 0:h.version)&&s.jsxs("span",{children:["v",h.version]}),L.p2p.available&&s.jsxs("span",{children:["P2P ",L.p2p.state==="connected"?"connected":L.p2p.state]}),L.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:L.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:fe.map(B=>s.jsxs("button",{onClick:()=>p(B.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${b===B.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[B.label,B.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${b===B.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:B.count})]},B.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[b==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(GS,{machineEntry:h,providers:T,recentLaunches:de,currentConversations:Ce,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",hh(h))}catch{}},onOpenRecent:oe,onOpenConversation:pe}),s.jsx(JS,{machine:L,machineId:t,providers:T,ideSessions:D,cliSessions:H,acpSessions:Q,actions:R,getIcon:F,initialCategory:N,initialWorkspaceId:be,initialWorkspacePath:Y,sendDaemonCommand:a,onOpenGitDialog:x})]}),b==="providers"&&s.jsx(rS,{machineId:t,providers:T,sendDaemonCommand:a}),b==="overview"&&s.jsx(qw,{machineId:t,machine:L,ideSessions:D,cliSessions:H,acpSessions:Q,actions:R,sendDaemonCommand:a}),b==="session-host"&&s.jsx(zS,{machineId:t,cliSessions:H,sendDaemonCommand:a}),b==="logs"&&s.jsx(BS,{machineId:t,sendDaemonCommand:a})]})})}),R.launchPick&&L&&s.jsx(VS,{machine:L,launchPick:R.launchPick,actions:R}),A&&s.jsx(mc,{title:A.title,description:A.description,details:A.details,workspaceOptions:A.workspaceOptions,selectedWorkspaceKey:k,onWorkspaceChange:B=>{S.current=B,O(B)},confirmLabel:A.confirmLabel,busyLabel:A.busyLabel,busy:P,onConfirm:me,onCancel:()=>{w.current=null,M(null)}}),g&&s.jsx(Wh,{daemonId:g.daemonId,workspace:g.workspace,onClose:()=>y(null)}),s.jsx($u,{toasts:l.toasts||[],onDismiss:B=>l.setToasts(Ae=>Ae.filter(Ee=>Ee.id!==B)),onClickToast:B=>{B.targetKey&&r(ws(B.targetKey))}}),s.jsx("style",{children:`
92
+ @keyframes toast-in {
93
+ from { opacity: 0; transform: translateX(40px); }
94
+ to { opacity: 1; transform: translateX(0); }
95
+ }
96
+ `})]})}function ZS(e){switch(e){case"online":return"#22c55e";case"dirty":return"#f59e0b";case"degraded":return"#ef4444";case"wrong_branch":return"#a855f7";case"offline":return"#6b7280";default:return"#9ca3af"}}function ek(e){switch(e){case"parentBranch":return"rgba(148,163,184,0.6)";case"worktreeLink":return"rgba(59,130,246,0.4)";case"sessionLink":return"rgba(168,85,247,0.4)";default:return"rgba(148,163,184,0.3)"}}function tk(e,t,r,n,a=120){const i=r/2,o=n/2;for(let l=0;l<a;l++){for(let d=0;d<e.length;d++)for(let u=d+1;u<e.length;u++){const h=e[u].x-e[d].x,f=e[u].y-e[d].y;let m=Math.sqrt(h*h+f*f)||1;const v=8e3/(m*m),b=h/m*v,p=f/m*v;e[d].vx-=b,e[d].vy-=p,e[u].vx+=b,e[u].vy+=p}for(const d of t){const u=e.find(x=>x.id===d.source),h=e.find(x=>x.id===d.target);if(!u||!h)continue;const f=h.x-u.x,m=h.y-u.y,v=Math.sqrt(f*f+m*m)||1,b=d.type==="parentBranch"?140:90,p=(v-b)/v*.08,g=f*p,y=m*p;u.vx+=g,u.vy+=y,h.vx-=g,h.vy-=y}for(const d of e)d.vx+=(i-d.x)*.003,d.vy+=(o-d.y)*.003;for(const d of e){d.vx*=.85,d.vy*=.85,d.x+=d.vx,d.y+=d.vy;const u=d.radius+10;d.x=Math.max(u,Math.min(r-u,d.x)),d.y=Math.max(u,Math.min(n-u,d.y))}}}function sk({data:e,width:t=800,height:r=500,onNodeClick:n,selectedNodeId:a}){const i=c.useRef(null),[o,l]=c.useState(1),[d,u]=c.useState({x:0,y:0}),[h,f]=c.useState(!1),m=c.useRef(null),v=c.useMemo(()=>{const x=e.nodes.map((N,j)=>({...N,x:t/2+Math.cos(j/Math.max(e.nodes.length,1)*Math.PI*2)*120,y:r/2+Math.sin(j/Math.max(e.nodes.length,1)*Math.PI*2)*120,vx:0,vy:0,radius:N.type==="defaultBranchNode"?28:20}));return tk(x,e.edges,t,r,120),x},[e,t,r]),b=c.useCallback(x=>{x.preventDefault();const N=x.deltaY>0?.9:1.1;l(j=>Math.max(.3,Math.min(3,j*N)))},[]),p=c.useCallback(x=>{m.current={startX:x.clientX,startY:x.clientY,panX:d.x,panY:d.y},f(!0)},[d]),g=c.useCallback(x=>{if(!m.current)return;const N=m.current;u({x:N.panX+(x.clientX-N.startX),y:N.panY+(x.clientY-N.startY)})},[]),y=c.useCallback(()=>{m.current=null,f(!1)},[]);return s.jsxs("div",{className:"relative rounded-xl border border-border-subtle bg-bg-panel overflow-hidden",style:{width:t,height:r},children:[s.jsxs("div",{className:"absolute top-2 left-2 z-10 flex flex-wrap gap-2",children:[s.jsxs("span",{className:"px-2 py-0.5 rounded bg-bg-glass text-[10px] text-text-muted border border-border-subtle",children:["Nodes: ",e.stats.totalNodes]}),s.jsxs("span",{className:"px-2 py-0.5 rounded bg-green-500/10 text-[10px] text-green-400 border border-green-500/20",children:["Online: ",e.stats.onlineNodes]}),e.stats.dirtyNodes>0&&s.jsxs("span",{className:"px-2 py-0.5 rounded bg-yellow-500/10 text-[10px] text-yellow-400 border border-yellow-500/20",children:["Dirty: ",e.stats.dirtyNodes]}),e.stats.orphanNodes>0&&s.jsxs("span",{className:"px-2 py-0.5 rounded bg-red-500/10 text-[10px] text-red-400 border border-red-500/20",children:["Orphan: ",e.stats.orphanNodes]}),e.stats.totalActiveSessions>0&&s.jsxs("span",{className:"px-2 py-0.5 rounded bg-blue-500/10 text-[10px] text-blue-400 border border-blue-500/20",children:["Sessions: ",e.stats.totalActiveSessions]})]}),s.jsxs("div",{className:"absolute bottom-2 right-2 z-10 flex flex-col gap-1",children:[s.jsx("button",{className:"w-7 h-7 rounded bg-bg-glass border border-border-subtle text-text-muted hover:text-text-primary flex items-center justify-center text-xs",onClick:()=>l(x=>Math.min(3,x*1.2)),children:"+"}),s.jsx("button",{className:"w-7 h-7 rounded bg-bg-glass border border-border-subtle text-text-muted hover:text-text-primary flex items-center justify-center text-xs",onClick:()=>l(x=>Math.max(.3,x/1.2)),children:"-"}),s.jsx("button",{className:"w-7 h-7 rounded bg-bg-glass border border-border-subtle text-text-muted hover:text-text-primary flex items-center justify-center text-[9px]",onClick:()=>{l(1),u({x:0,y:0})},children:"⟲"})]}),e.warnings.length>0&&s.jsx("div",{className:"absolute top-2 right-2 z-10 flex flex-col gap-1 max-w-[200px]",children:e.warnings.map((x,N)=>s.jsxs("div",{className:"px-2 py-0.5 rounded bg-red-500/10 text-[10px] text-red-400 border border-red-500/20",children:["⚠ ",x]},N))}),s.jsx("svg",{ref:i,width:t,height:r,onWheel:b,onMouseDown:p,onMouseMove:g,onMouseUp:y,onMouseLeave:y,style:{cursor:h?"grabbing":"grab"},children:s.jsxs("g",{transform:`translate(${d.x}, ${d.y}) scale(${o})`,children:[e.edges.map(x=>{const N=v.find(w=>w.id===x.source),j=v.find(w=>w.id===x.target);return!N||!j?null:s.jsxs("g",{children:[s.jsx("line",{x1:N.x,y1:N.y,x2:j.x,y2:j.y,stroke:ek(x.type),strokeWidth:x.type==="parentBranch"?2:1,strokeDasharray:x.type==="worktreeLink"?"4 3":void 0}),x.label&&s.jsx("text",{x:(N.x+j.x)/2,y:(N.y+j.y)/2-4,fill:"#94a3b8",fontSize:9,textAnchor:"middle",children:x.label})]},x.id)}),v.map(x=>s.jsxs("g",{transform:`translate(${x.x}, ${x.y})`,onClick:()=>n==null?void 0:n(x),style:{cursor:"pointer"},children:[x.hasConflicts&&s.jsxs("circle",{r:x.radius+6,fill:"none",stroke:"#ef4444",strokeWidth:1.5,opacity:.5,children:[s.jsx("animate",{attributeName:"r",values:`${x.radius+4};${x.radius+8};${x.radius+4}`,dur:"2s",repeatCount:"indefinite"}),s.jsx("animate",{attributeName:"opacity",values:"0.6;0.2;0.6",dur:"2s",repeatCount:"indefinite"})]}),s.jsx("circle",{r:x.radius,fill:ZS(x.health),opacity:x.health==="offline"?.4:.9,stroke:a===x.id?"#38bdf8":"#0f172a",strokeWidth:a===x.id?3:2}),x.dirty&&s.jsx("circle",{r:x.radius-4,fill:"none",stroke:"#f59e0b",strokeWidth:a===x.id?3:2,strokeDasharray:"3 2"}),s.jsx("text",{y:x.radius+14,fill:"#e2e8f0",fontSize:10,textAnchor:"middle",fontWeight:600,children:x.label}),x.branch&&s.jsx("text",{y:x.radius+26,fill:"#94a3b8",fontSize:9,textAnchor:"middle",children:x.branch}),(x.ahead>0||x.behind>0)&&s.jsxs("g",{transform:`translate(${x.radius-6}, -${x.radius-6})`,children:[s.jsx("circle",{r:10,fill:"#0f172a",stroke:"#334155",strokeWidth:1}),s.jsx("text",{y:3,fill:"#e2e8f0",fontSize:8,textAnchor:"middle",children:x.ahead>0?`+${x.ahead}`:`-${x.behind}`})]}),x.activeSessionCount>0&&s.jsxs("g",{transform:`translate(-${x.radius-6}, -${x.radius-6})`,children:[s.jsx("circle",{r:10,fill:"#0f172a",stroke:"#3b82f6",strokeWidth:1}),s.jsx("text",{y:3,fill:"#60a5fa",fontSize:8,textAnchor:"middle",children:x.activeSessionCount})]})]},x.id))]})})]})}function Ts({label:e,value:t}){return t==null||t===""?null:s.jsxs("div",{className:"flex justify-between text-[11px] py-0.5 border-b border-border-subtle/50",children:[s.jsx("span",{className:"text-text-muted",children:e}),s.jsx("span",{className:"text-text-secondary font-medium",children:String(t)})]})}function rk({health:e}){const t={online:"bg-green-500/10 text-green-400 border-green-500/20",dirty:"bg-yellow-500/10 text-yellow-400 border-yellow-500/20",degraded:"bg-red-500/10 text-red-400 border-red-500/20",wrong_branch:"bg-purple-500/10 text-purple-400 border-purple-500/20",offline:"bg-gray-500/10 text-gray-400 border-gray-500/20",unknown:"bg-gray-500/10 text-gray-400 border-gray-500/20"};return s.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] border ${t[e]||t.unknown}`,children:e})}function nk({node:e,onClose:t}){return e?s.jsxs("div",{className:"w-64 rounded-xl border border-border-subtle bg-bg-panel p-4 flex flex-col gap-2 shadow-lg",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary truncate",children:e.label}),t&&s.jsx("button",{onClick:t,className:"text-text-muted hover:text-text-primary text-xs",children:"✕"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(rk,{health:e.health}),e.dirty&&s.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-yellow-500/10 text-yellow-400 border border-yellow-500/20",children:"Dirty"}),e.hasConflicts&&s.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-red-500/10 text-red-400 border border-red-500/20",children:"Conflict"}),e.isOrphan&&s.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-red-500/10 text-red-400 border border-red-500/20",children:"Orphan"})]}),s.jsxs("div",{className:"flex flex-col gap-0.5 mt-1",children:[s.jsx(Ts,{label:"Workspace",value:e.workspace}),s.jsx(Ts,{label:"Branch",value:e.branch}),s.jsx(Ts,{label:"Ahead",value:e.ahead>0?`+${e.ahead}`:null}),s.jsx(Ts,{label:"Behind",value:e.behind>0?`-${e.behind}`:null}),s.jsx(Ts,{label:"Dirty files",value:e.dirtyFiles>0?e.dirtyFiles:null}),s.jsx(Ts,{label:"Active sessions",value:e.activeSessionCount>0?e.activeSessionCount:null}),s.jsx(Ts,{label:"Providers",value:e.providers.join(", ")||null})]}),e.orphanReasons.length>0&&s.jsxs("div",{className:"mt-1",children:[s.jsx("div",{className:"text-[10px] font-semibold text-red-400 mb-1",children:"Orphan reasons"}),s.jsx("ul",{className:"list-disc list-inside text-[10px] text-red-300 space-y-0.5",children:e.orphanReasons.map((r,n)=>s.jsx("li",{children:r},n))})]}),e.nextStepHint&&s.jsxs("div",{className:"mt-1 px-2 py-1.5 rounded bg-blue-500/10 border border-blue-500/20 text-[10px] text-blue-300",children:["💡 ",e.nextStepHint]})]}):s.jsx("div",{className:"w-64 rounded-xl border border-border-subtle bg-bg-panel p-4 text-text-muted text-xs",children:"Select a node to view details."})}var cd=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),ak=80,ik=32;function ok(e,t){const r={},n={...e,...t||{}};for(const[a,i]of Object.entries(n))typeof i=="string"&&(r[a]=i);for(const a of Object.keys(r))(a==="INIT_CWD"||a==="npm_command"||a==="npm_execpath"||a==="npm_node_execpath"||a.startsWith("npm_")||a.startsWith("npm_config_")||a.startsWith("npm_package_")||a.startsWith("npm_lifecycle_")||a.startsWith("PNPM_")||a.startsWith("YARN_")||a.startsWith("BUN_")||a.startsWith("VSCODE_")||a.startsWith("ELECTRON_"))&&delete r[a];return delete r.CODEX_THREAD_ID,delete r.CODEX_INTERNAL_ORIGINATOR_OVERRIDE,ck(r),r}function ck(e){e.NO_COLOR||((!e.TERM||e.TERM==="xterm-color")&&(e.TERM="xterm-256color"),e.COLORTERM||(e.COLORTERM="truecolor"),process.platform==="win32"&&(e.FORCE_COLOR||(e.FORCE_COLOR="1"),e.CLICOLOR||(e.CLICOLOR="1")))}function lk(e){if(vt.platform()!=="win32")try{const t=cd("fs"),r=ze.resolve(ze.dirname(cd.resolve("node-pty")),".."),n=`${vt.platform()}-${vt.arch()}`,a=ze.join(r,"prebuilds",n,"spawn-helper");if(t.existsSync(a)){const i=t.statSync(a);i.mode&73||(t.chmodSync(a,i.mode|493),e==null||e(`Fixed spawn-helper permissions: ${a}`))}}catch{}}var Kt={},dk=Object.defineProperty,uk=Object.getOwnPropertyNames,Ir=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),wt=(e,t)=>function(){return e&&(t=(0,e[uk(e)[0]])(e=0)),t},js=(e,t)=>{for(var r in t)dk(e,r,{get:t[r],enumerable:!0})},Sc,kc=wt({"src/repo-mesh-types.ts"(){Sc={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,spawnedSessionVisibility:"visible",sessionCleanupOnNodeRemove:"preserve",maxTaskRetries:1}}}),hk={};js(hk,{createWorktree:()=>pk,listWorktrees:()=>mk,parseWorktreeListOutput:()=>zh,removeWorktree:()=>fk,resolveWorktreePath:()=>Hh});function Hh(e,t,r){const n=r.replace(/[/\\:*?"<>|]/g,"-").replace(/^\.+|\.+$/g,""),a=t.replace(/[/\\:*?"<>|]/g,"-").replace(/^\.+|\.+$/g,""),i=ze.dirname(e);return ze.join(i,Vh,a,n)}async function pk(e){const{repoRoot:t,branch:r,baseBranch:n,meshName:a}=e,i=e.targetDir||Hh(t,a,r);if(Ot(i))throw new Error(`Worktree target directory already exists: ${i}`);await Bf(ze.dirname(i),{recursive:!0});const o=["worktree","add",i,"-b",r];n&&o.push(n);try{await Ws("git",o,{cwd:t,encoding:"utf8",timeout:Us,maxBuffer:dr,windowsHide:!0})}catch(l){const d=typeof l.stderr=="string"?l.stderr:"";throw/already exists/i.test(d)?new Error(`Branch '${r}' already exists or is checked out in another worktree`):new Error(`git worktree add failed: ${d.trim()||l.message}`)}return{success:!0,worktreePath:i,branch:r}}async function fk(e,t,r={}){if(!Ot(t))return await xk(e),{success:!0,removedPath:t};if(r.requireClean){const{stdout:n}=await Ws("git",["status","--porcelain"],{cwd:t,encoding:"utf8",timeout:Us,maxBuffer:dr,windowsHide:!0});if(n.trim())throw new Error(`Refusing to remove dirty worktree: ${t}`)}try{await Ws("git",["worktree","remove",t],{cwd:e,encoding:"utf8",timeout:Us,maxBuffer:dr,windowsHide:!0})}catch(n){const a=typeof n.stderr=="string"?n.stderr:"",i=typeof n.stdout=="string"?n.stdout:"",o=`${a}
97
+ ${i}
98
+ ${n.message||""}`;if(r.allowSubmoduleForceFallback&&Gh.test(o)){try{await Ws("git",["worktree","remove","--force",t],{cwd:e,encoding:"utf8",timeout:Us,maxBuffer:dr,windowsHide:!0})}catch(l){const d=typeof l.stderr=="string"?l.stderr:"",u=typeof l.stdout=="string"?l.stdout:"";throw new Error(`git worktree remove --force fallback failed: ${d.trim()||u.trim()||l.message}`)}return{success:!0,removedPath:t,fallback:"git_worktree_remove_force_submodule",forced:!0,reason:"working_trees_containing_submodules"}}throw new Error(`git worktree remove failed: ${a.trim()||i.trim()||n.message}`)}return{success:!0,removedPath:t}}async function mk(e){const{stdout:t}=await Ws("git",["worktree","list","--porcelain"],{cwd:e,encoding:"utf8",timeout:Us,maxBuffer:dr,windowsHide:!0});return zh(t)}function zh(e){const t=[],r=e.trim().split(/\n\n+/);for(const n of r){if(!n.trim())continue;const a=n.trim().split(`
99
+ `),i={path:"",head:"",branch:null,bare:!1};for(const o of a)if(o.startsWith("worktree "))i.path=o.slice(9).trim();else if(o.startsWith("HEAD "))i.head=o.slice(5).trim();else if(o.startsWith("branch ")){const l=o.slice(7).trim();i.branch=l.replace(/^refs\/heads\//,"")}else o==="bare"&&(i.bare=!0);i.path&&t.push(i)}return t}async function xk(e){try{await Ws("git",["worktree","prune"],{cwd:e,encoding:"utf8",timeout:Us,windowsHide:!0})}catch{}}var Ws,Vh,Us,dr,Gh,gk=wt({"src/git/git-worktree.ts"(){Ws=Ad(Id),Vh=".adhdev-worktrees",Us=3e4,dr=4*1024*1024,Gh=/working trees containing submodules cannot be moved or removed/i}}),bk={};js(bk,{generateMachineId:()=>Yh,getConfigDir:()=>Ar,isSetupComplete:()=>Sk,isStableMachineId:()=>Jh,loadConfig:()=>Ga,markSetupComplete:()=>wk,resetConfig:()=>kk,resolveProviderSourceMode:()=>qh,saveConfig:()=>xn,updateConfig:()=>Zh});function qh(e,t){return e==="normal"||e==="no-upstream"?e:t===!0?"no-upstream":"normal"}function es(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Fi(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Is(e){return typeof e=="string"?e:null}function Gn(e){return typeof e=="string"&&e.trim()?e:void 0}function ld(e,t){return typeof e=="boolean"?e:t}function yk(e){if(!es(e))return{};const t={};for(const[r,n]of Object.entries(e)){if(!es(n))continue;const a={};n.enabled===!0&&(a.enabled=!0),typeof n.executable=="string"&&n.executable.trim()&&(a.executable=n.executable.trim()),Array.isArray(n.args)&&(a.args=n.args.filter(i=>typeof i=="string")),es(n.lastDetection)&&(a.lastDetection=n.lastDetection),es(n.lastVerification)&&(a.lastVerification=n.lastVerification),t[r]=a}return t}function Xh(e){const t=es(e)?e:{};return{serverUrl:typeof t.serverUrl=="string"&&t.serverUrl.trim()?t.serverUrl:Ks.serverUrl,allowServerApiProxy:ld(t.allowServerApiProxy,Ks.allowServerApiProxy??!1),selectedIde:Is(t.selectedIde),configuredIdes:Fi(t.configuredIdes),installedExtensions:Fi(t.installedExtensions),userEmail:Is(t.userEmail),userName:Is(t.userName),setupCompleted:ld(t.setupCompleted,Ks.setupCompleted),setupDate:Is(t.setupDate),enabledIdes:Fi(t.enabledIdes),workspaces:Array.isArray(t.workspaces)?t.workspaces:[],defaultWorkspaceId:Is(t.defaultWorkspaceId)??Is(t.activeWorkspaceId),machineNickname:Is(t.machineNickname),machineId:Gn(t.machineId),machineSecret:t.machineSecret===null?null:Gn(t.machineSecret),registeredMachineId:Gn(t.registeredMachineId),providerSettings:es(t.providerSettings)?t.providerSettings:{},machineProviders:yk(t.machineProviders),ideSettings:es(t.ideSettings)?t.ideSettings:{},providerSourceMode:qh(t.providerSourceMode,t.disableUpstream),providerDir:Gn(t.providerDir),updateChannel:t.updateChannel==="preview"?"preview":"stable",terminalSizingMode:t.terminalSizingMode==="fit"?"fit":"measured"}}function Yh(){return`${jc}${yn().replace(/-/g,"")}`}function Jh(e){return typeof e=="string"&&e.startsWith(jc)}function Wi(e){return Jh(e.machineId)?{config:e,changed:!1}:{config:{...e,machineId:Yh()},changed:!0}}function Ar(){const e=Kt.ADHDEV_CONFIG_DIR,t=e&&e.trim()?e.trim():ks(Gf(),".adhdev");return Ot(t)||Lo(t,{recursive:!0}),t}function Qh(){return ks(Ar(),"config.json")}function vk(e){const t=ks(Ar(),"state.json");if(Ot(t))return;const r=Array.isArray(e.recentActivity)?e.recentActivity:[],n=Array.isArray(e.savedProviderSessions)?e.savedProviderSessions:[],a=es(e.recentSessionReads)?e.recentSessionReads:{},i=es(e.sessionReads)?e.sessionReads:{},o=es(e.sessionReadMarkers)?e.sessionReadMarkers:{};if(!(r.length>0||n.length>0||Object.keys(i).length>0||Object.keys(a).length>0||Object.keys(o).length>0))return;const d=Object.fromEntries(Object.entries({...a,...i}).filter(([,f])=>typeof f=="number"&&Number.isFinite(f))),u=Object.fromEntries(Object.entries(o).filter(([,f])=>typeof f=="string"));_a(t,JSON.stringify({recentActivity:r,savedProviderSessions:n,sessionReads:d,sessionReadMarkers:u},null,2),{encoding:"utf-8",mode:384})}function Ga(){const e=Qh();if(!Ot(e)){const t=Wi({...Ks});try{xn(t.config)}catch{}return t.config}try{const t=Ma(e,"utf-8"),r=JSON.parse(t);vk(r);const n=Xh(r),a=Wi(n),i=a.config;if(a.changed||JSON.stringify(r)!==JSON.stringify(i))try{xn(i)}catch{}return i}catch{return Wi({...Ks}).config}}function xn(e){const t=Qh(),r=Ar(),n=Xh(e);Ot(r)||Lo(r,{recursive:!0,mode:448}),_a(t,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384});try{Wf(t,384)}catch{}}function Zh(e){const r={...Ga(),...e};return xn(r),r}function wk(e,t){const r=Array.isArray(e)?e:[e];return Zh({selectedIde:r[0],configuredIdes:r,installedExtensions:t,setupCompleted:!0,setupDate:new Date().toISOString()})}function Sk(){return Ga().setupCompleted}function kk(){xn({...Ks})}var Ks,jc,Ht=wt({"src/config/config.ts"(){Ks={serverUrl:"https://api.adhf.dev",allowServerApiProxy:!1,selectedIde:null,configuredIdes:[],installedExtensions:[],userEmail:null,userName:null,setupCompleted:!1,setupDate:null,enabledIdes:[],workspaces:[],defaultWorkspaceId:null,machineNickname:null,machineId:void 0,machineSecret:null,registeredMachineId:void 0,providerSettings:{},machineProviders:{},ideSettings:{},providerSourceMode:"normal",updateChannel:"stable",terminalSizingMode:"measured"},jc="mach_"}}),jk={};js(jk,{addNode:()=>Ak,createMesh:()=>Ck,deleteMesh:()=>Ik,getMesh:()=>Nc,getMeshByRepo:()=>rp,listMeshes:()=>Nk,normalizeRepoIdentity:()=>tp,removeNode:()=>Mk,updateMesh:()=>Tk,updateNode:()=>_k});function ep(){return ks(Ar(),"meshes.json")}function ds(){const e=ep();if(!Ot(e))return{meshes:[]};try{const t=JSON.parse(Ma(e,"utf-8"));return!t||!Array.isArray(t.meshes)?{meshes:[]}:t}catch{return{meshes:[]}}}function Mr(e){const t=ep();_a(t,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function tp(e){let t=e.trim();if(t.startsWith("http://")||t.startsWith("https://"))try{const n=new URL(t),a=n.pathname.replace(/^\//,"").replace(/\.git$/,"");return`${n.hostname}/${a}`}catch{}const r=t.match(/^(?:ssh:\/\/)?[\w.-]+@([\w.-]+)[:/]([\w.\-/]+?)(?:\.git)?$/);return r?`${r[1]}/${r[2]}`:t}function sp(e,t){const r={...Sc,...e||{},...t||{}};["block","warn","checkpoint_then_continue"].includes(r.dirtyWorkspaceBehavior)||(r.dirtyWorkspaceBehavior="warn");const n=Number(r.maxParallelTasks);return r.maxParallelTasks=Number.isFinite(n)?Math.max(1,Math.min(8,Math.floor(n))):2,np.has(String(r.sessionCleanupOnNodeRemove))||(r.sessionCleanupOnNodeRemove="preserve"),ap.has(String(r.spawnedSessionVisibility))||(r.spawnedSessionVisibility="visible"),r}function Nk(){return ds().meshes}function Nc(e){return ds().meshes.find(t=>t.id===e)}function rp(e){return ds().meshes.find(t=>t.repoIdentity===e)}function Ck(e){const t=ds();if(t.meshes.length>=20)throw new Error("Maximum 20 meshes allowed");const r=e.repoIdentity||(e.repoRemoteUrl?tp(e.repoRemoteUrl):"");if(!r)throw new Error("Either repoRemoteUrl or repoIdentity is required");const n=new Date().toISOString(),a={id:`mesh_${yn().replace(/-/g,"")}`,name:e.name.trim().slice(0,100),repoIdentity:r,repoRemoteUrl:e.repoRemoteUrl,defaultBranch:e.defaultBranch,policy:sp(void 0,e.policy),coordinator:e.coordinator||{},nodes:[],createdAt:n,updatedAt:n};return t.meshes.push(a),Mr(t),a}function Tk(e,t){const r=ds(),n=r.meshes.find(a=>a.id===e);if(n)return t.name!==void 0&&(n.name=t.name.trim().slice(0,100)),t.defaultBranch!==void 0&&(n.defaultBranch=t.defaultBranch),t.policy&&(n.policy=sp(n.policy,t.policy)),t.coordinator&&(n.coordinator=t.coordinator),n.updatedAt=new Date().toISOString(),Mr(r),n}function Ik(e){const t=ds(),r=t.meshes.findIndex(n=>n.id===e);return r===-1?!1:(t.meshes.splice(r,1),Mr(t),!0)}function Ak(e,t){const r=ds(),n=r.meshes.find(i=>i.id===e);if(!n)return;if(n.nodes.length>=10)throw new Error("Maximum 10 nodes per mesh");if(n.nodes.some(i=>i.workspace===t.workspace))throw new Error("This workspace is already in the mesh");const a={id:`node_${yn().replace(/-/g,"")}`,workspace:t.workspace.trim(),repoRoot:t.repoRoot,daemonId:t.daemonId,machineId:t.machineId,userOverrides:t.userOverrides||{},policy:t.policy||{},isLocalWorktree:t.isLocalWorktree,worktreeBranch:t.worktreeBranch,clonedFromNodeId:t.clonedFromNodeId};return n.nodes.push(a),n.updatedAt=new Date().toISOString(),Mr(r),a}function Mk(e,t){const r=ds(),n=r.meshes.find(i=>i.id===e);if(!n)return!1;const a=n.nodes.findIndex(i=>i.id===t);return a===-1?!1:(n.nodes.splice(a,1),n.updatedAt=new Date().toISOString(),Mr(r),!0)}function _k(e,t,r){const n=ds(),a=n.meshes.find(o=>o.id===e);if(!a)return;const i=a.nodes.find(o=>o.id===t);if(i)return r.userOverrides&&(i.userOverrides={...i.userOverrides,...r.userOverrides}),r.policy&&(i.policy={...i.policy,...r.policy}),a.updatedAt=new Date().toISOString(),Mr(n),i}var np,ap,Cc=wt({"src/config/mesh-config.ts"(){Ht(),kc(),np=new Set(["preserve","stop","delete_stopped","stop_and_delete"]),ap=new Set(["visible","hidden"])}}),Rk={};js(Rk,{buildCoordinatorSystemPrompt:()=>Pk});function Pk(e){var o,l;const{mesh:t,status:r,userInstruction:n,coordinatorCliType:a}=e,i=[];return i.push(`You are a **Repo Mesh Coordinator** — a technical team lead who orchestrates work across multiple agent sessions on a shared Git repository.
100
+
101
+ Your mesh: **${t.name}**
102
+ Repository: \`${t.repoIdentity}\`${t.defaultBranch?`
103
+ Default branch: \`${t.defaultBranch}\``:""}`),(o=r==null?void 0:r.nodes)!=null&&o.length?i.push(Lk(r.nodes)):t.nodes.length?i.push(Ek(t)):i.push("## Nodes\nNo nodes configured yet. Ask the user to add nodes with `adhdev mesh add-node`."),i.push(Dk({...Sc,...t.policy||{}})),i.push(ip),i.push(op),i.push(cp),i.push($k(a)),n&&i.push(`## Additional Context
104
+ ${n}`),(l=t.coordinator)!=null&&l.systemPromptSuffix&&i.push(t.coordinator.systemPromptSuffix),i.join(`
105
+
106
+ `)}function Lk(e){var r;const t=["## Current Node Status",""];for(const n of e){const a=n.health==="online"?"🟢":n.health==="dirty"?"🟡":n.health==="offline"?"⚫":"🔴",i=n.activeSessions.length>0?`sessions: ${n.activeSessions.join(", ")}`:"no active sessions",o=(r=n.git)!=null&&r.branch?`branch: \`${n.git.branch}\``:"";t.push(`- ${a} **${n.machineLabel}** (${n.nodeId})`),t.push(` workspace: \`${n.workspace}\` | ${o} | ${i}`),n.error&&t.push(` ⚠️ ${n.error}`)}return t.join(`
107
+ `)}function Ek(e){var r;const t=["## Configured Nodes",""];for(const n of e.nodes){const a=[];n.isLocalWorktree&&a.push("worktree"),(r=n.policy)!=null&&r.readOnly&&a.push("read-only");const i=a.length?` [${a.join(", ")}]`:"";t.push(`- **${n.workspace}** (${n.id})${i}`)}return t.push("","_Use `mesh_status` to probe live health before delegating work._"),t.join(`
108
+ `)}function Dk(e){const t=[];e.requirePreTaskCheckpoint&&t.push("- Create a git checkpoint **before** starting each task"),e.requirePostTaskCheckpoint&&t.push("- Create a git checkpoint **after** each task completes"),e.requireApprovalForPush&&t.push("- **Ask for user approval** before pushing to remote"),e.requireApprovalForDestructiveGit&&t.push("- **Ask for user approval** before destructive git operations (force push, reset, etc.)");const r={block:"- **Do not** send tasks to nodes with dirty workspaces",warn:"- Warn the user if a node has uncommitted changes before sending a task",checkpoint_then_continue:"- Auto-checkpoint dirty nodes before sending tasks"}[e.dirtyWorkspaceBehavior]||"";return r&&t.push(r),t.push(`- Maximum **${e.maxParallelTasks}** tasks running in parallel`),`## Policy
109
+ ${t.join(`
110
+ `)}`}function $k(e){return`## Rules
111
+
112
+ - **Minimize coordinator context.** The coordinator's job is routing, not implementing. Do not read source files, run commands, or analyze code directly — delegate all of that to node agents. Your context should stay lean.
113
+ - **Delegate analysis too.** If you need to understand a bug or explore the codebase, send that investigation as a task to the queue or a node. Do not do it yourself.
114
+ - **Respect explicit provider requests.** If the user names an agent/provider, pass the matching provider type to \`mesh_launch_session\`: Hermes → \`hermes-cli\`, Claude Code/Claude → \`claude-cli\`, Codex → \`codex-cli\`, Gemini → \`gemini-cli\`. Never substitute \`claude-cli\` just because the coordinator itself is Claude Code.
115
+ - **Front-load new task messages.** When calling \`mesh_enqueue_task\` or \`mesh_send_task\` for a new task, include everything the agent needs: what files to touch, what the problem is, what the fix should look like. The agent won't ask follow-up questions.
116
+ - **Avoid context-wasting restarts.** For follow-up, retry, commit/push, preview, or cleanup work on the same issue, prefer the existing idle session and send only the delta from its last verified state. Start a fresh chat/session only for genuinely independent work, explicit provider/user request, unsafe transcript contamination, or required branch/worktree isolation.
117
+ - **Don't inspect code.** Treat delegated agent summaries as self-reports, not verification. Verify side effects via \`mesh_git_status\` (including related repo freshness when configured), not by reading source files.
118
+ - **Don't over-parallelize.** Start with 1-2 concurrent tasks. Scale up if they succeed. Never launch a duplicate session or second worker solely because \`mesh_read_chat\` has no final assistant message while the delegated session is still showing tool/terminal activity.
119
+ - **Handle failures with context.** If a task fails, check \`mesh_task_history\` first to see if this task was attempted before and how it failed. Read the chat to understand why, then decide: retry on the same node, reassign to a different node, or escalate to the user.
120
+ - **Check history before starting.** At the beginning of a coordination session, call \`mesh_task_history\` to understand what was previously delegated and its outcomes. This prevents duplicate work and informs recovery decisions.
121
+ - **Keep the user informed.** Report progress after each delegation round — one or two sentences, not a narration.
122
+ - **Respect node capabilities.** Don't send build tasks to read-only nodes. Don't push from nodes that aren't allowed to.
123
+ - **Never fabricate tool results.** Always call the actual tool; never pretend you did.
124
+ - **Clean up worktree nodes.** After a worktree task completes and its changes are merged or checkpointed, call \`mesh_remove_node\` to free resources.
125
+ - **Do not strand completed branches.** A checkpointed or clean feature/worktree branch is not done by itself. Merge/refine it to the mesh default branch, or explicitly report one of \`pushed_feature_branch_needs_merge\`, \`blocked_review\`, \`cleanup_candidate\`, or \`not_mergeable\` with the next action.
126
+ - **Name worktree branches meaningfully.** Use descriptive names like \`feat/auth-refactor\` or \`fix/build-123\`.${e?`
127
+ - **Coordinator runtime is not a delegation default.** This coordinator is running as \`${e}\`, but delegated node sessions must follow the user's requested provider, not the coordinator's own runtime.`:""}`}var ip,op,cp,Bk=wt({"src/mesh/coordinator-prompt.ts"(){kc(),ip="## Available Tools\n\n| Tool | Purpose |\n|------|---------|\n| `mesh_status` | Check all nodes' health, git state, active sessions, and branch convergence |\n| `mesh_list_nodes` | List nodes with workspace paths |\n| `mesh_enqueue_task` | Add a task to the pull-based work queue; idle nodes auto-claim |\n| `mesh_view_queue` | View queue status — pending, assigned, completed, failed, cancelled tasks |\n| `mesh_queue_cancel` | Cancel a queue task without deleting audit history |\n| `mesh_queue_requeue` | Return a task to pending for retry; clears stale session targets |\n| `mesh_send_task` | Legacy push: enqueue a task targeted at a specific node |\n| `mesh_launch_session` | Start a new agent session on a node |\n| `mesh_read_chat` | Read recent chat messages from a delegated agent session |\n| `mesh_read_debug` | Collect a daemon-side chat/parser debug bundle for a session |\n| `mesh_task_history` | Read the task ledger — dispatches, completions, failures. Use to understand what has been done before deciding next steps |\n| `mesh_git_status` | Check git status on a specific node |\n| `mesh_checkpoint` | Create a git checkpoint on a node |\n| `mesh_approve` | Approve/reject a pending agent action |\n| `mesh_clone_node` | Create a worktree node for isolated parallel branch work |\n| `mesh_refine_node` | Validate and merge a completed worktree node back into its base branch |\n| `mesh_remove_node` | Remove a node (cleans up worktree if applicable) |\n| `mesh_cleanup_sessions` | Manually clean up delegated session records for a node |",op="## Tool Exposure Preflight\n\nBefore doing any coordinator work, confirm that the actual callable tool list includes `mesh_status` and the other `mesh_*` tools from the table above. If this Repo Mesh coordinator prompt is present but the callable `mesh_*` tools are missing, the MCP server/tool manifest is stale or not injected yet. Do not substitute terminal/file/git tools, do not inspect or edit the repository directly, and do not continue as a non-mesh local coding agent. Stop immediately and tell the user to run `/reload-mcp` or start a fresh coordinator session so ADHDev can reconnect `adhdev-mesh`.",cp='## Orchestration Workflow\n\n1. **Assess** — Call `mesh_status` to see which nodes are healthy and available. Check `mesh_task_history` to understand what has already been done in this mesh — previous delegations, completions, and failures.\n2. **Plan** — Decompose the user\'s request into independent tasks for parallel execution, or sequential tasks when dependencies exist. If `mesh_task_history` shows a recent failure for a task, decide whether to retry or reassign.\n3. **Queue / Delegate** — The Mesh uses an autonomous pull-based Work Queue:\n a. **General Tasks**: Enqueue tasks using `mesh_enqueue_task`. Idle node agents will automatically pull tasks from the queue and begin working.\n b. **Node Preparation**: Reuse an existing idle session on the correct node/provider before launching a new chat/session. Call `mesh_launch_session` only when no suitable session exists, when the user explicitly asks for a fresh provider/session, or when branch/worktree isolation requires it. If you need branch isolation for parallel work, call `mesh_clone_node` to create a worktree node first.\n c. **Targeted Tasks**: Use `mesh_send_task` only when you need to bypass the queue and force a specific node to execute a task immediately.\n d. For the first dispatch of a new task, provide a **complete, self-contained** instruction that includes all context the agent needs (file paths, line numbers, what to change, why). Do not send partial instructions expecting future follow-up.\n e. For a continuation of the same issue in an existing session, send a concise **delta instruction**: current verified state, the exact failed/blocked step, the newly approved action, and final reporting requirements. Do not resend the full original task or open a new chat solely to continue the same work; that wastes coordinator and worker context.\n4. **Monitor** — Prefer event-driven completion/status notifications. Do **not** poll `mesh_read_chat` repeatedly. Use `mesh_view_queue` to see the status of all pending, assigned, completed, and failed tasks. Do not call `mesh_read_chat` again within a few seconds for the same generating session. Use at most one compact `mesh_read_chat` check after a completion/approval signal. Handle approvals via `mesh_approve`.\n5. **Verify** — When a task reports completion or git work is visible, call `mesh_git_status` to verify changes were made.\n6. **Checkpoint** — Call `mesh_checkpoint` to save the work.\n7. **Converge branches** — Before marking any task complete, classify every touched node/branch into exactly one final state: `merged_to_main`, `pushed_feature_branch_needs_merge`, `blocked_review`, `cleanup_candidate`, or `not_mergeable`. Use `mesh_status` branchConvergenceSummary and `mesh_refine_node` for clean worktree branches when safe. A task that remains on a non-main branch is not fully complete unless the final report names the follow-up state and next step.\n8. **Clean up** — Remove worktree nodes via `mesh_remove_node` after their work is merged or no longer needed.\n9. **Report** — Summarize what was done, what changed, any issues, and the branch convergence state.\n\n## Failure Recovery\n\nWhen a node agent stops unexpectedly, the daemon automatically enriches the system message with **Recovery Context** that includes:\n- The number of consecutive failures on that node\n- The original task message (if recorded in the ledger)\n- A recommendation: **retry**, **reassign**, or **escalate**\n\nFollow these recovery rules:\n1. **If "Retry recommended"**: Check `mesh_view_queue` first — the daemon may have auto-requeued. If not, re-launch the session on the same node (`mesh_launch_session`), then resend the original task (`mesh_send_task`). The system message includes the original task text.\n2. **If "Max retries exceeded"**: Do NOT retry on the same node. Either reassign the task to a different node, or inform the user that the task requires manual intervention.\n3. **If no recovery context**: The stop may be intentional (normal completion). Use `mesh_read_chat` once to verify, then move on.\n4. **Always record what happened**: After handling a failure, briefly note the outcome in your report to the user.'}}),Ok={};js(Ok,{MAX_LEDGER_SLICE_LIMIT:()=>Ya,appendLedgerEntry:()=>on,appendRemoteLedgerEntries:()=>Uk,buildTaskCompletionEvidence:()=>vo,getLedgerDir:()=>qa,getLedgerSummary:()=>lp,getSessionRecoveryContext:()=>dp,isIntentionalCleanupStopEntry:()=>gn,meshLedgerEvents:()=>Ja,readLedgerEntries:()=>_r,readLedgerSlice:()=>Kk});function gn(e){if(e.kind!=="session_stopped"&&e.kind!=="task_failed"&&e.kind!=="task_stalled")return!1;const t=e.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{};return t.intentional===!0&&(t.reason==="operator_cleanup"||t.intentionalStopReason==="operator_cleanup"||t.source==="mesh_cleanup_sessions"||t.source==="mesh_remove_node")}function qa(){const e=ks(Ar(),up);return Ot(e)||Lo(e,{recursive:!0,mode:448}),e}function Xa(e){const t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return ks(qa(),`${t}.jsonl`)}function dd(e,t){const r=e.replace(/[^a-zA-Z0-9_-]/g,"_");return ks(qa(),`${r}.${t}.jsonl`)}function vo(e){var n,a;const t=((n=e.providerSessionId)==null?void 0:n.trim())||void 0,r=((a=e.providerType)==null?void 0:a.trim())||void 0;return{source:"agent_status_event",event:e.event,nodeId:e.nodeId,sessionId:e.sessionId,providerType:r,completedAt:e.completedAt||new Date().toISOString(),transcriptHandle:{kind:t?"provider_session":"runtime_session",sessionId:e.sessionId,providerSessionId:t,finalSummaryAvailable:typeof e.finalSummary=="string"&&e.finalSummary.trim().length>0},git:{status:"deferred",reason:"ordinary_completion_git_status_not_checked"},validation:{status:"deferred",commandsRun:[],reason:"ordinary_completion_validation_not_run"},checkpoint:{attempted:!1,reason:"not_attempted_for_ordinary_completion"}}}function on(e,t){const r={id:yn(),meshId:e,timestamp:new Date().toISOString(),...t},n=Xa(e);if(Ot(n))try{Uf(n).size>=hp&&Hk(e,n)}catch{}try{const a=JSON.stringify(r)+`
128
+ `;return Td(n,a,{encoding:"utf-8",mode:384}),Ja.emit("append",e,r),r}catch(a){throw new Error(`Failed to append to ledger for mesh ${e}: ${a.message}`)}}function Fk(e){return typeof e!="number"||!Number.isFinite(e)?pp:Math.max(1,Math.min(Ya,Math.floor(e)))}function Wk(e,t){if(!t||typeof t!="object"||Array.isArray(t))return!1;const r=t;return!(typeof r.id!="string"||!r.id.trim()||r.meshId!==e||typeof r.timestamp!="string"||Number.isNaN(new Date(r.timestamp).getTime())||typeof r.kind!="string"||!r.kind.trim()||!r.payload||typeof r.payload!="object"||Array.isArray(r.payload))}function Uk(e,t){if(t.length===0)return{accepted:0,skippedDuplicate:0,rejectedInvalid:0,entries:[]};const r=Xa(e),n=new Set(_r(e).map(l=>l.id)),a=[];let i=0,o=0;for(const l of t){if(!Wk(e,l)){i++;continue}if(n.has(l.id)){o++;continue}n.add(l.id),a.push(l)}if(a.length===0)return{accepted:0,skippedDuplicate:o,rejectedInvalid:i,entries:[]};try{const l=a.map(d=>JSON.stringify(d)).join(`
129
+ `)+`
130
+ `;Td(r,l,{encoding:"utf-8",mode:384});for(const d of a)Ja.emit("append",e,d);return{accepted:a.length,skippedDuplicate:o,rejectedInvalid:i,entries:a}}catch(l){throw new Error(`Failed to append remote ledger entries for mesh ${e}: ${l.message}`)}}function _r(e,t){var o;const r=Xa(e);if(!Ot(r))return[];let n;try{n=Ma(r,"utf-8")}catch{return[]}const a=n.split(`
131
+ `).filter(l=>l.trim());let i=[];for(const l of a)try{const d=JSON.parse(l);if(!d.id||!d.kind)continue;i.push(d)}catch{}if(t!=null&&t.since){const l=new Date(t.since).getTime();isNaN(l)||(i=i.filter(d=>new Date(d.timestamp).getTime()>=l))}if((o=t==null?void 0:t.kind)!=null&&o.length){const l=new Set(t.kind);i=i.filter(d=>l.has(d.kind))}return t!=null&&t.tail&&t.tail>0&&i.length>t.tail&&(i=i.slice(-t.tail)),i}function Kk(e,t){const r=Fk(t==null?void 0:t.limit);let n=_r(e,{since:t==null?void 0:t.since,kind:t==null?void 0:t.kind});const a=typeof(t==null?void 0:t.afterId)=="string"&&t.afterId.trim()?t.afterId.trim():null;if(a){const o=n.findIndex(l=>l.id===a);n=o>=0?n.slice(o+1):n}const i=n.slice(0,r);return{protocol:"adhdev.mesh.ledger.slice.v1",meshId:e,entries:i,cursor:{afterId:a,nextAfterId:i.length?i[i.length-1].id:a,limit:r,hasMore:n.length>i.length},summary:lp(e),sourceOfTruth:{kind:"local_jsonl",path:Xa(e),bounded:!0,maxLimit:Ya}}}function lp(e){const t=_r(e),n=Date.now()-Tc,a={meshId:e,totalEntries:t.length,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};for(const i of t)switch(i.kind){case"task_dispatched":a.taskDispatched++;break;case"task_completed":a.taskCompleted++;break;case"task_failed":{if(gn(i))break;a.taskFailed++,new Date(i.timestamp).getTime()>=n&&a.recentFailures++;break}case"task_stalled":{gn(i)||a.taskStalled++;break}case"session_launched":a.sessionLaunched++;break;case"checkpoint_created":a.checkpointCreated++;break}return t.length>0&&(a.lastActivityAt=t[t.length-1].timestamp),a}function dp(e,t){var m,v;const r=t.maxRetries??1,n=_r(e);let a=null;for(let b=n.length-1;b>=0;b--){const p=n[b];if(p.kind==="task_dispatched"){if(t.sessionId&&p.sessionId===t.sessionId){a=p;break}if(t.nodeId&&p.nodeId===t.nodeId){a=p;break}}}const i=typeof((m=a==null?void 0:a.payload)==null?void 0:m.message)=="string"?a.payload.message:null,l=Date.now()-Tc;let d=0;for(let b=n.length-1;b>=0;b--){const p=n[b];if(new Date(p.timestamp).getTime()<l)break;if(!(t.nodeId&&p.nodeId!==t.nodeId)){if(p.kind==="task_failed"){if(gn(p))continue;d++}else if(p.kind==="task_completed"||p.kind==="task_dispatched")break}}let u=0;if(i){const b=i.slice(0,200);for(const p of n)p.kind==="task_dispatched"&&typeof((v=p.payload)==null?void 0:v.message)=="string"&&p.payload.message.startsWith(b)&&u++}const h=d<=r;let f;if(d===0)f="No recent failures detected. This may be a normal stop.";else if(h){const b=r-d+1;f=`Retry recommended (${d}/${r+1} attempts used, ${b} remaining). `+(i?"Re-launch the session and resend the original task.":"Re-launch the session. Original task message not found in ledger.")}else f=`Max retries exceeded (${d} consecutive failures). Consider: (1) reassigning to a different node, (2) simplifying the task, or (3) escalating to the user.`;return{lastTaskMessage:i,failedNodeId:t.nodeId||null,failedSessionId:t.sessionId||null,failedProviderType:null,consecutiveNodeFailures:d,taskAttemptCount:u,retryRecommended:h,advice:f}}function Hk(e,t){let r=1;for(;Ot(dd(e,r))&&(r++,!(r>10)););r>10&&(r=10);try{Kf(t,dd(e,r))}catch{}}var up,hp,Tc,pp,Ya,Ja,Ic=wt({"src/mesh/mesh-ledger.ts"(){Ht(),up="mesh-ledger",hp=10*1024*1024,Tc=30*60*1e3,pp=100,Ya=500,Ja=new qf}}),zk={};js(zk,{ACTIVE_MESH_QUEUE_STATUSES:()=>bp,HISTORICAL_MESH_QUEUE_STATUSES:()=>yp,cancelTask:()=>Vk,claimNextTask:()=>xp,enqueueTask:()=>mp,getMeshQueueStats:()=>qk,getQueue:()=>Qa,recordTaskAutoLaunch:()=>gp,requeueTask:()=>Gk,updateSessionTaskStatus:()=>aa,updateTaskStatus:()=>wo});function fp(e){const t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return ks(qa(),`${t}.queue.json`)}function us(e){const t=fp(e);if(!Ot(t))return[];try{const r=Ma(t,"utf-8");return JSON.parse(r)}catch{return[]}}function Js(e,t){const r=fp(e);_a(r,JSON.stringify(t,null,2),"utf-8")}function mp(e,t,r){const n=us(e),a={id:yn(),meshId:e,message:t,status:"pending",targetNodeId:r==null?void 0:r.targetNodeId,targetSessionId:r==null?void 0:r.targetSessionId,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return n.push(a),Js(e,n),a}function Qa(e,t){var n;let r=us(e);if((n=t==null?void 0:t.status)!=null&&n.length){const a=new Set(t.status);r=r.filter(i=>a.has(i.status))}return r}function xp(e,t,r){const n=us(e);if(n.some(l=>l.status==="assigned"&&(l.assignedSessionId===r||l.assignedNodeId===t)))return null;let i=n.findIndex(l=>l.status==="pending"&&l.targetSessionId===r);if(i===-1&&(i=n.findIndex(l=>l.status==="pending"&&l.targetNodeId===t&&!l.targetSessionId)),i===-1&&(i=n.findIndex(l=>l.status==="pending"&&!l.targetNodeId&&!l.targetSessionId)),i===-1)return null;const o=n[i];return o.status="assigned",o.assignedNodeId=t,o.assignedSessionId=r,o.dispatchTimestamp=new Date().toISOString(),o.updatedAt=new Date().toISOString(),Js(e,n),o}function wo(e,t,r){const n=us(e),a=n.findIndex(i=>i.id===t);return a===-1?null:(n[a].status=r,n[a].updatedAt=new Date().toISOString(),Js(e,n),n[a])}function gp(e,t,r){const n=us(e),a=n.findIndex(o=>o.id===t);if(a===-1)return null;const i=new Date().toISOString();return n[a].autoLaunch={...r,updatedAt:i},n[a].updatedAt=i,Js(e,n),n[a]}function Vk(e,t,r){const n=us(e),a=n.findIndex(o=>o.id===t);if(a===-1)return null;const i=new Date().toISOString();return n[a].status="cancelled",n[a].updatedAt=i,n[a].cancelledAt=i,r!=null&&r.reason&&(n[a].cancelReason=r.reason),Js(e,n),n[a]}function Gk(e,t,r){const n=us(e),a=n.findIndex(l=>l.id===t);if(a===-1)return null;const i=n[a],o=new Date().toISOString();return i.status="pending",delete i.assignedNodeId,delete i.assignedSessionId,delete i.cancelledAt,delete i.cancelReason,r!=null&&r.clearTargetNode&&delete i.targetNodeId,typeof(r==null?void 0:r.targetNodeId)=="string"&&(i.targetNodeId=r.targetNodeId),(r==null?void 0:r.clearTargetSession)!==!1&&delete i.targetSessionId,typeof(r==null?void 0:r.targetSessionId)=="string"&&(i.targetSessionId=r.targetSessionId),i.updatedAt=o,i.requeuedAt=o,i.requeueCount=(i.requeueCount||0)+1,r!=null&&r.reason&&(i.requeueReason=r.reason),Js(e,n),i}function aa(e,t,r){const n=us(e);let a=-1,i=0;for(let o=n.length-1;o>=0;o--)if(n[o].assignedSessionId===t&&n[o].status==="assigned"){const l=new Date(n[o].dispatchTimestamp||n[o].updatedAt).getTime();l>i&&(i=l,a=o)}return a===-1?null:(n[a].status=r,n[a].updatedAt=new Date().toISOString(),Js(e,n),n[a])}function qk(e){const t=us(e),r=t.filter(l=>l.status==="pending").length,n=t.filter(l=>l.status==="assigned").length,a=t.filter(l=>l.status==="completed").length,i=t.filter(l=>l.status==="failed").length,o=t.filter(l=>l.status==="cancelled").length;return{total:t.length,active:r+n,historical:a+i+o,pending:r,assigned:n,completed:a,failed:i,cancelled:o,activeCounts:{pending:r,assigned:n},historicalCounts:{completed:a,failed:i,cancelled:o},activeAssignments:t.filter(l=>l.status==="assigned").map(l=>({id:l.id,nodeId:l.assignedNodeId,sessionId:l.assignedSessionId,message:l.message}))}}var bp,yp,Ac=wt({"src/mesh/mesh-work-queue.ts"(){Ic(),bp=["pending","assigned"],yp=["completed","failed","cancelled"]}});function vp(e){return/^[a-zA-Z0-9_./:@%+=,-]+$/.test(e)?e:`"${e.replace(/(["\\$`])/g,"\\$1")}"`}function Xk(e){const t=e.trim();return t.startsWith("~")?ze.join(vt.homedir(),t.slice(1)):t}function Yk(e){const t=e.trim();return ze.isAbsolute(t)||t.includes("/")||t.includes("\\")||t.startsWith("~")}function wp(e){const t=e.trim();if(!t)return null;if(Yk(t)){const r=Xk(t),n=ze.isAbsolute(r)?r:ze.resolve(r);return Ot(n)?n:null}return null}function Sp(e,t=5e3){return new Promise(r=>{Vf(e,{encoding:"utf-8",timeout:t,...process.platform==="win32"?{windowsHide:!0}:{}},(a,i)=>{a||!(i!=null&&i.trim())?r(null):r(i.trim())}).on("error",()=>r(null))})}async function Jk(e,t){const n=vt.platform()==="win32"?"where":"which",a=(t==null?void 0:t.includeVersion)!==!1,i=e?e.getCliDetectionList():[];return await Promise.all(i.map(async l=>{try{const d=wp(l.command),u=d||await Sp(`${n} ${vp(l.command)}`);if(!u)return{...l,installed:!1};const h=d||u.split(`
132
+ `)[0];return{...l,installed:!0,version:void 0,path:h}}catch{return{...l,installed:!1}}}))}async function Qk(e,t,r){const n=t?t.resolveAlias(e):e;if(t){const o=t.getCliDetectionList().find(l=>l.id===n);if(o){const d=vt.platform()==="win32"?"where":"which";try{const u=wp(o.command),h=u||await Sp(`${d} ${vp(o.command)}`);if(!h)return null;const f=u||h.split(`
133
+ `)[0];let m;return r==null||r.includeVersion,{...o,installed:!0,version:m,path:f}}catch{return null}}}return(await Jk(t,r)).find(i=>i.id===n&&i.installed)||null}var Cn=wt({"src/detection/cli-detector.ts"(){}});function So(){return new Date().toISOString().slice(0,10)}function Zk(){const e=So();e!==cn&&(cn=e,ur=ze.join(Yt,`daemon-${cn}.log`),kp())}function kp(){try{const e=Dt.readdirSync(Yt).filter(n=>n.startsWith("daemon-")&&n.endsWith(".log")),t=new Date;t.setDate(t.getDate()-Tp);const r=t.toISOString().slice(0,10);for(const n of e){const a=n.match(/daemon-(\d{4}-\d{2}-\d{2})/);if(a&&a[1]<r)try{Dt.unlinkSync(ze.join(Yt,n))}catch{}}}catch{}}function ej(){try{if(Dt.statSync(ur).size>Cp){const t=ur.replace(".log",".1.log");try{Dt.unlinkSync(t)}catch{}Dt.renameSync(ur,t)}}catch{}}function tj(e){try{++Ip%1e3===0&&(Zk(),ej()),Dt.appendFileSync(ur,e+`
134
+ `)}catch{}}function sj(){return new Date().toISOString().slice(11,23)}function ss(e,t,r="info"){const n=ko[r]>=ko[Np],a=jp[r],i=`[${sj()}] [${a}] [${e}] ${t}`;n&&(tj(i),Jr.push({ts:Date.now(),level:r,category:e,message:t}),Jr.length>jo&&Jr.splice(0,Jr.length-jo),Ap(i))}var ko,jp,Np,Yt,Cp,Tp,cn,ur,Ip,jo,Jr,Ap,Fe,dt=wt({"src/logging/logger.ts"(){ko={debug:0,info:1,warn:2,error:3},jp={debug:"DBG",info:"INF",warn:"WRN",error:"ERR"},Np="info",Yt=process.platform==="win32"?ze.join(Kt.LOCALAPPDATA||Kt.APPDATA||ze.join(vt.homedir(),"AppData","Local"),"adhdev","logs"):process.platform==="darwin"?ze.join(vt.homedir(),"Library","Logs","adhdev"):ze.join(vt.homedir(),".local","share","adhdev","logs"),Cp=5*1024*1024,Tp=7;try{Dt.mkdirSync(Yt,{recursive:!0})}catch{}cn=So(),ur=ze.join(Yt,`daemon-${cn}.log`),kp();try{const e=ze.join(Yt,"daemon.log");if(Dt.existsSync(e)){const n=Dt.statSync(e).mtime.toISOString().slice(0,10);Dt.renameSync(e,ze.join(Yt,`daemon-${n}.log`))}const t=ze.join(Yt,"daemon.log.old");Dt.existsSync(t)&&Dt.unlinkSync(t)}catch{}Ip=0,jo=200,Jr=[],Ap=console.log.bind(console),console.error.bind(console),console.warn.bind(console),Fe={debug:(e,t)=>ss(e,t,"debug"),info:(e,t)=>ss(e,t,"info"),warn:(e,t)=>ss(e,t,"warn"),error:(e,t)=>ss(e,t,"error"),forComponent(e){return{debug:t=>ss(e,t,"debug"),info:t=>ss(e,t,"info"),warn:t=>ss(e,t,"warn"),error:t=>ss(e,t,"error"),asLogFn:(t="info")=>r=>ss(e,r,t)}}},ze.join(Yt,`daemon-${So()}.log`)}}),rj={};js(rj,{clearPendingMeshCoordinatorEvents:()=>ij,drainPendingMeshCoordinatorEvents:()=>nj,getPendingMeshCoordinatorEvents:()=>aj,handleMeshForwardEvent:()=>jj,setupMeshEventForwarding:()=>Nj,triggerMeshQueue:()=>Sj,tryAssignQueueTask:()=>Sr});function nj(){return kr.splice(0)}function aj(){return kr.slice()}function ij(){kr.splice(0)}function Te(e){return typeof e=="string"&&e.trim()?e.trim():""}function As(e,t){return Te(e.targetSessionId)||Te(e.sessionId)||Te(e.instanceId)||Te(t)}function Mp(e){return typeof e=="string"&&Lp.has(e)}function oj(e){const t=[Te(e.targetSessionId)?`session_id=${Te(e.targetSessionId)}`:"",Te(e.providerType)?`provider=${Te(e.providerType)}`:"",Te(e.providerSessionId)?`provider_session_id=${Te(e.providerSessionId)}`:""].filter(Boolean);return t.length>0?` (${t.join("; ")})`:""}function Mc(e,t){var n;const r=Nc(t);return r||((n=e.router)==null?void 0:n.getCachedInlineMesh(t))}function cj(e){return e.intentional===!0||e.intentionalStop===!0||e.operatorCleanup===!0||e.reason==="operator_cleanup"||e.stopReason==="operator_cleanup"||e.cleanupReason==="operator_cleanup"||e.source==="mesh_cleanup_sessions"||e.source==="mesh_remove_node"}function lj(e,t,r){if(!t&&!r)return!1;const n=Date.now()-Dp,a=_r(e);for(let i=a.length-1;i>=0;i--){const o=a[i],l=new Date(o.timestamp).getTime();if(!Number.isNaN(l)&&l<n)break;if(gn(o)&&(t&&o.sessionId===t||!t&&r&&o.nodeId===r))return!0}return!1}function dj(e){return e.event!=="agent:stopped"&&e.event!=="monitor:long_generating"?!1:cj(e.metadataEvent)?!0:lj(e.meshId,e.sessionId,e.nodeId)}function Sr(e,t,r,n,a){const i=xp(t,r,n);if(!i)return!1;Fe.info("MeshQueue",`Node ${r} (${n}) pulled task ${i.id}`);const o=Mc(e,t),l=o==null?void 0:o.nodes.find(d=>d.id===r);return l!=null&&l.daemonId&&e.dispatchMeshCommand&&!e.cliManager.adapters.has(n)?(e.dispatchMeshCommand(l.daemonId,"agent_command",{targetSessionId:n,cliType:a,action:"send_chat",message:i.message}).catch(u=>{Fe.error("MeshQueue",`Failed to dispatch task via P2P to remote node ${r}: ${u==null?void 0:u.message}`),wo(t,i.id,"failed")}),!0):(e.cliManager.handleCliCommand("agent_command",{targetSessionId:n,cliType:a,action:"send_chat",message:i.message}).catch(d=>{Fe.error("MeshQueue",`Failed to dispatch task locally to node ${r}: ${d==null?void 0:d.message}`),wo(t,i.id,"failed")}),!0)}function uj(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e.providerPriority:void 0;if(!Array.isArray(t))return[];const r=new Set;return t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean).filter(n=>r.has(n)?!1:(r.add(n),!0))}function _p(e){return["stopped","failed","terminated","exited","closed"].includes(e)}function hj(e){var r;const t=Te(e==null?void 0:e.status).toLowerCase();return _p(t)?!1:t==="idle"||((r=e==null?void 0:e.activeChat)==null?void 0:r.status)==="waiting_input"}function pj(e){var t;return(e==null?void 0:e.health)==="dirty"||((t=e==null?void 0:e.git)==null?void 0:t.dirty)===!0}function fj(e){if(!e||e.status==="disabled"||e.status==="removed")return!1;const t=Te(e.health).toLowerCase();return t?t==="online"||t==="unknown":!0}function mj(e){const t=Te(e==null?void 0:e.daemonId),r=Te(e==null?void 0:e.machineId),n=Ga(),a=Te(n.machineId)||Te(n.registeredMachineId),i=a?`daemon_${a}`:"",o=a?`standalone_${a}`:"",l=!t||t===i||t===o,d=!r||a&&r===a;return(e==null?void 0:e.isLocalWorktree)===!0||t||r?l&&d?null:"remote_auto_launch_unsupported":null}function xj(e){return Qa(e,{status:["assigned"]}).length}function gj(e,t){return Qa(e,{status:["assigned"]}).some(r=>r.assignedNodeId===t)}function bj(e,t,r){return e.instanceManager.getByCategory("cli").filter(n=>{const a=n.getState(),i=a.settings||{};if(Te(i.meshNodeFor)!==t||(Te(i.meshNodeId)||Te(i.nodeId))!==r)return!1;const l=Te(a.status).toLowerCase();return!_p(l)}).length}function yj(e,t){try{on(e,{kind:"session_auto_launch",nodeId:t.nodeId,sessionId:t.sessionId,providerType:t.providerType,payload:{phase:t.phase,taskId:t.taskId,reason:t.reason,error:t.error}})}catch(r){Fe.warn("MeshQueue",`Failed to record auto-launch ledger event: ${(r==null?void 0:r.message)||r}`)}}function Rt(e,t,r){gp(e,t,{status:r.status,reason:r.reason||r.error,nodeId:r.nodeId,providerType:r.providerType,sessionId:r.sessionId}),yj(e,{phase:r.status,taskId:t,nodeId:r.nodeId,providerType:r.providerType,sessionId:r.sessionId,reason:r.reason,error:r.error})}async function vj(e,t,r){var o;const n=uj(r==null?void 0:r.policy);if(!n.length)return{reason:"missing_provider_priority"};const a=e.providerLoader;if(!a)return{reason:"provider_loader_unavailable"};const i=[];for(const l of n){const d=typeof a.resolveAlias=="function"?a.resolveAlias(l):l;if(typeof a.isMachineProviderEnabled=="function"&&!a.isMachineProviderEnabled(d)){i.push(`${l}: disabled`);continue}let u;try{u=await Qk(d,a,{includeVersion:!1})}catch(h){i.push(`${l}: detect failed: ${(h==null?void 0:h.message)||h}`);continue}if(typeof a.setCliDetectionResults=="function"&&a.setCliDetectionResults([{id:d,installed:!!u,path:u==null?void 0:u.path}],!1),(o=e.onStatusChange)==null||o.call(e),u)return{providerType:d};i.push(`${l}: not detected`)}return{reason:`provider_priority_unusable: ${i.join("; ")||t}`}}async function wj(e,t,r){var o,l,d;const a=Qa(t).filter(u=>u.status==="pending");if(!a.length)return!1;const i=Math.max(1,Math.floor(Number((o=r==null?void 0:r.policy)==null?void 0:o.maxParallelTasks)||2));for(const u of a){if(xj(t)>=i)return Rt(t,u.id,{status:"skipped",reason:"max_parallel_tasks_reached"}),!1;if(u.targetSessionId){Rt(t,u.id,{status:"skipped",reason:"target_session_constraint"});continue}const h=Array.isArray(r==null?void 0:r.nodes)?r.nodes.filter(f=>u.targetNodeId?(f==null?void 0:f.id)===u.targetNodeId:!0):[];if(!h.length){Rt(t,u.id,{status:"skipped",reason:"no_matching_node",nodeId:u.targetNodeId});continue}for(const f of h){const m=Te(f==null?void 0:f.id);if(!m)continue;const v=`${t}:${m}`,b=Qr.get(v)||0;if(ia.has(v)){Rt(t,u.id,{status:"skipped",reason:"auto_launch_in_progress",nodeId:m});continue}if(Date.now()<b){Rt(t,u.id,{status:"skipped",reason:"auto_launch_cooldown",nodeId:m});continue}if(pj(f)){Rt(t,u.id,{status:"skipped",reason:"dirty_workspace",nodeId:m});continue}if(!fj(f)){Rt(t,u.id,{status:"skipped",reason:"node_not_launch_ready",nodeId:m});continue}const p=mj(f);if(p){Rt(t,u.id,{status:"skipped",reason:p,nodeId:m});continue}if(gj(t,m)){Rt(t,u.id,{status:"skipped",reason:"node_has_active_assignment",nodeId:m});continue}const g=Number((l=f==null?void 0:f.policy)==null?void 0:l.maxConcurrentSessions);if(Number.isFinite(g)&&g>=0&&bj(e,t,m)>=g){Rt(t,u.id,{status:"skipped",reason:"max_concurrent_sessions_reached",nodeId:m});continue}ia.add(v);try{const y=await vj(e,m,f);if(!y.providerType){Rt(t,u.id,{status:"skipped",reason:y.reason||"provider_unusable",nodeId:m});continue}Rt(t,u.id,{status:"started",nodeId:m,providerType:y.providerType});const x=await e.cliManager.handleCliCommand("launch_cli",{cliType:y.providerType,dir:f.workspace,settings:{meshNodeFor:t,meshNodeId:m,spawnedSessionVisibility:((d=r==null?void 0:r.policy)==null?void 0:d.spawnedSessionVisibility)||"hidden",launchedByCoordinator:!0,autoLaunchedForQueueTaskId:u.id}});if(!(x!=null&&x.success)){const j=(x==null?void 0:x.error)||"launch_cli_failed";return Rt(t,u.id,{status:"failed",reason:j,nodeId:m,providerType:y.providerType}),Qr.set(v,Date.now()+oa),!1}const N=Te(x.sessionId)||Te(x.id)||Te(x.runtimeSessionId);return N?(Rt(t,u.id,{status:"completed",nodeId:m,providerType:y.providerType,sessionId:N}),Sr(e,t,m,N,y.providerType),!0):(Rt(t,u.id,{status:"failed",reason:"launch_missing_session_id",nodeId:m,providerType:y.providerType}),Qr.set(v,Date.now()+oa),!1)}catch(y){return Rt(t,u.id,{status:"failed",error:(y==null?void 0:y.message)||String(y),nodeId:m}),Qr.set(v,Date.now()+oa),!1}finally{ia.delete(v)}}}return!1}async function Sj(e,t){const r=Mc(e,t);if(!r)return;const n=e.instanceManager.getByCategory("cli");for(const a of n){const i=a.getState(),o=i.settings||{};if(Te(o.meshNodeFor)!==t)continue;const d=Te(o.meshNodeId)||Te(o.nodeId);if(!d||!hj(i))continue;const u=i.instanceId,h=i.type||Te(o.providerType);h&&Sr(e,t,d,u,h)}for(const[a,i]of xs.entries())r.nodes.find(l=>l.id===i.nodeId)&&Sr(e,t,i.nodeId,i.sessionId,i.providerType)&&xs.delete(a);await wj(e,t,r)}function kj(e){const t=oj(e.metadataEvent);if(e.event==="agent:generating_completed")return`[System] ${e.nodeLabel} has completed its task and is now idle${t}. This completion came from the agent status event path; use mesh_read_chat once to review its final progress, but do not poll repeatedly.`;if(e.event==="agent:waiting_approval")return`[System] ${e.nodeLabel} is waiting for approval to proceed${t}. You may use mesh_read_chat and mesh_approve to handle it.`;if(e.event==="agent:stopped"){const r=e.recoveryContext;if(r&&r.consecutiveNodeFailures>0){const n=[`[System] ${e.nodeLabel} has stopped unexpectedly${t}.`,`
135
+
136
+ **Recovery Context:**`,`- Consecutive failures on this node: ${r.consecutiveNodeFailures}`,r.taskAttemptCount>0?`- This task has been attempted ${r.taskAttemptCount} time(s)`:"",`- Recommendation: ${r.advice}`];return r.retryRecommended&&r.lastTaskMessage?n.push(`
137
+
138
+ **Original task to retry:**`,`> ${r.lastTaskMessage.length>300?r.lastTaskMessage.slice(0,300)+"...":r.lastTaskMessage}`,"\nTo retry: call `mesh_launch_session` for this node, then `mesh_send_task` with the original task."):r.retryRecommended||n.push(`
139
+ Do NOT retry on this node. Consider reassigning to a different node or asking the user for guidance.`),n.filter(Boolean).join(`
140
+ `)}return`[System] ${e.nodeLabel} has stopped${t}. Use mesh_read_chat once if you need to inspect its last output.`}return e.event==="monitor:long_generating"?`[System] ${e.nodeLabel} has been generating for a long time${t}. Use mesh_read_chat once for a status check, but do not poll repeatedly.`:""}function Rp(e,t){var h,f;const r=As(t.metadataEvent,t.sourceInstanceId),n=Te(t.nodeId)||Te(t.metadataEvent.meshNodeId);if(dj({event:t.event,meshId:t.meshId,metadataEvent:t.metadataEvent,sessionId:r||void 0,nodeId:n||void 0}))return r&&n&&xs.delete(`${n}:${r}`),Fe.info("MeshEvents",`Suppressed ${t.event} for intentionally cleanup-stopped session ${r||"(unknown session)"}`),{success:!0,forwarded:0,suppressed:!0,intentionalCleanupStop:!0};let i=null;if(t.event==="agent:generating_completed"){const m=As(t.metadataEvent,t.sourceInstanceId),v=Te(t.nodeId)||Te(t.metadataEvent.meshNodeId),b=Te(t.metadataEvent.providerType);if(m){const p=aa(t.meshId,m,"completed");i=p?{id:p.id}:null,v&&b&&setTimeout(()=>{Sr(e,t.meshId,v,m,b)},500)}}else if(t.event==="agent:ready"){const m=As(t.metadataEvent,t.sourceInstanceId),v=Te(t.nodeId)||Te(t.metadataEvent.meshNodeId),b=Te(t.metadataEvent.providerType),p=m?aa(t.meshId,m,"completed"):null;if(p){i={id:p.id};try{on(t.meshId,{kind:"task_completed",nodeId:v||void 0,sessionId:m,providerType:b||void 0,payload:{event:t.event,nodeLabel:t.nodeLabel,taskId:p.id,completedViaReady:!0,providerSessionId:Te(t.metadataEvent.providerSessionId)||void 0,finalSummary:Te(t.metadataEvent.finalSummary)||void 0,evidence:vo({event:"agent:ready",nodeId:v,sessionId:m,providerType:b||void 0,providerSessionId:Te(t.metadataEvent.providerSessionId)||void 0,finalSummary:Te(t.metadataEvent.finalSummary)||void 0})}})}catch(g){Fe.warn("MeshLedger",`Failed to record task_completed from ready: ${(g==null?void 0:g.message)||g}`)}}m&&v&&b&&(xs.set(`${v}:${m}`,{nodeId:v,sessionId:m,providerType:b}),setTimeout(()=>{Sr(e,t.meshId,v,m,b)&&xs.delete(`${v}:${m}`)},500))}else if(t.event==="agent:generating_started"){const m=As(t.metadataEvent,t.sourceInstanceId),v=Te(t.nodeId)||Te(t.metadataEvent.meshNodeId);m&&v&&xs.delete(`${v}:${m}`)}else if(t.event==="agent:stopped"){const m=As(t.metadataEvent,t.sourceInstanceId),v=Te(t.nodeId)||Te(t.metadataEvent.meshNodeId);m&&v&&xs.delete(`${v}:${m}`),m&&aa(t.meshId,m,"failed")}const o=Ep[t.event];if(o)try{const m=Te(t.nodeId)||Te(t.metadataEvent.meshNodeId)||void 0,v=As(t.metadataEvent,t.sourceInstanceId)||void 0,b=Te(t.metadataEvent.providerType)||void 0,p=o==="task_completed"&&m&&v?vo({event:"agent:generating_completed",nodeId:m,sessionId:v,providerType:b,providerSessionId:Te(t.metadataEvent.providerSessionId)||void 0,finalSummary:Te(t.metadataEvent.finalSummary)||void 0}):void 0;on(t.meshId,{kind:o,nodeId:m,sessionId:v,providerType:b,payload:{event:t.event,nodeLabel:t.nodeLabel,taskId:(i==null?void 0:i.id)||void 0,providerSessionId:Te(t.metadataEvent.providerSessionId)||void 0,finalSummary:Te(t.metadataEvent.finalSummary)||void 0,evidence:p}})}catch(m){Fe.warn("MeshLedger",`Failed to record ${o}: ${(m==null?void 0:m.message)||m}`)}let l=null;if(t.event==="agent:stopped")try{const m=Nc(t.meshId),v=((h=m==null?void 0:m.policy)==null?void 0:h.maxTaskRetries)??1;if(l=dp(t.meshId,{sessionId:As(t.metadataEvent,t.sourceInstanceId)||void 0,nodeId:Te(t.nodeId)||Te(t.metadataEvent.meshNodeId)||void 0,maxRetries:v}),l.failedProviderType=Te(t.metadataEvent.providerType)||null,l.retryRecommended&&l.consecutiveNodeFailures>0&&(on(t.meshId,{kind:"recovery_attempted",nodeId:l.failedNodeId||void 0,sessionId:l.failedSessionId||void 0,providerType:l.failedProviderType||void 0,payload:{consecutiveFailures:l.consecutiveNodeFailures,taskAttemptCount:l.taskAttemptCount,retryRecommended:l.retryRecommended,advice:l.advice}}),l.lastTaskMessage&&l.failedNodeId&&l.failedProviderType)){const b=l.failedNodeId;try{const p=mp(t.meshId,l.lastTaskMessage,{targetNodeId:b});Fe.info("MeshRecovery",`Auto-requeued failed task: ${p.id} for node ${b}`);const g=m==null?void 0:m.nodes.find(y=>y.id===b);g&&e.cliManager.handleCliCommand("launch_cli",{cliType:l.failedProviderType,dir:g.workspace,settings:{meshNodeFor:t.meshId,meshNodeId:g.id,spawnedSessionVisibility:((f=m==null?void 0:m.policy)==null?void 0:f.spawnedSessionVisibility)||"hidden",launchedByCoordinator:!0}}).catch(y=>Fe.error("MeshRecovery",`Failed to auto-relaunch session for ${g.id}: ${y==null?void 0:y.message}`))}catch(p){Fe.warn("MeshRecovery",`Failed to execute auto-recovery: ${p==null?void 0:p.message}`)}}Fe.info("MeshRecovery",`Recovery context for ${t.nodeLabel}: ${l.advice}`)}catch(m){Fe.warn("MeshRecovery",`Failed to build recovery context: ${(m==null?void 0:m.message)||m}`)}const d=e.instanceManager.getByCategory("cli").filter(m=>{var b;const v=m.getState();return!(((b=v.settings)==null?void 0:b.meshCoordinatorFor)!==t.meshId||t.sourceInstanceId&&v.instanceId===t.sourceInstanceId)});if(d.length===0)return kr.length<Pp&&(kr.push({event:t.event,meshId:t.meshId,nodeLabel:t.nodeLabel,metadataEvent:{...t.metadataEvent,...l?{recoveryContext:l}:{}},queuedAt:Date.now()}),Fe.info("MeshEvents",`Queued ${t.event} for MCP coordinator (mesh ${t.meshId})`)),{success:!0,forwarded:0};const u=kj({event:t.event,nodeLabel:t.nodeLabel,metadataEvent:t.metadataEvent,recoveryContext:l});if(!u)return{success:!1,error:"unsupported mesh event"};for(const m of d){const v=m.getState();Fe.info("MeshEvents",`Forwarding mesh event to coordinator ${v.instanceId}`),m.onEvent("send_message",{input:{text:u,textFallback:u}})}return{success:!0,forwarded:d.length}}function jj(e,t){const r=Te(t.event);if(!Mp(r))return{success:!1,error:"unsupported mesh event"};const n=Te(t.meshId);if(!n)return{success:!1,error:"meshId required"};const a=Te(t.nodeId),i=Te(t.workspace),o=a?`Node '${a}'`:i?`Agent at ${i}`:"Remote agent";return Rp(e,{meshId:n,nodeId:a,nodeLabel:o,event:r,metadataEvent:{targetSessionId:Te(t.targetSessionId)||Te(t.sessionId)||Te(t.instanceId),providerType:Te(t.providerType),providerSessionId:Te(t.providerSessionId),finalSummary:Te(t.finalSummary)||Te(t.summary),intentional:t.intentional===!0,intentionalStop:t.intentionalStop===!0,operatorCleanup:t.operatorCleanup===!0,reason:Te(t.reason),stopReason:Te(t.stopReason),cleanupReason:Te(t.cleanupReason),source:Te(t.source)}})}function Nj(e){e.instanceManager.onEvent(t=>{var p;if(!Mp(t.event))return;const r=Te(t.instanceId);if(!r)return;const n=e.instanceManager.getInstance(r);if(!n||n.category!=="cli")return;const a=n.getState(),i=Te(a.workspace);if(!i)return;const o=a.settings&&typeof a.settings=="object"?a.settings:{};if(Te(o.meshCoordinatorFor))return;const l=Te(o.meshNodeFor);if(!!!(l||o.launchedByCoordinator))return;const u=l?Mc(e,l):rp(i),h=l||Te(u==null?void 0:u.id);if(!h)return;const f=(p=u==null?void 0:u.nodes)==null?void 0:p.find(g=>g.workspace===i),m=Te(o.meshNodeId),v=(f==null?void 0:f.id)||m,b=f?`Node '${f.id}'`:m?`Node '${m}'`:`Agent at ${i}`;Rp(e,{meshId:h,sourceInstanceId:r,nodeId:v,nodeLabel:b,event:t.event,metadataEvent:t})})}var xs,Pp,kr,Lp,Ep,Dp,ia,Qr,oa,_c=wt({"src/mesh/mesh-events.ts"(){Ht(),Cc(),Cn(),dt(),Ic(),Ac(),xs=new Map,Pp=50,kr=[],Lp=new Set(["agent:generating_started","agent:generating_completed","agent:waiting_approval","agent:stopped","agent:ready","monitor:long_generating"]),Ep={"agent:generating_completed":"task_completed","agent:waiting_approval":"task_approval_needed","agent:stopped":"task_failed","monitor:long_generating":"task_stalled"},Dp=30*60*1e3,ia=new Set,Qr=new Map,oa=5e3}});function $p(){return{...No,traceCategories:[...No.traceCategories]}}var ud,hd,No,Rc=wt({"src/logging/debug-config.ts"(){ud=200,hd={logLevel:"info",collectDebugTrace:!1,traceContent:!1,traceBufferSize:ud,traceCategories:[]},No={...hd}}});function Cj(e,t){if(!(e instanceof Error))return!1;const r=e.message||"";return("code"in e?e.code:void 0)==="MODULE_NOT_FOUND"&&r.includes(t)}function Tj(e,t){var n;const r=(n=e==null?void 0:e.default)!=null&&n.createTerminal?e.default:e!=null&&e.createTerminal?e:null;if(!r)throw new Error(`Ghostty VT binding "${t}" does not export createTerminal()`);return r}function Ij(){var t;const e=(t=Kt.ADHDEV_GHOSTTY_VT_BINDING)==null?void 0:t.trim();return e?[e]:Op}function Bp(e){if(Zs!==void 0){if(!Zs&&e&&nr)throw nr;return Zs}const t=[];for(const r of Ij())try{const n=Ir(r);return Zs=Tj(n,r),nr=null,Zs}catch(n){if(Cj(n,r)){t.push(`${r}: module not found`);continue}const a=n instanceof Error?n.message:String(n);t.push(`${r}: ${a}`)}if(Zs=null,nr=new Error(`ghostty-vt backend requested but no binding is available (${t.join("; ")||"no candidates tried"})`),e)throw nr;return null}function Aj(){var t;const e=(t=Kt.ADHDEV_TERMINAL_BACKEND)==null?void 0:t.trim().toLowerCase();return e==="ghostty-vt"||e==="xterm"||e==="auto"?e:"auto"}function Mj(){return!!Bp(!1)}var Op,Zs,nr,Co,_j=wt({"src/cli-adapters/terminal-backends/ghostty-vt-backend.ts"(){Op=["@adhdev/ghostty-vt-node"],nr=null,Co=class{constructor(e){ee(this,"kind","ghostty-vt");ee(this,"terminal");const t=Bp(!0);if(!t)throw new Error("ghostty-vt backend requested but no binding is available");this.terminal=t.createTerminal({cols:Math.max(1,e.cols|0),rows:Math.max(1,e.rows|0),scrollback:Math.max(0,e.scrollback|0)})}resize(e,t){this.terminal.resize(Math.max(1,t|0),Math.max(1,e|0))}write(e){e&&this.terminal.write(e)}getText(){return this.terminal.formatPlainText({trim:!0})||""}getCursorPosition(){return this.terminal.getCursorPosition()}dispose(){this.terminal.dispose()}}}});function Rj(){var e;if(!Zr){const t=Ir("@xterm/xterm");if(Zr=t.Terminal||((e=t.default)==null?void 0:e.Terminal)||t.default,!Zr)throw new Error("@xterm/xterm Terminal export not found")}return Zr}var Zr,Fp,Pj=wt({"src/cli-adapters/terminal-backends/xterm-backend.ts"(){Zr=null,Fp=class{constructor(e){ee(this,"kind","xterm");ee(this,"rows");ee(this,"cols");ee(this,"terminal");this.rows=Math.max(1,e.rows|0),this.cols=Math.max(1,e.cols|0),this.terminal=this.createTerminal(e.scrollback)}resize(e,t){this.rows=Math.max(1,e|0),this.cols=Math.max(1,t|0),this.terminal.resize(this.cols,this.rows)}write(e){e&&this.terminal.write(e)}getText(){var o,l;const e=this.terminal.buffer.active,t=Math.max(0,e.viewportY||0),r=Math.max(t,Math.min(e.length||0,t+this.rows)),n=[];for(let d=t;d<r;d++){const u=e.getLine(d);n.push(u?u.translateToString(!0):"")}let a=0,i=n.length;for(;a<i&&!((o=n[a])!=null&&o.trim());)a++;for(;i>a&&!((l=n[i-1])!=null&&l.trim());)i--;return n.slice(a,i).join(`
141
+ `)}getCursorPosition(){const e=this.terminal.buffer.active;return{col:Math.max(0,e.cursorX||0),row:Math.max(0,e.cursorY||0)}}dispose(){this.terminal.dispose()}createTerminal(e){const t=Rj();return new t({cols:this.cols,rows:this.rows,scrollback:e})}}}});function Lj(e,t){const r=Mj();if(t==="ghostty-vt"){const a=new Co(e);return Ui(t,r,a.kind),a}if(t==="auto"&&r){const a=new Co(e);return Ui(t,r,a.kind),a}const n=new Fp(e);return Ui(t,r,n.kind),n}function Ui(e,t,r){const n=`${e}:${t}:${r}`;if(!To.has(n)){if(To.add(n),r==="xterm"&&e!=="xterm"&&!t){const a=`[terminal-screen] ghostty-vt unavailable; using xterm fallback (preference=${e})`;e==="auto"?Fe.info("Terminal",a):Fe.warn("Terminal",a);return}Fe.info("Terminal",`[terminal-screen] backend=${r} preference=${e} ghosttyAvailable=${t}`)}}var pd,To,Wp,Up=wt({"src/cli-adapters/terminal-screen.ts"(){dt(),_j(),Pj(),pd=2e3,To=new Set,Wp=class{constructor(e=40,t=120){ee(this,"backendKind");ee(this,"rows");ee(this,"cols");ee(this,"preference");ee(this,"terminal");this.rows=Math.max(1,e|0),this.cols=Math.max(1,t|0),this.preference=Aj(),this.terminal=this.createBackend(),this.backendKind=this.terminal.kind}reset(e=this.rows,t=this.cols){this.rows=Math.max(1,e|0),this.cols=Math.max(1,t|0),this.terminal.dispose(),this.terminal=this.createBackend()}resize(e,t){this.rows=Math.max(1,e|0),this.cols=Math.max(1,t|0),this.terminal.resize(this.rows,this.cols)}write(e){this.terminal.write(e)}getText(){return this.terminal.getText()}getCursorPosition(){return this.terminal.getCursorPosition()}dispose(){this.terminal.dispose()}createBackend(){return Lj({cols:this.cols,rows:this.rows,scrollback:pd},this.preference)}}}}),Kp=wt({"src/cli-adapters/spawn-env.ts"(){}});function Ej(){if(Hr!==void 0)return Hr;try{Hr=Ir("node-pty"),lk()}catch{Hr=null}return Hr}var Hr,fd,Hp,zp=wt({"src/cli-adapters/pty-transport.ts"(){Kp(),fd=class{constructor(e){ee(this,"ready",Promise.resolve());ee(this,"terminalQueriesHandled",!1);this.handle=e}get pid(){return this.handle.pid}write(e){this.handle.write(e)}resize(e,t){this.handle.resize(e,t)}kill(){this.handle.kill()}getMetadata(){return null}onData(e){this.handle.onData(e)}onExit(e){this.handle.onExit(e)}},Hp=class{spawn(e,t,r){const n=Ej();if(!n)throw new Error("node-pty is not installed");let a=r.cwd;if(a)try{Ir("fs").statSync(a).isDirectory()||(a=vt.homedir())}catch{a=vt.homedir()}const i=n.spawn(e,t,{name:"xterm-256color",cols:r.cols,rows:r.rows,cwd:a,env:r.env});return new fd(i)}}}});function Dj(e){return e.replace(/\x1B\][^\x07]*(?:\x07|\x1B\\)/g,"").replace(/\x1B[P^_X][\s\S]*?(?:\x07|\x1B\\)/g,"").replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"")}function $j(e,t=1){const r=Number(String(e||"").split(";")[0]||t);return Math.max(1,Number.isFinite(r)?r:t)}function Bj(e){return/[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/.test(e)}function Oj(e){const t=e.codePointAt(0)||0;return t>=4352&&(t<=4447||t===9001||t===9002||t>=11904&&t<=42191&&t!==12351||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65135||t>=65280&&t<=65376||t>=65504&&t<=65510||t>=127744&&t<=129791)}function Fj(e){return String(e||"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g,"").replace(/\r+/g,`
142
+ `).replace(/[ \t]+\n/g,`
143
+ `).replace(/\n{4,}/g,`
144
+
145
+
146
+ `)}function hr(e){const t=new Pc;return Fj(Dj(t.append(e)))}function qn(e){return e?Object.entries(e).filter(([,t])=>typeof t=="function").map(([t])=>t):[]}function Wj(e){return String(e||"").replace(/\u0007/g,"").replace(/\r\n/g,`
147
+ `).replace(/\r/g,`
148
+ `).split(`
149
+ `).map(t=>t.replace(/\s+$/,""))}function Uj(e){const t=String(e||"").trim();return t?/^[❯›>]\s*(?:$|\S.*)$/.test(t):!1}function ns(e){const t=String(e||"").replace(/\r\n/g,`
150
+ `).replace(/\r/g,`
151
+ `),n=Wj(t).map((d,u,h)=>{const f=String(d||"").trim();return{index:u,fromTop:u,fromBottom:h.length-u-1,text:d,trimmed:f,isEmpty:f.length===0}}),a=n.filter(d=>!d.isEmpty),i=a[0]??null,o=a[a.length-1]??null;let l=-1;for(let d=n.length-1;d>=0;d-=1)if(Uj(n[d].text)){l=d;break}return{text:t,lineCount:n.length,lines:n,nonEmptyLines:a,firstNonEmptyLineIndex:(i==null?void 0:i.index)??-1,lastNonEmptyLineIndex:(o==null?void 0:o.index)??-1,firstNonEmptyLine:i,lastNonEmptyLine:o,promptLineIndex:l,promptLine:l>=0?n[l]:null,linesAbovePrompt:l>=0?n.slice(0,l):[...n],linesBelowPrompt:l>=0?n.slice(l+1):[]}}function Kj(e){const t=String(e||"").trim();if(!t)return t;const r=t.startsWith("~")?ze.join(vt.homedir(),t.slice(1)):t;if(ze.isAbsolute(r)||r.includes("/")||r.includes("\\"))return ze.isAbsolute(r)?r:ze.resolve(r);const n=vt.platform()==="win32";try{const a=n?`where ${t}`:`which ${t}`;return zf(a,{encoding:"utf-8",timeout:5e3,stdio:["pipe","pipe","pipe"],...n?{windowsHide:!0}:{}}).trim().split(`
152
+ `)[0].trim()}catch{return n?`${t}.cmd`:t}}function md(e){if(!ze.isAbsolute(e))return!1;try{const t=Ir("fs"),r=t.realpathSync(e),n=Buffer.alloc(8),a=t.openSync(r,"r");t.readSync(a,n,0,8,0),t.closeSync(a);let i=0;return n[0]===239&&n[1]===187&&n[2]===191&&(i=3),n[i]===35&&n[i+1]===33}catch{return!1}}function Hj(e){if(!ze.isAbsolute(e))return!1;try{const t=Ir("fs"),r=t.realpathSync(e),n=Buffer.alloc(8),a=t.openSync(r,"r");t.readSync(a,n,0,8,0),t.closeSync(a);let i=0;n[0]===239&&n[1]===187&&n[2]===191&&(i=3);const o=n.subarray(i);if(o.length<4)return!1;if(o[0]===127&&o[1]===69&&o[2]===76&&o[3]===70)return!0;const l=o.readUInt32LE(0),d=o.readUInt32BE(0);return[4277009102,4277009103,3405691582,3199925962].some(h=>h===l||h===d)}catch{return!1}}function Vp(e){return/^[a-zA-Z0-9@%_+=:,./-]+$/.test(e)?e:vt.platform()==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function xd(e,t=80){const r=String(e||"").replace(/\r/g,"");return r?r.split(`
153
+ `).reduce((n,a)=>n+Math.max(1,Math.ceil(Math.max(1,a.length)/t)),0):1}function zj(e){const t=String(e||"").replace(/\r/g,"").split(`
154
+ `).map(n=>n.trim()).filter(Boolean);return(t[t.length-1]||t[0]||"").slice(-120)}function ln(e){return String(e||"").replace(/\s+/g," ").trim()}function dn(e){return String(e||"").replace(/\s+/g,"").trim()}function Ki(e,t){const r=ln(t);if(!r)return!1;const n=ln(e);if(n.includes(r))return!0;const a=dn(e),i=dn(t);if(i&&a.includes(i))return!0;const o=r.split(/[^A-Za-z0-9_.:/-]+/).map(u=>u.trim()).filter(u=>u.length>=4);if(o.length===0)return!1;const l=Math.min(o.length,3);return o.filter(u=>n.includes(u)||a.includes(dn(u))).length>=l}function Hi(e){return hr(String(e||"")).replace(/\s+/g," ").trim()}function Vj(e){if(e instanceof RegExp)return e;if(e&&typeof e=="object"&&typeof e.source=="string")try{const t=e;return new RegExp(t.source,t.flags||"")}catch{return null}return null}function Gj(e){return Array.isArray(e)?e.map(Vj).filter(t=>t!=null):[]}function qj(e){const t=e&&typeof e=="object"?e.patterns:void 0;return{patterns:{approval:Gj(t&&typeof t=="object"?t.approval:void 0)}}}var Pc,Gp,Ca=wt({"src/cli-adapters/provider-cli-shared.ts"(){Kp(),Pc=class{constructor(){ee(this,"lines",[[]]);ee(this,"row",0);ee(this,"col",0);ee(this,"savedCursor",null);ee(this,"pendingEscape","")}append(e){const t=this.pendingEscape+String(e||"");this.pendingEscape="";for(let r=0;r<t.length;r+=1){let n=t[r];if(n==="\x1B"){const i=this.consumeEscape(t.slice(r));if(i===0){this.pendingEscape=t.slice(r);break}r+=i-1;continue}const a=t.codePointAt(r);a&&a>65535&&(n=String.fromCodePoint(a),r+=1),this.writeControlOrChar(n)}return this.getText()}reset(){this.lines=[[]],this.row=0,this.col=0,this.savedCursor=null,this.pendingEscape=""}getText(){return this.lines.map(e=>e.join("").replace(/[ \t]+$/g,"")).join(`
155
+ `)}ensureRow(e=this.row){for(;this.lines.length<=e;)this.lines.push([])}writeControlOrChar(e){if(e==="\r"){this.col=0;return}if(e===`
156
+ `){this.row+=1,this.col=0,this.ensureRow();return}if(e==="\b"){this.col=Math.max(0,this.col-1);return}if(e<" "||e==="")return;this.ensureRow();const t=this.lines[this.row];if(Bj(e)&&this.col>0){t[this.col-1]=`${t[this.col-1]||""}${e}`;return}for(;t.length<this.col;)t.push(" ");const r=Oj(e);t[this.col]=e,r&&(t[this.col+1]=""),this.col+=r?2:1}consumeEscape(e){if(e.length<2)return 0;const t=e[1];if(t==="7")return this.savedCursor={row:this.row,col:this.col},2;if(t==="8")return this.savedCursor&&(this.row=this.savedCursor.row,this.col=this.savedCursor.col,this.ensureRow()),2;if(t==="]"){const r=e.indexOf("\x07",2),n=e.indexOf("\x1B\\",2);return r>=0&&(n<0||r<n)?r+1:n>=0?n+2:0}if(t==="["){const r=e.match(/^\x1B\[([0-?]*)([ -/]*)([@-~])/);return r?(this.applyCsi(r[1]||"",r[3]),r[0].length):e.length<32?0:1}if(/[P^_X]/.test(t)){const r=e.indexOf("\x07",2),n=e.indexOf("\x1B\\",2);return r>=0&&(n<0||r<n)?r+1:n>=0?n+2:0}return 2}applyCsi(e,t){const r=$j(e);if(this.ensureRow(),t==="A")this.row=Math.max(0,this.row-r);else if(t==="B")this.row+=r;else if(t==="C")this.col+=r;else if(t==="D")this.col=Math.max(0,this.col-r);else if(t==="G")this.col=Math.max(0,r-1);else if(t==="H"||t==="f"){const n=String(e||"").split(";");this.row=Math.max(0,(Number(n[0]||1)||1)-1),this.col=Math.max(0,(Number(n[1]||1)||1)-1)}else if(t==="J"){const n=Number(e||0)||0;if(n===2||n===3)this.lines=[[]],this.row=0,this.col=0;else if(n===0)this.lines[this.row]=this.lines[this.row].slice(0,this.col),this.lines.splice(this.row+1);else if(n===1){for(let i=0;i<this.row;i+=1)this.lines[i]=[];const a=this.lines[this.row];for(let i=0;i<=Math.min(this.col,a.length-1);i+=1)a[i]=" "}}else if(t==="K"){const n=Number(e||0)||0,a=this.lines[this.row];if(n===2)this.lines[this.row]=[];else if(n===1)for(let i=0;i<=Math.min(this.col,a.length-1);i+=1)a[i]=" ";else this.lines[this.row]=a.slice(0,this.col)}else t==="s"?this.savedCursor={row:this.row,col:this.col}:t==="u"&&this.savedCursor&&(this.row=this.savedCursor.row,this.col=this.savedCursor.col);this.ensureRow()}},Gp=ok}});function Ta(e,t){return e?!Number.isFinite(t)||t<=0?e:t>=e.length?"":e.slice(t):""}function zi(e,t){return Array.isArray(e)?e:[]}function gd(e){const{accumulatedBuffer:t,accumulatedRawBuffer:r,recentOutputBuffer:n,terminalScreenText:a,baseMessages:i,partialResponse:o,isWaitingForResponse:l,scope:d,runtimeSettings:u}=e,h=d?Ta(t,d.bufferStart):t,f=d?Ta(r,d.rawBufferStart):r,m=a,v=h.slice(-1e3)||n;return{buffer:h,rawBuffer:f,recentBuffer:v,screenText:m,screen:ns(m),bufferScreen:ns(h),recentScreen:ns(v),messages:[...i],partialResponse:o,isWaitingForResponse:l,promptText:(d==null?void 0:d.prompt)||"",settings:{...u}}}function Je(e,t=800){const r=hr(String(e||""));return r.length<=t?r:`…${r.slice(-t)}`}function Xj(e,t=3){return e.slice(-t).map(r=>({role:r.role,content:Je(r.content,240),timestamp:r.timestamp}))}function fs(e){const{accumulatedBuffer:t,accumulatedRawBuffer:r,responseBuffer:n,partialResponse:a,scope:i}=e,o=i?Ta(t,i.bufferStart):t,l=i?Ta(r,i.rawBufferStart):r;return{currentTurnScope:i||null,responseBuffer:Je(n,1200),partialResponse:Je(a||n,1200),turnBuffer:Je(o,1600),turnRawPreview:Je(l,1600),turnSanitizedRawPreview:Je(hr(l),1600)}}var Yj=wt({"src/cli-adapters/provider-cli-parse.ts"(){Ca()}});function Jj(e){const t=e.timeouts||{},r=e.approvalKeys;return{timeouts:{ptyFlush:t.ptyFlush??50,dialogAccept:t.dialogAccept??300,approvalCooldown:t.approvalCooldown??3e3,generatingIdle:t.generatingIdle??6e3,idleFinish:t.idleFinish??5e3,idleFinishConfirm:t.idleFinishConfirm??2e3,statusActivityHold:t.statusActivityHold??2e3,maxResponse:t.maxResponse??3e5,shutdownGrace:t.shutdownGrace??1e3,outputSettle:t.outputSettle??300},approvalKeys:r&&typeof r=="object"?r:{},sendDelayMs:typeof e.sendDelayMs=="number"?Math.max(0,e.sendDelayMs):0,sendKey:typeof e.sendKey=="string"&&e.sendKey.length>0?e.sendKey:"\r",submitStrategy:e.submitStrategy==="immediate"?"immediate":"wait_for_echo",requirePromptEchoBeforeSubmit:e.requirePromptEchoBeforeSubmit===!0,providerResolutionMeta:{type:e.type,name:e.name,resolvedVersion:e._resolvedVersion||null,resolvedOs:e._resolvedOs||null,providerDir:e._resolvedProviderDir||null,scriptDir:e._resolvedScriptDir||null,scriptsPath:e._resolvedScriptsPath||null,scriptsSource:e._resolvedScriptsSource||null,versionWarning:e._versionWarning||null}}}var Qj=wt({"src/cli-adapters/provider-cli-config.ts"(){}});function Zj(e){const{provider:t,runtimeSettings:r,workingDir:n,extraArgs:a,extraEnv:i}=e,{spawn:o}=t,l=typeof r.executablePath=="string"&&r.executablePath.trim()?r.executablePath.trim():o.command,d=Kj(l),u=vt.platform()==="win32",h=[...o.args,...a];let f,m;const v=!u&&(!!o.shell||!ze.isAbsolute(d)||md(d)||!Hj(d)),b=u&&/\.(cmd|bat)$/i.test(d),p=!!o.shell||b||!ze.isAbsolute(d)||md(d),g=u?p:v;g?(f=u?"cmd.exe":Kt.SHELL||"/bin/zsh",u?m=["/c",d,...h]:m=["-l","-c",[d,...h].map(Vp).join(" ")]):(f=d,m=h);const y=Gp(Kt,{...o.env||{},...i||{}});return y.TERMINAL_CWD=n,{binaryPath:d,allArgs:h,shellCmd:f,shellArgs:m,isWin:u,useShell:g,ptyOptions:{cols:ak,rows:ik,cwd:n,env:y}}}function e1(e){const t=Kt.SHELL||"/bin/zsh",r=[e.binaryPath,...e.allArgs].map(Vp).join(" ");return{shellCmd:t,shellArgs:["-l","-c",r]}}function t1(e,t,r){return r?/error code 267|ERROR_DIRECTORY/i.test(e)?" (working directory does not exist or is not a directory)":/error code 740|elevation/i.test(e)?" (requires administrator privileges)":/error code 2|ENOENT|not found/i.test(e)?` (executable not found: ${t})`:null:null}function s1(e){const{ptyProcess:t,pendingTail:r,data:n,terminalScreen:a}=e;if(!t||!n)return r;const i=r+n,o=/\x1b\[(\?)?6n/g;let l;for(;(l=o.exec(i))!==null;){const f=a.getCursorPosition(),m=Math.max(1,(f.row|0)+1),v=Math.max(1,(f.col|0)+1),b=l[1]?`\x1B[?${m};${v}R`:`\x1B[${m};${v}R`;t.write(b)}const d=["\x1B[6n","\x1B[?6n"],u=d.reduce((f,m)=>Math.max(f,m.length),0)-1,h=Math.max(0,i.length-u);for(let f=h;f<i.length;f++){const m=i.slice(f);if(d.some(v=>m.length<v.length&&v.startsWith(m)))return m}return""}var r1=wt({"src/cli-adapters/provider-cli-runtime.ts"(){Ca()}}),n1={};js(n1,{ProviderCliAdapter:()=>qp,appendBoundedText:()=>Io,normalizeCliProviderForRuntime:()=>qj});function Io(e,t,r){if(!t)return e.length<=r?e:e.slice(-r);if(r<=0)return"";if(t.length>=r)return t.slice(-r);const n=r-t.length;return e.length<=n?e+t:e.slice(-n)+t}var qp,Lc=wt({"src/cli-adapters/provider-cli-adapter.ts"(){var e;dt(),Rc(),Up(),zp(),Ca(),Yj(),Qj(),r1(),Ca(),qp=(e=class{constructor(r,n,a=[],i={},o=new Hp){ee(this,"cliType");ee(this,"cliName");ee(this,"workingDir");ee(this,"provider");ee(this,"ptyProcess",null);ee(this,"transportFactory");ee(this,"currentStatus","starting");ee(this,"onStatusChange",null);ee(this,"responseBuffer","");ee(this,"recentOutputBuffer","");ee(this,"isWaitingForResponse",!1);ee(this,"activeModal",null);ee(this,"parseErrorMessage",null);ee(this,"responseTimeout",null);ee(this,"idleTimeout",null);ee(this,"ready",!1);ee(this,"startupBuffer","");ee(this,"startupParseGate",!1);ee(this,"startupSettleTimer",null);ee(this,"spawnAt",0);ee(this,"startupFirstOutputAt",0);ee(this,"onPtyDataCallback",null);ee(this,"pendingOutputParseChunks",[]);ee(this,"pendingOutputParseTimer",null);ee(this,"ptyOutputChunks",[]);ee(this,"ptyOutputFlushTimer",null);ee(this,"pendingTerminalQueryTail","");ee(this,"lastOutputAt",0);ee(this,"lastNonEmptyOutputAt",0);ee(this,"lastScreenChangeAt",0);ee(this,"lastScreenSnapshot","");ee(this,"lastScreenText","");ee(this,"lastScreenSnapshotReadAt",Number.NEGATIVE_INFINITY);ee(this,"serverConn",null);ee(this,"logBuffer",[]);ee(this,"lastApprovalResolvedAt",0);ee(this,"approvalTransitionBuffer","");ee(this,"approvalExitTimeout",null);ee(this,"pendingScriptStatus",null);ee(this,"pendingScriptStatusSince",0);ee(this,"pendingScriptStatusTimer",null);ee(this,"settleTimer",null);ee(this,"settledBuffer","");ee(this,"submitPendingUntil",0);ee(this,"responseSettleIgnoreUntil",0);ee(this,"responseEpoch",0);ee(this,"submitRetryTimer",null);ee(this,"submitRetryUsed",!1);ee(this,"submitRetryPromptSnippet","");ee(this,"idleFinishCandidate",null);ee(this,"finishRetryTimer",null);ee(this,"finishRetryCount",0);ee(this,"resizeSuppressUntil",0);ee(this,"statusHistory",[]);ee(this,"cliScripts");ee(this,"scriptState",null);ee(this,"runtimeSettings",{});ee(this,"accumulatedBuffer","");ee(this,"transcriptAccumulator",new Pc);ee(this,"accumulatedRawBuffer","");ee(this,"terminalScreen",new Wp(24,80));ee(this,"responseBufferDroppedChars",0);ee(this,"recentOutputDroppedChars",0);ee(this,"accumulatedBufferDroppedChars",0);ee(this,"accumulatedRawBufferDroppedChars",0);ee(this,"currentTurnScope",null);ee(this,"traceEntries",[]);ee(this,"traceSeq",0);ee(this,"traceSessionId","");ee(this,"parsedStatusCache",null);ee(this,"providerResolutionMeta");ee(this,"timeouts");ee(this,"approvalKeys");ee(this,"sendDelayMs");ee(this,"sendKey");ee(this,"submitStrategy");ee(this,"requirePromptEchoBeforeSubmit");this.extraArgs=a,this.extraEnv=i,this.provider=r,this.transportFactory=o,this.cliType=r.type,this.cliName=r.name,this.workingDir=n.startsWith("~")?n.replace(/^~/,vt.homedir()):n;const l=Jj(r);this.timeouts=l.timeouts,this.approvalKeys=l.approvalKeys,this.sendDelayMs=l.sendDelayMs,this.sendKey=l.sendKey,this.submitStrategy=l.submitStrategy,this.requirePromptEchoBeforeSubmit=l.requirePromptEchoBeforeSubmit,this.providerResolutionMeta=l.providerResolutionMeta,this.cliScripts=r.scripts||{},this.scriptState=typeof this.cliScripts.createState=="function"?this.cliScripts.createState()??null:null;const d=qn(this.cliScripts);if(d.length>0)Fe.info("CLI",`[${this.cliType}] CLI scripts: [${d.join(", ")}]`),Fe.info("CLI",`[${this.cliType}] Provider resolution: providerDir=${this.providerResolutionMeta.providerDir||"-"} scriptDir=${this.providerResolutionMeta.scriptDir||"-"} scriptsPath=${this.providerResolutionMeta.scriptsPath||"-"} source=${this.providerResolutionMeta.scriptsSource||"-"} version=${this.providerResolutionMeta.resolvedVersion||"-"}`);else{const u=`providerDir=${this.providerResolutionMeta.providerDir||"-"} scriptDir=${this.providerResolutionMeta.scriptDir||"-"} scriptsPath=${this.providerResolutionMeta.scriptsPath||"-"} source=${this.providerResolutionMeta.scriptsSource||"-"} version=${this.providerResolutionMeta.resolvedVersion||"-"}`;!!(this.providerResolutionMeta.providerDir||this.providerResolutionMeta.scriptDir||this.providerResolutionMeta.scriptsPath||this.providerResolutionMeta.scriptsSource||this.providerResolutionMeta.resolvedVersion)?Fe.warn("CLI",`[${this.cliType}] ⚠ No CLI scripts loaded! Provider needs scripts/{version}/scripts.js (${u})`):Fe.info("CLI",`[${this.cliType}] CLI scripts not yet resolved (${u})`)}}getBufferState(){const r=(l,d)=>l>0?{truncated:!0,droppedChars:l,maxChars:d}:void 0,n=r(this.responseBufferDroppedChars,e.MAX_RESPONSE_BUFFER),a=r(this.recentOutputDroppedChars,e.MAX_RECENT_OUTPUT_BUFFER),i=r(this.accumulatedBufferDroppedChars,e.MAX_ACCUMULATED_BUFFER),o=r(this.accumulatedRawBufferDroppedChars,e.MAX_ACCUMULATED_BUFFER);if(!(!n&&!a&&!i&&!o))return{...n?{responseBuffer:n}:{},...a?{recentOutputBuffer:a}:{},...i?{accumulatedBuffer:i}:{},...o?{accumulatedRawBuffer:o}:{}}}recordBoundedAppendDrop(r,n,a){return Math.max(0,r+n-a)}readTerminalScreenText(r=Date.now()){const n=this.terminalScreen.getText()||"";return this.lastScreenText=n,this.lastScreenSnapshotReadAt=r,n}getParseScreenText(r){const n=Hi(r),a=this.lastScreenSnapshot;if(!a||a===n)return r;const i=/\besc to (?:interrupt|stop)\b|Enter to interrupt, Ctrl\+C to cancel|Enter to confirm\s*[·•-]\s*Esc to cancel|\b(?:MCP servers?|tool calls?)\b[^\n\r]{0,160}\brequire approval\b/i,o=i.test(a),l=/(?:^|\n|\r)\s*[❯›>]\s*(?:Try\s+["“][^\n\r"”]+["”])?\s*(?:\n|\r|$)/.test(r)&&!i.test(r);return o&&l||n.length>=a.length?r:`${r}
157
+ ${a}`}shouldReadTerminalScreenSnapshot(r){return this.lastScreenText?r-this.lastScreenSnapshotReadAt>=e.SCREEN_SNAPSHOT_MIN_INTERVAL_MS:!0}resetTerminalScreen(r,n){this.terminalScreen.reset(r,n),this.transcriptAccumulator.reset(),this.lastScreenText="",this.lastScreenSnapshot="",this.lastScreenChangeAt=0,this.lastScreenSnapshotReadAt=Number.NEGATIVE_INFINITY}getAccumulatedRawBufferCacheKey(){return this.accumulatedRawBuffer.replace(/\x1B\][^\x07]*(?:\x07|\x1B\\)/g,"").replace(/\x1B[P^_X][\s\S]*?(?:\x07|\x1B\\)/g,"").replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"")}getFreshParsedStatusCache(){const r=this.parsedStatusCache,n=this.getAccumulatedRawBufferCacheKey();return r&&r.responseBuffer===this.responseBuffer&&r.currentTurnScope===this.currentTurnScope&&r.recentOutputBuffer===this.recentOutputBuffer&&r.accumulatedBuffer===this.accumulatedBuffer&&r.accumulatedRawBufferKey===n&&r.screenText===this.lastScreenText&&r.currentStatus===this.currentStatus&&r.activeModal===this.activeModal&&r.cliName===this.cliName?r.result:null}providerOwnsTranscript(){return this.provider.transcriptAuthority==="provider"}shouldUseFullProviderTranscriptContext(){return this.providerOwnsTranscript()&&this.provider.transcriptContext==="full"}getIdleFinishConfirmMs(){return this.timeouts.idleFinishConfirm}getStatusActivityHoldMs(){return this.timeouts.statusActivityHold}setStatus(r,n){const a=this.currentStatus;a!==r&&(this.currentStatus=r,this.statusHistory.push({status:r,at:Date.now(),trigger:n}),this.statusHistory.length>50&&this.statusHistory.shift(),this.recordTrace("status",{previousStatus:a,trigger:n||null}),Fe.info("CLI",`[${this.cliType}] status: ${a} → ${r}${n?` (${n})`:""}`))}clearIdleFinishCandidate(r){this.idleFinishCandidate&&(this.recordTrace("idle_candidate_reset",{reason:r,candidate:this.idleFinishCandidate}),this.idleFinishCandidate=null)}armIdleFinishCandidate(r){const n=Date.now(),a=this.getIdleFinishConfirmMs();this.idleFinishCandidate={armedAt:n,lastOutputAt:this.lastOutputAt,lastScreenChangeAt:this.lastScreenChangeAt,responseEpoch:this.responseEpoch,assistantLength:r},this.recordTrace("idle_candidate_armed",{confirmMs:a,candidate:this.idleFinishCandidate,...fs({accumulatedBuffer:this.accumulatedBuffer,accumulatedRawBuffer:this.accumulatedRawBuffer,responseBuffer:this.responseBuffer,partialResponse:this.responseBuffer,scope:this.currentTurnScope})}),this.settleTimer&&clearTimeout(this.settleTimer),this.settleTimer=setTimeout(()=>{this.settleTimer=null,this.settledBuffer=this.recentOutputBuffer,this.evaluateSettled()},a)}recordTrace(r,n={}){const a={id:++this.traceSeq,at:Date.now(),type:r,status:this.currentStatus,isWaitingForResponse:this.isWaitingForResponse,activeModal:this.activeModal?{message:this.activeModal.message,buttons:[...this.activeModal.buttons]}:null,payload:n};this.traceEntries.push(a),this.traceEntries.length>e.MAX_TRACE_ENTRIES&&this.traceEntries.splice(0,this.traceEntries.length-e.MAX_TRACE_ENTRIES)}resetTraceSession(){this.traceEntries=[],this.traceSeq=0,this.traceSessionId=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,this.recordTrace("session_start",{providerType:this.cliType,workingDir:this.workingDir})}setCliScripts(r){this.cliScripts=r,this.parsedStatusCache=null,this.parseErrorMessage=null,this.scriptState=typeof r.createState=="function"?r.createState()??null:null;const n=qn(r);Fe.info("CLI",`[${this.cliType}] CLI scripts injected: [${n.join(", ")}]`)}refreshProviderDefinition(r){this.provider=r,this.setCliScripts(r.scripts||{})}updateRuntimeSettings(r){this.runtimeSettings={...r}}setServerConn(r){this.serverConn=r,this.serverConn&&this.logBuffer.length>0&&(this.logBuffer.forEach(n=>this.serverConn.sendMessage("log",n)),this.logBuffer=[])}setOnStatusChange(r){this.onStatusChange=r}setOnPtyData(r){this.onPtyDataCallback=r}flushPendingOutputParse(){if(this.pendingOutputParseTimer&&(clearTimeout(this.pendingOutputParseTimer),this.pendingOutputParseTimer=null),this.pendingOutputParseChunks.length===0)return;const r=this.pendingOutputParseChunks.join("");this.pendingOutputParseChunks=[],this.handleOutput(r)}async spawn(){var n;if(this.ptyProcess)return;const r=Zj({provider:this.provider,runtimeSettings:this.runtimeSettings,workingDir:this.workingDir,extraArgs:this.extraArgs,extraEnv:this.extraEnv});Fe.info("CLI",`[${this.cliType}] Spawning in ${this.workingDir}`),this.resetTraceSession(),this.recordTrace("spawn",{shellCommand:r.shellCmd,shellArgs:r.shellArgs,cwd:r.ptyOptions.cwd,cols:r.ptyOptions.cols,rows:r.ptyOptions.rows,providerResolution:this.providerResolutionMeta});try{this.ptyProcess=this.transportFactory.spawn(r.shellCmd,r.shellArgs,r.ptyOptions)}catch(a){const i=(a==null?void 0:a.message)||String(a);if(!r.isWin&&!r.useShell&&/posix_spawn|spawn/i.test(i)){Fe.warn("CLI",`[${this.cliType}] Direct spawn failed (${i}), retrying via login shell`);const o=e1(r);this.ptyProcess=this.transportFactory.spawn(o.shellCmd,o.shellArgs,r.ptyOptions)}else{const o=t1(i,r.shellCmd,r.isWin);throw o?new Error(`Failed to spawn CLI${o}: ${i}`):a}}this.ptyProcess.onData(a=>{var i;Date.now()<this.resizeSuppressUntil||((i=this.ptyProcess)!=null&&i.terminalQueriesHandled||(this.pendingTerminalQueryTail=s1({ptyProcess:this.ptyProcess,pendingTail:this.pendingTerminalQueryTail,data:a,terminalScreen:this.terminalScreen})),this.pendingOutputParseChunks.push(a),this.pendingOutputParseTimer||(this.pendingOutputParseTimer=setTimeout(()=>{this.pendingOutputParseTimer=null,this.flushPendingOutputParse()},this.timeouts.ptyFlush)),this.onPtyDataCallback&&(this.ptyOutputChunks.push(a),this.ptyOutputFlushTimer||(this.ptyOutputFlushTimer=setTimeout(()=>{this.ptyOutputChunks.length>0&&this.onPtyDataCallback&&this.onPtyDataCallback(this.ptyOutputChunks.join("")),this.ptyOutputChunks=[],this.ptyOutputFlushTimer=null},this.timeouts.ptyFlush))))}),this.ptyProcess.onExit(({exitCode:a})=>{var i;Fe.info("CLI",`[${this.cliType}] Exit code ${a}`),this.flushPendingOutputParse(),this.recordTrace("exit",{exitCode:a}),this.ptyProcess=null,this.setStatus("stopped","pty_exit"),this.ready=!1,this.startupParseGate=!1,this.spawnAt=0,this.scriptState=null,(i=this.onStatusChange)==null||i.call(this)}),this.spawnAt=Date.now(),this.startupParseGate=!0,this.startupBuffer="",this.startupFirstOutputAt=0,this.startupSettleTimer&&(clearTimeout(this.startupSettleTimer),this.startupSettleTimer=null),this.resetTerminalScreen(24,80),this.pendingTerminalQueryTail="",this.currentTurnScope=null,this.finishRetryCount=0,this.finishRetryTimer&&(clearTimeout(this.finishRetryTimer),this.finishRetryTimer=null),this.ready=!1,await this.ptyProcess.ready,this.recordTrace("ready",{runtimeMeta:this.getRuntimeMetadata()}),this.setStatus("starting","pty_ready"),this.scheduleStartupSettleCheck(),(n=this.onStatusChange)==null||n.call(this)}handleOutput(r){this.terminalScreen.write(r);const n=hr(r),a=this.transcriptAccumulator.append(r),i=Date.now(),o=this.shouldReadTerminalScreenSnapshot(i),l=o?this.readTerminalScreenText(i):this.lastScreenText,d=o?Hi(l):this.lastScreenSnapshot;if(this.lastOutputAt=i,n.trim()&&(this.lastNonEmptyOutputAt=i),o&&d!==this.lastScreenSnapshot&&(this.lastScreenSnapshot=d,this.lastScreenChangeAt=i),this.startupParseGate&&!this.startupFirstOutputAt&&(n.trim()||d.trim())&&(this.startupFirstOutputAt=i),this.idleFinishCandidate&&(r.length>0||n.length>0)&&this.clearIdleFinishCandidate("new_output"),$p().collectDebugTrace&&this.recordTrace("output",{rawLength:r.length,cleanLength:n.length,rawPreview:Je(r,300),cleanPreview:Je(n,300)}),this.startupParseGate&&this.scheduleStartupSettleCheck(),this.isWaitingForResponse&&n){const p=this.responseBuffer.length;this.responseBuffer=Io(this.responseBuffer,n,e.MAX_RESPONSE_BUFFER),this.responseBufferDroppedChars+=this.recordBoundedAppendDrop(p,n.length,this.responseBuffer.length)}n.trim()&&(this.serverConn?this.serverConn.sendMessage("log",{message:n.trim(),level:"info"}):this.logBuffer.push({message:n.trim(),level:"info"})),this.recentOutputBuffer.length;const u=this.accumulatedRawBuffer.length,h=a.length<=e.MAX_ACCUMULATED_BUFFER?a:a.slice(-e.MAX_ACCUMULATED_BUFFER),f=h.slice(-e.MAX_RECENT_OUTPUT_BUFFER);this.recentOutputBuffer=f,this.accumulatedBuffer=h,this.accumulatedRawBuffer=Io(this.accumulatedRawBuffer,r,e.MAX_ACCUMULATED_BUFFER);const m=Math.max(0,a.length-e.MAX_RECENT_OUTPUT_BUFFER),v=Math.max(0,a.length-this.accumulatedBuffer.length),b=this.recordBoundedAppendDrop(u,r.length,this.accumulatedRawBuffer.length);this.recentOutputDroppedChars+=m,this.accumulatedBufferDroppedChars+=v,this.accumulatedRawBufferDroppedChars+=b,this.currentTurnScope&&(v>0&&(this.currentTurnScope.bufferStart=Math.max(0,this.currentTurnScope.bufferStart-v)),b>0&&(this.currentTurnScope.rawBufferStart=Math.max(0,this.currentTurnScope.rawBufferStart-b))),this.resolveStartupState("output",l,d,i),this.scheduleSettle()}resolveStartupState(r,n,a,i){var m;if(!this.startupParseGate)return;const o=typeof i=="number"?i:Date.now(),l=typeof n=="string"?n:this.readTerminalScreenText(),d=typeof a=="string"?a:Hi(l);if(!(!!this.startupFirstOutputAt||!!d.trim()))return;const h=this.lastScreenChangeAt?o-this.lastScreenChangeAt:0;if(h<2e3)return;const f=this.runParseApproval(this.recentOutputBuffer);this.startupParseGate=!1,this.startupSettleTimer&&(clearTimeout(this.startupSettleTimer),this.startupSettleTimer=null),this.ready=!0,f?(this.activeModal=f,this.setStatus("waiting_approval",`startup_ready:${r}`)):((this.currentStatus==="waiting_approval"||this.activeModal)&&(this.lastApprovalResolvedAt=Date.now()),this.activeModal=null,this.setStatus("idle",`startup_ready:${r}`)),Fe.info("CLI",`[${this.cliType}] Startup settled (${r}, stableMs=${h}, modal=${!!f}) providerDir=${this.providerResolutionMeta.providerDir||"-"} scriptDir=${this.providerResolutionMeta.scriptDir||"-"} scriptsPath=${this.providerResolutionMeta.scriptsPath||"-"}`),(m=this.onStatusChange)==null||m.call(this)}scheduleStartupSettleCheck(){if(!this.startupParseGate)return;this.startupSettleTimer&&clearTimeout(this.startupSettleTimer);const r=Date.now(),n=this.lastScreenChangeAt?r-this.lastScreenChangeAt:0,a=Math.max(250,2050-n);this.startupSettleTimer=setTimeout(()=>{this.startupSettleTimer=null,this.resolveStartupState("startup_timer"),this.startupParseGate&&Date.now()-this.spawnAt<1e4&&this.scheduleStartupSettleCheck()},a)}scheduleSettle(){this.settleTimer&&clearTimeout(this.settleTimer);const r=this.responseEpoch,n=Math.max(this.timeouts.outputSettle,this.submitPendingUntil>Date.now()?this.submitPendingUntil-Date.now()+this.timeouts.outputSettle:0);this.settleTimer=setTimeout(()=>{this.settleTimer=null,r===this.responseEpoch&&(this.settledBuffer=this.recentOutputBuffer,this.evaluateSettled())},n)}armApprovalExitTimeout(){this.approvalExitTimeout&&clearTimeout(this.approvalExitTimeout),this.approvalExitTimeout=setTimeout(()=>{var i,o,l;if(!this.hasActionableApproval())return;const r=this.recentOutputBuffer;this.terminalScreen.getText();const n=this.runParseApproval(r);if(this.runDetectStatus(r)==="waiting_approval"||!!n){if(!n){Fe.warn("CLI",`[${this.cliType}] approval timeout check found no actionable modal; keeping approval state fail-closed`),this.activeModal=null,(i=this.onStatusChange)==null||i.call(this),this.armApprovalExitTimeout();return}this.activeModal=n,(o=this.onStatusChange)==null||o.call(this),this.armApprovalExitTimeout();return}Fe.warn("CLI",`[${this.cliType}] Approval timeout — auto-clearing`),this.activeModal=null,this.lastApprovalResolvedAt=Date.now(),this.setStatus("idle","approval_timeout"),(l=this.onStatusChange)==null||l.call(this)},6e4)}shouldRetryFinishResponse(r){if(!this.currentTurnScope||this.hasActionableApproval()||this.finishRetryCount>=e.MAX_FINISH_RETRIES||r.hasAssistant&&r.assistantContent.trim()||this.runDetectStatus(this.recentOutputBuffer)!=="idle")return!1;const n=Date.now(),a=this.lastNonEmptyOutputAt?n-this.lastNonEmptyOutputAt:Number.MAX_SAFE_INTEGER,i=this.lastScreenChangeAt?n-this.lastScreenChangeAt:0;return a<1200||i<1200||!r.hasAssistant}hasRecentInteractiveActivity(r){const n=this.lastNonEmptyOutputAt?r-this.lastNonEmptyOutputAt:Number.MAX_SAFE_INTEGER,a=this.lastScreenChangeAt?r-this.lastScreenChangeAt:Number.MAX_SAFE_INTEGER,i=this.getStatusActivityHoldMs();return n<i||a<i}shouldDeferIdleTimeoutFinish(){return!this.isWaitingForResponse||this.hasActionableApproval()?!1:(this.runDetectStatus(this.recentOutputBuffer)||this.currentStatus)==="generating"?(this.settledBuffer=this.recentOutputBuffer,this.evaluateSettled(),!0):!1}async waitForInteractivePrompt(r=5e3){const n=Date.now();let a=!1;for(;Date.now()-n<r;){this.resolveStartupState("interactive_wait");const o=this.terminalScreen.getText()||"",l=this.lastScreenChangeAt?Date.now()-this.lastScreenChangeAt:0,d=this.lastNonEmptyOutputAt?Date.now()-this.lastNonEmptyOutputAt:Number.MAX_SAFE_INTEGER,u=this.runDetectStatus(this.recentOutputBuffer)||this.currentStatus;if(u==="idle"&&l>=700&&d>=350){a&&Fe.info("CLI",`[${this.cliType}] Interactive prompt ready after ${Date.now()-n}ms (stableMs=${l}, recentOutputMs=${d})`);return}!a&&Date.now()-n>=400&&(a=!0,Fe.info("CLI",`[${this.cliType}] Waiting for interactive prompt: status=${u} stableMs=${l} recentOutputMs=${d} screen=${JSON.stringify(Je(o,220)).slice(0,260)}`)),await new Promise(f=>setTimeout(f,50))}const i=this.terminalScreen.getText()||"";Fe.warn("CLI",`[${this.cliType}] Interactive prompt wait timed out after ${r}ms; proceeding with screen=${JSON.stringify(Je(i,240)).slice(0,280)}`)}clearAllTimers(){this.responseTimeout&&(clearTimeout(this.responseTimeout),this.responseTimeout=null),this.idleTimeout&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.approvalExitTimeout&&(clearTimeout(this.approvalExitTimeout),this.approvalExitTimeout=null),this.submitRetryTimer&&(clearTimeout(this.submitRetryTimer),this.submitRetryTimer=null),this.finishRetryTimer&&(clearTimeout(this.finishRetryTimer),this.finishRetryTimer=null),this.settleTimer&&(clearTimeout(this.settleTimer),this.settleTimer=null),this.pendingScriptStatusTimer&&(clearTimeout(this.pendingScriptStatusTimer),this.pendingScriptStatusTimer=null),this.pendingOutputParseTimer&&(clearTimeout(this.pendingOutputParseTimer),this.pendingOutputParseTimer=null),this.ptyOutputFlushTimer&&(clearTimeout(this.ptyOutputFlushTimer),this.ptyOutputFlushTimer=null)}clearStaleIdleResponseGuard(r){const n=this.activeModal||this.runParseApproval(this.recentOutputBuffer),a=this.runDetectStatus(this.recentOutputBuffer)==="idle";return!this.isWaitingForResponse||this.currentStatus!=="idle"||!a||n?!1:(this.clearAllTimers(),this.clearIdleFinishCandidate(r),this.responseBuffer="",this.isWaitingForResponse=!1,this.responseSettleIgnoreUntil=0,this.submitRetryUsed=!1,this.submitRetryPromptSnippet="",this.finishRetryCount=0,this.currentTurnScope=null,this.activeModal=null,this.recordTrace("stale_idle_response_cleared",{reason:r}),!0)}hasMeaningfulResponseBuffer(r){const n=String(this.responseBuffer||"").trim();if(!n)return!1;const a=dn(r);if(!a)return!0;const i=dn(n);return!i||i===a?!1:i.startsWith(a)?i.slice(a.length).replace(/[─═\-]+/g,"").replace(/⏵⏵accepteditson\([^)]*\)/gi,"").replace(/accepteditson\([^)]*\)/gi,"").replace(/(?:◐|◑|◒|◓|◔|◕|◉|●|·)?(?:x?high|medium|low|max)·?\/effort/gi,"").replace(/updateavailable!run:[a-z0-9:._\-/]+/gi,"").replace(/esctointerrupt/gi,"").replace(/❯/g,"").replace(/^[\s\-–—:;,.!/?]+/,"").trim().length>0:!0}evaluateSettled(){var g,y,x;const r=Date.now();if(this.submitPendingUntil>r||this.responseSettleIgnoreUntil>r){const N=Math.max(this.submitPendingUntil-r,this.responseSettleIgnoreUntil-r)+50;this.settleTimer&&clearTimeout(this.settleTimer),this.settleTimer=setTimeout(()=>{this.settleTimer=null,this.settledBuffer=this.recentOutputBuffer,this.evaluateSettled()},N);return}if(this.resolveStartupState("settled"),this.startupParseGate)return;if(!this.isWaitingForResponse&&!this.currentTurnScope&&!this.activeModal&&!this.parseErrorMessage){const N=this.settledBuffer||this.recentOutputBuffer,j=this.runParseApproval(N),w=(g=this.cliScripts)!=null&&g.detectStatus?this.runDetectStatus(N):null;if(!j&&w==="idle"&&this.currentStatus==="idle")return}const n=this.runParseSession();if(!n)return;const{status:a,messages:i,parsedStatus:o}=n,l=n.activeModal??n.modal??null,d=zi(i,{lastOutputAt:this.lastOutputAt});if(this.maybeCommitVisibleIdleTranscript(n,d))return;const u=[...d].reverse().find(N=>N.role==="assistant"),h=ln(this.submitRetryPromptSnippet||((y=this.currentTurnScope)==null?void 0:y.prompt)||""),f=this.terminalScreen.getText()||"";if(this.recordTrace("settled",{tail:Je(this.settledBuffer,500),screenText:Je(f,1200),detectStatus:a,parsedStatus:o||null,parsedMessageCount:d.length,parsedLastAssistant:u?Je(u.content,280):"",parsedActiveModal:l,approval:l,...fs({accumulatedBuffer:this.accumulatedBuffer,accumulatedRawBuffer:this.accumulatedRawBuffer,responseBuffer:this.responseBuffer,partialResponse:this.responseBuffer,scope:this.currentTurnScope})}),this.currentTurnScope&&!u&&!this.submitRetryUsed&&this.ptyProcess&&!this.hasActionableApproval()&&Ki(f,h)&&!this.hasMeaningfulResponseBuffer(h)){this.submitRetryUsed=!0,this.responseSettleIgnoreUntil=Date.now()+this.timeouts.outputSettle+400,Fe.info("CLI",`[${this.cliType}] Retrying submit key from settled parser (no assistant yet)`),this.recordTrace("submit_write",{mode:"settled_retry",sendKey:this.sendKey,screenText:Je(f,500)}),this.ptyProcess.write(this.sendKey),this.settleTimer&&clearTimeout(this.settleTimer),this.settleTimer=setTimeout(()=>{this.settleTimer=null,this.settledBuffer=this.recentOutputBuffer,this.evaluateSettled()},this.timeouts.outputSettle+150);return}if(this.currentTurnScope&&!u&&Fe.debug("CLI",`[${this.cliType}] Settled without assistant: prompt=${JSON.stringify(this.currentTurnScope.prompt).slice(0,140)} responseBuffer=${JSON.stringify(Je(this.responseBuffer,220)).slice(0,260)} screen=${JSON.stringify(Je(f,220)).slice(0,260)} providerDir=${this.providerResolutionMeta.providerDir||"-"} scriptDir=${this.providerResolutionMeta.scriptDir||"-"}`),!a)return;const m=this.currentStatus,v={now:r,modal:l,status:a,parsedMessages:d,lastParsedAssistant:u,parsedStatus:o||null,prevStatus:m};if(!this.applyPendingScriptStatusDebounce(v))return;const b=this.hasRecentInteractiveActivity(r);if(Fe.debug("CLI",`[${this.cliType}] settled diagnostics prompt=${JSON.stringify(((x=this.currentTurnScope)==null?void 0:x.prompt)||"").slice(0,140)} status=${String(a||"")} parsedStatus=${String(o||"")} parsedMsgCount=${d.length} lastParsedAssistant=${JSON.stringify(Je((u==null?void 0:u.content)||"",120)).slice(0,160)} responseBuffer=${JSON.stringify(Je(this.responseBuffer,160)).slice(0,220)} screen=${JSON.stringify(Je(f,160)).slice(0,220)}`),a==="idle"&&this.isWaitingForResponse&&!l&&b&&!(o==="idle"&&u)){this.applyHoldGenerating(v,b);return}if(a==="waiting_approval"){this.applyWaitingApproval(v);return}if(a==="generating"){this.applyGenerating(v);return}a==="idle"&&this.applyIdle(v,r)}applyPendingScriptStatusDebounce(r){const{now:n,status:a,prevStatus:i}=r;if(!(i==="idle"&&!this.isWaitingForResponse&&!this.currentTurnScope&&(a==="generating"||a==="waiting_approval")))return this.pendingScriptStatus=null,this.pendingScriptStatusSince=0,this.pendingScriptStatusTimer&&(clearTimeout(this.pendingScriptStatusTimer),this.pendingScriptStatusTimer=null),!0;const l=u=>{this.pendingScriptStatusTimer&&clearTimeout(this.pendingScriptStatusTimer),this.pendingScriptStatusTimer=setTimeout(()=>{this.pendingScriptStatusTimer=null,this.settledBuffer=this.recentOutputBuffer,this.evaluateSettled()},u)};if(this.pendingScriptStatus!==a)return this.pendingScriptStatus=a,this.pendingScriptStatusSince=n,l(e.SCRIPT_STATUS_DEBOUNCE_MS),!1;const d=n-this.pendingScriptStatusSince;return d<e.SCRIPT_STATUS_DEBOUNCE_MS?(l(e.SCRIPT_STATUS_DEBOUNCE_MS-d),!1):!0}applyHoldGenerating(r,n){var i;const{status:a}=r;this.clearIdleFinishCandidate("hold_generating_recent_activity"),this.setStatus("generating","recent_activity_hold"),this.idleTimeout&&clearTimeout(this.idleTimeout),this.idleTimeout=setTimeout(()=>{if(this.isWaitingForResponse&&!this.hasActionableApproval()){if(this.shouldDeferIdleTimeoutFinish())return;this.finishResponse()}},this.timeouts.generatingIdle),this.recordTrace("hold_generating_recent_activity",{scriptStatus:a,recentInteractiveActivity:n,lastNonEmptyOutputAt:this.lastNonEmptyOutputAt,lastScreenChangeAt:this.lastScreenChangeAt,holdMs:this.getStatusActivityHoldMs(),...fs({accumulatedBuffer:this.accumulatedBuffer,accumulatedRawBuffer:this.accumulatedRawBuffer,responseBuffer:this.responseBuffer,partialResponse:this.responseBuffer,scope:this.currentTurnScope})}),(i=this.onStatusChange)==null||i.call(this)}applyWaitingApproval(r){var i,o;const{modal:n}=r;this.clearIdleFinishCandidate("waiting_approval");const a=this.lastApprovalResolvedAt&&Date.now()-this.lastApprovalResolvedAt<this.timeouts.approvalCooldown;if(a&&!n){this.approvalExitTimeout&&(clearTimeout(this.approvalExitTimeout),this.approvalExitTimeout=null),this.activeModal=null,this.isWaitingForResponse?(this.setStatus("idle",a?"approval_cooldown_non_actionable":"approval_prompt_gone_non_actionable"),this.idleTimeout&&clearTimeout(this.idleTimeout),this.idleTimeout=setTimeout(()=>{if(this.isWaitingForResponse&&!this.hasActionableApproval()){if(this.shouldDeferIdleTimeoutFinish())return;this.finishResponse()}},this.timeouts.generatingIdle)):this.setStatus("idle",a?"approval_cooldown_non_actionable":"approval_prompt_gone_non_actionable"),(i=this.onStatusChange)==null||i.call(this);return}if(!a){if(!n){Fe.warn("CLI",`[${this.cliType}] detectStatus reported waiting_approval without parseApproval modal; ignoring non-actionable approval state`);return}this.isWaitingForResponse=!0,this.setStatus("waiting_approval","script_detect"),this.activeModal=n,this.idleTimeout&&clearTimeout(this.idleTimeout),this.armApprovalExitTimeout(),(o=this.onStatusChange)==null||o.call(this)}}applyGenerating(r){var v;const{modal:n,parsedMessages:a,lastParsedAssistant:i,parsedStatus:o,prevStatus:l}=r;this.clearIdleFinishCandidate("generating");const u=this.terminalScreen.getText()||""||this.accumulatedBuffer,h=!this.currentTurnScope,f=/(^|\n)\s*[❯›>]\s*(?:\n|$)/m.test(u),m=o==="generating"&&!!i;l==="idle"&&!this.isWaitingForResponse&&h&&!n&&f&&!m||(l==="waiting_approval"&&(this.approvalExitTimeout&&(clearTimeout(this.approvalExitTimeout),this.approvalExitTimeout=null),this.activeModal=null,this.lastApprovalResolvedAt=Date.now()),this.isWaitingForResponse||(this.isWaitingForResponse=!0,this.responseBuffer=""),this.setStatus("generating","script_detect"),this.idleTimeout&&clearTimeout(this.idleTimeout),this.idleTimeout=setTimeout(()=>{if(this.isWaitingForResponse){if(this.shouldDeferIdleTimeoutFinish())return;this.finishResponse()}},this.timeouts.generatingIdle),(v=this.onStatusChange)==null||v.call(this))}applyIdle(r,n){var g,y;const{modal:a,lastParsedAssistant:i,prevStatus:o}=r;if(o==="waiting_approval"&&(this.approvalExitTimeout&&(clearTimeout(this.approvalExitTimeout),this.approvalExitTimeout=null),this.activeModal=null,this.lastApprovalResolvedAt=Date.now(),this.setStatus("idle","approval_prompt_gone_script_idle")),!this.isWaitingForResponse){o!=="idle"&&(this.clearIdleFinishCandidate("idle_without_response"),this.setStatus("idle","script_detect"),(g=this.onStatusChange)==null||g.call(this));return}const l=this.lastNonEmptyOutputAt?n-this.lastNonEmptyOutputAt:Number.MAX_SAFE_INTEGER,d=this.lastScreenChangeAt?n-this.lastScreenChangeAt:0,u=!!i,h=((y=i==null?void 0:i.content)==null?void 0:y.length)||0,f=this.getIdleFinishConfirmMs(),m=Math.max(f,this.timeouts.outputSettle),v=!a&&u&&l>=m&&d>=f,b=this.idleFinishCandidate,p=!!b&&b.responseEpoch===this.responseEpoch&&b.lastOutputAt===this.lastOutputAt&&b.lastScreenChangeAt===this.lastScreenChangeAt&&h>=b.assistantLength&&n-b.armedAt>=f;if(this.recordTrace("idle_decision",{quietForMs:l,screenStableMs:d,hasAssistantTurn:u,assistantLength:h,hasModal:!!a,idleQuietThresholdMs:m,idleStableThresholdMs:f,idleReady:v,idleFinishConfirmMs:f,idleFinishCandidate:b,candidateQuiet:p,canFinishImmediately:v&&p,submitPendingUntil:this.submitPendingUntil,responseSettleIgnoreUntil:this.responseSettleIgnoreUntil,...fs({accumulatedBuffer:this.accumulatedBuffer,accumulatedRawBuffer:this.accumulatedRawBuffer,responseBuffer:this.responseBuffer,partialResponse:this.responseBuffer,scope:this.currentTurnScope})}),v&&p){this.clearIdleFinishCandidate("finish_response"),this.idleTimeout&&clearTimeout(this.idleTimeout),this.finishResponse();return}if(v){if(!b){this.armIdleFinishCandidate(h);return}}else this.clearIdleFinishCandidate("idle_not_ready");this.idleTimeout&&clearTimeout(this.idleTimeout),this.idleTimeout=setTimeout(()=>{if(this.isWaitingForResponse&&!this.hasActionableApproval()){if(this.shouldDeferIdleTimeoutFinish())return;this.clearIdleFinishCandidate("idle_timeout_finish"),this.finishResponse()}},this.timeouts.idleFinish)}finishResponse(){var n;if(this.submitPendingUntil>Date.now()||this.responseSettleIgnoreUntil>Date.now())return;this.clearIdleFinishCandidate("finish_response_enter"),this.recordTrace("finish_response",{...fs({accumulatedBuffer:this.accumulatedBuffer,accumulatedRawBuffer:this.accumulatedRawBuffer,responseBuffer:this.responseBuffer,partialResponse:this.responseBuffer,scope:this.currentTurnScope})});const r=this.commitCurrentTranscript();if(this.shouldRetryFinishResponse(r)){this.finishRetryCount+=1,this.recordTrace("finish_response_retry",{retryCount:this.finishRetryCount,retryDelayMs:e.FINISH_RETRY_DELAY_MS,assistantContent:Je(r.assistantContent,220),...fs({accumulatedBuffer:this.accumulatedBuffer,accumulatedRawBuffer:this.accumulatedRawBuffer,responseBuffer:this.responseBuffer,partialResponse:this.responseBuffer,scope:this.currentTurnScope})}),this.finishRetryTimer&&clearTimeout(this.finishRetryTimer),this.finishRetryTimer=setTimeout(()=>{this.finishRetryTimer=null,this.isWaitingForResponse&&!this.hasActionableApproval()&&this.finishResponse()},e.FINISH_RETRY_DELAY_MS);return}this.clearAllTimers(),this.responseBuffer="",this.isWaitingForResponse=!1,this.responseSettleIgnoreUntil=0,this.submitRetryUsed=!1,this.submitRetryPromptSnippet="",this.finishRetryCount=0,this.currentTurnScope=null,this.activeModal=null,this.setStatus("idle","response_finished"),(n=this.onStatusChange)==null||n.call(this)}maybeCommitVisibleIdleTranscript(r,n){var o;if(!(this.provider.allowInputDuringGeneration===!0)||!r||r.status!=="idle"||!this.isWaitingForResponse||!this.currentTurnScope||this.activeModal||r.modal)return!1;const i=[...n].reverse().find(l=>l.role==="assistant"&&l.content.trim());return i?(this.clearAllTimers(),this.responseBuffer="",this.isWaitingForResponse=!1,this.responseSettleIgnoreUntil=0,this.submitRetryUsed=!1,this.submitRetryPromptSnippet="",this.finishRetryCount=0,this.currentTurnScope=null,this.activeModal=null,this.setStatus("idle","script_idle_commit"),(o=this.onStatusChange)==null||o.call(this),this.recordTrace("script_idle_commit",{messageCount:n.length,lastAssistant:Je(i.content,320)}),!0):!1}commitCurrentTranscript(){const r=this.parseCurrentTranscript([],this.responseBuffer,this.currentTurnScope);if(r&&Array.isArray(r.messages)){const n=zi(r.messages,{lastOutputAt:this.lastOutputAt}),a=[...n].reverse().find(o=>o.role==="assistant");return this.currentTurnScope&&Fe.info("CLI",`[${this.cliType}] commitCurrentTranscript parserMessages=${n.length} finalLastAssistant=${JSON.stringify(Je((a==null?void 0:a.content)||"",220)).slice(0,260)}`),this.recordTrace("commit_transcript",{parsedStatus:r.status||null,messageCount:n.length,lastAssistant:a?Je(a.content,320):"",messages:Xj(n),...fs({accumulatedBuffer:this.accumulatedBuffer,accumulatedRawBuffer:this.accumulatedRawBuffer,responseBuffer:this.responseBuffer,partialResponse:this.responseBuffer,scope:this.currentTurnScope})}),!a&&this.currentTurnScope&&Fe.warn("CLI",`[${this.cliType}] Commit without assistant turn: prompt=${JSON.stringify(this.currentTurnScope.prompt).slice(0,140)} responseBuffer=${JSON.stringify(Je(this.responseBuffer,220)).slice(0,260)} providerDir=${this.providerResolutionMeta.providerDir||"-"} scriptDir=${this.providerResolutionMeta.scriptDir||"-"} scriptsPath=${this.providerResolutionMeta.scriptsPath||"-"}`),{hasAssistant:!!a,assistantContent:(a==null?void 0:a.content)||""}}return this.currentTurnScope&&Fe.info("CLI",`[${this.cliType}] commitCurrentTranscript parsed.messages=none responseBufferLen=${this.responseBuffer.length} accumulatedBufferLen=${this.accumulatedBuffer.length} parsedStatus=${(r==null?void 0:r.status)||"-"} providerDir=${this.providerResolutionMeta.providerDir||"-"} scriptDir=${this.providerResolutionMeta.scriptDir||"-"}`),{hasAssistant:!1,assistantContent:""}}invokeCliScript(r,n){var o;return typeof((o=this.cliScripts)==null?void 0:o.createState)=="function"||this.scriptState!==null||r.length>=2?r(this.scriptState,n):r(n)}runParseSession(){var r;if(typeof((r=this.cliScripts)==null?void 0:r.parseSession)!="function")return this.parseErrorMessage=`${this.cliType} parseSession unavailable`,null;try{const n=this.terminalScreen.getText(),a=this.getParseScreenText(n),i=this.recentOutputBuffer.slice(-500),o=gd({accumulatedBuffer:this.accumulatedBuffer,accumulatedRawBuffer:this.accumulatedRawBuffer,recentOutputBuffer:this.recentOutputBuffer,terminalScreenText:a,baseMessages:[],partialResponse:this.responseBuffer,isWaitingForResponse:this.isWaitingForResponse,scope:this.currentTurnScope,runtimeSettings:this.runtimeSettings}),l=this.invokeCliScript(this.cliScripts.parseSession,{...o,tail:i,tailScreen:ns(i)});return this.parseErrorMessage=null,l&&typeof l=="object"?l:null}catch(n){const a=(n==null?void 0:n.message)||String(n);return this.parseErrorMessage=a,Fe.warn("CLI",`[${this.cliType}] parseSession error: ${a}`),null}}runDetectStatus(r){var n;if(!((n=this.cliScripts)!=null&&n.detectStatus))return null;try{const a=this.terminalScreen.getText();return this.invokeCliScript(this.cliScripts.detectStatus,{tail:r.slice(-500),screenText:a,rawBuffer:this.accumulatedRawBuffer,isWaitingForResponse:this.isWaitingForResponse,screen:ns(a),tailScreen:ns(r.slice(-500))})}catch(a){return Fe.warn("CLI",`[${this.cliType}] detectStatus error: ${a.message}`),null}}runParseApproval(r){var n;if(!((n=this.cliScripts)!=null&&n.parseApproval))return null;try{const a=this.terminalScreen.getText(),i=a||this.accumulatedBuffer;return this.invokeCliScript(this.cliScripts.parseApproval,{buffer:i,screenText:a,rawBuffer:this.accumulatedRawBuffer,tail:r,screen:ns(a),bufferScreen:ns(i),tailScreen:ns(r)})}catch(a){return Fe.warn("CLI",`[${this.cliType}] parseApproval error: ${a.message}`),null}}hasActionableApproval(r=null){return!!(r||this.activeModal)}projectEffectiveStatus(r=null){return this.parseErrorMessage?"error":this.hasActionableApproval(r)?"waiting_approval":this.isWaitingForResponse&&this.currentTurnScope&&this.currentStatus!=="stopped"?"generating":this.currentStatus}getStatus(r={}){const n=r.allowParse!==!1,a=n&&this.startupParseGate?this.runParseApproval(this.recentOutputBuffer):null;let i=this.projectEffectiveStatus(a),o=a||this.activeModal;if(n&&!a&&!o){const d=this.getFreshParsedStatusCache(),u=d!=null&&d.activeModal&&Array.isArray(d.activeModal.buttons)&&d.activeModal.buttons.some(h=>typeof h=="string"&&h.trim())?d.activeModal:null;(d==null?void 0:d.status)==="waiting_approval"&&u&&(i="waiting_approval",o=u)}const l=this.getBufferState();return{status:i,messages:[],workingDir:this.workingDir,activeModal:o,errorMessage:this.parseErrorMessage||void 0,errorReason:this.parseErrorMessage?"parse_error":void 0,...l?{bufferState:l}:{}}}getScriptParsedStatus(){const r=this.readTerminalScreenText(),n=this.getParseScreenText(r),a=this.parsedStatusCache,i=this.getAccumulatedRawBufferCacheKey();if(a&&a.responseBuffer===this.responseBuffer&&a.currentTurnScope===this.currentTurnScope&&a.recentOutputBuffer===this.recentOutputBuffer&&a.accumulatedBuffer===this.accumulatedBuffer&&a.accumulatedRawBufferKey===i&&a.screenText===n&&a.currentStatus===this.currentStatus&&a.activeModal===this.activeModal&&a.cliName===this.cliName)return a.result;const o=this.runParseSession();if(!o||!Array.isArray(o.messages))throw new Error(this.parseErrorMessage||`${this.cliType} parseSession did not return messages`);const l=o.activeModal??o.modal??null,d=this.getBufferState(),u={id:o.id||"cli_session",status:o.status||this.currentStatus,title:o.title||this.cliName,messages:zi(o.messages,{lastOutputAt:this.lastOutputAt}),activeModal:l,providerSessionId:typeof o.providerSessionId=="string"?o.providerSessionId:void 0,...d?{bufferState:d}:{},...o.transcriptAuthority==="provider"||o.transcriptAuthority==="daemon"?{transcriptAuthority:o.transcriptAuthority}:this.providerOwnsTranscript()?{transcriptAuthority:"provider"}:{},...o.coverage==="full"||o.coverage==="tail"||o.coverage==="current-turn"?{coverage:o.coverage}:this.providerOwnsTranscript()?{coverage:this.shouldUseFullProviderTranscriptContext()?"full":"tail"}:{}};return this.parsedStatusCache={responseBuffer:this.responseBuffer,currentTurnScope:this.currentTurnScope,recentOutputBuffer:this.recentOutputBuffer,accumulatedBuffer:this.accumulatedBuffer,accumulatedRawBufferKey:i,screenText:n,currentStatus:this.currentStatus,activeModal:this.activeModal,cliName:this.cliName,result:u},u}async invokeScript(r,n){var o;const a=(o=this.cliScripts)==null?void 0:o[r];if(typeof a!="function")throw new Error(`CLI script '${r}' not available`);const i=gd({accumulatedBuffer:this.accumulatedBuffer,accumulatedRawBuffer:this.accumulatedRawBuffer,recentOutputBuffer:this.recentOutputBuffer,terminalScreenText:this.getParseScreenText(this.terminalScreen.getText()),baseMessages:[],partialResponse:this.responseBuffer,isWaitingForResponse:this.isWaitingForResponse,scope:this.currentTurnScope,runtimeSettings:this.runtimeSettings});return await Promise.resolve(this.invokeCliScript(a,{...i,args:n&&typeof n=="object"?{...n}:{}}))}parseCurrentTranscript(r,n,a,i){return this.runParseSession()}hasCliScripts(){var r;return typeof((r=this.cliScripts)==null?void 0:r.detectStatus)=="function"}async resolveAction(r){let n="";if(this.cliScripts&&typeof this.cliScripts.resolveAction=="function")try{n=this.cliScripts.resolveAction(r)}catch(a){Fe.warn("CLI",`[${this.cliType}] resolveAction error: ${a.message}`)}if(!n){Fe.warn("CLI",`[${this.cliType}] resolveAction skipped: provider script did not supply a prompt`);return}await this.sendMessage(n)}isSubmitStuck(r){if(!this.ptyProcess||!this.isWaitingForResponse||this.submitRetryUsed||this.hasActionableApproval()||this.hasMeaningfulResponseBuffer(r))return!1;const n=this.terminalScreen.getText();if(!Ki(n,r)||this.runParseApproval(n)||this.runParseApproval(this.recentOutputBuffer))return!1;const i=this.runDetectStatus(n)||this.runDetectStatus(this.recentOutputBuffer);return i!=="generating"&&i!=="waiting_approval"}async writeToPty(r){if(!this.ptyProcess)throw new Error(`${this.cliName} is not running`);await this.ptyProcess.write(r)}resetPendingSendState(r){this.isWaitingForResponse=!1,this.responseBuffer="",this.currentTurnScope=null,this.submitPendingUntil=0,this.clearIdleFinishCandidate(r),this.responseTimeout&&(clearTimeout(this.responseTimeout),this.responseTimeout=null),this.submitRetryTimer&&(clearTimeout(this.submitRetryTimer),this.submitRetryTimer=null),this.finishRetryTimer&&(clearTimeout(this.finishRetryTimer),this.finishRetryTimer=null)}commitSendUserTurn(r){r.didCommitUserTurn||(r.didCommitUserTurn=!0)}armResponseTimeout(){this.responseTimeout&&clearTimeout(this.responseTimeout);const r=this.timeouts.maxResponse;if(!Number.isFinite(r)||r<=0){this.responseTimeout=null;return}this.responseTimeout=setTimeout(()=>{if(this.responseTimeout=null,!this.isWaitingForResponse)return;const n=this.runDetectStatus(this.recentOutputBuffer);if(this.recordTrace("response_timeout_check",{timeoutMs:r,detectedStatus:n,currentStatus:this.currentStatus,isWaitingForResponse:this.isWaitingForResponse,hasActionableApproval:this.hasActionableApproval(),...fs({accumulatedBuffer:this.accumulatedBuffer,accumulatedRawBuffer:this.accumulatedRawBuffer,responseBuffer:this.responseBuffer,partialResponse:this.responseBuffer,scope:this.currentTurnScope})}),this.settledBuffer=this.recentOutputBuffer,this.evaluateSettled(),this.isWaitingForResponse&&!this.hasActionableApproval()){const a=this.runDetectStatus(this.recentOutputBuffer);this.recordTrace("response_timeout_kept_open",{timeoutMs:r,detectedStatusBeforeEval:n,detectedStatusAfterEval:a,currentStatus:this.currentStatus,isWaitingForResponse:this.isWaitingForResponse}),this.armResponseTimeout()}},r)}writeSubmitKeyForRetry(r){this.writeToPty(this.sendKey).catch(n=>{Fe.warn("CLI",`[${this.cliType}] ${r} write failed: ${(n==null?void 0:n.message)||n}`)})}retrySubmitIfStuck(r,n){if(this.submitRetryTimer=null,!this.isSubmitStuck(r.normalizedPromptSnippet))return;const a=this.terminalScreen.getText();if(this.responseSettleIgnoreUntil=Date.now()+this.timeouts.outputSettle+400,Fe.info("CLI",`[${this.cliType}] Retrying submit key for stuck prompt (attempt ${n})`),this.recordTrace("submit_write",{mode:"submit_retry",attempt:n,sendKey:this.sendKey,screenText:Je(a,500)}),this.writeSubmitKeyForRetry("submit_retry"),n>=3){this.submitRetryUsed=!0;return}this.submitRetryTimer=setTimeout(()=>this.retrySubmitIfStuck(r,n+1),r.retryDelayMs)}retryImmediateSubmitIfStuck(r){if(this.submitRetryTimer=null,!this.isSubmitStuck(r.normalizedPromptSnippet))return;const n=this.terminalScreen.getText();this.responseSettleIgnoreUntil=Date.now()+this.timeouts.outputSettle+400,Fe.info("CLI",`[${this.cliType}] Retrying submit key for stuck prompt (attempt 1)`),this.recordTrace("submit_write",{mode:"immediate_retry",attempt:1,sendKey:this.sendKey,screenText:Je(n,500)}),this.writeSubmitKeyForRetry("immediate_retry"),this.submitRetryUsed=!0}submitSendKey(r,n){if(!this.ptyProcess){n.resolveOnce();return}this.submitPendingUntil=0;const a=this.terminalScreen.getText();this.recordTrace("submit_write",{mode:"submit_key",sendKey:this.sendKey,screenText:Je(a,500)}),this.writeToPty(this.sendKey).then(()=>{this.commitSendUserTurn(r),this.submitRetryTimer=setTimeout(()=>this.retrySubmitIfStuck(r,1),r.retryDelayMs),this.armResponseTimeout(),n.resolveOnce()},n.rejectOnce)}submitImmediatePrompt(r,n){this.submitPendingUntil=0,this.recordTrace("submit_write",{mode:"immediate",text:Je(r.text,500),sendKey:this.sendKey,screenText:Je(this.terminalScreen.getText(),500)}),this.writeToPty(r.text+this.sendKey).then(()=>{this.commitSendUserTurn(r),this.submitRetryTimer=setTimeout(()=>this.retryImmediateSubmitIfStuck(r),r.retryDelayMs),this.armResponseTimeout(),n.resolveOnce()},n.rejectOnce)}waitForEchoAndSubmit(r,n,a,i="",o=a){if(!this.ptyProcess){n.resolveOnce();return}const l=Date.now(),d=l-a,u=this.terminalScreen.getText(),h=ln(u),f=h!==i?l:o;if(!r.normalizedPromptSnippet||Ki(u,r.normalizedPromptSnippet)){const v=l-f>=500;if(d>=r.submitDelayMs&&v){this.submitSendKey(r,n);return}}if(d>=r.maxEchoWaitMs){const v={elapsed:d,maxEchoWaitMs:r.maxEchoWaitMs,submitDelayMs:r.submitDelayMs,promptSnippet:r.normalizedPromptSnippet,requirePromptEchoBeforeSubmit:this.requirePromptEchoBeforeSubmit,screenText:Je(u,1e3)};if(this.recordTrace("submit_echo_missing",v),this.requirePromptEchoBeforeSubmit){Fe.warn("CLI",`[${this.cliType}] prompt echo was not observed before submit; sending guarded submit key anyway elapsed=${d}ms maxEchoWaitMs=${r.maxEchoWaitMs} screen=${JSON.stringify(v.screenText).slice(0,240)}`),this.submitSendKey(r,n);return}Fe.warn("CLI",`[${this.cliType}] prompt echo was not observed before submit; sending submit key anyway elapsed=${d}ms maxEchoWaitMs=${r.maxEchoWaitMs}`),this.submitSendKey(r,n);return}setTimeout(()=>this.waitForEchoAndSubmit(r,n,a,h,f),50)}async sendMessage(r){if(!this.ptyProcess)throw new Error(`${this.cliName} is not running`);const n=this.provider.allowInputDuringGeneration===!0,a=n&&this.isWaitingForResponse&&!this.hasActionableApproval();if(this.startupParseGate){const v=Date.now()+1e4;for(;this.startupParseGate&&Date.now()<v;)this.resolveStartupState("send_wait"),await new Promise(b=>setTimeout(b,50))}if(a||await this.waitForInteractivePrompt(),this.ready||(this.resolveStartupState("send_precheck"),this.runDetectStatus(this.recentOutputBuffer)==="idle"&&this.currentStatus==="idle"&&(this.ready=!0,this.startupParseGate=!1,Fe.info("CLI",`[${this.cliType}] sendMessage recovered idle prompt readiness`))),!this.ready)throw new Error(`${this.cliName} not ready (status: ${this.currentStatus})`);const i=n?null:(()=>{var v;try{return((v=this.getScriptParsedStatus)==null?void 0:v.call(this))||null}catch{return null}})(),o=typeof(i==null?void 0:i.status)=="string"?String(i.status):"";if(!n&&(o==="generating"||o==="long_generating")){const v=(i==null?void 0:i.activeModal)??(i==null?void 0:i.modal)??null,b=!!(v&&Array.isArray(v.buttons)&&v.buttons.some(g=>typeof g=="string"&&g.trim()));if(!(this.currentStatus==="idle"&&this.runDetectStatus(this.recentOutputBuffer)==="idle"&&!this.isWaitingForResponse&&!this.currentTurnScope&&!this.hasActionableApproval()&&!b))throw new Error(`${this.cliName} is still processing the previous prompt`)}if(this.isWaitingForResponse&&!n&&!this.clearStaleIdleResponseGuard("send_message_guard"))throw new Error(`${this.cliName} is still processing the previous prompt`);this.isWaitingForResponse=!0,this.responseBuffer="",this.finishRetryCount=0,this.finishRetryTimer&&(clearTimeout(this.finishRetryTimer),this.finishRetryTimer=null),this.clearIdleFinishCandidate("send_message"),this.currentTurnScope={prompt:r,startedAt:Date.now(),bufferStart:this.accumulatedBuffer.length,rawBufferStart:this.accumulatedRawBuffer.length},this.recordTrace("send_message",{text:Je(r,500),estimatedLines:xd(r),turnScope:this.currentTurnScope}),Fe.info("CLI",`[${this.cliType}] sendMessage turn scope buffer=${this.currentTurnScope.bufferStart} raw=${this.currentTurnScope.rawBufferStart} prompt=${JSON.stringify(r).slice(0,120)}`),this.submitRetryUsed=!1,this.submitRetryPromptSnippet=zj(r);const l=ln(this.submitRetryPromptSnippet);this.submitRetryTimer&&(clearTimeout(this.submitRetryTimer),this.submitRetryTimer=null);const d=xd(r),u=this.sendDelayMs+Math.min(2e3,Math.max(0,d-1)*350),h=u+Math.max(1500,Math.min(5e3,d*500)),f=Math.max(350,Math.min(1500,Math.max(this.sendDelayMs,u))),m={text:r,normalizedPromptSnippet:l,submitDelayMs:u,maxEchoWaitMs:h,retryDelayMs:f,didCommitUserTurn:!1};this.settleTimer&&(clearTimeout(this.settleTimer),this.settleTimer=null),this.responseEpoch+=1,this.responseSettleIgnoreUntil=Date.now()+u+this.timeouts.outputSettle+250,await new Promise((v,b)=>{let p=!1;const g={resolveOnce:()=>{p||(p=!0,v())},rejectOnce:x=>{p||(this.resetPendingSendState("send_write_failed"),p=!0,b(x))}};if(this.submitStrategy==="immediate"){this.submitImmediatePrompt(m,g);return}u>0&&(this.submitPendingUntil=Date.now()+u),this.recordTrace("submit_write",{mode:"type_then_submit",text:Je(r,500),sendKey:this.sendKey,screenText:Je(this.terminalScreen.getText(),500)});const y=Date.now();this.writeToPty(r).then(()=>this.waitForEchoAndSubmit(m,g,y),g.rejectOnce)})}getPartialResponse(){return this.isWaitingForResponse?this.responseBuffer:""}getDebugSnapshot(){var a;const r=this.readTerminalScreenText(),n=(a=this.parsedStatusCache)!=null&&a.result&&typeof this.parsedStatusCache.result=="object"?this.parsedStatusCache.result:null;return{cliType:this.cliType,cliName:this.cliName,workingDir:this.workingDir,currentStatus:this.currentStatus,ready:this.ready,isWaitingForResponse:this.isWaitingForResponse,activeModal:this.activeModal,parseErrorMessage:this.parseErrorMessage,messageCounts:{parsedCache:Array.isArray(n==null?void 0:n.messages)?n.messages.length:void 0},buffers:{accumulatedLength:this.accumulatedBuffer.length,accumulatedRawLength:this.accumulatedRawBuffer.length,recentOutputLength:this.recentOutputBuffer.length,responseLength:this.responseBuffer.length,startupLength:this.startupBuffer.length,accumulatedTail:this.accumulatedBuffer.slice(-24e3),accumulatedRawTail:this.accumulatedRawBuffer.slice(-24e3),recentOutputTail:this.recentOutputBuffer.slice(-12e3),responseTail:this.responseBuffer.slice(-12e3)},terminal:{screenText:r,lastScreenSnapshot:this.lastScreenSnapshot,lastScreenText:this.lastScreenText,lastOutputAt:this.lastOutputAt,lastNonEmptyOutputAt:this.lastNonEmptyOutputAt,lastScreenChangeAt:this.lastScreenChangeAt,lastScreenSnapshotReadAt:this.lastScreenSnapshotReadAt},parser:{scriptNames:qn(this.cliScripts),traceSessionId:this.traceSessionId,traceSeq:this.traceSeq,currentTurnScope:this.currentTurnScope,parsedStatusCache:n?{id:n.id,status:n.status,title:n.title,providerSessionId:n.providerSessionId,transcriptAuthority:n.transcriptAuthority,coverage:n.coverage,messageCount:Array.isArray(n.messages)?n.messages.length:void 0,activeModal:n.activeModal}:null,pendingScriptStatus:this.pendingScriptStatus,pendingScriptStatusSince:this.pendingScriptStatusSince},runtimeMetadata:this.getRuntimeMetadata(),statusHistory:this.statusHistory.slice(-80),traceEntries:this.traceEntries.slice(-120),timing:{spawnAt:this.spawnAt,startupFirstOutputAt:this.startupFirstOutputAt,submitPendingUntil:this.submitPendingUntil,responseSettleIgnoreUntil:this.responseSettleIgnoreUntil,responseEpoch:this.responseEpoch,resizeSuppressUntil:this.resizeSuppressUntil,lastApprovalResolvedAt:this.lastApprovalResolvedAt},finish:{idleFinishCandidate:this.idleFinishCandidate,finishRetryCount:this.finishRetryCount,submitRetryUsed:this.submitRetryUsed,submitRetryPromptSnippet:this.submitRetryPromptSnippet}}}getRuntimeMetadata(){return!this.ptyProcess||typeof this.ptyProcess.getMetadata!="function"?null:this.ptyProcess.getMetadata()}updateRuntimeMeta(r,n=!1){!this.ptyProcess||typeof this.ptyProcess.updateMeta!="function"||this.ptyProcess.updateMeta(r,n)}cancel(){this.shutdown()}async saveAndStop(){if(!this.ptyProcess)return;const r=this.provider.resume;if(!(r!=null&&r.supported)){this.shutdown();return}const n=r.stopStrategy||"command",a=typeof r.stopCommand=="string"?r.stopCommand.trim():"",i=Math.max(this.timeouts.shutdownGrace,typeof r.shutdownGraceMs=="number"?r.shutdownGraceMs:3e3),o=this.currentStatus==="generating"||this.currentStatus==="waiting_approval";try{if(o&&this.ptyProcess.write(""),n==="command"&&a){const d=()=>{if(!this.ptyProcess)return;const h=a.endsWith("\r")||a.endsWith(`
158
+ `)?a:`${a}${this.sendKey}`;this.ptyProcess.write(h)},u=typeof r.interruptGraceMs=="number"?Math.max(100,r.interruptGraceMs):500;o?setTimeout(d,u):d()}else this.ptyProcess.write("")}catch(d){Fe.warn("CLI",`[${this.cliType}] saveAndStop signal failed: ${(d==null?void 0:d.message)||d}`)}await this.waitForStopped(i)||(Fe.warn("CLI",`[${this.cliType}] graceful stop timed out, forcing shutdown`),this.shutdown(),await this.waitForStopped(this.timeouts.shutdownGrace+500))}waitForStopped(r){return new Promise(n=>{const a=Date.now(),i=setInterval(()=>{if(!this.ptyProcess||this.currentStatus==="stopped"){clearInterval(i),n(!0);return}Date.now()-a>=r&&(clearInterval(i),n(!1))},100)})}shutdown(){this.clearIdleFinishCandidate("shutdown"),this.clearAllTimers(),this.pendingOutputParseChunks=[],this.pendingTerminalQueryTail="",this.ptyOutputChunks=[],this.finishRetryCount=0,this.ptyProcess&&(this.ptyProcess.write(""),setTimeout(()=>{var r,n;try{(r=this.ptyProcess)==null||r.kill()}catch{}this.ptyProcess=null,this.setStatus("stopped","stop_cmd"),this.ready=!1,this.startupParseGate=!1,this.spawnAt=0,(n=this.onStatusChange)==null||n.call(this)},this.timeouts.shutdownGrace))}detach(){var r;if(this.clearIdleFinishCandidate("detach"),this.clearAllTimers(),this.pendingOutputParseChunks=[],this.pendingTerminalQueryTail="",this.ptyOutputChunks=[],this.finishRetryCount=0,this.ptyProcess){try{typeof this.ptyProcess.detach=="function"?this.ptyProcess.detach():this.ptyProcess.kill()}catch{}this.ptyProcess=null}this.ready=!1,this.startupParseGate=!1,this.spawnAt=0,(r=this.onStatusChange)==null||r.call(this)}clearHistory(){var r,n,a;this.clearIdleFinishCandidate("clear_history"),this.accumulatedBuffer="",this.accumulatedRawBuffer="",this.currentTurnScope=null,this.submitRetryUsed=!1,this.submitRetryPromptSnippet="",this.pendingOutputParseTimer&&(clearTimeout(this.pendingOutputParseTimer),this.pendingOutputParseTimer=null),this.pendingOutputParseChunks=[],this.pendingTerminalQueryTail="",this.ptyOutputFlushTimer&&(clearTimeout(this.ptyOutputFlushTimer),this.ptyOutputFlushTimer=null),this.ptyOutputChunks=[],this.finishRetryTimer&&(clearTimeout(this.finishRetryTimer),this.finishRetryTimer=null),this.finishRetryCount=0,this.resetTerminalScreen(),(n=(r=this.ptyProcess)==null?void 0:r.clearBuffer)==null||n.call(r),(a=this.onStatusChange)==null||a.call(this)}isProcessing(){return this.isWaitingForResponse}isReady(){return this.ready}async writeRaw(r){this.recordTrace("write_raw",{keys:JSON.stringify(r),length:r.length}),await this.writeToPty(r)}resolveModal(r){var a,i,o;let n=this.activeModal||this.runParseApproval(this.recentOutputBuffer);if(!n&&typeof((a=this.cliScripts)==null?void 0:a.parseSession)=="function")try{const l=this.getScriptParsedStatus(),d=l!=null&&l.activeModal&&Array.isArray(l.activeModal.buttons)&&l.activeModal.buttons.some(u=>typeof u=="string"&&u.trim())?l.activeModal:null;(l==null?void 0:l.status)==="waiting_approval"&&d&&(n=d,this.activeModal=d,this.currentStatus!=="waiting_approval"&&(this.setStatus("waiting_approval","resolve_modal_parse"),(i=this.onStatusChange)==null||i.call(this)))}catch{}if(!(!this.ptyProcess||this.currentStatus!=="waiting_approval"&&!n))if(this.clearIdleFinishCandidate("resolve_modal"),this.recordTrace("resolve_modal",{buttonIndex:r,activeModal:n}),this.activeModal=null,this.lastApprovalResolvedAt=Date.now(),this.responseSettleIgnoreUntil=Date.now()+this.timeouts.outputSettle+400,this.approvalExitTimeout&&(clearTimeout(this.approvalExitTimeout),this.approvalExitTimeout=null),this.setStatus("generating","approval_resolved"),(o=this.onStatusChange)==null||o.call(this),r in this.approvalKeys)this.ptyProcess.write(this.approvalKeys[r]);else{const l=Array.isArray(n==null?void 0:n.buttons)?n.buttons.length:0,d=l>0?Math.min(Math.max(0,r),l-1):Math.max(0,r),h="\x1B[B".repeat(d)+"\r";this.ptyProcess.write(h)}}resize(r,n){if(this.ptyProcess)try{this.ptyProcess.resize(r,n),this.terminalScreen.resize(n,r),this.resizeSuppressUntil=Date.now()+300}catch{}}getParsedDebugState(){var r;if(this.startupParseGate||typeof((r=this.cliScripts)==null?void 0:r.parseSession)!="function")return null;try{const n=this.getScriptParsedStatus();return n&&typeof n=="object"?n:null}catch{return null}}getDebugState(){const r=hr(this.terminalScreen.getText()),n=this.startupParseGate?this.runParseApproval(this.recentOutputBuffer):null,a=this.projectEffectiveStatus(n),i=this.ready||!!n,o=this.getParsedDebugState(),l=Array.isArray(o==null?void 0:o.messages)?o.messages:[];return{type:this.cliType,name:this.cliName,providerResolution:this.providerResolutionMeta,status:a,projectedStatus:a,rawStatus:this.currentStatus,lifecycleStatus:this.isWaitingForResponse?"awaiting_response":"idle",ready:i,startupParseGate:this.startupParseGate,spawnAt:this.spawnAt,workingDir:this.workingDir,messages:l,messageCount:l.length,parsedStatus:o?{id:o.id,status:o.status,title:o.title,providerSessionId:o.providerSessionId,transcriptAuthority:o.transcriptAuthority,coverage:o.coverage,activeModal:o.activeModal,messageCount:l.length}:null,screenText:r.slice(-4e3),currentTurnScope:this.currentTurnScope,startupBuffer:this.startupBuffer.slice(-4e3),recentOutputBuffer:this.recentOutputBuffer.slice(-500),settledBuffer:this.settledBuffer.slice(-500),accumulatedBufferLength:this.accumulatedBuffer.length,accumulatedRawBufferLength:this.accumulatedRawBuffer.length,rawBufferPreview:this.accumulatedRawBuffer.slice(-1e3),sanitizedRawPreview:hr(this.accumulatedRawBuffer).slice(-1e3),responseBuffer:this.responseBuffer.slice(-1e3),lastOutputAt:this.lastOutputAt,lastNonEmptyOutputAt:this.lastNonEmptyOutputAt,lastScreenChangeAt:this.lastScreenChangeAt,lastScreenSnapshot:this.lastScreenSnapshot.slice(-500),isWaitingForResponse:this.isWaitingForResponse,activeModal:n||this.activeModal,lastApprovalResolvedAt:this.lastApprovalResolvedAt,sendDelayMs:this.sendDelayMs,sendKey:this.sendKey,submitStrategy:this.submitStrategy,requirePromptEchoBeforeSubmit:this.requirePromptEchoBeforeSubmit,submitPendingUntil:this.submitPendingUntil,responseSettleIgnoreUntil:this.responseSettleIgnoreUntil,resizeSuppressUntil:this.resizeSuppressUntil,hasCliScripts:this.hasCliScripts(),scriptNames:qn(this.cliScripts),traceSessionId:this.traceSessionId,traceEntryCount:this.traceEntries.length,statusHistory:this.statusHistory.slice(-30),timeouts:this.timeouts,pendingOutputParseBufferLength:this.pendingOutputParseChunks.reduce((d,u)=>d+u.length,0),pendingOutputParseScheduled:!!this.pendingOutputParseTimer,ptyAlive:!!this.ptyProcess}}getTraceState(r=120){const n=Math.max(1,Math.min(500,Number.isFinite(r)?Math.floor(r):120));return{sessionId:this.traceSessionId,providerResolution:this.providerResolutionMeta,entryCount:this.traceEntries.length,entries:this.traceEntries.slice(-n),screenText:Je(this.terminalScreen.getText(),4e3),recentOutputBuffer:Je(this.recentOutputBuffer,1e3),responseBuffer:Je(this.responseBuffer,1200),status:this.projectEffectiveStatus(),projectedStatus:this.projectEffectiveStatus(),rawStatus:this.currentStatus,lifecycleStatus:this.isWaitingForResponse?"awaiting_response":"idle",activeModal:this.activeModal,currentTurnScope:this.currentTurnScope,messages:[]}}getProviderResolutionMeta(){return{...this.providerResolutionMeta}}},ee(e,"MAX_RESPONSE_BUFFER",8e3),ee(e,"MAX_RECENT_OUTPUT_BUFFER",1e3),ee(e,"MAX_ACCUMULATED_BUFFER",262144),ee(e,"SCREEN_SNAPSHOT_MIN_INTERVAL_MS",250),ee(e,"MAX_TRACE_ENTRIES",250),ee(e,"FINISH_RETRY_DELAY_MS",300),ee(e,"MAX_FINISH_RETRIES",2),ee(e,"SCRIPT_STATUS_DEBOUNCE_MS",3e3),e)}});kc();var a1=Ad(Id),i1=5e3,o1=1024*1024,Nt=class extends Error{constructor(t,r,n={}){super(r);ee(this,"reason");ee(this,"stdout");ee(this,"stderr");ee(this,"exitCode");ee(this,"signal");ee(this,"argv");ee(this,"cwd");n.cause!==void 0&&(this.cause=n.cause),this.name="GitCommandError",this.reason=t,this.stdout=jr(n.stdout),this.stderr=jr(n.stderr),this.exitCode=n.exitCode,this.signal=n.signal,this.argv=n.argv?[...n.argv]:void 0,this.cwd=n.cwd}};async function Ec(e,t={}){const r=await Ao(e),n=await Yp(r,["rev-parse","--show-toplevel"],t,{mapNotGitRepo:!0}),a=ze.resolve(n.stdout.trim());if(!a)throw new Nt("not_git_repo","Git did not return a repository root",{stdout:n.stdout,stderr:n.stderr,argv:["rev-parse","--show-toplevel"],cwd:r});return{workspace:r,repoRoot:a,isGitRepo:!0}}async function gs(e,t,r={}){Xp(t);const n=typeof e=="string"?await Ec(e,r):e;if(!n.repoRoot||!n.isGitRepo)throw new Nt("not_git_repo","Workspace is not a Git repository",{argv:t,cwd:n.workspace});const a=r.cwd?await Ao(r.cwd):await Ao(n.workspace),i=await Hc(n.repoRoot),o=await Hc(a);if(!c1(i,o))throw new Nt("path_outside_repo","Git cwd is outside the repository root",{argv:t,cwd:a});return Yp(a,t,r)}function jr(e){return typeof e=="string"?e.replace(/\r\n/g,`
159
+ `):Buffer.isBuffer(e)?e.toString("utf8").replace(/\r\n/g,`
160
+ `):e==null?"":String(e).replace(/\r\n/g,`
161
+ `)}function c1(e,t){const r=ze.relative(ze.resolve(e),ze.resolve(t));return r===""||!r.startsWith("..")&&!ze.isAbsolute(r)}async function Ao(e){if(typeof e!="string"||e.length===0||e.includes("\0"))throw new Nt("invalid_args","Workspace must be a non-empty path");if(!ze.isAbsolute(e))throw new Nt("invalid_args","Workspace must be an absolute path",{cwd:e});const t=ze.resolve(e);try{if(!(await Of(t)).isDirectory())throw new Nt("invalid_args","Workspace must be an existing directory",{cwd:t});await Ff(t,Hf.R_OK)}catch(r){throw r instanceof Nt?r:new Nt("invalid_args","Workspace must be an existing directory",{cwd:t,cause:r})}return t}function Xp(e){if(!Array.isArray(e)||e.length===0)throw new Nt("invalid_args","Git argv must be a non-empty string array",{argv:e});for(const t of e)if(typeof t!="string"||t.length===0||t.includes("\0"))throw new Nt("invalid_args","Git argv contains an invalid argument",{argv:e});if(e.includes("-C")||e.some(t=>t.startsWith("--git-dir")||t.startsWith("--work-tree")))throw new Nt("invalid_args","Git argv contains unsafe repository override arguments",{argv:e})}async function Yp(e,t,r,n={}){Xp(t);try{const a=await a1("git",[...t],{cwd:e,encoding:"utf8",timeout:r.timeoutMs??i1,maxBuffer:r.maxBuffer??o1,windowsHide:!0});return{stdout:jr(a.stdout),stderr:jr(a.stderr)}}catch(a){throw l1(a,e,t,n)}}function l1(e,t,r,n){const a=e,i=jr(a.stdout),o=jr(a.stderr),l=a.code,d=a.signal,u=[o.trim(),a.message].filter(Boolean).join(`
162
+ `);return l==="ENOENT"?new Nt("git_not_installed","Git executable was not found",{stdout:i,stderr:o,exitCode:l,signal:d,argv:r,cwd:t,cause:e}):a.killed||/timed out/i.test(a.message)?new Nt("timeout","Git command timed out",{stdout:i,stderr:o,exitCode:l,signal:d,argv:r,cwd:t,cause:e}):n.mapNotGitRepo&&/not a git repository/i.test(o+`
163
+ `+a.message)?new Nt("not_git_repo","Workspace is not a Git repository",{stdout:i,stderr:o,exitCode:l,signal:d,argv:r,cwd:t,cause:e}):new Nt("git_command_failed",u||"Git command failed",{stdout:i,stderr:o,exitCode:l,signal:d,argv:r,cwd:t,cause:e})}async function d1(e,t={}){const r=Date.now();try{const n=await Ec(e,t),a=await gs(n,["status","--porcelain=v2","--branch"],t),i=u1(a.stdout),o=await h1(n,t),l=await p1(n,t);return{workspace:n.workspace,repoRoot:n.repoRoot,isGitRepo:!0,branch:i.branch,headCommit:o.commit,headMessage:o.message,upstream:i.upstream,ahead:i.ahead,behind:i.behind,staged:i.staged,modified:i.modified,untracked:i.untracked,deleted:i.deleted,renamed:i.renamed,hasConflicts:i.conflictFiles.length>0,conflictFiles:i.conflictFiles,stashCount:l,lastCheckedAt:r}}catch(n){return n instanceof Nt?bd(e,r,n):bd(e,r,new Nt("git_command_failed","Failed to read Git status",{cause:n}))}}function u1(e){const t={branch:null,upstream:null,ahead:0,behind:0,staged:0,modified:0,untracked:0,deleted:0,renamed:0,conflictFiles:[]};for(const r of e.split(`
164
+ `))if(r){if(r.startsWith("# branch.head ")){const n=r.slice(14).trim();t.branch=n&&n!=="(detached)"?n:null;continue}if(r.startsWith("# branch.upstream ")){t.upstream=r.slice(18).trim()||null;continue}if(r.startsWith("# branch.ab ")){const n=r.match(/\+(-?\d+)\s+-(-?\d+)/);n&&(t.ahead=Number.parseInt(n[1]??"0",10)||0,t.behind=Number.parseInt(n[2]??"0",10)||0);continue}if(r.startsWith("? ")){t.untracked+=1;continue}if(r.startsWith("u ")){const a=r.split(" ").slice(10).join(" ");a&&t.conflictFiles.push(a);continue}if(r.startsWith("1 ")||r.startsWith("2 ")){const n=r.split(" "),a=n[1]??"..",i=a[0]??".",o=a[1]??".";if(f1(i)&&(t.staged+=1),(o==="M"||o==="T")&&(t.modified+=1),(i==="D"||o==="D")&&(t.deleted+=1),(i==="R"||o==="R")&&(t.renamed+=1),a.includes("U")){const l=n.slice(r.startsWith("2 ")?9:8).join(" ").split(" ")[0]??"";l&&t.conflictFiles.push(l)}}}return t.conflictFiles=Array.from(new Set(t.conflictFiles)),t}async function h1(e,t){try{const n=(await gs(e,["log","-1","--pretty=%h%x00%s"],t)).stdout.trimEnd();if(!n)return{commit:null,message:null};const[a,...i]=n.split("\0");return{commit:a||null,message:i.join("\0")||null}}catch{return{commit:null,message:null}}}async function p1(e,t){try{return(await gs(e,["stash","list","--format=%gd"],t)).stdout.split(`
165
+ `).filter(n=>n.trim().length>0).length}catch{return 0}}function f1(e){return e!=="."&&e!=="?"&&e!=="U"}function bd(e,t,r){return{workspace:e,repoRoot:null,isGitRepo:!1,branch:null,headCommit:null,headMessage:null,upstream:null,ahead:0,behind:0,staged:0,modified:0,untracked:0,deleted:0,renamed:0,hasConflicts:!1,conflictFiles:[],stashCount:0,lastCheckedAt:t,error:r.stderr||r.message,reason:r.reason}}var m1=200,x1=2e5;async function g1(e,t={}){const r=Date.now();try{const n=await Ec(e,t),a=n.repoRoot,[i,o,l,d,u]=await Promise.all([gs(n,["diff","--no-ext-diff","--name-status"],{...t,cwd:a}),gs(n,["diff","--no-ext-diff","--numstat"],{...t,cwd:a}),gs(n,["diff","--cached","--no-ext-diff","--name-status"],{...t,cwd:a}),gs(n,["diff","--cached","--no-ext-diff","--numstat"],{...t,cwd:a}),gs(n,["ls-files","--others","--exclude-standard"],{...t,cwd:a})]),h=S1(i.stdout+o.stdout+l.stdout+d.stdout+u.stdout),f=[...yd(i.stdout,o.stdout,!1),...yd(l.stdout,d.stdout,!0),...v1(u.stdout)],m=vd(t.maxFiles,m1),v=vd(t.maxBytes,x1),b=f.slice(0,m),p=f.length>b.length||h>v;return{workspace:n.workspace,repoRoot:a,isGitRepo:!0,files:b,totalInsertions:b.reduce((g,y)=>g+y.insertions,0),totalDeletions:b.reduce((g,y)=>g+y.deletions,0),truncated:p,lastCheckedAt:r}}catch(n){const a=n instanceof Nt?n:new Nt("git_command_failed","Failed to read Git diff summary",{cause:n});return{workspace:e,repoRoot:null,isGitRepo:!1,files:[],totalInsertions:0,totalDeletions:0,truncated:!1,lastCheckedAt:r,error:a.stderr||a.message,reason:a.reason}}}function yd(e,t,r){const n=b1(e),a=y1(t);return n.map((i,o)=>{const l=a[o];return{path:i.path,oldPath:i.oldPath,status:i.status,staged:r,insertions:(l==null?void 0:l.insertions)??0,deletions:(l==null?void 0:l.deletions)??0,binary:(l==null?void 0:l.binary)||void 0}})}function b1(e){return e.split(`
166
+ `).filter(Boolean).map(t=>{const r=t.split(" "),a=(r[0]??"")[0]??"M";return a==="R"?{oldPath:r[1]??"",path:r[2]??r[1]??"",status:"renamed"}:a==="C"?{oldPath:r[1]??"",path:r[2]??r[1]??"",status:"copied"}:{path:r[1]??"",status:w1(a)}}).filter(t=>t.path.length>0)}function y1(e){return e.split(`
167
+ `).filter(Boolean).map(t=>{const r=t.split(" "),n=r[0]??"0",a=r[1]??"0",i=n==="-"||a==="-";return{path:r.slice(2).join(" "),insertions:i?0:Number.parseInt(n,10)||0,deletions:i?0:Number.parseInt(a,10)||0,binary:i}})}function v1(e){return e.split(`
168
+ `).filter(Boolean).map(t=>({path:t,status:"untracked",staged:!1,insertions:0,deletions:0}))}function w1(e){switch(e){case"A":return"added";case"D":return"deleted";case"R":return"renamed";case"C":return"copied";case"U":return"conflict";case"M":case"T":default:return"modified"}}function S1(e){return Buffer.byteLength(e,"utf8")}function vd(e,t){return!Number.isFinite(e)||e==null||e<=0?t:Math.floor(e)}function k1(e){return Math.max(1,Math.floor(e??100))}function j1(e){return{workspace:e.workspace,repoRoot:e.repoRoot,isGitRepo:e.isGitRepo,files:[],totalInsertions:0,totalDeletions:0,truncated:!1,lastCheckedAt:e.lastCheckedAt,error:e.error,reason:e.reason}}function wd(e){return`${e.oldPath??""}\0${e.path}`}function zr(e){return Array.from(new Set(Array.from(e).filter(Boolean))).sort((t,r)=>t.localeCompare(r))}function Sd(e,t,r=`${t}s`){return e===1?t:r}function N1(e,t){const r=new Set(e.diffSummary.files.map(wd)),n=t.diffSummary.files.filter(g=>!r.has(wd(g))),a=[],i=[],o=[],l=[],d=[],u=[];let h=0,f=0;for(const g of n)switch(h+=g.insertions,f+=g.deletions,g.status){case"added":case"copied":a.push(g.path);break;case"modified":i.push(g.path);break;case"deleted":o.push(g.path);break;case"renamed":l.push({oldPath:g.oldPath??g.path,path:g.path});break;case"untracked":d.push(g.path);break;case"conflict":u.push(g.path);break}l.sort((g,y)=>`${g.oldPath}\0${g.path}`.localeCompare(`${y.oldPath}\0${y.path}`));const m=zr([...t.status.conflictFiles,...u]),v=n.length,b=t.status.hasConflicts||m.length>0,p=[];return v>0&&p.push(`${v} ${Sd(v,"file")} changed`),a.length>0&&p.push(`${a.length} added`),i.length>0&&p.push(`${i.length} modified`),o.length>0&&p.push(`${o.length} deleted`),l.length>0&&p.push(`${l.length} renamed`),d.length>0&&p.push(`${d.length} untracked`),b&&p.push(`${m.length||1} ${Sd(m.length||1,"conflict")}`),{beforeSnapshotId:e.id,afterSnapshotId:t.id,workspace:t.workspace,repoRoot:t.repoRoot,changedFiles:v,addedFiles:zr(a),modifiedFiles:zr(i),deletedFiles:zr(o),renamedFiles:l,untrackedFiles:zr(d),conflictFiles:m,totalInsertions:h,totalDeletions:f,hasConflicts:b,currentStatus:t.status,summaryText:p.length>0?p.join(", "):"No file-set changes between snapshots."}}var C1=class{constructor(e={}){ee(this,"snapshots",new Map);ee(this,"order",[]);ee(this,"capacity");ee(this,"now");ee(this,"idPrefix");ee(this,"getStatusProvider");ee(this,"getDiffSummaryProvider");ee(this,"counter",0);this.capacity=k1(e.capacity),this.now=e.now??Date.now,this.idPrefix=e.idPrefix??"git-snapshot",this.getStatusProvider=e.getStatus,this.getDiffSummaryProvider=e.getDiffSummary}async create(e){const t=e.getStatus??this.getStatusProvider;if(!t)throw new Error("GitSnapshotStore requires an injected getStatus provider");const r=await t(e.workspace),n=e.getDiffSummary??this.getDiffSummaryProvider,a=n?await n(e.workspace,r):j1(r),i=this.now(),o=`${this.idPrefix}-${i}-${++this.counter}`,l={id:o,workspace:e.workspace,repoRoot:r.repoRoot??e.workspace,sessionId:e.sessionId,turnId:e.turnId,reason:e.reason,status:r,diffSummary:a,createdAt:i};return this.snapshots.set(o,l),this.order.push(o),this.enforceCapacity(),l}get(e){return this.snapshots.get(e)}compare(e,t){const r=this.snapshots.get(e);if(!r)throw new Error(`Unknown before snapshot: ${e}`);const n=this.snapshots.get(t);if(!n)throw new Error(`Unknown after snapshot: ${t}`);return N1(r,n)}list(e={}){const t=Math.max(1,Math.floor(e.limit??this.capacity));return this.order.map(r=>this.snapshots.get(r)).filter(r=>!!r).filter(r=>!e.workspace||r.workspace===e.workspace).filter(r=>!e.sessionId||r.sessionId===e.sessionId).slice(-t)}clear(){this.snapshots.clear(),this.order.splice(0,this.order.length)}enforceCapacity(){for(;this.order.length>this.capacity;){const e=this.order.shift();e&&this.snapshots.delete(e)}}};function T1(e={}){return new C1(e)}T1({getStatus:e=>d1(e),getDiffSummary:e=>g1(e)});gk();Ht();Cc();Bk();Cc();Ic();Ac();function I1(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function A1(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function M1(e,t){const r=[],n=e.git;return n?n.isGitRepo?(n.branch===null&&n.headCommit&&r.push("Detached HEAD"),n.branch&&n.upstream,n.branch&&n.upstream,e.error&&r.push(`Error: ${e.error}`),r):(r.push("Not a git repository"),r):(r.push("No git status available"),r)}function kd(e){switch(e){case"online":return 0;case"dirty":return 1;case"degraded":return 2;case"wrong_branch":return 3;case"offline":return 4;case"unknown":return 5;default:return 5}}function _1(e){return e.length===0?"unknown":e.reduce((t,r)=>kd(r)>kd(t)?r:t)}function R1(e){var v,b,p;const t=[],r=[],n=[],a=new Map;for(const g of e.nodes){const y=g.git,x=(y==null?void 0:y.branch)||null,N=M1(g,null),j=I1(y),w=A1(y);let A="worktreeNode";N.length>0&&(A="orphanNode");const M={id:g.nodeId,type:A,label:g.machineLabel||g.nodeId.slice(0,8),workspace:g.workspace,branch:x,health:g.health,ahead:(y==null?void 0:y.ahead)??0,behind:(y==null?void 0:y.behind)??0,dirty:j,dirtyFiles:w,hasConflicts:(y==null?void 0:y.hasConflicts)??!1,activeSessionCount:((v=g.activeSessions)==null?void 0:v.length)??0,activeSessions:g.activeSessions??[],providers:g.providers??[],isOrphan:N.length>0,orphanReasons:N,source:g};if(t.push(M),x){const S=a.get(x)??[];S.push(M.id),a.set(x,S)}}const i=new Map;for(const g of e.nodes){const y=(b=g.git)==null?void 0:b.branch,x=(p=g.git)==null?void 0:p.upstream;y&&x&&i.set(y,(i.get(y)??0)+1)}let o=null,l=0;for(const[g,y]of i)y>l&&(l=y,o=g);const d=o?`__branch_${o}`:null;if(d&&o){const g=a.get(o)??[],y=g.map(j=>t.find(w=>w.id===j).health),x={id:d,type:"defaultBranchNode",label:o,workspace:"",branch:o,health:_1(y),ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],nextStepHint:g.length>0?`${g.length} node(s) on default branch`:void 0,source:{nodeId:d,machineLabel:o,workspace:"",health:"online",providers:[],activeSessions:[]}};t.push(x);const N=new Set;for(const j of t)if(j.type!=="defaultBranchNode"&&j.branch){if(j.branch===o){r.push({id:`${d}--${j.id}`,source:d,target:j.id,type:"parentBranch",label:"default"});continue}N.has(j.branch)||(N.add(j.branch),r.push({id:`${d}--branch_${j.branch}`,source:d,target:j.branch,type:"parentBranch",label:j.branch}))}}for(const[g,y]of a)if(!(y.length<2))for(let x=1;x<y.length;x++)r.push({id:`wt_${y[0]}--${y[x]}`,source:y[0],target:y[x],type:"worktreeLink",label:g});const u=t.filter(g=>g.isOrphan).length;u>0&&n.push(`${u} orphan node(s) detected`);const h=t.filter(g=>g.hasConflicts).length;h>0&&n.push(`${h} node(s) with merge conflicts`);const f=t.filter(g=>g.health==="offline").length;f>0&&n.push(`${f} node(s) offline`);const m={totalNodes:e.nodes.length,onlineNodes:e.nodes.filter(g=>g.health==="online").length,dirtyNodes:t.filter(g=>g.dirty).length,orphanNodes:u,errorNodes:e.nodes.filter(g=>!!g.error).length,offlineNodes:f,totalActiveSessions:e.nodes.reduce((g,y)=>{var x;return g+(((x=y.activeSessions)==null?void 0:x.length)??0)},0)};return{meshId:e.meshId,meshName:e.meshName,repoIdentity:e.repoIdentity,refreshedAt:e.refreshedAt,nodes:t,edges:r,stats:m,warnings:n}}_c();Ht();Cn();dt();var P1=["standard","thought","tool","terminal","system"],L1=["tool_call","terminal_command","runtime_activity"],E1=["runtime_status","provider_chrome","control"];new Set(P1);new Set(L1);new Set(E1);ze.join(vt.homedir(),".adhdev","history");dt();dt();dt();Ac();dt();dt();Rc();function D1(e){const t=[];return{record(r){return null},list(r={}){const n=Math.max(1,Math.floor(r.limit||100));return t.filter(a=>!r.interactionId||a.interactionId===r.interactionId).filter(a=>!r.category||a.category===r.category).slice(-n).map(a=>({...a,payload:a.payload?{...a.payload}:{}}))},clear(){t.splice(0,t.length)}}}D1({capacity:$p().traceBufferSize});Ht();dt();Ht();Lc();Cn();Ht();Lc();dt();dt();dt();var Vi=Lf;typeof Vi.yellow=="function"||Vi.default;dt();Ht();Cn();dt();var Ia=process.platform==="win32"?ze.join(Kt.LOCALAPPDATA||Kt.APPDATA||ze.join(vt.homedir(),"AppData","Local"),"adhdev","logs"):process.platform==="darwin"?ze.join(vt.homedir(),"Library","Logs","adhdev"):ze.join(vt.homedir(),".local","share","adhdev","logs"),$1=7;try{Dt.mkdirSync(Ia,{recursive:!0})}catch{}function B1(){return new Date().toISOString().slice(0,10)}var O1=B1();ze.join(Ia,`commands-${O1}.jsonl`);function F1(){try{const e=Dt.readdirSync(Ia).filter(n=>n.startsWith("commands-")&&n.endsWith(".jsonl")),t=new Date;t.setDate(t.getDate()-$1);const r=t.toISOString().slice(0,10);for(const n of e){const a=n.match(/commands-(\d{4}-\d{2}-\d{2})/);if(a&&a[1]<r)try{Dt.unlinkSync(ze.join(Ia,n))}catch{}}}catch{}}F1();dt();_c();Ht();Up();dt();process.argv.includes("--dev")||Kt.ADHDEV_READ_DEBUG;process.argv.includes("--dev")||Kt.ADHDEV_READ_DEBUG;dt();dt();Rc();dt();dt();dt();ze.join(vt.homedir(),".adhdev","version-history.json");Ht();dt();dt();Lc();zp();dt();Cn();dt();Ht();_c();const Xn=[{value:"preserve",label:"Preserve history and runtimes",description:"Keep completed chat history and leave live runtimes alone."},{value:"stop",label:"Stop live runtimes only",description:"Release running session processes, but keep chat records/transcripts."},{value:"delete_stopped",label:"Delete stopped sessions only",description:"Clean completed/stopped chat clutter without killing live runtimes."},{value:"stop_and_delete",label:"Stop and delete sessions",description:"Stop matching runtimes, then remove their session records/transcripts."}],W1={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function ca(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function U1(e){const t=ca(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"launch not ready unless an explicit provider is selected"}}function K1(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function H1(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",r=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${r}`}function z1(e,t){return[...Array.isArray(t==null?void 0:t.cliSessions)?t.cliSessions:[],...Array.isArray(t==null?void 0:t.acpSessions)?t.acpSessions:[],...Array.isArray(t==null?void 0:t.sessions)?t.sessions:[]].filter(n=>{var a;return((a=n==null?void 0:n.settings)==null?void 0:a.meshNodeId)===e.id||(n==null?void 0:n.workspace)===e.workspace}).map(n=>{var a;return{id:n.sessionId||n.id||n.instanceId||"unknown",provider:n.providerType||n.cliType||n.acpType||n.type||"unknown",status:n.status||((a=n.activeChat)==null?void 0:a.status)||"unknown"}})}function Gi(e){return{...W1,...(e==null?void 0:e.policy)||{}}}function V1({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const i=a.id.toLowerCase(),o=a.name.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||o.includes("hermes")}),n=fh(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(Tt,{title:"Hermes MCP Config",description:"Hermes does not auto-import repo-local .mcp.json. Add this YAML under mcp_servers in Hermes config, then start a fresh Hermes session.",children:s.jsx(Oh,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function G1(){var ce;const{sendCommand:e}=Ct(),{ides:t}=Ss(),r=t.find(E=>E.daemonMode||E.type==="adhdev-daemon"),n=(r==null?void 0:r.id)||"",a=[];let i=[];if(r){const E=r.availableProviders||[];i=ly(E);for(const z of E)z.category==="cli"&&a.push({id:z.type||z.id,name:z.displayName||z.name||z.type,meshCoordinator:z.meshCoordinator})}const[o,l]=c.useState([]),[d,u]=c.useState(null),[h,f]=c.useState(!0),[m,v]=c.useState(null),[b,p]=c.useState(!1),[g,y]=c.useState(null),[x,N]=c.useState({}),[j,w]=c.useState([]),[A,M]=c.useState(null),[S,k]=c.useState(null),[O,P]=c.useState(!1),[I,W]=c.useState(null),[K,R]=c.useState(null),[T,C]=c.useState(!1),[F,L]=c.useState(""),[D,H]=c.useState(""),[Q,ge]=c.useState(!1),[ue,Z]=c.useState(""),[xe,Se]=c.useState([]),be=o.find(E=>E.id===d)||null;c.useEffect(()=>{N(Object.fromEntries(((be==null?void 0:be.nodes)||[]).map(E=>[E.id,ca(E)])))},[be]),c.useEffect(()=>{const E=dy(i);Q&&xe.length===0&&E.length>0&&Se(E)},[Q,i,xe.length]),c.useEffect(()=>{const E=new Set(((be==null?void 0:be.nodes)||[]).map(z=>z.id));A&&!E.has(A)&&M(null)},[be,A]);const Y=c.useCallback(async()=>{if(n){f(!0);try{const E=await e(n,"list_meshes");E!=null&&E.success?(l(E.meshes||[]),v(null)):v((E==null?void 0:E.error)||"Failed to load meshes")}catch(E){v((E==null?void 0:E.message)||"Failed to load meshes")}finally{f(!1)}}},[n,e]),he=c.useCallback(async E=>{if(!n||!E){w([]);return}try{const z=await e(n,"get_mesh_queue",{meshId:E});z!=null&&z.success?w(Array.isArray(z.queue)?z.queue:[]):w([])}catch{w([])}},[n,e]);c.useEffect(()=>{Y()},[Y]),c.useEffect(()=>{he(d)},[he,d]);async function ye(){if(!(!n||!d))try{P(!0),W(null);const E=await e(n,"mesh_status",{meshId:d});if(E!=null&&E.success){const z=E.status||E.result||E;if(z&&typeof z=="object"){const le=R1(z);k(le)}else W("Invalid mesh_status response format")}else W((E==null?void 0:E.error)||"mesh_status failed")}catch(E){W((E==null?void 0:E.message)||"Failed to load mesh graph")}finally{P(!1)}}c.useEffect(()=>{d&&(k(null),W(null),R(null),ye())},[d]);async function se(){var E;if(!(!n||!F.trim()))try{const z=await e(n,"create_mesh",{name:F.trim(),repoIdentity:D.trim()||void 0});z!=null&&z.success?(C(!1),L(""),H(""),await Y(),u(((E=z.mesh)==null?void 0:E.id)||null)):v((z==null?void 0:z.error)||"Create failed")}catch(z){v((z==null?void 0:z.message)||"Create failed")}}async function de(E){if(!(!n||!confirm("Delete this mesh?")))try{await e(n,"delete_mesh",{meshId:E}),u(null),await Y()}catch(z){v((z==null?void 0:z.message)||"Delete failed")}}async function Ce(){if(!(!n||!d||!ue.trim()))try{const E=await e(n,"add_mesh_node",{meshId:d,workspace:ue.trim(),providerPriority:lo(xe,i)});E!=null&&E.success?(ge(!1),Z(""),Se([]),await Y(),await he(d)):v((E==null?void 0:E.error)||"Add node failed")}catch(E){v((E==null?void 0:E.message)||"Add node failed")}}async function pe(E){var re;if(!n||!d)return;const z=Gi(be),le=((re=Xn.find(q=>q.value===z.sessionCleanupOnNodeRemove))==null?void 0:re.label)||"Preserve history and runtimes";if(confirm(`Remove this node?
169
+
170
+ Node removal cleanup policy: ${le}`))try{await e(n,"remove_mesh_node",{meshId:d,nodeId:E}),A===E&&M(null),await Y(),await he(d)}catch(q){v((q==null?void 0:q.message)||"Remove node failed")}}async function me(E){if(!n||!d)return;const z={...Gi(be),...E};try{p(!0),v(null);const le=await e(n,"update_mesh",{meshId:d,policy:z});if((le==null?void 0:le.success)===!1){v(le.error||"Policy update failed");return}await Y()}catch(le){v((le==null?void 0:le.message)||"Policy update failed")}finally{p(!1)}}async function oe(E){if(!n||!d)return;const z=lo(x[E.id]||ca(E),i),le={...E.policy||{}};delete le.provider_priority,z.length?le.providerPriority=z:delete le.providerPriority;try{y(E.id),v(null);const re=await e(n,"update_mesh_node",{meshId:d,nodeId:E.id,policy:le});if((re==null?void 0:re.success)===!1){v(re.error||"Node policy update failed");return}await Y()}catch(re){v((re==null?void 0:re.message)||"Node policy update failed")}finally{y(null)}}if(!n)return s.jsx(rn,{icon:s.jsx(Rn,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})});if(!be)return s.jsxs(rn,{icon:s.jsx(Rn,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>C(!0),children:"+ Create Mesh"}),children:[m&&s.jsx(ir,{variant:"error",className:"mb-4",children:m}),T&&s.jsx(Tt,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Ft,{label:"Name",children:s.jsx(fi,{value:F,onChange:E=>L(E.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(Ft,{label:"Repo Identity (optional)",children:s.jsx(fi,{value:D,onChange:E=>H(E.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:se,disabled:!F.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>C(!1),children:"Cancel"})]})]})}),h?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):o.length===0?s.jsx(wa,{icon:s.jsx(Rn,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:o.map(E=>s.jsxs("button",{className:"text-left w-full p-4 rounded-xl border border-border-subtle bg-bg-panel hover:border-accent-primary/40 transition-colors",onClick:()=>u(E.id),children:[s.jsx("div",{className:"font-semibold text-sm",children:E.name}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:E.repoIdentity||"No repo identity"}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[E.nodes.length," node(s)"]})]},E.id))})]});const fe=Gi(be);return s.jsxs(rn,{icon:s.jsx(Rn,{}),title:be.name,subtitle:be.repoIdentity||"Repo Mesh",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>u(null),children:"← Back"}),s.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>de(be.id),children:"Delete"})]}),children:[m&&s.jsx(ir,{variant:"error",className:"mb-4",children:m}),s.jsxs(Tt,{title:"Policy",description:"Coordinator safety defaults and node-removal session cleanup behavior for this local mesh.",children:[s.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[s.jsx(Ft,{label:"Checkpoint before task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.requirePreTaskCheckpoint?"yes":"no",onChange:E=>me({requirePreTaskCheckpoint:E.target.value==="yes"}),disabled:b,children:[s.jsx("option",{value:"no",children:"No"}),s.jsx("option",{value:"yes",children:"Yes"})]})}),s.jsx(Ft,{label:"Checkpoint after task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.requirePostTaskCheckpoint?"yes":"no",onChange:E=>me({requirePostTaskCheckpoint:E.target.value==="yes"}),disabled:b,children:[s.jsx("option",{value:"yes",children:"Yes"}),s.jsx("option",{value:"no",children:"No"})]})}),s.jsx(Ft,{label:"Push approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.requireApprovalForPush?"required":"not_required",onChange:E=>me({requireApprovalForPush:E.target.value==="required"}),disabled:b,children:[s.jsx("option",{value:"required",children:"Require approval before push"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(Ft,{label:"Destructive git approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.requireApprovalForDestructiveGit?"required":"not_required",onChange:E=>me({requireApprovalForDestructiveGit:E.target.value==="required"}),disabled:b,children:[s.jsx("option",{value:"required",children:"Require approval"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(Ft,{label:"Dirty workspace behavior",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.dirtyWorkspaceBehavior||"warn",onChange:E=>me({dirtyWorkspaceBehavior:E.target.value}),disabled:b,children:[s.jsx("option",{value:"warn",children:"Warn and continue"}),s.jsx("option",{value:"block",children:"Block task"}),s.jsx("option",{value:"checkpoint_then_continue",children:"Checkpoint then continue"})]})}),s.jsx(Ft,{label:"Max parallel tasks",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:String(fe.maxParallelTasks??2),onChange:E=>me({maxParallelTasks:Number(E.target.value)}),disabled:b,children:[1,2,3,4,5,6,7,8].map(E=>s.jsx("option",{value:E,children:E},E))})})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(Ft,{label:"Node removal session cleanup",hint:"Separate transcript cleanup from runtime/process cleanup. Preserve is safest when completed work may need review.",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.sessionCleanupOnNodeRemove||"preserve",onChange:E=>me({sessionCleanupOnNodeRemove:E.target.value}),disabled:b,children:Xn.map(E=>s.jsx("option",{value:E.value,children:E.label},E.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((ce=Xn.find(E=>E.value===fe.sessionCleanupOnNodeRemove))==null?void 0:ce.description)||Xn[0].description})]}),b&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),s.jsxs(Tt,{title:"Visualization",description:"Live mesh topology: branches, worktrees, sessions, and orphan detection.",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500"}),"healthy"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-amber-500"}),"dirty"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-red-500"}),"error"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-gray-500"}),"offline"]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:ye,disabled:O,children:O?"Loading...":"Refresh Graph"})]}),I&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:I}),S?s.jsxs("div",{className:"flex gap-4",style:{minHeight:420},children:[s.jsx("div",{className:"flex-1 rounded-xl border border-border-subtle bg-bg-secondary overflow-hidden",style:{minHeight:420},children:s.jsx(sk,{data:S,onNodeClick:E=>R(z=>(z==null?void 0:z.id)===E.id?null:E),selectedNodeId:(K==null?void 0:K.id)||null})}),K&&s.jsx("div",{className:"w-80 shrink-0",children:s.jsx(nk,{node:K,onClose:()=>R(null)})})]}):s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:O?"Loading graph...":"Refresh the graph to view mesh topology."})]}),s.jsxs(Tt,{title:"Nodes",description:"Workspaces participating in this mesh.",children:[s.jsx("div",{className:"flex justify-end mb-3",children:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>ge(!0),children:"+ Add Node"})}),Q&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:"Add Node"}),s.jsx("button",{onClick:()=>ge(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(It,{size:16})})]}),s.jsx(Ft,{label:"Workspace Path",children:s.jsx(fi,{value:ue,onChange:E=>Z(E.target.value),placeholder:"/Users/dev/projects/myapp",autoFocus:!0})}),s.jsx(Ft,{label:"Provider Priority",hint:"Order used when launching without an explicit provider. Empty means fail closed unless a provider is selected explicitly.",children:s.jsx(jl,{value:xe,availableProviders:i,onChange:Se})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:Ce,disabled:!ue.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>ge(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),be.nodes.length===0?s.jsx(wa,{icon:s.jsx(zs,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:be.nodes.map(E=>{const z=ca(E),le=U1(E),re=K1(E,j),q=z1(E,r),je=A===E.id;return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary cursor-pointer transition-colors ${je?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`,role:"button",tabIndex:0,onClick:()=>M(je?null:E.id),onKeyDown:we=>{(we.key==="Enter"||we.key===" ")&&(we.preventDefault(),M(je?null:E.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"text-sm font-medium",children:E.workspace.split("/").pop()}),re.length>0&&s.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-orange-500/15 text-orange-300 border border-orange-500/25",children:[re.length," active task",re.length===1?"":"s"]})]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:E.workspace}),s.jsx("div",{className:"mt-3 max-w-2xl",onClick:we=>we.stopPropagation(),children:s.jsxs(Ft,{label:"Provider priority",hint:"Used when launches omit an explicit provider. Empty keeps fail-closed behavior until a provider is selected manually.",children:[s.jsx(jl,{value:x[E.id]??z,availableProviders:i,onChange:we=>N(Pe=>({...Pe,[E.id]:we})),disabled:g===E.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:we=>{we.stopPropagation(),oe(E)},disabled:g===E.id,children:g===E.id?"Saving...":"Save policy"})}),s.jsxs("div",{className:"mt-2 text-[12px]",children:[s.jsx("span",{className:"text-text-muted",children:"Effective provider priority: "}),s.jsx("span",{className:le.configured?"text-text-primary font-mono":"text-amber-400",children:le.label}),le.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",le.launchBlockedMessage,")"]})]})]})})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:we=>{we.stopPropagation(),pe(E.id)},children:s.jsx(It,{size:14})})]}),je&&s.jsxs("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Node ID:"})," ",s.jsx("span",{className:"font-mono",children:E.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:le.configured?"text-green-400":"text-amber-400",children:le.configured?"yes":"provider priority not configured"})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Repo root:"})," ",s.jsx("span",{className:"font-mono",children:E.repoRoot||E.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",q.length]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Branch / git:"})," not loaded in standalone list view"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Health:"})," ",re.length>0||q.length>0?"active":"idle/unknown"]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),re.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:re.map(we=>s.jsx("li",{className:"font-mono",children:H1(we)},we.id))})]}),q.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active sessions"}),s.jsx("ul",{className:"m-0 pl-4",children:q.map(we=>s.jsxs("li",{className:"font-mono",children:[we.provider," / ",we.status," / ",we.id]},we.id))})]})]})]},E.id)})})]}),s.jsx(V1,{meshId:be.id,availableCliAgents:a})]})}function Dc(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function q1(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=Dc();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Jt(e,t){return await fetch(q1(e),{credentials:"same-origin",...t})}function Jp(){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 X1{constructor(){ee(this,"adapters",new Map);ee(this,"states",new Map);ee(this,"runtimeListeners",new Map);ee(this,"screenshotCallbacks",new Map);ee(this,"statusCallbacks",new Set)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r)}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}sendData(t,r){return!1}sendPtyInput(t,r,n){return!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,i,o){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:i,rows:o})}emitSessionOutput(t,r,n){!t||typeof r!="string"||!r||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(t,r){const n=this.runtimeListeners.get(t)||new Set;return n.add(r),this.runtimeListeners.set(t,n),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,r,n){if(!r)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`,window.location.origin);typeof(n==null?void 0:n.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(n.sinceSeq));const i=await Jt(`${a.pathname}${a.search}`);if(!i.ok){let l=`Runtime snapshot unavailable (${i.status})`;try{const d=await i.json();d!=null&&d.error&&(l=d.error)}catch{}return{success:!1,error:l}}const o=await i.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof o.seq=="number"?o.seq:0,text:typeof o.text=="string"?o.text:"",truncated:!!o.truncated,cols:typeof o.cols=="number"?o.cols:void 0,rows:typeof o.rows=="number"?o.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const rs=new X1;function Y1(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Dc();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Yn=Y1(),jd=3e3,J1=3e4;let Gt=null,Q1=0;const Aa=new Map;let Ms=null,un=null;function Nd(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Vr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function Z1(e){return e==="connected"?"connected":e}async function la(e,t,r){const n=Wu(e,r||{}),a=Gt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++Q1}_${Date.now()}`;return new Promise((o,l)=>{const d=setTimeout(()=>{Aa.delete(i),l(new Error(`WS command timeout: ${t}`))},3e4);Aa.set(i,{resolve:u=>{clearTimeout(d),o(u)},reject:u=>{clearTimeout(d),l(u)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Mo(e,t){const r=Gt;if(!r||r.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(t)),!0}catch{return!1}}function eN(e,t,r){const n=Gt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Wu(e,{sessionId:t,targetSessionId:t,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}class tN{constructor(t){ee(this,"daemonId");ee(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Gt==null?void 0:Gt.readyState)===WebSocket.OPEN}get connectionState(){return(Gt==null?void 0:Gt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return la(this.daemonId,t,r)}async sendInput(t,r){return la(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Ms&&(clearInterval(Ms),Ms=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await la(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());rs.emitScreenshot(this.daemonId,a)}}catch{}};r(),Ms=setInterval(r,2e3)}stopScreenshots(t){Ms&&(clearInterval(Ms),Ms=null)}}let Ut=null;function sN(e){return(!Ut||Ut.daemonId!==e)&&(Ut=new tN(e)),Ut}function rN({children:e}){const t=c.useRef(pn()),r=pn();t.current=r;const{setUserName:n}=Ss(),a=c.useRef(n);a.current=n;const i=c.useRef(null),o=c.useRef(null),[,l]=c.useState("disconnected"),d=c.useCallback((p,g)=>{l(p),un==null||un(p,g)},[]),u=c.useRef(null),h=c.useRef(),f=c.useRef(jd),m=c.useRef(!0),v=c.useRef(!1),b=c.useRef("initial_connect");return c.useEffect(()=>{m.current=!0,v.current=!1;function p(){var x,N;if(!m.current||((x=u.current)==null?void 0:x.readyState)===WebSocket.OPEN||((N=u.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Yn}...`),Vr("connect_attempt",{url:Yn,reason:b.current,delayMs:f.current});let y;try{y=new WebSocket(Yn)}catch(j){console.error("[Standalone WS] Failed to create WebSocket:",j),g();return}u.current=y,y.onopen=()=>{if(!m.current){y.close();return}d("connected"),f.current=jd,Vr("open",{url:Yn,reason:b.current}),os.resubscribeAll({sendData:Mo}),console.log("[Standalone WS] Connected")},Gt=y,y.onmessage=j=>{var w,A;try{const M=JSON.parse(j.data);if((M.type==="command_result"||M.type==="error")&&M.requestId){const S=Aa.get(M.requestId);S&&(Aa.delete(M.requestId),M.type==="error"?S.reject(new Error(((w=M.data)==null?void 0:w.message)||"Command failed")):S.resolve(M.data));return}if(M.type==="session_output"){const S=M.sessionId||M.cliId||M.cliType;S&&rs.emitSessionOutput(S,typeof M.data=="string"?M.data:"",typeof M.seq=="number"?M.seq:void 0);return}if(M.type==="runtime_snapshot"){rs.emitRuntimeSnapshot(M.sessionId,typeof M.text=="string"?M.text:"",typeof M.seq=="number"?M.seq:0,!!M.truncated,typeof M.cols=="number"?M.cols:void 0,typeof M.rows=="number"?M.rows:void 0);return}if(M.type==="topic_update"){const S=M.update;S&&os.publish(S);return}if(M.type==="status"||M.type==="initial_state"){const S=M.data;if(!S)return;const{injectEntries:k,markLoaded:O,getIdes:P}=t.current,I=S.instanceId||"standalone",W=P().find(T=>T.id===I),K=sN(I);rs.register(I,K),rs.setState(I,"connected"),d("connected",I),rs.emitStatus(I,S);const R=ya(S,{daemonId:I,existingDaemon:W,existingEntries:P()});Nd("ws_status",{type:M.type,daemonId:I,sessions:(S.sessions||[]).map(T=>({id:T.id,parentId:T.parentId,providerType:T.providerType,kind:T.kind,transport:T.transport,unread:T.unread,inboxBucket:T.inboxBucket,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,title:T.title})),recentLaunches:(S.recentLaunches||[]).map(T=>({id:T.id,providerType:T.providerType,kind:T.kind,workspace:T.workspace,lastLaunchedAt:T.lastLaunchedAt}))}),Nd("entries",{daemonId:I,entries:R.filter(T=>T.type!=="adhdev-daemon").map(T=>({id:T.id,type:T.type,unread:T.unread,inboxBucket:T.inboxBucket,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,sessionId:T.sessionId}))}),R.length>0&&k(R,{authoritativeDaemonIds:[I]}),O(),o.current!==I&&((A=i.current)==null||A.call(i),o.current=I,i.current=os.subscribe({sendData:Mo},I,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${I}`,params:{includeSessions:!0}},T=>{if(T.topic!=="daemon.metadata")return;const C=t.current.getIdes(),F=C.find(D=>D.id===I),L=ya(T.status,{daemonId:I,existingDaemon:F,existingEntries:C,timestamp:T.timestamp});L.length>0&&t.current.injectEntries(L,{authoritativeDaemonIds:[I]}),T.userName&&a.current&&a.current(T.userName)}))}}catch(M){console.error("[Standalone WS] Parse error:",M)}},y.onclose=j=>{m.current&&(Ut==null||Ut.stopScreenshots(),Ut&&rs.setState(Ut.daemonId,"disconnected"),d("disconnected"),u.current=null,b.current=`close:${j.code}${j.wasClean?":clean":":unclean"}`,Vr("close",{code:j.code,reason:j.reason||"",wasClean:j.wasClean}),g())},y.onerror=j=>{v.current||!m.current||(b.current="error",Vr("error",{message:j instanceof Event?"event":String(j),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",j))}}function g(){if(!m.current)return;clearTimeout(h.current);const y=f.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),Vr("schedule_reconnect",{reason:b.current,delayMs:y}),h.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,J1),p()},y)}return p(),()=>{var y;m.current=!1,v.current=!0,(y=i.current)==null||y.call(i),i.current=null,o.current=null,clearTimeout(h.current),u.current&&(u.current.onerror=null,u.current.onclose=null,u.current.close(),u.current=null,Gt=null),Ut&&(Ut.stopScreenshots(),rs.unregister(Ut.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function nN({children:e}){const[t,r]=c.useState("disconnected"),[n,a]=c.useState(null);c.useEffect(()=>(un=(o,l)=>{r(o),l&&a(l)},()=>{un=null}),[]);const i=c.useMemo(()=>{const o=t==="connected",l=Z1(t),d={};return n&&(d[n]=l),d.standalone=l,{wsStatus:t,isConnected:o,connectionStates:d}},[t,n]);return s.jsx(cm,{connectionOverrides:i,children:s.jsx(rN,{children:e})})}const Qp="adhdev_standalone_font_preferences",Hs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Za=[{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"}],bn=[{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"}],aN=new Set(Za.map(e=>e.id)),iN=new Set(bn.map(e=>e.id));function Zt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:da("chat",t.chat),code:da("code",t.code),terminal:da("terminal",t.terminal)}}function da(e,t){const r=Hs[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?aN:iN).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function ua(e,t){var a;const r=da(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?Za:bn;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function oN(e){const t=Zt(e),r=ua("chat",t.chat),n=ua("code",t.code),a=ua("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Rs(e,t=document.documentElement){const r=Zt(e),n=oN(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))t.style.setProperty(a,i);return r}function _o(e){const t=Zt(e);try{localStorage.setItem(Qp,JSON.stringify(t))}catch{}return t}function cN(){try{const e=localStorage.getItem(Qp);if(e)return Zt(JSON.parse(e))}catch{}return Hs}function lN(){return Rs(cN())}function Gr(e,t){var n;const r=e==="chat"?Za:bn;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const dN=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Bd,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(ys,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(mr,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(Ra,{}),label:"Settings"}];function uN({children:e}){const t=Nr(),r=Po(),n=c.useMemo(()=>dN.map(i=>({...i,active:r.pathname.startsWith(i.path),onSelect:()=>t(i.path)})),[r.pathname,t]),a=c.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Docs"}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(Fd,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Wd,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(wy,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.76"]}),footerActions:({collapsed:i,toggleCollapsed:o})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:o,title:i?"Expand sidebar":"Collapse sidebar",children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const hN=[{icon:s.jsx(ys,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(cs,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Ud,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Bt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(mr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Fd,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],pN=[{icon:s.jsx(Nm,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Bd,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Pa,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(bm,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Od,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(vm,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],fN=[{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 mN(){return s.jsxs(rn,{icon:s.jsx(Wd,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:s.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.76"]}),children:[s.jsx(Tt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),s.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."}),s.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."})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.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 ↗"}),s.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 ↗"}),s.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 ↗"})]})]})}),s.jsx(Tt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:hN.map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.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]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(Tt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Uu.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Hu.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Ku.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(Tt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:pN.map(e=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.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]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(Tt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),s.jsx("tbody",{children:fN.map((e,t)=>s.jsxs("tr",{className:t%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),s.jsx(wa,{icon:s.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:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(Em,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function qi(e,t,r){return{...e,[t]:r}}function Xi({surface:e,title:t,description:r,value:n,options:a,onChange:i}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.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:o=>{const l=o.target.value;i(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(o=>s.jsx("option",{value:o.id,children:o.label},o.id))}),n.preset==="custom"&&s.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:o=>i({preset:"custom",customFamily:o.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:ua(e,n)})]})]})]})}function xN({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:i,onSave:o,onResetToSaved:l,onResetToDefaults:d}){const u=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.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&&s.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&&s.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}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Xi,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Za,onChange:h=>i(qi(e,"chat",h))}),s.jsx(Xi,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:bn,onChange:h=>i(qi(e,"code",h))}),s.jsx(Xi,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:bn,onChange:h=>i(qi(e,"terminal",h))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",Gr("chat",e.chat.preset)," · Code: ",Gr("code",e.code.preset)," · Terminal: ",Gr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Gr("chat",Hs.chat.preset)," / ",Gr("code",Hs.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:o,disabled:r||!u,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"}),s.jsx("button",{type:"button",onClick:l,disabled:r||!u,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"}),s.jsx("button",{type:"button",onClick:d,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 gN(){const{ides:e}=Ss(),t=e.find(Y=>Y.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=Ct(),{userName:a}=Ss(),[i,o]=c.useState(a||""),[l,d]=c.useState(null),[u,h]=c.useState(null),[f,m]=c.useState(Hs),[v,b]=c.useState(!1),[p,g]=c.useState(""),[y,x]=c.useState(""),[N,j]=c.useState("127.0.0.1"),[w,A]=c.useState(""),[M,S]=c.useState(""),[k,O]=c.useState(""),[P,I]=c.useState(""),[W,K]=c.useState(""),[R,T]=c.useState(!1),C=async()=>{const he=await(await Jt("/auth/session")).json();d(he)},F=async()=>{const he=await(await Jt("/api/v1/standalone/preferences")).json();h(he),j(he.standaloneBindHost);const ye=Zt(he.standaloneFontPreferences);m(ye),Rs(ye),_o(ye)};c.useEffect(()=>{a!==void 0&&o(a)},[a]),c.useEffect(()=>{Promise.all([C(),F()]).catch(Y=>{I(Y instanceof Error?Y.message:String(Y))})},[]),c.useEffect(()=>{Rs(f)},[f]);const L=Y=>{const he=Y.target.value.trim();t!=null&&t.id&&he!==a&&n(t.id,"set_user_name",{userName:he}).catch(console.error)},[D,H]=c.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),Q=Y=>{H(Y);try{localStorage.setItem("adhdev_sound",Y?"1":"0")}catch{}},ge=async()=>{g(""),x(""),b(!0);try{const Y=Zt(f),he=await Jt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:Y})}),ye=await he.json();if(!he.ok)throw new Error((ye==null?void 0:ye.error)||"Failed to save standalone font preferences");const se=Zt(ye.standaloneFontPreferences);h(ye),m(se),Rs(se),_o(se),x("Standalone chat fonts saved for this self-hosted dashboard.")}catch(Y){g(Y instanceof Error?Y.message:String(Y))}finally{b(!1)}},ue=()=>{const Y=Zt(u==null?void 0:u.standaloneFontPreferences);g(""),x(""),m(Y),Rs(Y)},Z=()=>{g(""),x(""),m(Hs),Rs(Hs)},xe=async()=>{I(""),K(""),T(!0);try{const Y=await Jt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:N})}),he=await Y.json();if(!Y.ok)throw new Error((he==null?void 0:he.error)||"Failed to save standalone network preference");h(he),j(he.standaloneBindHost),K(he.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(Y){I(Y instanceof Error?Y.message:String(Y))}finally{T(!1)}},Se=async()=>{if(I(""),K(""),M.trim().length<4){I("Password must be at least 4 characters.");return}if(M!==k){I("New password and confirmation do not match.");return}T(!0);try{const Y=await Jt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,newPassword:M})}),he=await Y.json();if(!Y.ok)throw new Error((he==null?void 0:he.error)||"Failed to save password");d(he),await F(),A(""),S(""),O(""),K(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Jp()}catch(Y){I(Y instanceof Error?Y.message:String(Y))}finally{T(!1)}},be=async()=>{I(""),K(""),T(!0);try{const Y=await Jt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,clear:!0})}),he=await Y.json();if(!Y.ok)throw new Error((he==null?void 0:he.error)||"Failed to clear password");d(he),await F(),A(""),S(""),O(""),K("Standalone password disabled.")}catch(Y){I(Y instanceof Error?Y.message:String(Y))}finally{T(!1)}};return s.jsxs(rn,{icon:s.jsx(Ra,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(ir,{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)&&s.jsx(ir,{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."}),s.jsx(Tt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:"Version"}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.76"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(u==null?void 0:u.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(u==null?void 0:u.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(Tt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.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."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.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:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:N==="127.0.0.1",onChange:()=>j("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.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."})]})]}),s.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:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:N==="0.0.0.0",onChange:()=>j("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),s.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."})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:()=>{xe()},disabled:R,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 default network mode"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(u==null?void 0:u.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(Tt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.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."}),P&&s.jsx(ir,{variant:"error",children:P}),W&&s.jsx(ir,{variant:"success",children:W}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.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:Y=>A(Y.target.value)}),s.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:M,onChange:Y=>S(Y.target.value)}),s.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:k,onChange:Y=>O(Y.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{Se()},disabled:R,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…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{be()},disabled:R,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"})]})]})}),s.jsx(Tt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(Y=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${Y.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:Y.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:Y.type})]},Y.type))})}),s.jsx(Tt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(My,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(Tt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(Ly,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),s.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."}),s.jsx(Uy,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),s.jsx(xN,{value:f,savedValue:Zt(u==null?void 0:u.standaloneFontPreferences),saving:v,error:p,notice:y,onChange:m,onSave:()=>{ge()},onResetToSaved:ue,onResetToDefaults:Z})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),s.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."}),s.jsx(zy,{})]})]})}),s.jsx(Tt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Ty,{}),s.jsx(_s,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Lm,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:D,onChange:Q})]})}),s.jsx(Tt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:s.jsx("div",{className:"flex flex-col gap-3",children:s.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:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(gm,{size:16,className:"text-text-secondary"})," Display Name"]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),s.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:Y=>o(Y.target.value),onBlur:L,onKeyDown:Y=>{Y.key==="Enter"&&Y.currentTarget.blur()}})]})})})]})}yy();Fy();lN();const bN=Dd({baseUrl:"",getToken:Dc});function yN({children:e}){const[t,r]=c.useState(null),[n,a]=c.useState(!0),[i,o]=c.useState(""),[l,d]=c.useState(""),[u,h]=c.useState(!1),f=async()=>{a(!0),d("");try{const b=await(await Jt("/auth/session")).json();r(b)}catch(v){d(v instanceof Error?v.message:String(v))}finally{a(!1)}};c.useEffect(()=>{f()},[]),c.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let v=!1;return(async()=>{try{const b=await Jt("/api/v1/standalone/preferences");if(!b.ok)return;const p=await b.json();if(v)return;const g=Zt(p.standaloneFontPreferences);Rs(g),_o(g)}catch{}})(),()=>{v=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const m=async v=>{v.preventDefault(),h(!0),d("");try{const b=await Jt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),p=await b.json();if(!b.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),o(""),Jp()}catch(b){d(b instanceof Error?b.message:String(b))}finally{h(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.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:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.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."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:m,children:[s.jsx("input",{type:"password",value:i,onChange:v=>o(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}),s.jsx("button",{type:"submit",disabled:u||!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:u?"Signing in…":"Unlock dashboard"})]}):s.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&&s.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})]})}):s.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 Cd(){const{ides:e,initialLoaded:t}=Ss();if(!t)return s.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?s.jsx(Qi,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Qi,{to:"/dashboard",replace:!0})}function vN(){const e=c.useMemo(()=>({sendCommand:la,sendData:Mo,sendPtyInput:eN}),[]);return s.jsx(Ef,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(um,{client:bN,children:s.jsx(yN,{children:s.jsx(nN,{children:s.jsx(pm,{value:e,children:s.jsx(uN,{children:s.jsxs(Df,{children:[s.jsx(ps,{path:"/dashboard",element:s.jsx(Vw,{})}),s.jsx(ps,{path:"/machine",element:s.jsx(Cd,{})}),s.jsx(ps,{path:"/machines/:id",element:s.jsx(QS,{})}),s.jsx(ps,{path:"/machines",element:s.jsx(Cd,{})}),s.jsx(ps,{path:"/about",element:s.jsx(mN,{})}),s.jsx(ps,{path:"/settings",element:s.jsx(gN,{})}),s.jsx(ps,{path:"/mesh",element:s.jsx(G1,{})}),s.jsx(ps,{path:"*",element:s.jsx(Qi,{to:"/dashboard",replace:!0})})]})})})})})})})}Ab({connectionManager:rs});$f(document.getElementById("root")).render(s.jsx(vN,{}));