@adhdev/daemon-standalone 0.9.82-rc.314 → 0.9.82-rc.316
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.
- package/dist/index.js +289 -25
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/index-BgoSEH_z.js +613 -0
- package/public/assets/index-C6hDLm-5.js +613 -0
- package/public/assets/terminal-BU39etVi.js +143 -0
- package/public/assets/vendor-CETaSQ-b.js +2821 -0
- package/public/index.html +2 -2
|
@@ -0,0 +1,613 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-BU39etVi.js","assets/vendor-CETaSQ-b.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
var pw=Object.defineProperty;var hw=(e,t,s)=>t in e?pw(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var re=(e,t,s)=>hw(e,typeof t!="symbol"?t+"":t,s);import{r as u,j as r,M as Wd,a as mw,b as fw,c as gw,R as Kt,d as Si,t as xw,e as bw,u as zi,D as yw,f as Hc,g as zc,E as vw,i as ww,C as Sw,h as kw,B as jw,k as Nw,l as _w,m as Cw,H as Sa,P as Zs,n as Iw,o as Aw,p as Tw,q as Mw,s as Ew,v as Rw,w as Ud,x as Pw,y as Dw,z as Lw,A as $w,F as Ow,G as Fw,I as Bw,J as er,N as Kc,K as Ww}from"./vendor-CETaSQ-b.js";import*as Uw from"child_process";import{exec as el,execFile as Hd,execFileSync as Hw}from"child_process";import*as Qe from"fs";import{constants as zw,existsSync as st,mkdirSync as Ki,readFileSync as As,writeFileSync as Ss,chmodSync as Kw,statSync as tl,appendFileSync as sl,renameSync as Lr,unlinkSync as ki}from"fs";import{realpath as go,stat as Gw,access as qw,readFile as Vw,mkdir as Xw}from"fs/promises";import*as Ee from"path";import{join as Dt,dirname as Yw,isAbsolute as Mf,basename as Ef,resolve as Qw}from"path";import{promisify as In}from"util";import*as ot from"os";import{homedir as Jw}from"os";import*as Zw from"crypto";import{randomUUID as Ts,createHash as Rf,randomBytes as eS}from"crypto";import{EventEmitter as tS}from"events";import{createRequire as Gc}from"module";import"net";import"http";import"stream";import"chokidar";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const o of a.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function s(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function n(i){if(i.ep)return;i.ep=!0;const a=s(i);fetch(i.href,a)}})();function sS(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),s=[];return{record(n){const i={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...n,payload:n.payload?{...n.payload}:{}};return s.push(i),s.length>t&&s.splice(0,s.length-t),i},list(n={}){const i=Math.max(1,Math.floor(n.limit||100));return s.filter(a=>!n.interactionId||a.interactionId===n.interactionId).filter(a=>!n.topic||a.topic===n.topic).filter(a=>!n.kind||a.kind===n.kind).slice(-i).map(a=>({...a,payload:a.payload?{...a.payload}:{}}))},clear(){s.splice(0,s.length)}}}const gn=sS();function Up(e){const t={};for(const s of e)s.transport&&(t[s.transport]=(t[s.transport]||0)+1);return{count:e.length,ids:e.map(s=>s.id),statuses:e.map(s=>String(s.status||"unknown")),transports:t}}function rS(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Hp(e){return Array.isArray(e)?[...e]:[]}function Pf(e,t){if(!e)return t??null;const s=Object.prototype.hasOwnProperty.call(e,"messages"),n=Object.prototype.hasOwnProperty.call(e,"activeModal"),i=typeof e.id=="string"?e.id.trim():"",a=typeof(t==null?void 0:t.id)=="string"?t.id.trim():"",o=!!i&&!!a&&i!==a;return t?{...t,...e,messages:s?Hp(e.messages):o?[]:t.messages,activeModal:n?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...s?{messages:Hp(e.messages)}:{},...n?{activeModal:e.activeModal??null}:{}}}function Jn(e,t){const s=rS(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:s??(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)??s??(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:Pf(e.activeChat,t==null?void 0:t.activeChat),activeInteractivePrompt:Object.prototype.hasOwnProperty.call(e,"activeInteractivePrompt")?e.activeInteractivePrompt??null:(t==null?void 0:t.activeInteractivePrompt)??null,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 Df(e,t,s){if(!(t!=null&&t.length))return(s==null?void 0:s.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const n=t.map(i=>{const a=e.find(o=>o.id===i.id);return a?Jn(i,a):i});if((s==null?void 0:s.preserveMissing)!==!1){const i=new Set(t.map(a=>a.id));for(const a of e)i.has(a.id)||n.push(a)}return n}function zp(e){return!!e&&typeof e=="object"&&"text"in e}function zd(e,t){const s=(t==null?void 0:t.joiner)??" ",n=(t==null?void 0:t.normalizeWhitespace)??!1;let i="";return typeof e=="string"?i=e:Array.isArray(e)?i=e.map(a=>typeof a=="string"?a:zp(a)?String(a.text||""):"").join(s):zp(e)?i=String(e.text||""):i=String(e||""),n?i.replace(/\s+/g," ").trim():i}function xn(e){return zd(e,{normalizeWhitespace:!0})}const Lf=u.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}),$f=u.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Kp(e){var s,n;let t=0;return e.activeChat!==void 0&&(t+=4),e.activeInteractivePrompt!==void 0&&(t+=2),(s=e.childSessions)!=null&&s.length&&(t+=2),e.workspace&&(t+=1),e.machine&&(t+=1),(n=e.agents)!=null&&n.length&&(t+=1),t}function Of(e,t,s){if(s.type!=="adhdev-daemon")return s;const n={...s},i=t.version??s.version??e.version,a=t.serverVersion??e.serverVersion??s.serverVersion,o=t.versionMismatch===!0||e.versionMismatch===!0,l=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,c=t.versionUpdateReason??e.versionUpdateReason??s.versionUpdateReason;return i&&(n.version=i),a&&(n.serverVersion=a),c&&(n.versionUpdateReason=c),i&&a&&i===a?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||o&&i&&a&&i!==a)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function nS(e){let t=2166136261;for(let s=0;s<e.length;s+=1)t^=e.charCodeAt(s),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function Ll(e){if(!e||typeof e!="object")return"";const t=e,s=nS(xn(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??""),s].join(":")}function iS(e,t){if(!Array.isArray(e))return e;if(t!=null&&t.has(e))return{count:e.length,sharedRef:!0};let s=2166136261;for(const n of e){const i=Ll(n);for(let a=0;a<i.length;a+=1)s^=i.charCodeAt(a),s=Math.imul(s,16777619)>>>0}return{count:e.length,hash:s.toString(16).padStart(8,"0"),first:Ll(e[0]),last:Ll(e[e.length-1])}}function qc(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function Vc(e,t,s){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(qc(e)&&qc(t)){const o=e.messages;Array.isArray(o)&&o===t.messages&&s.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)Vc(e[l],t[l],s);return}const n=e,i=t,a=new Set([...Object.keys(n),...Object.keys(i)]);for(const o of a)o!=="messages"&&Vc(n[o],i[o],s)}function ai(e,t){return Array.isArray(e)?e.map(s=>ai(s,t)):!e||typeof e!="object"?e:qc(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[i])=>n.localeCompare(i)).map(([n,i])=>[n,n==="messages"?iS(i,t):ai(i,t)])):Object.fromEntries(Object.entries(e).filter(([s])=>s!=="timestamp"&&s!=="_lastUpdate").sort(([s],[n])=>s.localeCompare(n)).map(([s,n])=>[s,ai(n,t)]))}function aS(e,t){try{const s=new WeakSet;return Vc(e,t,s),JSON.stringify(ai(e,s))===JSON.stringify(ai(t,s))}catch{return!1}}function Xc(e,t,s){return aS(e,t)?(e._lastUpdate=s,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Ff(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function oS(e,t,s){t[s]!==void 0&&(e[s]=t[s])}function Gp(e,t,s,n){var l;const i=(l=t.chats)!=null&&l.length?t.chats:e.chats,a=Df(e.childSessions,t.childSessions,{preserveMissing:n}),o=Pf(t.activeChat,e.activeChat);return Of(e,t,{...e,...t,chats:i,childSessions:a,activeChat:o,_lastUpdate:s})}function lS(e,t,s){var i,a;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=Df(e.childSessions,t.childSessions,{preserveMissing:s})),(i=t.chats)!=null&&i.length&&!((a=e.chats)!=null&&a.length)&&(n.chats=t.chats);for(const o of["title","workspace","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","activeInteractivePrompt","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])oS(n,t,o);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function cS(e,t,s,n){const i=lS(e,t,n),a=Object.keys(i).length>0?Of(e,t,{...e,...i,_lastUpdate:s}):{...e,_lastUpdate:s};return Xc(e,a,s)}function dS(e){const t=new Set(e.map(a=>a.id)),s=new Set,n=new Set,i=new Set;for(const a of e){const o=Ff(a);o&&s.add(o),o&&a.type!=="adhdev-daemon"&&n.add(o),o&&a.type==="adhdev-daemon"&&a._sessionListAuthoritative&&i.add(o)}return{incomingIds:t,incomingDaemonIds:s,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:i}}function uS(e,t,s,n,i,a){return!i.has(t)||!a.has(t)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?s>1e4:e.transport==="cdp-page"?s>3e4:!1}function pS(e,t,s,n,i){return e.transport?s.has(t)&&!n.has(t)?!0:i.has(t):!1}function hS(e,t,s){var p,h;const n=Date.now(),i=new Set((s==null?void 0:s.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(m=>({...m,_lastUpdate:n}));const a=new Map;for(const m of t)a.set(m.id,m);const{incomingIds:o,incomingDaemonIds:l,daemonIdsWithSessionEntries:c,daemonIdsWithAuthoritativeSessionList:d}=dS(e);for(const m of e){const g=a.get(m.id);if(!g){a.set(m.id,{...m,_lastUpdate:n});continue}const b=Kp(m),f=Kp(g),v=Ff(m),w=!i.has(v);if(b>f){const k=Gp(g,m,n,w);a.set(m.id,Xc(g,k,n));continue}if(b<f){a.set(m.id,cS(g,m,n,w));continue}const x=m.timestamp||n,S=g._lastUpdate||g.timestamp||0;if(x>=S){const k=Gp(g,m,n,w);a.set(m.id,Xc(g,k,n));continue}(p=m.chats)!=null&&p.length&&!((h=g.chats)!=null&&h.length)&&a.set(m.id,{...g,chats:m.chats})}for(const[m,g]of a){const b=g.daemonId||m.split(":")[0];if(!l.has(b))continue;if(i.has(b)&&d.has(b)&&!o.has(m)){a.delete(m);continue}const f=n-(g._lastUpdate||g.timestamp||0);uS(g,b,f,o,i,c)&&a.delete(m)}for(const[m,g]of a){const b=g.daemonId||m.split(":")[0];if(pS(g,b,l,c,a))continue;n-(g._lastUpdate||g.timestamp||0)>3e5&&g.status!=="online"&&a.delete(m)}return Array.from(a.values())}function mS(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s]!==t[s])return!1;return!0}function fS({children:e,connectionOverrides:t}){const[s,n]=u.useState([]),[i,a]=u.useState(!1),[o,l]=u.useState([]),[c,d]=u.useState(void 0),p=u.useRef(s);u.useEffect(()=>{p.current=s},[s]);const h=u.useCallback((w,x)=>{n(S=>{let k=!1;const j=S.map(y=>y.id!==w||y.chats===x?y:(k=!0,{...y,chats:x}));return k?j:S})},[]),m=u.useCallback((w,x)=>{n(S=>{const k=S.length===0?w:hS(w,S,x),j=!mS(S,k);return j&&gn.record({kind:"dashboard.entries_applied",payload:{incoming:Up(w),next:Up(k)}}),j?k:S})},[]),g=u.useCallback(()=>a(!0),[]),b=u.useMemo(()=>({injectEntries:m,markLoaded:g,getIdes:()=>p.current}),[m,g]),f=t,v=u.useMemo(()=>({ides:s,updateRouteChats:h,initialLoaded:i,toasts:o,setToasts:l,wsStatus:(f==null?void 0:f.wsStatus)??"connected",isConnected:(f==null?void 0:f.isConnected)??!0,connectionStates:(f==null?void 0:f.connectionStates)??{},connectionTransports:(f==null?void 0:f.connectionTransports)??{},showReconnected:(f==null?void 0:f.showReconnected)??!1,retryConnection:f==null?void 0:f.retryConnection,retryServerConnection:f==null?void 0:f.retryServerConnection,connectionLoginUrl:f==null?void 0:f.connectionLoginUrl,isP2PActive:(f==null?void 0:f.isP2PActive)??!1,p2pStates:(f==null?void 0:f.p2pStates)??{},userRole:f==null?void 0:f.userRole,connectionRetryStatuses:f==null?void 0:f.connectionRetryStatuses,userName:c,setUserName:d}),[s,h,i,o,f==null?void 0:f.wsStatus,f==null?void 0:f.isConnected,f==null?void 0:f.connectionStates,f==null?void 0:f.connectionTransports,f==null?void 0:f.showReconnected,f==null?void 0:f.retryConnection,f==null?void 0:f.retryServerConnection,f==null?void 0:f.connectionLoginUrl,f==null?void 0:f.isP2PActive,f==null?void 0:f.p2pStates,f==null?void 0:f.userRole,f==null?void 0:f.connectionRetryStatuses,c]);return r.jsx($f.Provider,{value:b,children:r.jsx(Lf.Provider,{value:v,children:e})})}function Fs(){return u.useContext(Lf)}function ji(){return u.useContext($f)}function Bf(e){const{baseUrl:t,getToken:s,onUnauthorized:n}=e;function i(l){return l.startsWith("http")?l:`${t}${l.startsWith("/")?"":"/"}${l}`}function a(l){const c=s==null?void 0:s(),d=i(l),p=l.startsWith("http")?new URL(d):new URL(d,typeof window<"u"?window.location.origin:"http://localhost");return c&&p.searchParams.set("token",c),!l.startsWith("http")&&!t?`${p.pathname}${p.search}${p.hash}`:p.toString()}async function o(l,c={}){const d={"Content-Type":"application/json",...c.headers||{}},p=s==null?void 0:s();p&&(d.Authorization=`Bearer ${p}`);const h=i(l),m=new AbortController,g=setTimeout(()=>m.abort(),15e3);try{const b=await fetch(h,{...c,headers:d,signal:m.signal});if(b.status===401)throw n==null||n(),new Error("Unauthorized");if(!b.ok){const f=await b.json().catch(()=>({error:b.statusText}));throw new Error(f.error||`API Error: ${b.status}`)}return b.json()}finally{clearTimeout(g)}}return{getDaemons:()=>o("/api/v1/daemons"),getDaemonStatus:l=>o(`/api/v1/daemons/${l}/status`),sendCommand:(l,c,d={})=>o(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:c,payload:d})}),execTerminal:(l,c,d)=>o(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:c,name:d})}),sendAgentMessage:(l,c,d)=>o(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:c,message:d})}),getAgentStatus:l=>o(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,c,d)=>o(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:c,action:d?"approve":"reject"})}),getMuxState:l=>o(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>o(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,c,d={})=>o(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:c,payload:d})}),getMuxEventsUrl:l=>a(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>a(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:o}}const gS=Bf({baseUrl:"http://localhost:3847"}),xS=u.createContext(gS);function bS({client:e,children:t}){return r.jsx(xS.Provider,{value:e,children:t})}const yS={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Wf=u.createContext(yS);function vS({value:e,children:t}){return r.jsx(Wf.Provider,{value:e,children:t})}function jt(){return u.useContext(Wf)}function Uf(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function wS(e){const t=Uf(e);if(!t||t.error!=="untrusted_external_provider")return null;const s=t.provider&&typeof t.provider=="object"?t.provider:null;return{providerType:typeof(s==null?void 0:s.type)=="string"?s.type:null,sourceName:typeof(s==null?void 0:s.sourceName)=="string"?s.sourceName:null,description:typeof t.hint=="string"?t.hint:void 0}}function SS(e){const[t,s]=u.useState(null),n=u.useCallback(async(o,l)=>{const c=h=>e(o,"launch_cli",{...l,...h}),d=await c({}),p=wS(d);return p?new Promise(h=>{s({providerType:p.providerType||String(l.cliType??"?"),sourceName:p.sourceName,description:p.description,retry:()=>c({confirmExternalUntrusted:!0}),resolve:m=>{m.cancelled?h({success:!1,error:"user_cancelled_untrusted_launch"}):h(m.response)}})}):d},[e]),i=u.useCallback(async()=>{const o=t;if(o){s(null);try{const l=await o.retry(),c=Uf(l);c!=null&&c.success?o.resolve({ok:!0,response:l}):o.resolve({ok:!1,error:(c==null?void 0:c.error)||"launch failed after confirm",response:l})}catch(l){o.resolve({ok:!1,error:(l==null?void 0:l.message)||String(l)})}}},[t]),a=u.useCallback(()=>{const o=t;o&&(s(null),o.resolve({ok:!1,cancelled:!0}))},[t]);return{launchCli:n,pending:t,confirm:i,cancel:a}}function kS({providerType:e,sourceName:t,description:s,onConfirm:n,onCancel:i}){const a=u.useRef(null);return u.useEffect(()=>{var o;(o=a.current)==null||o.focus()},[]),u.useEffect(()=>{const o=l=>{l.key==="Escape"&&i()};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[i]),r.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Confirm untrusted external provider",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onClick:i,style:{pointerEvents:"auto"},children:r.jsxs("div",{className:"bg-[var(--surface-primary)] text-text-primary border border-amber-500/40 rounded-lg shadow-xl max-w-lg w-full",onClick:o=>o.stopPropagation(),children:[r.jsxs("div",{className:"px-4 py-3 border-b border-border-subtle flex items-center gap-2",children:[r.jsx("span",{"aria-hidden":!0,className:"text-amber-400 text-base",children:"⚠"}),r.jsx("h2",{className:"text-sm font-semibold",children:"Activate untrusted external provider?"})]}),r.jsxs("div",{className:"px-4 py-3 text-[12px] flex flex-col gap-3",children:[r.jsxs("p",{children:["You're about to activate ",r.jsx("span",{className:"font-mono",children:e}),t?r.jsxs(r.Fragment,{children:[" from ",r.jsx("span",{className:"font-mono",children:t})]}):null,"."]}),r.jsx("p",{className:"text-text-secondary",children:s??"This manifest ships JavaScript that the daemon will execute. Treat as untrusted code — review the source before enabling."}),r.jsx("p",{className:"text-text-secondary",children:"Only proceed if you trust the source URL you added and have reviewed the manifest."})]}),r.jsxs("div",{className:"px-4 py-2 border-t border-border-subtle flex justify-end gap-2",children:[r.jsx("button",{ref:a,type:"button",onClick:i,className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:"Cancel"}),r.jsx("button",{type:"button",onClick:n,className:"px-3 py-1 text-sm rounded bg-amber-500 text-black font-semibold hover:opacity-90",children:"Activate"})]})]})})}const Hf=u.createContext(null);function jS({sendDaemonCommand:e,children:t}){const s=SS(e),n=u.useMemo(()=>({launchCli:s.launchCli}),[s.launchCli]);return r.jsxs(Hf.Provider,{value:n,children:[t,s.pending&&r.jsx(kS,{providerType:s.pending.providerType,sourceName:s.pending.sourceName,description:s.pending.description,onConfirm:s.confirm,onCancel:s.cancel})]})}function rl(){const e=u.useContext(Hf);return e||{launchCli:async()=>{throw new Error("useLaunchCli must be used inside <LaunchCliProvider>")}}}function NS(e){let t=2166136261;for(const s of e){const n=String(s||"");for(let i=0;i<n.length;i+=1)t^=n.charCodeAt(i),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function _S(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function zf(e){return e?NS([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),_S(e.content)]):""}const Ke={size:18};function Kf({size:e=Ke.size,className:t}){return r.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:[r.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),r.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),r.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),r.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function Kd({size:e=Ke.size,className:t}){return r.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:r.jsx("polyline",{points:"15 18 9 12 15 6"})})}function cr({size:e=Ke.size,className:t}){return r.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:[r.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),r.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),r.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),r.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),r.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),r.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function Gf({size:e=Ke.size,className:t}){return r.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:[r.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),r.jsx("circle",{cx:"9",cy:"7",r:"4"}),r.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),r.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function CS({size:e=Ke.size,className:t}){return r.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:[r.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),r.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function IS({size:e=Ke.size,className:t}){return r.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:r.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 qf({size:e=Ke.size,className:t}){return r.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:[r.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),r.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"}),r.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),r.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function AS({size:e=Ke.size,className:t}){return r.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:[r.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"}),r.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),r.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),r.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),r.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function nl({size:e=Ke.size,className:t}){return r.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:[r.jsx("circle",{cx:"12",cy:"12",r:"3"}),r.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 Vf({size:e=Ke.size,className:t}){return r.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:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),r.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function TS({size:e=Ke.size,className:t}){return r.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:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),r.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function MS({size:e=Ke.size,className:t}){return r.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:r.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function zr({size:e=Ke.size,className:t}){return r.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:r.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 _s({size:e=Ke.size,className:t}){return r.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:[r.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),r.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),r.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Gd({size:e=Ke.size,className:t}){return r.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:[r.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),r.jsx("polyline",{points:"14 2 14 8 20 8"}),r.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),r.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function bn({size:e=Ke.size,className:t}){return r.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:r.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 il({size:e=Ke.size,className:t}){return r.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:[r.jsx("polyline",{points:"23 4 23 10 17 10"}),r.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function yn({size:e=Ke.size,className:t}){return r.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:[r.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"}),r.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),r.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function vn({size:e=Ke.size,className:t}){return r.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:[r.jsx("path",{d:"M12 22v-5"}),r.jsx("path",{d:"M9 8V2"}),r.jsx("path",{d:"M15 8V2"}),r.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function qs({size:e=Ke.size,className:t}){return r.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:[r.jsx("circle",{cx:"12",cy:"5",r:"2"}),r.jsx("circle",{cx:"5",cy:"19",r:"2"}),r.jsx("circle",{cx:"19",cy:"19",r:"2"}),r.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),r.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),r.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function ES({size:e=Ke.size,className:t}){return r.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:[r.jsx("polygon",{points:"12 2 2 7 12 12 22 7 12 2"}),r.jsx("polyline",{points:"2 12 12 17 22 12"}),r.jsx("polyline",{points:"2 17 12 22 22 17"})]})}function Xf({size:e=Ke.size,className:t}){return r.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:[r.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),r.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function qd({size:e=Ke.size,className:t}){return r.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:[r.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"}),r.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"}),r.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),r.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Yf({size:e=Ke.size,className:t}){return r.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:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function RS({size:e=Ke.size,className:t}){return r.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:[r.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),r.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),r.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function Vd({size:e=Ke.size,className:t}){return r.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:[r.jsx("polyline",{points:"4 17 10 11 4 5"}),r.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function PS({size:e=Ke.size,className:t}){return r.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:[r.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),r.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Qf({size:e=Ke.size,className:t}){return r.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:r.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Jf({size:e=Ke.size,className:t}){return r.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:[r.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),r.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function Ot({size:e=Ke.size,className:t}){return r.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:[r.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),r.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function DS({size:e=Ke.size,className:t}){return r.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:[r.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"}),r.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"}),r.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),r.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function LS({size:e=Ke.size,className:t}){return r.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:[r.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),r.jsx("path",{d:"M12 2v6"}),r.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),r.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function $S({size:e=Ke.size,className:t}){return r.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:r.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 OS({size:e=Ke.size,className:t}){return r.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:[r.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),r.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 Gi({size:e=Ke.size,className:t}){return r.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:[r.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),r.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function FS({size:e=Ke.size,className:t}){return r.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:[r.jsx("circle",{cx:"12",cy:"12",r:"5"}),r.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),r.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),r.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),r.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),r.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),r.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),r.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),r.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function BS({size:e=Ke.size,className:t}){return r.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:r.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function WS({size:e=Ke.size,className:t}){return r.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:[r.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),r.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),r.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Zf({size:e=Ke.size,className:t}){return r.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:[r.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),r.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function US({size:e=Ke.size,className:t}){return r.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:r.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function HS({size:e=Ke.size,className:t}){return r.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:[r.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),r.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 zS({size:e=Ke.size,className:t}){return r.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:[r.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"}),r.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"}),r.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 KS({size:e=Ke.size,className:t}){return r.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:[r.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),r.jsx("path",{d:"M13 2h9v9"}),r.jsx("path",{d:"M22 2L13 11"})]})}function GS({size:e=Ke.size,className:t}){return r.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:[r.jsx("polyline",{points:"9 14 4 9 9 4"}),r.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function qS({size:e=Ke.size,className:t}){return r.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:[r.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),r.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),r.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),r.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),r.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),r.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),r.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),r.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),r.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),r.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function VS({size:e=Ke.size,className:t}){return r.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:[r.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),r.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 XS({size:e=Ke.size,className:t}){return r.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:[r.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),r.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),r.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const eg="adhdev_chat_activity_visible",qp=new Set(["hidden","debug","internal"]),Vp=new Set(["visible","user","chat"]),YS=new Set(["debug","trace","internal"]),QS=new Set(["tool_call","terminal_command","runtime_activity"]),JS=new Set(["runtime_status","provider_chrome","control"]),ZS=new Set(["thought","tool","terminal"]);function tg(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function en(e){return typeof e=="string"?e.trim().toLowerCase():""}function $l(e,t,s){return e[s]??(t==null?void 0:t[s])}function Xp(e,t,s){const n=e;return s.some(i=>n[i]===!0||(t==null?void 0:t[i])===!0)}function ek(e,t){const s=en(e.kind);return s||(t==="tool"?"tool":"standard")}function Ol(e,t,s){const n=tg(e),i=typeof(n==null?void 0:n.label)=="string"?n.label.trim():"";return i||(t==="terminal"||s==="terminal_command"?"Terminal":t==="tool"||s==="tool_call"?"Tool":t==="thought"?"Thought":s==="runtime_activity"?"Runtime":"Activity")}function tk(e){const t=e.content;return Array.isArray(t)&&t.some(s=>!!s&&typeof s=="object"&&s.type!=="text")}function Xd(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=tg(e),s=en(e.role),n=ek(e,s),i=en($l(e,t,"visibility")),a=en(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??i),o=en($l(e,t,"audience")),l=en($l(e,t,"source")),c=qp.has(i)||qp.has(a)||YS.has(o)||Xp(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),d=Vp.has(i)||Vp.has(a)||o==="chat"||Xp(e,t,["userFacing"]),p=ZS.has(n)||QS.has(l);if(c)return{surface:p?"activity":"internal",isUserFacing:!1,isActivityFacing:p,isInternal:!p,role:s,kind:n,label:Ol(e,n,l)};if(d)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:s,kind:n,label:Ol(e,n,l)};if((s==="system"||n==="system")&&tk(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:s,kind:n,label:"Chat"};if(JS.has(l)||s==="system"||n==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:s,kind:n,label:"Internal"};if(p)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:s,kind:n,label:Ol(e,n,l)};const h=(s==="user"||s==="human"||s==="assistant")&&(n==="standard"||n==="");return{surface:h?"chat":"internal",isUserFacing:h,isActivityFacing:!1,isInternal:!h,role:s,kind:n,label:h?"Chat":"Internal"}}function sk(e){return(Array.isArray(e)?e:[]).filter(t=>Xd(t).isUserFacing)}function sg(e){return(Array.isArray(e)?e:[]).filter(t=>Xd(t).isActivityFacing)}function rk(e,t,s){return!s||t.length===0?e:[...e,...t].sort((n,i)=>{const a=Number(n.receivedAt??n.timestamp??0)||0,o=Number(i.receivedAt??i.timestamp??0)||0;if(a!==o)return a-o;const l=Number(n.index??0)||0,c=Number(i.index??0)||0;return l-c})}function Yp(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(eg))==="1"}catch{return!1}}const rg=[mw,{singleTilde:!1}],ng=[rg,fw,gw],nk=[rg],Yd=200,ik=80,Qp=650,Pn=new Map;function xo(e,t){if(!e)return!1;const s=String(e.messageFingerprint||"");return s?s===String(t||""):!0}function ak(e,t){if(!Array.isArray(e)||e.length===0)return"0:empty";const s=String(t||"").trim();if(s)return`${e.length}:${s}`;const n=e[e.length-1];return`${e.length}:${zf(n)}`}function ok(e,t,s,n){return e||!t?!1:xo(s,n)}function lk({scrollTop:e,scrollHeight:t,clientHeight:s,topThresholdPx:n=ik,bottomThresholdPx:i=Yd}){const a=Math.max(0,Number(e)||0),o=Math.max(0,Number(t)||0),l=Math.max(0,Number(s)||0);return Math.max(0,o-l)<=0?{showTop:!1,showBottom:!1}:{showTop:a>n,showBottom:Math.max(0,o-a-l)>i}}function ck(e){return lk({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Zn(e,t=Yd){return!!e&&e.fromBottom>=t}function dk(e,t){return xo(e,t)?!Zn(e):!0}function uk({hasSelection:e,userScrolledUp:t,hasChatContentChanged:s=!0}){return!(e||t||!s)}function pk({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:s}){return e?!1:s||!t}function Fl(e,t){const s=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(s)?s:t.top}function ig(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function hk(e,t,s){return Number(e.receivedAt||s[bo(e,t)]||0)||0}function ag(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function mk(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function Dn(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 Bl(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 ka(e,t,s){return r.jsxs("div",{className:"rounded-md border border-border-subtle p-2 text-sm",role:"note",children:[r.jsx("span",{className:"font-medium",children:e}),t?r.jsx("span",{className:"ml-1 break-all",children:t}):null,s?r.jsx("div",{className:"mt-1 opacity-80",style:{whiteSpace:"pre-wrap"},children:s}):null]})}function Jp(e,t){return e?t?r.jsx("pre",{className:"chat-preformatted",children:e}):ag(e)?r.jsx(Wd,{remarkPlugins:ng,children:e}):r.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}const fk=u.memo(function({content:t,renderAsPreformatted:s,renderAsMarkdown:n}){return s?r.jsx("pre",{className:"chat-preformatted",children:t}):n?r.jsx(Wd,{remarkPlugins:ng,children:t}):r.jsx("div",{style:{whiteSpace:"pre-wrap"},children:t})});function Ln({parts:e,renderAsPreformatted:t}){return r.jsx("div",{className:"flex flex-col gap-2",children:e.map((s,n)=>{if(s.type==="text")return r.jsx("div",{children:Jp(String(s.text||""),t)},`text-${n}`);if(s.type==="image"){const i=Bl(s),a=s.alt||s.description||Dn(s.uri,"image");return i?r.jsx("img",{src:i,alt:a,className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):r.jsx("div",{children:ka("Image",a,s.mimeType)},`image-fallback-${n}`)}if(s.type==="audio"){const i=Bl(s);return i?r.jsxs("div",{className:"flex flex-col gap-1",children:[r.jsx("audio",{controls:!0,src:i,className:"max-w-full"}),s.transcript?r.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:s.transcript}):null]},`audio-${n}`):r.jsx("div",{children:ka("Audio",Dn(s.uri,"audio"),s.transcript||s.mimeType)},`audio-fallback-${n}`)}if(s.type==="video"){const i=Bl(s),a=s.title||s.name||s.alt||Dn(s.uri,"video"),o=[s.transcript,s.description,s.mimeType].filter(Boolean).join(`
|
|
3
|
+
`);return r.jsxs("div",{className:"flex flex-col gap-1",children:[i?r.jsx("video",{controls:!0,src:i,poster:s.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):ka("Video",a,o),i&&o?r.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:o}):null]},`video-${n}`)}if(s.type==="resource_link"){const i=s.title||s.name||Dn(s.uri,"resource"),a=[s.description,s.mimeType].filter(Boolean).join(`
|
|
4
|
+
`);return r.jsxs("div",{className:"flex flex-col gap-1",children:[s.uri?r.jsx("a",{href:s.uri,target:"_blank",rel:"noreferrer",download:!0,className:"underline break-all",children:i}):ka("Resource",i,a),s.uri&&a?r.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:a}):null]},`resource-link-${n}`)}if(s.type==="resource"&&s.resource){const i=Dn(s.resource.uri,"resource");if(s.resource.text)return r.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[r.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:i}),Jp(s.resource.text,!0)]},`resource-${n}`);if(s.resource.uri)return r.jsx("a",{href:s.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:i},`resource-uri-${n}`)}return null})})}function bo(e,t){const s=e,n=zd(e.content,{joiner:`
|
|
5
|
+
`});return[e.id?`id:${e.id}`:"",s._localId?`local:${s._localId}`:"",s._turnKey?`turn:${s._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 gk=u.memo(function({log:t}){return r.jsxs("div",{className:"self-center chat-msg-action",children:[r.jsx(Wd,{remarkPlugins:nk,children:t.text}),r.jsx("span",{className:"action-time",children:ig(t.timestamp)})]})},(e,t)=>e.log===t.log);function Zp(e){const t=e.meta;return[zf(e),e.kind||"",e.senderName||"",e.bubbleId||"",e.bubbleState||"",e.visibility||"",e.transcriptVisibility||"",e.audience||"",e.source||"",e.userFacing===void 0?"":String(e.userFacing),e.internal===void 0?"":String(e.internal),e.isInternal===void 0?"":String(e.isInternal),e.debug===void 0?"":String(e.debug),t?String(t.label??""):"",t?String(t.isRunning??""):"",t?String(t.renderMode??""):""].join("")}const xk=u.memo(function({message:t,receivedAt:s,agentName:n,userName:i,isCliMode:a,isTextExpanded:o,onToggleTextExpanded:l}){var _,C,D;const c=(t.role||"").toLowerCase(),d=c==="user"||c==="human",p=t.kind||(c==="tool"?"tool":"standard"),h=Xd(t),m=mk(t.content)?t.content:null,g=!!(m!=null&&m.some(T=>T.type!=="text")),b=zd(t.content,{joiner:`
|
|
6
|
+
`});if(h.isActivityFacing&&p!=="thought"&&p!=="tool"&&p!=="terminal"){const T=h.label||"Activity";return r.jsxs("div",{className:"self-start chat-msg-activity","data-chat-activity-row":"true",children:[r.jsxs("div",{className:"chat-msg-activity-meta","aria-label":"Activity message",children:[r.jsx("span",{className:"activity-dot"}),r.jsx("span",{children:T})]}),g&&m?r.jsx("div",{className:"chat-msg-activity-body",children:r.jsx(Ln,{parts:m,renderAsPreformatted:!1})}):r.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:b})]})}if(p==="thought"){const T=typeof((_=t.meta)==null?void 0:_.label)=="string"?t.meta.label:"Thought";return r.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":h.isActivityFacing?"true":void 0,children:[r.jsxs("div",{className:"chat-msg-header",children:[r.jsx($S,{size:13}),r.jsx("span",{children:T})]}),r.jsx("div",{className:"chat-msg-body",children:b})]})}if(p==="tool")return r.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":h.isActivityFacing?"true":void 0,children:[r.jsxs("div",{className:"chat-msg-tool-meta","aria-label":"Tool message",children:[r.jsx("span",{className:"tool-icon",children:"⏺"}),r.jsx("span",{className:"tool-label",children:"Tool"})]}),g&&m?r.jsx("div",{className:"tool-text w-full",children:r.jsx(Ln,{parts:m,renderAsPreformatted:!1})}):r.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:b})]});if(p==="terminal"){const T=(C=t.meta)!=null&&C.isRunning?"⏳":"✅",A=typeof((D=t.meta)==null?void 0:D.label)=="string"?t.meta.label:"Ran command";return r.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":h.isActivityFacing?"true":void 0,children:[r.jsxs("div",{className:"chat-msg-header",children:[r.jsx("span",{children:T}),r.jsx("span",{children:A})]}),g&&m?r.jsx("div",{className:"chat-msg-body",children:r.jsx(Ln,{parts:m,renderAsPreformatted:!0})}):r.jsx("pre",{className:"chat-msg-body",children:b})]})}if(p==="system")return r.jsx("div",{className:"self-center chat-msg-system",children:g&&m?r.jsx(Ln,{parts:m,renderAsPreformatted:!1}):b.slice(0,100)});const f=t.meta,w=(typeof(f==null?void 0:f.renderMode)=="string"?f.renderMode.trim():"")==="preformatted",x=b,S=!1,k=x,j=w,y=!d&&!j&&ag(k),N=["chat-message-row",d?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return r.jsx("div",{className:N,children:(x||g||d)&&r.jsxs("div",{className:`chat-bubble ${d?"chat-bubble-user":"chat-bubble-assistant"}`,children:[r.jsxs("div",{className:`chat-bubble-header ${x||g?"mb-1.5":"mb-0"}`,children:[r.jsx("span",{className:"chat-sender",children:d?i||"You":t.senderName||n}),s!=null&&r.jsx("span",{className:"chat-time",children:ig(s)})]}),(x||g)&&r.jsx("div",{className:"chat-markdown",children:g&&m?r.jsx(Ln,{parts:m,renderAsPreformatted:j}):r.jsx(fk,{content:k,renderAsPreformatted:j,renderAsMarkdown:y})}),S]})})},(e,t)=>(e.message===t.message||Zp(e.message)===Zp(t.message))&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),bk=u.forwardRef(function({messages:t,actionLogs:s,agentName:n="Agent",userName:i,isCliMode:a=!1,isWorking:o=!1,contextKey:l="",receivedAtMap:c={},lastMessageHash:d,showActivityMessages:p=!1,emptyState:h,onLoadMore:m,isLoadingMore:g,hasMoreHistory:b,hiddenLiveCount:f=0,loadError:v,scrollToBottomRequestNonce:w,isVisible:x=!0},S){const k=u.useRef(null),j=u.useRef(null),y=u.useRef(null),N=u.useRef(0),_=u.useRef(""),C=u.useRef(""),D=u.useRef(!1),T=u.useRef(null),A=u.useRef(!1),P=u.useRef(null),F=u.useRef(!1),[J,R]=u.useState(new Set),[I,E]=u.useState({showTop:!1,showBottom:!1}),$=u.useRef(!1),M=u.useRef(!1),O=u.useRef(x),H=u.useRef(x),ae=u.useRef(null);H.current=x;const z=()=>{const ce=k.current;return ce?ce.scrollHeight-ce.scrollTop-ce.clientHeight<Yd:!0},X=u.useCallback(()=>{const ce=k.current,L=ce?ck(ce):{showTop:!1,showBottom:!1};E(de=>de.showTop===L.showTop&&de.showBottom===L.showBottom?de:L)},[]),te=u.useCallback((ce="auto")=>{var de;const L=k.current;L&&(L.scrollTo({top:L.scrollHeight,behavior:ce}),(de=L.ownerDocument.defaultView)==null||de.requestAnimationFrame(()=>X()))},[X]),he=u.useCallback((ce="auto")=>{var de;const L=k.current;L&&(L.scrollTo({top:0,behavior:ce}),(de=L.ownerDocument.defaultView)==null||de.requestAnimationFrame(()=>X()))},[X]),ke=u.useCallback(()=>{var ie;const ce=k.current,L=(ie=window.getSelection)==null?void 0:ie.call(window);if(!ce||!L||L.rangeCount===0||L.isCollapsed){F.current=!1;return}const de=L.anchorNode,U=L.focusNode;F.current=!!(de&&U&&ce.contains(de)&&ce.contains(U))},[]),Q=u.useMemo(()=>{const ce=sk(t),L=sg(t);return rk(ce,L,p)},[t,p]),q=Q.length===t.length?d:void 0,me=ak(Q,q),we=u.useCallback(()=>{const ce=k.current;if(!ce||!l||!H.current)return;const L={top:ce.scrollTop,fromBottom:Math.max(0,ce.scrollHeight-ce.scrollTop-ce.clientHeight),messageFingerprint:me};ae.current={contextKey:l,snapshot:L},Pn.set(l,L)},[l,me]),ye=u.useCallback((ce="auto")=>{T.current!=null&&cancelAnimationFrame(T.current),T.current=requestAnimationFrame(()=>{T.current=null,te(ce)})},[te]),Te=u.useCallback(()=>{$.current=!1,A.current=!0,M.current=!0,P.current!=null&&window.clearTimeout(P.current),P.current=window.setTimeout(()=>{A.current=!1,P.current=null},Qp)},[]);u.useEffect(()=>{const ce=!D.current,L=C.current!==l;if(C.current=l,ce||L){D.current=!0;const U=l?Pn.get(l):null,ie=!!U&&xo(U,me);$.current=ie?Zn(U):!1,A.current=dk(U,me),F.current||(ie?requestAnimationFrame(()=>{const Y=k.current;Y&&(Fl(Y,U),$.current=Zn(U),X(),M.current=!0)}):ye("auto")),N.current=Q.length,_.current=me;return}Q.length>N.current;const de=me!==_.current;uk({hasSelection:F.current,userScrolledUp:$.current,hasChatContentChanged:de})&&ye("auto"),N.current=Q.length,_.current=me},[me,l,Q.length,ye,X]),u.useEffect(()=>{w&&(Te(),F.current||ye("auto"))},[Te,ye,w]),u.useEffect(()=>{const ce=O.current;ce&&!x&&we(),H.current=x,O.current=x;const L=l?Pn.get(l):null;if(ok(ce,x,L,me)){if(!L)return;$.current=Zn(L),A.current=!1,F.current||requestAnimationFrame(()=>{const de=k.current;de&&(Fl(de,L),X())});return}},[x,l,me,Te,we,ye,X]),u.useEffect(()=>()=>{const ce=ae.current;ce&&Pn.set(ce.contextKey,ce.snapshot),T.current!=null&&cancelAnimationFrame(T.current),P.current!=null&&window.clearTimeout(P.current)},[]),u.useEffect(()=>{const ce=j.current,L=k.current;if(!ce||!L)return;const de=()=>{P.current!=null&&window.clearTimeout(P.current),P.current=window.setTimeout(()=>{A.current=!1,P.current=null},Qp)},U=new ResizeObserver(()=>{X();const ie=A.current;pk({hasSelection:F.current,userScrolledUp:$.current,contextAutoScrollActive:ie})&&(ye("auto"),ie&&de())});return U.observe(ce),L!==ce&&U.observe(L),()=>{U.disconnect(),P.current!=null&&(window.clearTimeout(P.current),P.current=null)}},[ye,l,X]),u.useImperativeHandle(S,()=>({scrollToBottom:(ce="smooth")=>{te(ce)}}),[te]),u.useEffect(()=>{const ce=k.current;if(!ce)return;let L;const de=()=>{we(),clearTimeout(L),L=setTimeout(()=>{$.current=!z(),X()},50)};return ce.addEventListener("scroll",de,{passive:!0}),()=>{ce.removeEventListener("scroll",de),clearTimeout(L)}},[we,X]),u.useEffect(()=>(document.addEventListener("selectionchange",ke),()=>document.removeEventListener("selectionchange",ke)),[ke]);const le=u.useRef(0),Se=u.useRef(!1);u.useEffect(()=>{const ce=k.current;if(!ce||!Se.current||le.current===0)return;const L=ce.scrollHeight-le.current;L>0&&(ce.scrollTop=L),X(),we(),le.current=0,Se.current=!1},[Q.length,we,X]),u.useEffect(()=>{if(M.current||!l)return;const ce=Pn.get(l),L=k.current;if(!(!ce||!L)){if(!xo(ce,me)){te("auto"),M.current=!0;return}Fl(L,ce),$.current=Zn(ce),X(),M.current=!0}},[l,me,Q.length,te,X]);const ge=()=>{const ce=k.current;ce&&(le.current=ce.scrollHeight),Se.current=!0,m==null||m()},G=()=>{$.current=!0,he("smooth"),we()},W=()=>{Te(),te("smooth"),we()},Z=u.useMemo(()=>{const ce=Q.map((ie,Y)=>({type:"message",data:ie,index:Y,ts:hk(ie,Y,c)}));if(!s||s.length===0)return ce;const L=[...s].sort((ie,Y)=>ie.timestamp-Y.timestamp).map((ie,Y)=>({type:"action",data:ie,index:Y,ts:ie.timestamp})),de=[];let U=0;for(const ie of ce){for(;U<L.length&&ie.ts>0&&L[U].ts<ie.ts;)de.push(L[U++]);de.push(ie)}for(;U<L.length;)de.push(L[U++]);return de},[Q,s,c]),oe=f>0||!!b,ue=f>0?`↑ Show ${Math.min(f,80)} earlier messages${f>80?` (${f} hidden)`:""}`:v?`↻ ${v}`:"↑ Load older messages";return r.jsxs("div",{className:"chat-scroll-frame",children:[r.jsx("div",{ref:k,"data-chat-scroll":!0,className:"chat-container",children:r.jsxs("div",{ref:j,className:"chat-container-content",children:[g&&r.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),oe&&!g&&r.jsx("div",{className:"text-center py-2",children:r.jsx("button",{type:"button",onClick:ge,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${v&&f===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:ue})}),Z.length===0&&!oe&&(h||r.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),Z.map(ce=>{if(ce.type==="action"){const Ce=ce.data;return r.jsx(gk,{log:Ce},`action-${ce.index}`)}const L=ce.data,de=ce.index,U=bo(L,de),ie=L.receivedAt||c[U],Y=`${l}-${U}`,Ae=J.has(Y);return r.jsx(xk,{message:L,receivedAt:ie,agentName:n,userName:i,isCliMode:a,isTextExpanded:Ae,onToggleTextExpanded:()=>R(Ce=>{const je=new Set(Ce);return Ae?je.delete(Y):je.add(Y),je})},`msg-${U}`)}),o&&r.jsx("div",{className:"self-start chat-typing-wrapper",children:r.jsxs("div",{className:"typing-indicator",children:[r.jsx("div",{className:"dot"}),r.jsx("div",{className:"dot"}),r.jsx("div",{className:"dot"}),r.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),r.jsx("div",{className:"min-h-10",ref:y})]})}),(I.showTop||I.showBottom)&&r.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[I.showTop&&r.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:G,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),I.showBottom&&r.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:W,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),yk=u.memo(bk,(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),vk="modulepreload",wk=function(e){return"/"+e},eh={},Sk=function(t,s,n){let i=Promise.resolve();if(s&&s.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"));i=Promise.allSettled(s.map(c=>{if(c=wk(c),c in eh)return;eh[c]=!0;const d=c.endsWith(".css"),p=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${p}`))return;const h=document.createElement("link");if(h.rel=d?"stylesheet":vk,d||(h.as="script"),h.crossOrigin="",h.href=c,l&&h.setAttribute("nonce",l),document.head.appendChild(h),d)return new Promise((m,g)=>{h.addEventListener("load",m),h.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${c}`)))})}))}function a(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return i.then(o=>{for(const l of o||[])l.status==="rejected"&&a(l.reason);return t().catch(a)})};let th=!1;const og=u.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:s,fontSize:n=13,readOnly:i=!1,sizingMode:a="measured"},o)=>{const l=u.useRef(null),[c,d]=u.useState(null),p=u.useRef([]),h=u.useRef(!1),m=u.useRef(!1),g=u.useRef(!1),b=u.useRef(!1),f=()=>{const v=l.current;if(v){h.current&&(v.clear(),h.current=!1);for(const w of p.current)v.write(w.data,w.onProcessed);p.current=[],m.current&&(v.fit(),m.current=!1),g.current&&(v.bumpResize(),g.current=!1),b.current&&(v.scrollToTop(),b.current=!1)}};return u.useImperativeHandle(o,()=>({write:(v,w)=>{l.current?l.current.write(v,w):p.current.push({data:v,onProcessed:w})},clear:()=>{l.current?l.current.clear():(p.current=[],h.current=!0)},reset:()=>{l.current&&typeof l.current.reset=="function"?l.current.reset():(p.current=[],h.current=!0)},resize:(v,w)=>{l.current&&typeof l.current.resize=="function"&&l.current.resize(v,w)},fit:()=>{l.current?l.current.fit():m.current=!0},bumpResize:()=>{l.current?l.current.bumpResize():g.current=!0},scrollToTop:()=>{l.current?l.current.scrollToTop():b.current=!0},getSelection:()=>{var v,w;return((w=(v=l.current)==null?void 0:v.getSelection)==null?void 0:w.call(v))||""},getVisibleText:()=>{var v,w;return((w=(v=l.current)==null?void 0:v.getVisibleText)==null?void 0:w.call(v))||""}}),[]),u.useEffect(()=>{c&&f()},[c]),u.useEffect(()=>{let v=!1;return Sk(()=>import("./terminal-BU39etVi.js"),__vite__mapDeps([0,1,2])).then(w=>{th||(th=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),v||d(()=>w.GhosttyTerminalView)}).catch(w=>{console.error("[CliTerminal] failed to load terminal renderer",w)}),()=>{v=!0}},[]),c?r.jsx(c,{ref:l,onInput:e,onViewportMetrics:t,onScrollMetrics:s,fontSize:n,readOnly:i,sizingMode:a,className:"w-full h-full rounded-lg overflow-hidden"}):r.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});og.displayName="CliTerminal";function ja({label:e,value:t,sub:s,icon:n}){return r.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[r.jsx("span",{className:"text-base flex items-center",children:n}),r.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),r.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:t}),s&&r.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:s})]})}function sh({value:e,max:t,label:s,color:n="#8b5cf6",detail:i,compact:a=!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 a?r.jsxs("div",{className:"flex-1",children:[r.jsxs("div",{className:"flex justify-between mb-0.5",children:[r.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:s}),r.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[o,"%"]})]}),r.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:r.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${o}%`,background:l}})})]}):r.jsxs("div",{className:"flex-1",children:[r.jsxs("div",{className:"flex justify-between mb-1.5",children:[r.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:s}),r.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[o,"%"]})]}),r.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:r.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${o}%`,background:`linear-gradient(90deg, ${l}, ${l}cc)`}})}),i&&r.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:i})]})}function kk({cursorPos:e,viewportRef:t,imgRef:s}){var x;if(!e||!s.current)return null;const n=s.current,i=n.getBoundingClientRect(),a=(x=t.current)==null?void 0:x.getBoundingClientRect();if(!a)return null;const o=n.naturalWidth||i.width,l=n.naturalHeight||i.height,c=o/l,d=i.width/i.height;let p,h,m,g;c>d?(p=i.width,h=i.width/c,m=0,g=(i.height-h)/2):(h=i.height,p=i.height*c,m=(i.width-p)/2,g=0);const b=i.left-a.left+m+p*e.nx,f=i.top-a.top+g+h*e.ny,v=Math.max(8,Math.min(a.width-8,b)),w=Math.max(8,Math.min(a.height-8,f));return r.jsxs("div",{style:{position:"absolute",left:v-8,top:w-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[r.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),r.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),r.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 jk({inputMode:e,onToggleInputMode:t,isImeOpen:s,setIsImeOpen:n,isMenuOpen:i,setIsMenuOpen:a,imeText:o,setImeText:l,handleImeSubmit:c,isConnActive:d,zoom:p,isMobile:h,mobileFillZoom:m,onZoomOut:g,onZoomReset:b,onZoomIn:f,transportType:v,screenshotUsage:w,lastActionStatus:x}){return r.jsxs(r.Fragment,{children:[r.jsxs("div",{onTouchStart:S=>S.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[r.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:[r.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),r.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),r.jsxs("div",{className:"relative",children:[r.jsx("div",{onClick:()=>{n(S=>!S),a(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${s?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:r.jsx("span",{className:"text-sm",children:"⌨️"})}),s&&r.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:r.jsx("input",{type:"text",placeholder:"Type & Enter...",value:o,autoFocus:!0,onTouchStart:S=>S.stopPropagation(),onChange:S=>l(S.target.value),onKeyDown:S=>{c(S)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),r.jsx("div",{className:"relative",children:r.jsx("div",{onClick:()=>{a(S=>!S),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${i?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:r.jsx("span",{className:"text-sm",children:"⚙️"})})}),r.jsx("div",{className:"w-px h-[18px] bg-white/10"}),r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:d?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[r.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:d?"#22c55e":"#eab308",boxShadow:d?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),r.jsx("span",{className:"text-[8px] font-extrabold",style:{color:d?"#22c55e":"#eab308"},children:d?"Connected":"WS"})]}),p>1&&r.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(p*100),"%"]}),v==="direct"&&r.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"}),v==="relay"&&r.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"}),w&&w.dailyBudgetMinutes>0&&r.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:w.budgetExhausted?"#ef4444":"#c4b5fd",background:w.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:w.budgetExhausted?"TURN blocked":`TURN ${w.dailyUsedMinutes}/${w.dailyBudgetMinutes}m`}),x&&r.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:x})]})]}),i&&r.jsxs("div",{onTouchStart:S=>S.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[r.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[r.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",p<=(h?m:1)+.01?h?"FILL":"FIT":`${Math.round(p*100)}%`]}),r.jsxs("div",{style:{display:"flex",gap:4},children:[r.jsx("button",{onClick:S=>{S.stopPropagation(),g()},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:"−"}),r.jsx("button",{onClick:S=>{S.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:h?"FILL":"FIT"}),r.jsx("button",{onClick:S=>{S.stopPropagation(),f()},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 Nk({waitingLabel:e,waitingHint:t,transportType:s}){return r.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[r.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:r.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),r.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),r.jsx("div",{className:"text-[11px] text-white/40",children:t}),s==="relay"&&r.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function _k(){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 rh(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 qi(e,t){const s=u.useRef(null),n=u.useRef(0);u.useEffect(()=>{if(!_k())return;n.current+=1;const i=s.current;if(!i){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([o,l])=>[o,rh(l)]))}),s.current=t;return}const a=Object.keys({...i,...t}).filter(o=>!Object.is(i[o],t[o]));a.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:a,snapshot:Object.fromEntries(a.map(o=>[o,rh(t[o])]))}),s.current=t})}function Ck({containerRef:e,viewportRef:t,imgRef:s,inputMode:n,setInputMode:i,minZoom:a,zoomRef:o,panXRef:l,panYRef:c,setPanX:d,setPanY:p,setZoom:h,lastWheelTimeRef:m,onAction:g,setLastActionStatus:b,spawnRippleFromNormalized:f,clampPan:v,isMobile:w,mobileFillZoom:x}){const[S,k]=u.useState(null),j=u.useRef(null),y=u.useRef(null),N=u.useRef(null),_=u.useRef(!1),C=u.useRef(null),D=u.useRef(0),T=u.useRef(null),A=u.useRef(1),P=u.useRef({x:0,y:0}),F=u.useRef(!1),J=u.useRef(n),R=u.useRef(g),I=30,E=550,$=18,M=60,O=400,H=12,ae=()=>{if(j.current)return;const te={nx:.5,ny:.5};j.current=te,k(te)};return u.useEffect(()=>{J.current=n,n==="mouse"&&ae()},[n]),u.useEffect(()=>{R.current=g},[g]),u.useEffect(()=>{const te=e.current;if(!te)return;const he=ye=>{if(!s.current)return null;const Te=s.current.getBoundingClientRect();return!Te.width||!Te.height?null:{nx:Math.max(0,Math.min(1,(ye.clientX-Te.left)/Te.width)),ny:Math.max(0,Math.min(1,(ye.clientY-Te.top)/Te.height))}},ke=(ye,Te)=>{if(!s.current)return{dnx:0,dny:0};const le=s.current,Se=le.getBoundingClientRect(),ge=le.naturalWidth||Se.width,G=le.naturalHeight||Se.height,W=ge/G,Z=Se.width/Se.height;let oe,ue;return W>Z?(oe=Se.width,ue=Se.width/W):(ue=Se.height,oe=Se.height*W),{dnx:ye/oe,dny:Te/ue}},Q=(ye,Te,le)=>{if(le<=1.05)return;const Se=-(ye-.5)*100,ge=-(Te-.5)*100,G=v(Se,ge,le);(Math.abs(G.x-l.current)>.1||Math.abs(G.y-c.current)>.1)&&(d(G.x),p(G.y),l.current=G.x,c.current=G.y)},q=ye=>{const Te=t.current;if(Te&&ye.target instanceof Node&&Te.contains(ye.target))ye.preventDefault();else return;if(ye.touches.length===1){const le=ye.touches[0];y.current={x:le.clientX,y:le.clientY,time:Date.now()},N.current={x:le.clientX,y:le.clientY},F.current||(_.current=!1),C.current=setTimeout(()=>{if(!_.current&&!F.current)if(_.current=!0,J.current==="mouse"){const Se=j.current||{nx:.5,ny:.5};b("Right Click"),f(Se.nx,Se.ny,"right"),R.current("input_click",{...Se,button:"right"}).catch(()=>{})}else{const Se=he(le);Se&&(b("Right Click"),f(Se.nx,Se.ny,"right"),R.current("input_click",{...Se,button:"right"}).catch(()=>{}))}},500);return}if(ye.touches.length===2){C.current&&clearTimeout(C.current),_.current=!0,F.current=!0;const le=ye.touches[1].clientX-ye.touches[0].clientX,Se=ye.touches[1].clientY-ye.touches[0].clientY;T.current=Math.sqrt(le*le+Se*Se),A.current=o.current,P.current={x:(ye.touches[0].clientX+ye.touches[1].clientX)/2,y:(ye.touches[0].clientY+ye.touches[1].clientY)/2}}},me=ye=>{const Te=t.current;if(Te&&ye.target instanceof Node&&Te.contains(ye.target)&&ye.preventDefault(),ye.touches.length===1&&N.current){const le=ye.touches[0],Se=le.clientX-N.current.x,ge=le.clientY-N.current.y;if(!_.current&&y.current){const G=le.clientX-y.current.x,W=le.clientY-y.current.y;Math.sqrt(G*G+W*W)>8&&(_.current=!0,C.current&&clearTimeout(C.current))}if(_.current)if(J.current==="mouse"){const G=ke(Se,ge),W=j.current||{nx:.5,ny:.5},Z=Math.max(0,Math.min(1,W.nx+G.dnx)),oe=Math.max(0,Math.min(1,W.ny+G.dny));j.current={nx:Z,ny:oe},k({nx:Z,ny:oe}),b(`Cursor: ${Math.round(Z*100)}%, ${Math.round(oe*100)}%`),Q(Z,oe,o.current);const ue=Date.now();ue-m.current>=30&&(m.current=ue,R.current("input_mouseMoved",{nx:Z,ny:oe}).catch(()=>{}))}else if(o.current>1){const G=t.current;if(G){const W=G.clientWidth,Z=G.clientHeight,oe=l.current+Se/W*100,ue=c.current+ge/Z*100,ce=v(oe,ue,o.current);d(ce.x),p(ce.y),l.current=ce.x,c.current=ce.y}}else{const G=he(le);if(G){const W=Date.now();W-m.current>=40&&(m.current=W,b("Scroll"),R.current("input_wheel",{nx:G.nx,ny:G.ny,deltaX:Math.round(-Se*2.5),deltaY:Math.round(-ge*2.5)}).catch(()=>{}))}}N.current={x:le.clientX,y:le.clientY};return}if(ye.touches.length===2&&T.current!==null){const le=ye.touches[1].clientX-ye.touches[0].clientX,Se=ye.touches[1].clientY-ye.touches[0].clientY,G=Math.sqrt(le*le+Se*Se)/T.current,W=(ye.touches[0].clientX+ye.touches[1].clientX)/2,Z=(ye.touches[0].clientY+ye.touches[1].clientY)/2,oe=W-P.current.x,ue=Z-P.current.y,ce=Math.abs(G-1)>.03;if(J.current==="mouse"){if(ce){const L=Math.max(a,Math.min(5,A.current*G));h(L),o.current=L}else if(Math.abs(oe)>2||Math.abs(ue)>2){const L=j.current||{nx:.5,ny:.5},de=Date.now();de-m.current>=30&&(m.current=de,b("Scroll"),R.current("input_wheel",{nx:L.nx,ny:L.ny,deltaX:Math.round(-oe*3),deltaY:Math.round(-ue*3)}).catch(()=>{}))}}else{const L=Math.max(a,Math.min(5,A.current*G));h(L),o.current=L;const de=t.current;if(de&&L>1){const U=de.clientWidth,ie=de.clientHeight,Y=l.current+oe/U*100,Ae=c.current+ue/ie*100,Ce=v(Y,Ae,L);d(Ce.x),p(Ce.y),l.current=Ce.x,c.current=Ce.y}}P.current={x:W,y:Z}}},we=ye=>{var Te;if(C.current&&clearTimeout(C.current),T.current=null,ye.touches.length===1&&F.current){const le=ye.touches[0];y.current={x:le.clientX,y:le.clientY,time:Date.now()},N.current={x:le.clientX,y:le.clientY},_.current=!0;return}if(ye.touches.length===0){if(F.current){F.current=!1,_.current=!1;return}if(ye.changedTouches.length===1){const le=ye.changedTouches[0],Se=Date.now(),ge=Se-(((Te=y.current)==null?void 0:Te.time)||0),G=y.current?le.clientX-y.current.x:0,W=y.current?le.clientY-y.current.y:0,Z=Math.sqrt(G*G+W*W);if(J.current==="mouse"){if(ge<I||ge>E||Z>$){_.current=!1;return}const oe=j.current||he(le);oe&&(b(`Click: ${Math.round(oe.nx*100)}%, ${Math.round(oe.ny*100)}%`),f(oe.nx,oe.ny,"left"),R.current("input_click",{...oe}).catch(()=>{}))}else{if(_.current){_.current=!1;return}if(ge<M||ge>O||Z>H){_.current=!1;return}const oe=he(le);if(!oe)return;Se-D.current<300?(b("Double tap"),f(oe.nx,oe.ny,"double"),R.current("input_click",{...oe,clickCount:2}).catch(()=>{}),D.current=0):(b(`Tap: ${Math.round(oe.nx*100)}%, ${Math.round(oe.ny*100)}%`),f(oe.nx,oe.ny,"left"),R.current("input_click",{...oe}).catch(()=>{}),D.current=Se)}}_.current=!1}};return te.addEventListener("touchstart",q,{passive:!1}),te.addEventListener("touchmove",me,{passive:!1}),te.addEventListener("touchend",we,{passive:!1}),()=>{te.removeEventListener("touchstart",q),te.removeEventListener("touchmove",me),te.removeEventListener("touchend",we),C.current&&clearTimeout(C.current)}},[e,t,s,a,o,l,c,d,p,h,m,b,f,v]),{cursorPos:S,cursorPosRef:j,handleToggleInputMode:()=>{i(te=>{const he=te==="touch"?"mouse":"touch";return he==="mouse"&&ae(),he})},handleZoomReset:()=>{const te=w?x:1;h(te),o.current=te,d(0),p(0),l.current=0,c.current=0}}}function lg({onAction:e,addLog:t,connState:s,connScreenshot:n,screenshotUsage:i,transportType:a}){const o=u.useRef(null),l=u.useRef(null),c=u.useRef(null),[d,p]=u.useState(null),[h,m]=u.useState(""),[,g]=u.useState(!1),[b,f]=u.useState([]),v=u.useRef(0),[w,x]=u.useState(!1),[S,k]=u.useState(!1),j=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[y,N]=u.useState(j?"mouse":"touch"),[_,C]=u.useState(1),D=u.useRef(!1),[T,A]=u.useState(1),[P,F]=u.useState(0),[J,R]=u.useState(0);qi("RemoteView",{connState:s,hasScreenshot:!!n,inputMode:y,zoom:T,panX:P,panY:J,isMenuOpen:w,isImeOpen:S});const I=u.useRef(0),E=u.useRef(T),$=u.useRef(P),M=u.useRef(J);u.useEffect(()=>{E.current=T},[T]),u.useEffect(()=>{$.current=P},[P]),u.useEffect(()=>{M.current=J},[J]),u.useEffect(()=>{var ge;(ge=o.current)==null||ge.focus()},[]);const O=s==="connected",H=n,ae=O?"Connected. Waiting for first frame...":s==="connecting"?"Connecting to Host...":"Reconnecting to Host...",z=O?"The remote stream is warming up":"Waiting for the remote stream to catch up";u.useEffect(()=>{if(!j||D.current||!H)return;const ge=c.current,G=l.current;if(!ge||!G)return;const W=()=>{const Z=G.clientWidth,oe=G.clientHeight,ue=ge.naturalWidth,ce=ge.naturalHeight;if(!ue||!ce||!Z||!oe)return;const L=Math.min(Z/ue,oe/ce),U=Math.max(Z/ue,oe/ce)/L;U>1.01&&(C(U),A(U),E.current=U),D.current=!0};ge.complete&&ge.naturalWidth?W():ge.addEventListener("load",W,{once:!0})},[H,j]);const X=.5;u.useEffect(()=>{T<=X&&(F(0),R(0))},[T,X]);const te=(ge,G,W)=>{if(W<=X)return{x:0,y:0};const Z=(W-1)/(2*W)*100,oe=(W-1)/(2*W)*100;return{x:Math.max(-Z,Math.min(Z,ge)),y:Math.max(-oe,Math.min(oe,G))}},he=(ge,G)=>{if(!c.current)return null;const W=c.current.getBoundingClientRect();return!W.width||!W.height?null:{nx:Math.max(0,Math.min(1,(ge-W.left)/W.width)),ny:Math.max(0,Math.min(1,(G-W.top)/W.height))}},ke=(ge,G,W)=>{const Z=l.current;if(!Z)return;const oe=Z.getBoundingClientRect(),ue=++v.current;f(ce=>[...ce,{id:ue,x:ge-oe.left,y:G-oe.top,type:W}]),setTimeout(()=>f(ce=>ce.filter(L=>L.id!==ue)),600)},Q=(ge,G,W)=>{const Z=c.current,oe=l.current;if(!Z||!oe)return;const ue=Z.getBoundingClientRect(),ce=oe.getBoundingClientRect(),L=Z.naturalWidth||ue.width,de=Z.naturalHeight||ue.height,U=L/de,ie=ue.width/ue.height;let Y,Ae,Ce,je;U>ie?(Y=ue.width,Ae=ue.width/U,Ce=0,je=(ue.height-Ae)/2):(Ae=ue.height,Y=ue.height*U,Ce=(ue.width-Y)/2,je=0);const qe=ue.left-ce.left+Ce+Y*ge,it=ue.top-ce.top+je+Ae*G,lt=++v.current;f(ft=>[...ft,{id:lt,x:qe,y:it,type:W}]),setTimeout(()=>f(ft=>ft.filter(ct=>ct.id!==lt)),600)},q=async ge=>{var W;const G=he(ge.clientX,ge.clientY);if(G){p(`Click: ${Math.round(G.nx*100)}%, ${Math.round(G.ny*100)}%`),ke(ge.clientX,ge.clientY,"left"),(W=o.current)==null||W.focus();try{const Z=await e("input_click",{nx:G.nx,ny:G.ny});Z!=null&&Z.success||t(`❌ Click failed: ${Z==null?void 0:Z.error}`)}catch(Z){t(`❌ Click error: ${Z.message||Z}`)}}},me=async(ge,G,W,Z=0)=>{try{await e("input_key",{type:W?"char":"keyDown",key:ge,code:G,text:W?ge:void 0,unmodifiedText:W?ge:void 0,modifiers:Z})}catch(oe){t(`❌ Key error: ${oe.message||oe}`)}},we=async ge=>{if(ge.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ge.key)&&ge.preventDefault();let W=0;ge.altKey&&(W|=1),ge.ctrlKey&&(W|=2),ge.metaKey&&(W|=4),ge.shiftKey&&(W|=8),p(`Key: ${ge.key}`),await me(ge.key,ge.code,ge.key.length===1,W)},ye=async ge=>{if(ge.key==="Enter"){if(ge.nativeEvent.isComposing)return;if(h){const G=h;m(""),p(`IME Sent: ${G}`);try{const W=await e("input_type",{text:G});W!=null&&W.success||t(`❌ IME error: ${W==null?void 0:W.error}`)}catch(W){t(`❌ IME error: ${W.message}`)}}else p("Key: Enter"),await me("Enter","Enter",!1)}};u.useEffect(()=>{const ge=o.current;if(!ge)return;const G=W=>{var Z;if((Z=c.current)!=null&&Z.contains(W.target)){W.preventDefault();const oe=Date.now();if(oe-I.current<40)return;I.current=oe;const ue=he(W.clientX,W.clientY);if(!ue)return;p(`Scroll: ${Math.round(W.deltaY)}`),e("input_wheel",{nx:ue.nx,ny:ue.ny,deltaX:Math.round(W.deltaX),deltaY:Math.round(W.deltaY)}).catch(()=>{})}};return ge.addEventListener("wheel",G,{passive:!1}),()=>ge.removeEventListener("wheel",G)},[e]);const{cursorPos:Te,handleToggleInputMode:le,handleZoomReset:Se}=Ck({containerRef:o,viewportRef:l,imgRef:c,inputMode:y,setInputMode:N,minZoom:X,zoomRef:E,panXRef:$,panYRef:M,setPanX:F,setPanY:R,setZoom:A,lastWheelTimeRef:I,onAction:e,setLastActionStatus:p,spawnRippleFromNormalized:Q,clampPan:te,isMobile:j,mobileFillZoom:_});return r.jsxs("div",{ref:o,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:we,onContextMenu:ge=>ge.preventDefault(),onFocus:()=>g(!0),onBlur:()=>g(!1),tabIndex:0,children:[r.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[H?r.jsx("img",{ref:c,src:H,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${T}) translate(${P}%, ${J}%)`,transformOrigin:"center center",cursor:y==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:q,onContextMenu:ge=>ge.preventDefault(),onDragStart:ge=>ge.preventDefault()}):r.jsx(Nk,{waitingLabel:ae,waitingHint:z,transportType:a}),y==="mouse"&&H&&r.jsx(kk,{cursorPos:Te,viewportRef:l,imgRef:c}),b.map(ge=>{const W={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ge.type];return r.jsxs("div",{style:{position:"absolute",left:ge.x,top:ge.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[r.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${W}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),r.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${W}, 0.9)`,boxShadow:`0 0 12px rgba(${W}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ge.id)})]}),r.jsx(jk,{inputMode:y,onToggleInputMode:le,isImeOpen:S,setIsImeOpen:k,isMenuOpen:w,setIsMenuOpen:x,imeText:h,setImeText:m,handleImeSubmit:ye,isConnActive:O,zoom:T,isMobile:j,mobileFillZoom:_,onZoomOut:()=>A(ge=>Math.max(.5,ge-.25)),onZoomReset:Se,onZoomIn:()=>A(ge=>Math.min(5,ge+.25)),transportType:a,screenshotUsage:i,lastActionStatus:d}),r.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 nh(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.promptId!="string"||!t.promptId.trim()||typeof t.providerType!="string"||!t.providerType.trim()||!Array.isArray(t.questions)||t.questions.length===0?null:t}function Ik(e){var t;return nh(e.activeInteractivePrompt)||nh((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function Ak(e){return e.sessionId||e.instanceId||e.id}function Tk(e,t){const s=typeof t=="string"?t.trim():"";for(const n of e){const i=Ik(n);if(!i)continue;const a=Ak(n);if(s&&s!==a&&s!==n.id)continue;return{daemonId:n.daemonId||n.id.split(":")[0]||n.id,sessionId:a,routeId:n.id,providerType:n.type,title:n.title||n.cliName||n.type,prompt:i}}return null}function cg(e,t){var n;const s={};for(const i of e.questions){const a=t[i.questionId]||{},o=Array.from(new Set((a.selectedLabels||[]).map(c=>c.trim()).filter(Boolean))),l=(n=a.freeformText)==null?void 0:n.trim();s[i.questionId]={selectedLabels:o,...l?{freeformText:l}:{}}}return{promptId:e.promptId,answers:s}}function ih(e){const t={};for(const s of(e==null?void 0:e.prompt.questions)||[])t[s.questionId]={selectedLabels:[],freeformText:""};return t}function ah(e,t){var s,n;return!!((s=t==null?void 0:t.freeformText)!=null&&s.trim())||(((n=t==null?void 0:t.selectedLabels)==null?void 0:n.length)||0)>0||e.options.length===0&&e.allowFreeform}function Mk({label:e,description:t,selected:s,multiSelect:n,disabled:i,onClick:a}){return r.jsx("button",{type:"button",disabled:i,role:n?"checkbox":"radio","aria-checked":s,onClick:a,className:`w-full text-left rounded-md border px-3 py-2 transition ${s?"border-accent-primary bg-accent-primary/15 text-text-primary":"border-border-primary bg-surface-secondary text-text-secondary hover:bg-surface-tertiary hover:text-text-primary"} ${i?"cursor-not-allowed opacity-60":""}`,children:r.jsxs("span",{className:"flex items-start gap-2",children:[r.jsx("span",{className:`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center border ${n?"rounded-sm":"rounded-full"} ${s?"border-accent-primary bg-accent-primary text-accent-on-primary":"border-border-secondary"}`,children:s?r.jsx(Zf,{size:12}):null}),r.jsxs("span",{className:"min-w-0",children:[r.jsx("span",{className:"block text-sm font-semibold leading-5",children:e}),t&&r.jsx("span",{className:"mt-0.5 block text-xs leading-5 text-text-muted",children:t})]})]})})}function dg({promptSession:e,isSubmitting:t=!1,error:s,onSubmit:n,onCancel:i}){var N;const[a,o]=u.useState(()=>ih(e)),[l,c]=u.useState(0);u.useEffect(()=>{o(ih(e)),c(0)},[e==null?void 0:e.prompt.promptId]);const d=(e==null?void 0:e.prompt.questions)||[],p=d.length,h=l===p-1,m=p===1,g=d[l],b=g?a[g.questionId]:void 0,f=g?ah(g,b):!1,v=u.useMemo(()=>e?e.prompt.questions.every(_=>ah(_,a[_.questionId])):!1,[e,a]);if(!e)return null;const w=(_,C)=>{o(D=>{const T=D[_.questionId]||{selectedLabels:[]},A=T.selectedLabels||[],P=_.multiSelect?A.includes(C)?A.filter(F=>F!==C):[...A,C]:[C];return{...D,[_.questionId]:{...T,selectedLabels:P}}})},x=(_,C)=>{o(D=>({...D,[_]:{...D[_]||{selectedLabels:[]},freeformText:C}}))},S=()=>{l<p-1&&c(_=>_+1)},k=()=>{l>0&&c(_=>_-1)},j=()=>{!v||t||n(a)},y=cg(e.prompt,a);return r.jsx("div",{className:"fixed inset-0 z-[80] flex items-center justify-center bg-black/50 px-4 py-6",children:r.jsxs("div",{className:"w-full max-w-2xl overflow-hidden rounded-lg border border-border-primary bg-surface-primary shadow-2xl",children:[r.jsxs("div",{className:"flex items-start justify-between gap-4 border-b border-border-primary px-5 py-4",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-normal text-status-warning",children:[r.jsx(yn,{size:15})," Action Required"]}),r.jsx("h2",{className:"mt-1 text-lg font-bold text-text-primary",children:e.title||e.providerType})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[!m&&r.jsxs("span",{className:"text-xs text-text-muted",children:[l+1," / ",p]}),r.jsx("button",{type:"button",onClick:i,className:"btn btn-ghost btn-sm h-8 w-8 p-0","aria-label":"Cancel interactive prompt",children:r.jsx(Ot,{size:16})})]})]}),!m&&r.jsx("div",{className:"flex gap-1.5 px-5 pt-3",children:d.map((_,C)=>r.jsx("div",{className:`h-1.5 flex-1 rounded-full transition-colors ${C<l?"bg-accent-primary":C===l?"bg-accent-primary/60":"bg-border-primary"}`},_.questionId))}),r.jsxs("div",{className:"space-y-4 px-5 py-4",children:[g&&r.jsxs("section",{className:"space-y-3",children:[r.jsxs("div",{children:[g.header&&r.jsx("div",{className:"mb-1 text-xs font-semibold uppercase tracking-normal text-text-muted",children:g.header}),r.jsxs("div",{className:"text-sm font-semibold text-text-primary",children:[m?"":`${l+1}. `,g.question]}),g.multiSelect&&g.options.length>0&&r.jsx("div",{className:"mt-0.5 text-xs text-text-muted",children:"Select all that apply"})]}),r.jsx("div",{className:"grid gap-2",role:g.multiSelect?"group":"radiogroup","aria-label":g.question,children:g.options.map(_=>{var C;return r.jsx(Mk,{label:_.label,description:_.description||_.preview,selected:(((C=y.answers[g.questionId])==null?void 0:C.selectedLabels)||[]).includes(_.label),multiSelect:g.multiSelect,disabled:t,onClick:()=>w(g,_.label)},_.label)})}),g.allowFreeform&&r.jsxs("label",{className:"block",children:[r.jsx("span",{className:"mb-1 block text-xs font-semibold text-text-muted",children:"Other"}),r.jsx("textarea",{value:((N=a[g.questionId])==null?void 0:N.freeformText)||"",disabled:t,onChange:_=>x(g.questionId,_.currentTarget.value),className:"w-full min-h-20 rounded-md border border-border-primary bg-surface-secondary px-3 py-2 text-sm text-text-primary outline-none focus:border-accent-primary"})]})]}),s&&r.jsx("div",{className:"rounded-md border border-status-error/30 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:s})]}),r.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-border-primary px-5 py-4",children:[r.jsx("div",{children:!m&&l>0&&r.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:k,disabled:t,children:"Back"})}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:i,disabled:t,children:"Cancel"}),m||h?r.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:j,disabled:!v||t,children:t?"Submitting...":"Submit"}):r.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:S,disabled:!f||t,children:"Next"})]})]})]})})}function al(e,t={}){if(!e)return"";const{suffix:s="",nowLabel:n="now",nowThreshold:i=60}=t,a=Date.now()-e,o=Math.floor(a/1e3);if(o<i)return n;const l=Math.floor(o/60);if(l<60)return`${l}m${s}`;const c=Math.floor(l/60);if(c<24)return`${c}h${s}`;const d=Math.floor(c/24);return d<7?`${d}d${s}`:new Date(e).toLocaleDateString()}const ug=e=>al(e);function Ek(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 An(e){const t=e.connectionState==="failed"||e.connectionState==="closed",s=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating"||e.status==="long_generating"||e.status==="streaming",i=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:s,isGenerating:n,isWaiting:i}}function Rk(e){const t=new Map,s=(n,i)=>{n&&t.set(n,{sessionId:n,...Ek(i)})};for(const n of e)if(n.type!=="adhdev-daemon"){s(n.sessionId,n);for(const i of n.childSessions||[])s(i.id,i)}return t}function yo(e,t){if(e.sessionId){const s=t.get(e.sessionId);if(s)return s}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,completionMarker:"",seenCompletionMarker:""}}function ol(e,t,s){const n=yo(e,t),i=An(e),a=i.isReconnecting,o=i.isConnecting,l=i.isGenerating,c=i.isWaiting,d=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||c,p=n.inboxBucket==="working"||l,m=!!(n.inboxBucket==="task_complete"&&n.unread&&!(s!=null&&s.hideOpenTaskCompleteUnread&&(s!=null&&s.isOpenConversation)));return{unread:m,requiresAction:d,isWorking:p,isReconnecting:a,isConnecting:o,isGenerating:l,isWaiting:c,inboxBucket:d?"needs_attention":p?"working":m?"task_complete":"idle"}}function Pk(e,t,s){return ol(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:s==null?void 0:s.isOpenConversation}).unread}function pg({activeConv:e,onModalButton:t}){const[s,n]=u.useState(null);if(u.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!An(e).isWaiting||!e.modalButtons)return null;const a=l=>{s||(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 r.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&&r.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)}),r.jsxs("div",{className:"flex justify-between items-center",children:[r.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[r.jsx(yn,{size:14})," ",s?"PROCESSING...":"ACTION REQUIRED"]}),r.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,c)=>{const d=o(l).toLowerCase(),p=/^(run|approve|accept|yes|allow|always)/.test(d),h=/^(reject|deny|delete|remove|abort)/.test(d),m=s===l,g=s!==null;return r.jsx("button",{onClick:()=>a(l),disabled:g,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${p?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${g&&!m?"opacity-40":"opacity-100"} ${g?"cursor-not-allowed":"cursor-pointer"}`,style:p?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:h?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:m?"⏳ ...":o(l)},c)})})]})]})}const Qd="adhdev_controls_bar_visible",Yc="adhdev:controlsbarvisibilitychange";function Wl(e){if(!e)return!1;try{return e.getItem(Qd)==="1"}catch{return!1}}function Dk(e,t){if(t)try{t.setItem(Qd,e?"1":"0")}catch{}}function Lk(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Yc,{detail:{visible:e}}))}function Jd(){const[e,t]=u.useState(()=>typeof window>"u"?!1:Wl(window.localStorage)),s=u.useRef(e),n=u.useCallback((o,l=!0)=>{s.current=o,t(o),typeof window<"u"&&Dk(o,window.localStorage),l&&Lk(o)},[]);u.useEffect(()=>{const o=c=>{const d=c.detail,p=typeof(d==null?void 0:d.visible)=="boolean"?d.visible:Wl(window.localStorage);s.current=p,t(p)},l=c=>{if(c.key!==Qd)return;const d=Wl(window.localStorage);s.current=d,t(d)};return window.addEventListener(Yc,o),window.addEventListener("storage",l),()=>{window.removeEventListener(Yc,o),window.removeEventListener("storage",l)}},[]);const i=u.useCallback(o=>{n(o)},[n]),a=u.useCallback(()=>{n(!s.current)},[n]);return{isVisible:e,setVisibility:i,toggleVisibility:a}}var $k=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Ok(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function us(e,t){if(Ok(t==null?void 0:t.activeModal))return"waiting_approval";const s=String(e||"idle").trim().toLowerCase();return s==="waiting_approval"?"waiting_approval":s==="waiting_choice"?"waiting_choice":$k.has(s)?"generating":s==="error"?"error":s==="stopped"?"stopped":s==="starting"?"starting":s==="panel_hidden"?"panel_hidden":s==="not_monitored"?"not_monitored":s==="disconnected"?"disconnected":"idle"}function Qc(e){return us(e)==="generating"}function oh(e,t){return us(e,t)==="waiting_approval"}function Vt(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Fk(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const s=Math.floor(t/60),n=t%60;if(s<24)return n>0?`${s}h ${n}m`:`${s}h`;const i=Math.floor(s/24),a=s%24;return`${i}d ${a}h`}function Ul(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function hg(e,t){const s=typeof t=="string"?t.trim():"";if(s)return s;const n=typeof e=="string"?e.trim():"";if(!n)return"";const i=n.replace(/[\\/]+$/,""),a=i.split(/[\\/]/).filter(Boolean);return a[a.length-1]||i}function Bk(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const t=e.split("_"),s=t[t.length-1];return s.length>12?`Machine-${s.substring(0,8)}`:s}return e}function Wk(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Uk(e){return Bk(e.trim().replace(/\.local$/i,""))}function Hk(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function mg(e,t={}){var i,a;const s=[e.hostname,(i=e.machine)==null?void 0:i.hostname,(a=e.system)==null?void 0:a.hostname].find(o=>typeof o=="string"&&o.trim().length>0&&!Wk(o));if(s&&s!=="Unknown")return Uk(s);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function hs(e,t={}){return Hk(e)||mg(e,t)}function fg(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 gg(e,t,s={}){const n=String(t).trim();if(!e||!Array.isArray(e.items)||!n)return"";const i=e.items.find(a=>String((a==null?void 0:a.id)||"").trim()===n);return i?String(s.preferShortValue?i.shortValue||i.value||"":i.value||i.shortValue||"").trim():""}function $r(e,t){return fg(e).join(" · ")}function Ni(e){return e.transport==="pty"}function un(e){return e.transport==="acp"}function zk(e,t){var s,n;return(s=t==null?void 0:t.providerLabels)!=null&&s[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:Vt(e)}function lh(e,t,s){const n=(e||"").trim().toLowerCase();if(!n)return!0;const i=(t||"").trim().toLowerCase(),a=(s||"").trim().toLowerCase(),o=Vt(s||"").trim().toLowerCase();return n===i||n===a||n===o}function Kk(e,t=[],s=[]){var c,d,p,h;const n=us(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(n==="waiting_approval")return"waiting_approval";if(n==="waiting_choice")return"waiting_choice";if(n==="generating")return"generating";const i=t.find(m=>oh(m.status,{activeModal:m.activeModal})||Qc(m.status));if(i)return us(i.status,{activeModal:i.activeModal});const a=s.find(m=>oh(m.status,{activeModal:m.activeModal})||Qc(m.status));if(a)return us(a.status,{activeModal:a.activeModal});if(n&&n!=="idle")return n;const o=us((c=t[0])==null?void 0:c.status,{activeModal:(d=t[0])==null?void 0:d.activeModal});if(o!=="idle")return o;const l=us((p=s[0])==null?void 0:p.status,{activeModal:(h=s[0])==null?void 0:h.activeModal});return l!=="idle"?l:"idle"}function Gk(e){return us(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function qk(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,s=["generating","waiting_approval","waiting_choice","connected","idle","panel_hidden"];for(const n of e){const i=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),a=t.get(i),o=us(n.status);if(!a){t.set(i,{...n,status:o});continue}const l=s.indexOf(a.status||"idle"),c=s.indexOf(o||"idle");c>=0&&(l<0||c<l)&&t.set(i,{...n,status:o})}return Array.from(t.values())}function Vk(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 Xk(e){var s,n;const t=(n=(s=e==null?void 0:e.messages)==null?void 0:s.at)==null?void 0:n.call(s,-1);return t&&Vk(t.receivedAt)||0}function Yk(e){return(e.recentLaunches||[]).reduce((s,n)=>Math.max(s,n.lastLaunchedAt||0),0)}function Jc(e){return Math.max(Yk(e),Xk(e.activeChat))}function Qk(e,t,s,n,i,a){const o=t-e;if(o!==0)return o;const l=s.localeCompare(n);return l!==0?l:i.localeCompare(a)}function Zd(e,t){return Qk(Jc(e),Jc(t),hs(e,{fallbackId:e.id}),hs(t,{fallbackId:t.id}),e.id,t.id)}const xg="adhdev_notification_prefs",ch={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Jk(){try{const e=localStorage.getItem(xg);if(e){const t=JSON.parse(e);return{...ch,...t}}}catch{}return{...ch}}function Zk(e){try{localStorage.setItem(xg,JSON.stringify(e))}catch{}}let Ks=Jk(),Ya=[];function ej(){Ya.forEach(e=>e())}function tj(e){Ks={...Ks,...e},Zk(Ks),ej()}function sj(){const[,e]=u.useState(0);u.useEffect(()=>{const s=()=>e(n=>n+1);return Ya.push(s),()=>{Ya=Ya.filter(n=>n!==s)}},[]);const t=u.useCallback(s=>{tj(s)},[]);return[{...Ks},t]}function oi(e){if(!Ks.globalEnabled)return!1;switch(e){case"disconnect":return Ks.disconnectAlert;case"completion":return Ks.completionAlert;case"approval":return Ks.approvalAlert;case"browser":return Ks.browserNotifications;default:return!0}}const rj={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function bg(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function yg(){return"Notification"in window&&Notification.permission==="granted"}let br=null;function nj(e){return e!==!1}async function ij(){if(br!==null)return br;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return br=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(br=!!await e.pushManager.getSubscription(),br):(br=!1,!1)}catch{return br=!1,!1}}function Zc(e,t,s){if(yg())try{const n=new Notification(e,{body:t,icon:"/otter-logo.png",tag:s||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function aj(e,t={}){const s={...rj,...t},n=u.useRef(new Map),i=u.useRef(0),[a,o]=u.useState(null);u.useEffect(()=>{let c=!1;return ij().then(d=>{c||o(d)}),()=>{c=!0}},[]);const l=u.useCallback((c,d,p)=>{const h=Date.now();h-i.current<s.throttleMs||(i.current=h,Zc(c,d,p))},[s.throttleMs]);u.useEffect(()=>{var c;if(!(!s.enabled||!yg())&&oi("browser")&&!nj(a)){if(document.hasFocus()){for(const d of e)n.current.set(d.id,us(d.status,{activeModal:d.activeModal}));return}for(const d of e){const p=n.current.get(d.id),h=us(d.status,{activeModal:d.activeModal}),m=d.name||d.id;if(s.onApproval&&oi("approval")&&h==="waiting_approval"&&p!=="waiting_approval"){const g=((c=d.activeModal)==null?void 0:c.message)||"Action requires your approval";l(`🔔 ${m} — Approval needed`,g.slice(0,120),`approval-${d.id}`)}s.onComplete&&oi("completion")&&Qc(p)&&h==="idle"&&l(`✅ ${m} — Task complete`,"Agent has finished generating",`complete-${d.id}`),s.onError&&h==="error"&&p!=="error"&&l(`⚠️ ${m} — Error`,"Agent encountered an error",`error-${d.id}`),n.current.set(d.id,h)}}},[e,s.enabled,s.onApproval,s.onComplete,s.onError,a,l])}const oj=/^(run|approve|accept|yes|allow|always)/,lj=/^(run|approve|accept|yes|allow|always|proceed|save)/,cj=/^(reject|deny|delete|remove|abort|cancel|no)/;function eu(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function dj(e){const t=eu(e).toLowerCase();return oj.test(t)?"primary":cj.test(t)?"danger":"default"}function uj(e){return lj.test(eu(e).toLowerCase())?"approve":"reject"}function pj(e){return e.map((t,s)=>({label:eu(t),variant:dj(t),action:uj(t),button:t,buttonIndex:s}))}function hj(e,t,s){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:s}function mj(e,t,s,n){return[{label:"Approve",variant:"primary",onClick:()=>{s(e,t,"approve").catch(i=>n==null?void 0:n("approve",i))}},{label:"Decline",variant:"danger",onClick:()=>{s(e,t,"reject").catch(i=>n==null?void 0:n("reject",i))}}]}class fj{constructor(){re(this,"dedupMap",new Map);re(this,"DEDUP_WINDOW_MS",5e3);re(this,"DEDUP_MAX_SIZE",50);re(this,"DEDUP_CLEANUP_AGE_MS",1e4);re(this,"toastCallbacks",[]);re(this,"statusEventCallbacks",[]);re(this,"resolveActionFn",null);re(this,"viewRequestRespondFn",null);re(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(s=>s!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(s=>s!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const s of this.toastCallbacks)s(t)}showToast(t,s="info",n){const i=(n==null?void 0:n.id)||Date.now();this.emitToast({id:i,message:t,type:s,timestamp:i,duration:5e3,...n})}isDuplicate(t){const s=Date.now(),n=this.dedupMap.get(t)||0;if(s-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,s),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[i,a]of this.dedupMap)s-a>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(i);return!1}resolveOwningDaemon(t){if(t.daemonId){const i=this.ides.find(a=>a.id===t.daemonId&&a.type==="adhdev-daemon");if(i)return i}const s=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(s){const i=s.daemonId;if(i){const a=this.ides.find(o=>o.id===i&&o.type==="adhdev-daemon");if(a)return a}}const n=this.ides.filter(i=>i.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(t){for(const s of this.ides)if(s.id===t||s.sessionId===t||(Array.isArray(s.childSessions)?s.childSessions:[]).some(i=>(i==null?void 0:i.id)===t))return s;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const s=this.findOwningSession(t.targetSessionId);return(s==null?void 0:s.id)||(s==null?void 0:s.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}handleRawEvent(t,s){var b;const n=this.resolveConversationKey(t),i=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),a=n||t.daemonId||"",o=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(i),l=`${a}:${t.event}:${o}`;if(this.isDuplicate(l))return;for(const f of this.statusEventCallbacks)f(t);const c=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,d=(c==null?void 0:c.type)||"";let p=Vt(d);const h=this.resolveOwningDaemon(t);if(h){const f=hs(h,{fallbackId:h.id});f&&(p=!d||d==="adhdev-daemon"?f:`${f}/${p}`)}let m="",g="info";if(t.event==="agent:generating_completed"){const f=t.duration?` (${t.duration}s)`:"";m=`✅ ${p} agent task completed${f}`,g="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=`⚡ ${p} approval needed`,g="warning",(b=t.modalButtons)!=null&&b.length&&this.resolveActionFn){const f=this.resolveActionRouteTarget(t);if(!f)return;const v=this.resolveActionFn,w=pj(t.modalButtons).map(k=>({label:k.label,variant:k.variant,onClick:()=>{v(f,"resolve_action",{action:k.action,button:k.button,buttonIndex:k.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),x=hj(p,t.modalMessage,m),S=Date.now();this.emitToast({id:S,message:x,type:g,timestamp:S,targetKey:n||f,actions:w,duration:15e3}),m=""}}else if(t.event==="monitor:long_generating"){const f=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";m=`⚠️ ${p} agent is taking a long time${f}`,g="warning",oi("browser")&&!document.hasFocus()&&Zc(`⚠️ ${p} — Long Running`,`Agent has been generating for over ${f.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const f=t.requesterName||"A team member",v=t.requestId,w=t.orgId;if(m=`👁️ ${f} wants to view your session`,g="warning",v&&w&&this.viewRequestRespondFn){const x=Date.now(),S=mj(w,v,this.viewRequestRespondFn,(k,j)=>console.error(`[EventManager] ${k} view request failed:`,j));this.emitToast({id:x,message:m,type:g,timestamp:x,actions:S,duration:3e4}),m=""}oi("browser")&&!document.hasFocus()&&Zc("👁️ View Request",`${f} wants to view your session`,`view-request-${v}`)}else t.event==="team:view_request_approved"?(m="✅ View request approved",g="success"):t.event==="team:view_request_rejected"&&(m=`❌ ${t.targetName||"Team member"} declined your view request`,g="warning");if(m){const f=Date.now();this.emitToast({id:f,message:m,type:g,timestamp:f,targetKey:n||t.daemonId,duration:5e3})}}}const ht=new fj,dh=new Map;function vo(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function pn(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function ll(e){return vo(e)?vo(e.result)?e.result:e:null}function gj(e){const t=ll(e);return!t||!vo(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function Na(e){const t=ll(e);return!t||!vo(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function $n(e){const t=ll(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function _a(e){const t=ll(e);return!!t&&t.success===!1}function xj(e){var t,s;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.message)){const i=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";ht.showToast(n.toast.message,i);continue}if(n.type==="notification"&&((s=n.notification)!=null&&s.body)){const i=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";ht.showToast(n.notification.body,i)}}}function bj(e,t){return e&&pn(e.currentValue)?e.currentValue:t}function yj(e,t){return pn(t)?pn(e)?typeof e=="string"&&e.trim()==="":!0:!1}function vj(e,t){var a,o;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(pn(l))return l}const n=(a=t.controlValues)==null?void 0:a[e];if(pn(n))return n;const i=(o=t.defaultValues)==null?void 0:o[e];return pn(i)?i:void 0}function Qa(e,t){return e.options||t[e.id]||[]}const wj={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 Sj(e,t,s){var n;return((n=wj[t])==null?void 0:n.has(s.id))===!0}function tu(e,t){return(e||[]).filter(s=>s.placement==="bar"&&s.hidden!==!0&&!Sj(t.hostIdeType,t.providerType,s)).sort((s,n)=>(s.order??50)-(n.order??50))}function Hl(e,t){return{value:t}}function kj(e,t,s){var i;return s?((i=Qa(e,t).find(a=>a.value===s))==null?void 0:i.label)||s:""}const jj={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Nj({routeId:e,sessionId:t,hostIdeType:s,providerType:n,displayLabel:i,controls:a,controlValues:o}){const{sendCommand:l}=jt(),c=`${e}:${t||n}`,d=jj[n]||"#94a3b8",[p,h]=u.useState({}),m=u.useRef({}),g=u.useRef(o);m.current=p,g.current=o;const b=u.useRef(0),f={};for(const I of a||[])I.defaultValue!==void 0&&(f[I.id]=I.defaultValue);const v={...f,...o||{},...Date.now()<b.current?p:{}};u.useEffect(()=>{o&&Date.now()>b.current&&h({})},[o]);const[w,x]=u.useState(dh.get(c)||{}),[S,k]=u.useState(null),[j,y]=u.useState(null),N=u.useCallback(async(I,E={})=>{const $={...E,...t&&{targetSessionId:t}};return await l(e,I,$)},[e,t,l]),_=u.useCallback(async(I,E={})=>{const $=t?{targetSessionId:t}:{agentType:n,...s?{ideType:s}:{}};return await N("invoke_provider_script",{...$,scriptName:I,...E})},[N,n,s,t]),C=u.useCallback((I,E,$)=>{const M=bj($,E);h(O=>({...O,[I.id]:M})),xj($==null?void 0:$.effects)},[]),D=u.useCallback((I,E)=>{h($=>{const M={...$};return E===void 0?delete M[I.id]:M[I.id]=E,M}),b.current=0},[]);if(!a||a.length===0)return null;const T=tu(a,{hostIdeType:s,providerType:n});if(T.length===0)return null;const A=async I=>{if(S===I.id){k(null);return}if(Qa(I,w).length>0){k(I.id);return}if(I.dynamic&&I.listScript){y(I.id);try{const $=await _(I.listScript,{}),M=gj($);if(!M){const ae=$n($);ae&&ht.showToast(ae,"warning");return}const O=M.options;x(ae=>{const z={...ae,[I.id]:O};return dh.set(c,z),z});const H=vj(I.id,{localOverrideUntil:b.current,localValues:m.current,controlValues:g.current,defaultValues:f});if(yj(H,M.currentValue)){const ae=M.currentValue;h(z=>({...z,[I.id]:ae}))}k(I.id)}catch($){const M=$ instanceof Error?$.message:`Could not load ${I.label}`;ht.showToast(M,"warning")}finally{y(null)}}},P=async(I,E)=>{k(null);const $=(o==null?void 0:o[I.id])??f[I.id];h(M=>({...M,[I.id]:E})),b.current=Date.now()+5e3;try{if(!I.setScript)return;const M=await _(I.setScript,Hl(I,E)),O=Na(M);if(O&&!O.ok||_a(M))throw new Error((O==null?void 0:O.error)||$n(M)||`Could not update ${I.label}`);C(I,E,O)}catch(M){D(I,$);const O=M instanceof Error?M.message:`Could not update ${I.label}`;ht.showToast(O,"warning")}},F=async I=>{const E=Qa(I,w).map(z=>z.value);if(E.length===0)return;const $=String(v[I.id]||""),O=(E.indexOf($)+1)%E.length,H=E[O];if(typeof H!="string")return;const ae=(o==null?void 0:o[I.id])??f[I.id];h(z=>({...z,[I.id]:H})),b.current=Date.now()+5e3;try{if(!I.setScript)return;const z=await _(I.setScript,Hl(I,H)),X=Na(z);if(X&&!X.ok||_a(z))throw new Error((X==null?void 0:X.error)||$n(z)||`Could not update ${I.label}`);C(I,H,X)}catch(z){D(I,ae);const X=z instanceof Error?z.message:`Could not update ${I.label}`;ht.showToast(X,"warning")}},J=async I=>{const $=!v[I.id],M=(o==null?void 0:o[I.id])??f[I.id];h(O=>({...O,[I.id]:$})),b.current=Date.now()+5e3;try{if(!I.setScript)return;const O=await _(I.setScript,Hl(I,$)),H=Na(O);if(H&&!H.ok||_a(O))throw new Error((H==null?void 0:H.error)||$n(O)||`Could not update ${I.label}`);C(I,$,H)}catch(O){D(I,M);const H=O instanceof Error?O.message:`Could not update ${I.label}`;ht.showToast(H,"warning")}},R=async I=>{if(!I.invokeScript)return;if(I.confirmMessage){const $=[I.confirmTitle,I.confirmMessage,I.confirmLabel].filter(O=>typeof O=="string"&&O.trim().length>0);if(!window.confirm($.join(`
|
|
30
|
+
|
|
31
|
+
`)))return}const E=(o==null?void 0:o[I.id])??f[I.id];try{const $=await _(I.invokeScript),M=Na($);if(M&&!M.ok||_a($))throw new Error((M==null?void 0:M.error)||$n($)||`Could not run ${I.label}`);M&&C(I,E??!0,M)}catch($){D(I,E);const M=$ instanceof Error?$.message:`Could not run ${I.label}`;ht.showToast(M,"warning")}};return r.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${d}33`,background:`${d}12`,color:d},children:i}),T.map(I=>{const E=String(v[I.id]||""),$=kj(I,w,E),M=S===I.id,O=j===I.id,H=Qa(I,w),ae="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(I.type){case"select":return r.jsxs("div",{className:"relative max-w-full",children:[r.jsxs("button",{type:"button",className:`${ae} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:M?`${d}55`:"var(--border-default)",background:M?`${d}10`:"var(--surface-tertiary)",color:E?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void A(I),title:I.label,children:[I.icon&&r.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),r.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:O?"Loading…":$||I.label}),r.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),M&&H.length>0&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>k(null)}),r.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:[r.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:I.label}),H.map(z=>r.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:z.value===E?`${d}14`:"transparent",color:z.value===E?"var(--text-primary)":"var(--text-secondary)",borderLeft:z.value===E?`2px solid ${d}`:"2px solid transparent"},title:z.description||z.label,onMouseEnter:X=>{X.currentTarget.style.background=`${d}10`},onMouseLeave:X=>{X.currentTarget.style.background=z.value===E?`${d}14`:"transparent"},onClick:()=>void P(I,z.value),children:[r.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:z.label}),z.value===E&&r.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:d},children:"✓"})]},z.value))]})]})]},I.id);case"cycle":return r.jsxs("button",{type:"button",className:`${ae} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:E?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void F(I),title:`Click to cycle: ${H.map(z=>z.label).join(" → ")}`,children:[I.icon&&r.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),r.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:$||I.label}),r.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},I.id);case"toggle":return r.jsxs("button",{type:"button",className:`${ae} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:E?`${d}44`:"var(--border-default)",background:E?`${d}14`:"var(--surface-tertiary)",color:E?d:"var(--text-muted)"},onClick:()=>void J(I),"aria-pressed":!!E,children:[I.icon&&r.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),I.label]},I.id);case"action":return r.jsxs("button",{type:"button",className:`${ae} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void R(I),children:[I.icon&&r.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),r.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:I.resultDisplay==="inline"&&E?`${I.label}: ${E}`:I.label})]},I.id);case"display":return r.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:E?"var(--text-primary)":"var(--text-muted)"},children:[I.icon&&r.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),r.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:E?`${I.label}: ${E}`:I.label})]},I.id);default:return null}})]})})}function _j({isActive:e=!0,isCliTerminal:t=!1,routeId:s,sessionId:n,hostIdeType:i,providerType:a,displayLabel:o,controls:l,controlValues:c}){const{isVisible:d}=Jd(),p=tu(l,{hostIdeType:i,providerType:a});return!e||t||p.length===0||!d?null:r.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:r.jsx(Nj,{routeId:s,sessionId:n,hostIdeType:i,providerType:a,displayLabel:o,controls:p,controlValues:c})})}const On=5,vg=10*1024*1024;function Cj({hasDraft:e,isBusy:t=!1}){return!e||t}function Ij(e){return new Promise((t,s)=>{const n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>s(new Error("Failed to read file")),n.readAsDataURL(e)})}async function Aj(e){if(e.size>vg)return null;const t=await Ij(e),s=t.indexOf(",");if(s<0)return null;const n=t.slice(s+1);return{mimeType:e.type||"image/png",data:n,name:e.name,previewUrl:t}}function Tj(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const wg=u.memo(function({contextKey:t,panelLabel:s,isSending:n,isBusy:i=!1,statusMessage:a=null,onSend:o,onForceSend:l,canForceSend:c=!1,isActive:d=!0,showControlsToggle:p=!1,animateVisibility:h=!0,onControlsToggle:m,messageInput:g}){const b=u.useRef(null),f=u.useRef(null),[v,w]=u.useState(""),[x,S]=u.useState([]),[k,j]=u.useState(null),[y,N]=u.useState(!1),_=u.useRef(!1),{isVisible:C,toggleVisibility:D}=Jd(),T=Tj(g),A=!!v.trim()||x.length>0;u.useEffect(()=>{w(""),S([]),j(null)},[t]),u.useEffect(()=>{var M;d&&((M=b.current)==null||M.focus({preventScroll:!0}))},[t,d]),u.useEffect(()=>{const M=b.current;M&&(M.style.height="auto",M.style.height=`${Math.min(M.scrollHeight,160)}px`)},[v]);const P=u.useCallback(async M=>{j(null);const O=Array.from(M).filter(he=>he.type.startsWith("image/"));if(O.length===0)return;const H=On-x.length;if(H<=0){j(`Max ${On} images`);return}const ae=O.slice(0,H);if(ae.filter(he=>he.size>vg).length>0){j("Image too large (max 10 MB)");return}const te=(await Promise.all(ae.map(Aj))).filter(he=>he!==null);S(he=>[...he,...te])},[x.length]),F=u.useCallback(M=>{S(O=>O.filter((H,ae)=>ae!==M))},[]),J=u.useCallback(async()=>{const M=v.trim();if(!M&&x.length===0||i||_.current)return;_.current=!0;const O=x.length>0?[...x]:void 0;try{await o(M,O)!==!1&&(w(""),S([]),j(null))}finally{_.current=!1}},[v,x,i,o]),R=u.useCallback(async()=>{if(!c||!l)return;const M=v.trim();if(!M&&x.length===0||_.current)return;_.current=!0;const O=x.length>0?[...x]:void 0;try{await l(M,O)!==!1&&(w(""),S([]),j(null))}finally{_.current=!1}},[x,c,v,l]),I=u.useCallback(M=>{T&&(M.preventDefault(),N(!0))},[T]),E=u.useCallback(()=>N(!1),[]),$=u.useCallback(M=>{T&&(M.preventDefault(),N(!1),M.dataTransfer.files.length>0&&P(M.dataTransfer.files))},[T,P]);return r.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",h?"transition-all duration-200 ease-out":"",y?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:d?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:d?200:0,opacity:d?1:0,transform:d?"translateY(0)":"translateY(10px)",padding:d?"10px 12px":"0 12px",pointerEvents:d?"auto":"none"},"aria-hidden":!d,onDragOver:I,onDragLeave:E,onDrop:$,children:[x.length>0&&r.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:x.map((M,O)=>r.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:[r.jsx("img",{src:M.previewUrl,alt:M.name,className:"w-full h-full object-cover"}),r.jsx("button",{type:"button",onClick:()=>F(O),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 ${M.name}`,children:"✕"})]},O))}),r.jsxs("div",{className:"flex gap-2 items-center",title:d?`Send message to ${s}`:void 0,children:[p&&r.jsx("button",{type:"button",onClick:()=>{D(),m==null||m()},"aria-label":C?"Hide controls":"Show controls","aria-pressed":C,title:C?"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:r.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[r.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),r.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),r.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),T&&r.jsxs(r.Fragment,{children:[r.jsx("input",{ref:f,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:M=>{M.target.files&&P(M.target.files),M.target.value=""}}),r.jsx("button",{type:"button",onClick:()=>{var M;return(M=f.current)==null?void 0:M.click()},disabled:x.length>=On,title:x.length>=On?`Max ${On} 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:r.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:r.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"})})})]}),r.jsx("div",{className:"flex-1 relative",children:r.jsx("textarea",{ref:b,rows:1,placeholder:a||(T&&x.length>0?"Add a message (optional)...":`Send message to ${s}... (Shift+Enter for newline)`),value:v,onChange:M=>w(M.target.value),onPaste:M=>{T&&M.clipboardData.files.length>0&&Array.from(M.clipboardData.files).some(H=>H.type.startsWith("image/"))&&(M.preventDefault(),P(M.clipboardData.files))},onKeyDown:M=>{M.key==="Enter"&&(M.nativeEvent.isComposing||M.shiftKey||(M.preventDefault(),J()))},className:"w-full rounded-[20px] px-4 py-2 bg-bg-secondary text-sm text-text-primary resize-none leading-[1.4] block",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))",minHeight:40,maxHeight:160,overflowY:"auto",whiteSpace:"pre-wrap"}})}),r.jsx("button",{onClick:()=>{J()},disabled:Cj({hasDraft:A,isBusy:i}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${A&&!i?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:A&&!i?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":"Send message",children:r.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:A?"text-white":"text-text-muted",children:r.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})}),c&&r.jsx("button",{type:"button",onClick:()=>{R()},disabled:!A,className:`h-10 px-3 rounded-full text-[11px] font-medium border border-border-subtle shrink-0 transition-colors ${A?"bg-bg-secondary text-text-primary hover:bg-[var(--surface-tertiary)]":"bg-bg-secondary text-text-muted cursor-default opacity-60"}`,"aria-label":"Force send message now",title:"Force send message now",children:"Force"})]}),(k||T&&y)&&r.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${k?"text-red-400":"text-[var(--accent-primary)]"}`,children:k||"Drop image here"}),a&&!k&&r.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:a})]})}),Mj=u.createContext(null);function su(){return u.useContext(Mj)}function xt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ie(...e){for(const t of e){if(typeof t!="string")continue;const s=t.trim();if(s)return s}}function ns(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function Zt(...e){for(const t of e)if(typeof t=="boolean")return t}function zl(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function Ej(e,t){const s=typeof e=="string"?e.trim().replace(/[\\/]+$/,""):"",n=typeof t=="string"?t.trim():"";if(n){if(/^(?:[A-Za-z]:[\\/]|\/)/.test(n))return n;if(s)return`${s}/${n.replace(/^[\\/]+/,"")}`}}function ru(e){switch(e){case"fresh":return 30;case"no_upstream":return 4;case"unchecked":case void 0:return 0;case"stale":return-10;case"unavailable":return-15;default:return 0}}function Rj(e,t){if(!Array.isArray(e))return;const s=e.map(n=>{const i=xt(n),a=Ie(i.path),o=Ie(i.commit),l=Ie(i.repoPath,i.repo_root)??Ej(t,a);if(!a||!o)return null;const c={path:a,commit:o,dirty:Zt(i.dirty)??!1,outOfSync:Zt(i.outOfSync,i.out_of_sync)??!1,lastCheckedAt:ns(i.lastCheckedAt,i.last_checked_at)??Date.now()};l&&(c.repoPath=l);const d=Ie(i.error);return d&&(c.error=d),c}).filter(n=>n!==null);return s.length>0?s:void 0}function Pj(e){return Zt(e.isGitRepo)!==void 0||!!Ie(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||!!Ie(e.repoRoot,e.repo_root,e.workspace)||ns(e.ahead,e.behind,e.staged,e.modified,e.untracked,e.deleted,e.renamed,e.lastCheckedAt,e.last_checked_at)!==void 0||Array.isArray(e.submodules)&&e.submodules.length>0}function Ja(e,t,s){const n=Zt(e.isGitRepo);if(!Object.keys(e).length||!Pj(e))return;const i=n??!0,a=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(S=>typeof S=="string"):[],o=ns(e.conflicts)??a.length,l=Zt(e.hasConflicts)??o>0,c=Ie(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,d=Rj(e.submodules,c),p=Ie(e.upstreamStatus,e.upstream_status),h=ns(e.upstreamFetchedAt,e.upstream_fetched_at),m=Ie(e.upstreamFetchError,e.upstream_fetch_error),g=Ie(e.error),b=ns(e.staged)??0,f=ns(e.modified)??0,v=ns(e.untracked)??0,w=ns(e.deleted)??0,x=ns(e.renamed)??0;return{workspace:Ie(e.workspace,t.workspace)||"",repoRoot:c??null,isGitRepo:i,branch:Ie(e.branch)??null,headCommit:Ie(e.headCommit)??null,headMessage:Ie(e.headMessage)??null,upstream:Ie(e.upstream)??null,upstreamStatus:p??"unchecked",...h!==void 0?{upstreamFetchedAt:h}:{},...m?{upstreamFetchError:m}:{},ahead:ns(e.ahead)??0,behind:ns(e.behind)??0,staged:b,modified:f,untracked:v,deleted:w,renamed:x,dirty:Zt(e.dirty,e.isDirty,e.is_dirty)??(b+f+v+w+x>0||l),hasConflicts:l,conflictFiles:a,stashCount:ns(e.stashCount,e.stash_count)??0,lastCheckedAt:(s==null?void 0:s.lastCheckedAt)??ns(e.lastCheckedAt,e.last_checked_at)??Date.now(),...d?{submodules:d}:{},...g?{error:g}:{}}}function Dj(e){if(!e)return Number.NEGATIVE_INFINITY;let t=0;return e.isGitRepo===!0&&(t+=50),e.isGitRepo===!1&&(t-=10),e.branch&&(t+=20),e.headCommit&&(t+=20),e.upstream&&(t+=10),t+=ru(e.upstreamStatus),typeof e.ahead=="number"&&(t+=2),typeof e.behind=="number"&&(t+=2),Array.isArray(e.submodules)&&e.submodules.length>0&&(t+=4+e.submodules.length),e.error&&(t-=20),t}function Lj(e,t){const s=xt(e.lastGit??e.last_git),n=xt(s.result),i=xt(s.status),a=xt(n.status),o=xt(e.lastProbe??e.last_probe),l=xt(o.git),c=xt(l.result),d=xt(l.status),p=xt(c.status),h=t==null?void 0:t.lastCheckedAt;let m=null;for(const g of[i,a,d,p]){const b=Ja(g,e,{lastCheckedAt:h??Date.now()});if(!b)continue;const f=Dj(b);(!m||f>m.score)&&(m={git:b,score:f})}return m==null?void 0:m.git}function $j(e){const t=[Ie(e.workspace),Ie(e.providerType,e.provider),Ie(e.role),Ie(e.state,e.status),Ie(e.title),Ie(e.createdAt,e.created_at),Ie(e.startedAt,e.started_at)].filter(s=>!!s);if(t.length!==0)return`synthetic:${t.join("|")}`}function ed(e){const t=xt(e),s=Ie(t.sessionId,t.session_id,t.id)??$j(t);return s?{sessionId:s,...Ie(t.providerType,t.provider)?{providerType:Ie(t.providerType,t.provider)}:{},...Ie(t.state,t.status)?{state:Ie(t.state,t.status)}:{},...Ie(t.chatStatus,t.chat_status)?{chatStatus:Ie(t.chatStatus,t.chat_status)}:{},...Ie(t.lifecycle)?{lifecycle:Ie(t.lifecycle)}:{},...Ie(t.surfaceKind,t.surface_kind)?{surfaceKind:Ie(t.surfaceKind,t.surface_kind)}:{},...Ie(t.recoveryState,t.recovery_state)?{recoveryState:Ie(t.recoveryState,t.recovery_state)}:{},...Ie(t.workspace)?{workspace:Ie(t.workspace)}:{},...Ie(t.title)?{title:Ie(t.title)}:{},...Ie(t.role)?{role:Ie(t.role)}:{},...Zt(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:Zt(t.isSelfCoordinator,t.is_self_coordinator)}:{},...Ie(t.statusNote,t.status_note)?{statusNote:Ie(t.statusNote,t.status_note)}:{},...Ie(t.createdAt,t.created_at)?{createdAt:Ie(t.createdAt,t.created_at)}:{},...Ie(t.startedAt,t.started_at)?{startedAt:Ie(t.startedAt,t.started_at)}:{},...Ie(t.lastActivityAt,t.last_activity_at)?{lastActivityAt:Ie(t.lastActivityAt,t.last_activity_at)}:{},...Zt(t.isCached,t.is_cached)!==void 0?{isCached:Zt(t.isCached,t.is_cached)}:{}}:null}function Oj(e){const t=e&&typeof e=="object"?e:{};return Ie(t.id,t.nodeId,t.node_id)}function Fj(e,t){if(!t)return!1;const s=t.trim();return s?Oj(e)===s:!1}function Bj(e){return Lj(e,{lastCheckedAt:Date.now()})}function Wj(e){const t=Array.isArray(e==null?void 0:e.submodules)?e.submodules:[];let s=!1,n=!1;for(const i of t)i!=null&&i.outOfSync&&(n=!0),i!=null&&i.dirty&&(s=!0);return{dirty:s,outOfSync:n}}function Uj(e){return e?(e.staged??0)>0||(e.modified??0)>0||(e.untracked??0)>0||(e.deleted??0)>0||(e.renamed??0)>0||e.hasConflicts===!0:!1}function wo(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=Wj(e);return t.outOfSync?"degraded":t.dirty||Uj(e)?"dirty":"online"}function Hj(e,t){const s=t?wo(t):void 0;return!e||e==="unknown"?s:e}function zj(e){const t=Array.isArray(e.activeSessionDetails)?e.activeSessionDetails:Array.isArray(e.active_session_details)?e.active_session_details:Array.isArray(e.sessions)?e.sessions:null;if(t){const a=t.map(ed).filter(o=>o!==null);if(a.length>0)return a}const s=xt(e.activeSession??e.active_session),n={...s,sessionId:Ie(s.sessionId,s.id,s.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id)},i=ed(n);return i?[i]:void 0}function Kj(e){const t=xt(e.connection);return Object.keys(t).length>0?t:void 0}function Gj(e){const t=e==null?void 0:e.source,s=e==null?void 0:e.transport;return{...e,perspective:(e==null?void 0:e.perspective)??"selected_coordinator",source:t&&t!=="not_reported"?t:"mesh_peer_status",state:"connected",transport:s&&s!=="unknown"?s:"direct",reported:!0,reason:"Live peer git snapshot reported by the selected coordinator."}}function nu(e){var s;const t=e.git;return!!(t&&(t.isGitRepo===!0||t.isGitRepo===!1||t.branch||t.upstream||t.headCommit||typeof t.lastCheckedAt=="number"||(((s=t.submodules)==null?void 0:s.length)??0)>0))}function uh(e){var n,i,a,o,l,c;let t=0;const s=e.git;return nu(e)&&(t+=80,(s==null?void 0:s.isGitRepo)===!0&&(t+=20),(s==null?void 0:s.isGitRepo)===!1&&(t+=5),s!=null&&s.branch&&(t+=20),s!=null&&s.upstream&&(t+=12),s!=null&&s.headCommit&&(t+=12),t+=ru(s==null?void 0:s.upstreamStatus),typeof(s==null?void 0:s.lastCheckedAt)=="number"&&(t+=6),t+=(((n=s==null?void 0:s.submodules)==null?void 0:n.length)??0)*6),(i=e.branchConvergence)!=null&&i.status&&(t+=12),(((a=e.connection)==null?void 0:a.state)==="connected"||((o=e.connection)==null?void 0:o.state)==="self")&&(t+=8),((l=e.connection)==null?void 0:l.transport)==="direct"&&(t+=4),((c=e.connection)==null?void 0:c.source)==="mesh_peer_status"&&(t+=4),e.health==="online"&&(t+=4),e.health==="dirty"&&(t+=3),e.health==="degraded"&&(t+=2),e.launchReady&&(t+=2),e.gitProbePending&&(t-=40),e.error&&(t-=10),t}function qj(e,t){var b,f,v,w;const s=uh(e),i=uh(t)>s?t:e,a=i===t?e:t,o=i.git??a.git,l=(((b=i.providers)==null?void 0:b.length)??0)>0?i.providers:a.providers,c=(((f=i.activeSessions)==null?void 0:f.length)??0)>0?i.activeSessions:a.activeSessions,d=(((v=i.activeSessionDetails)==null?void 0:v.length)??0)>0?i.activeSessionDetails:a.activeSessionDetails,p=(((w=i.providerPriority)==null?void 0:w.length)??0)>0?i.providerPriority:a.providerPriority,h=i.connection??a.connection,m={...a,...i,machineLabel:i.machineLabel||a.machineLabel,workspace:i.workspace||a.workspace,...i.repoRoot||a.repoRoot?{repoRoot:i.repoRoot||a.repoRoot}:{},...i.daemonId||a.daemonId?{daemonId:i.daemonId||a.daemonId}:{},...i.machineId||a.machineId?{machineId:i.machineId||a.machineId}:{},...i.machineStatus||a.machineStatus?{machineStatus:i.machineStatus||a.machineStatus}:{},health:o&&(!i.health||i.health==="unknown")?wo(o):i.health,providers:l??[],activeSessions:c??[],...d&&d.length>0?{activeSessionDetails:d}:{},...p&&p.length>0?{providerPriority:p}:{},...h?{connection:h}:{},...o?{git:o}:{}},g=xt(i.branchConvergence);return Object.keys(g).length>0?Object.assign(m,{branchConvergence:g}):delete m.branchConvergence,o&&(delete m.gitProbePending,delete m.error),m}function Sg(e){const t=xt(e),s=Ie(t.nodeId,t.id);if(!s)return null;const n=xt(t.cachedStatus),i=Bj(t),a=i?void 0:Ja(xt(t.git),t)??Ja(t,t),o=i??a,l=o?void 0:Ja(xt(n.git),t),c=o??l,d=Ie(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),p=Ie(t.health),h=i?wo(c):Hj(p,o)||(c?wo(c):void 0)||Ie(n.health)||d||Ie(t.status)||"unknown",g=(i?void 0:Ie(t.error))??(o?void 0:Ie(n.error)),b=zj(t),f=zl(t.activeSessions),v=(b==null?void 0:b.map(_=>_.sessionId))??[],w=zl(t.providerPriority),x=Zt(t.gitProbePending,t.git_probe_pending),S=o?void 0:x,k=Kj(t),j=xt(t.branchConvergence??t.branch_convergence),y=k==null?void 0:k.state,N=i&&(!(k!=null&&k.reported)||y==="unknown")?Gj(k):k;return{nodeId:s,machineLabel:Ie(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,s)||s,workspace:Ie(t.workspace,c==null?void 0:c.workspace)||"",...Ie(t.repoRoot,t.repo_root,c==null?void 0:c.repoRoot)?{repoRoot:Ie(t.repoRoot,t.repo_root,c==null?void 0:c.repoRoot)}:{},...Ie(t.daemonId,t.daemon_id)?{daemonId:Ie(t.daemonId,t.daemon_id)}:{},...Ie(t.machineId,t.machine_id)?{machineId:Ie(t.machineId,t.machine_id)}:{},...d?{machineStatus:d}:{},...Zt(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Zt(t.isLocalWorktree,t.is_local_worktree)}:{},...Ie(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:Ie(t.worktreeBranch,t.worktree_branch)}:{},...Ie(t.clonedFromNodeId,t.cloned_from_node_id)?{clonedFromNodeId:Ie(t.clonedFromNodeId,t.cloned_from_node_id)}:{},health:h,...c?{git:c}:{},...S!==void 0?{gitProbePending:S}:{},providers:zl(t.providers),activeSessions:f.length>0?f:v,...b&&b.length>0?{activeSessionDetails:b}:{},...w.length>0?{providerPriority:w}:{},...Zt(t.launchReady)!==void 0?{launchReady:Zt(t.launchReady)}:i?{launchReady:!0}:{},...Ie(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:Ie(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},...Ie(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:Ie(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...N?{connection:N}:{},...Object.keys(j).length>0?{branchConvergence:j}:{},...g?{error:g}:{}}}function ph(e){const t=new Map;for(const s of e){const n=t.get(s.sessionId);t.set(s.sessionId,n?{...n,...s}:s)}return[...t.values()]}function kg(e,t){const s=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],n=s.map(ed).filter(i=>i!==null);return n.length===0?t:t.map(i=>{const a=n.filter(l=>{const c=xt(s.find(m=>{const g=xt(m);return Ie(g.sessionId,g.session_id,g.id)===l.sessionId})),d=Ie(c.nodeId,c.node_id),p=Ie(c.daemonId,c.daemon_id),h=Ie(c.workspace);return d&&d===i.nodeId?!0:p&&i.daemonId&&p===i.daemonId?!h||!i.workspace||h===i.workspace:!!(h&&i.workspace&&h===i.workspace)});if(a.length===0)return i;const o=ph([...i.activeSessionDetails??[],...a]);return{...i,activeSessionDetails:o,activeSessions:ph([...i.activeSessionDetails??[],...a,...(i.activeSessions??[]).map(l=>({sessionId:l}))]).map(l=>l.sessionId)}})}function Vj(e){const t=xt(e);return Array.isArray(t.sessions)||Array.isArray(t.active_session_details)||Ie(t.daemon_id,t.machine_id,t.repo_root,t.worktree_branch,t.cloned_from_node_id)!==void 0||Zt(t.is_local_worktree)!==void 0}function jg(e){const t=new Map,s=[];for(const n of e){const i=Vj(n)?Sg(n)??n:n;if(!(i!=null&&i.nodeId))continue;const a=t.get(i.nodeId);if(!a){t.set(i.nodeId,i),s.push(i);continue}const o=qj(a,i);t.set(i.nodeId,o);const l=s.findIndex(c=>c.nodeId===i.nodeId);l>=0&&(s[l]=o)}return s}function iu(e){const t=jg(e.nodes??[]);return{...e,nodes:kg(e,t)}}function Xj(e){var s;const t=e==null?void 0:e.git;return{nodeId:(e==null?void 0:e.nodeId)??null,chosenSource:t?"live_git":e!=null&&e.gitProbePending?"pending_git":"no_git",hasLiveGit:nu(e??{git:void 0}),branch:(t==null?void 0:t.branch)??null,upstream:(t==null?void 0:t.upstream)??null,headCommit:(t==null?void 0:t.headCommit)??null,submoduleCount:((s=t==null?void 0:t.submodules)==null?void 0:s.length)??0,pendingGit:(e==null?void 0:e.gitProbePending)===!0,connection:e!=null&&e.connection?{state:e.connection.state,transport:e.connection.transport,source:e.connection.source}:null}}function Yj(e){const t=Ie(e.meshId,e.mesh_id,e.id),s=e.nodes,n=Array.isArray(s)?s.map(c=>Sg(c)).filter(c=>c!==null):null;if(!t||!n)return null;const i=kg(e,jg(n)),a=Ie(e.meshName,e.mesh_name,e.name),o=Ie(e.repoIdentity,e.repo_identity),l=Ie(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!a||!o||!l?null:{...e,meshId:t,meshName:a,repoIdentity:o,refreshedAt:l,nodes:i}}function Qj(e){var a;let t=0;const s=xt(e.sourceOfTruth),n=xt(s.directPeerTruth);Ie(s.currentStatus)==="live_git_and_session_probes"&&(t+=100),s.coordinatorOwnsLiveTruth===!0&&(t+=25),n.satisfied===!0&&(t+=15);for(const o of e.nodes){const l=o.git;if(!l){o.gitProbePending&&(t-=8);continue}t+=10,l.isGitRepo===!0&&(t+=5),l.isGitRepo===!1&&(t+=1),l.branch&&(t+=4),l.upstream&&(t+=3),l.headCommit&&(t+=3),t+=ru(l.upstreamStatus),typeof l.ahead=="number"&&(t+=1),typeof l.behind=="number"&&(t+=1),typeof l.lastCheckedAt=="number"&&(t+=2),t+=(((a=l.submodules)==null?void 0:a.length)??0)*2}return t}function Jj(e){const t=e.refreshedAt;if(typeof t!="string"||t.length===0)return 0;const s=Date.parse(t);return Number.isFinite(s)?s:0}const Zj=20;function hh(e){let t=null;for(const s of e){const n=Yj(xt(s));if(!n)continue;const i=Qj(n),a=Jj(n);if(!t){t={status:n,score:i,refreshedAt:a};continue}(Math.abs(i-t.score)<=Zj?a>t.refreshedAt||a===t.refreshedAt&&i>t.score:i>t.score)&&(t={status:n,score:i,refreshedAt:a})}return(t==null?void 0:t.status)??null}function au(e){const s=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,n=hh([s==null?void 0:s.status,s]);return n||hh([e==null?void 0:e.status,e])}function eN(e){var n;if(!e)return null;const t=(n=e.coordinator)==null?void 0:n.meshId;if(typeof t=="string"&&t.trim())return t.trim();const s=e.settings||{};for(const i of["meshNodeFor","meshCoordinatorFor"]){const a=s[i];if(typeof a=="string"&&a.trim())return a.trim()}return null}function tN(e){const t=(e==null?void 0:e.settings)||{};for(const s of["meshNodeId","nodeId"]){const n=t[s];if(typeof n=="string"&&n.trim())return n.trim()}return null}function sN(e,t){var i;if(!t)return null;const s=au(e),n=(i=s==null?void 0:s.nodes)==null?void 0:i.find(a=>Fj(a,t));return n?{nodeId:n.nodeId,workspace:n.workspace,repoRoot:n.repoRoot,daemonId:n.daemonId,role:n.role,machineStatus:n.machineStatus,health:n.health,isLocalWorktree:n.isLocalWorktree,worktreeBranch:n.worktreeBranch,launchReady:n.launchReady,providers:n.providers,providerPriority:n.providerPriority,git:n.git?{branch:n.git.branch,headCommit:n.git.headCommit,ahead:n.git.ahead,behind:n.git.behind,dirty:n.git.dirty,upstream:n.git.upstream}:void 0,connection:n.connection?{transport:n.connection.transport,state:n.connection.state,rttMs:n.connection.rttMs}:void 0}:null}function mh(e){if(!e||!Number.isFinite(e))return"—";try{return`${new Date(e).toLocaleString()} (${e})`}catch{return String(e)}}function fh(e){if(!e)return"";const t=Date.now()-e;if(t<0)return"";const s=Math.floor(t/1e3);if(s<60)return`${s}s ago`;const n=Math.floor(s/60);if(n<60)return`${n}m ago`;const i=Math.floor(n/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function rN({sessionId:e,daemonId:t,conv:s,onClose:n}){var k,j;const{sendCommand:i}=jt(),a=su(),[o,l]=u.useState(!0),[c,d]=u.useState(null),[p,h]=u.useState(null),[m,g]=u.useState(null),[b,f]=u.useState(null),v=u.useMemo(()=>eN(s),[s]),w=u.useMemo(()=>tN(s),[s]),x=u.useCallback(async()=>{l(!0),h(null);try{const y=await i(t,"get_session_info",{targetSessionId:e}),N=y&&typeof y=="object"?y:{},_=N.result&&typeof N.result=="object"?N.result:N;_!=null&&_.success?d(_):(h((_==null?void 0:_.error)||"Failed to load session info"),d(null))}catch(y){h((y==null?void 0:y.message)||String(y)),d(null)}finally{l(!1)}},[i,t,e]);u.useEffect(()=>{x()},[x]);const S=u.useCallback(async()=>{if(g(null),f(null),!(!v||!w||!(a!=null&&a.loadMeshStatus)))try{const y=await a.loadMeshStatus(t,v,{refresh:!1}),N=sN(y,w);if(!N){f("This session is stamped to a mesh node that the coordinator no longer reports.");return}g(N)}catch(y){f((y==null?void 0:y.message)||"Failed to load mesh node info")}},[a,t,v,w]);return u.useEffect(()=>{S()},[S]),u.useEffect(()=>{const y=N=>{N.key==="Escape"&&n()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[n]),r.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Session info",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onClick:n,style:{pointerEvents:"auto"},children:r.jsxs("div",{className:"bg-[var(--surface-primary)] text-text-primary border border-border-default rounded-lg shadow-xl max-w-2xl w-full max-h-[85vh] flex flex-col",onClick:y=>y.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between border-b border-border-subtle px-4 py-3",children:[r.jsx("h2",{className:"text-base font-semibold",children:"Session info"}),r.jsx("button",{type:"button",onClick:n,className:"text-text-secondary hover:text-text-primary px-2 py-1 rounded","aria-label":"Close",children:"×"})]}),r.jsxs("div",{className:"overflow-y-auto px-4 py-3 text-sm space-y-4",children:[o&&r.jsx("div",{className:"text-text-secondary",children:"Loading…"}),p&&r.jsx("div",{className:"text-red-500",children:p}),(c==null?void 0:c.session)&&r.jsxs(tn,{title:"Session",children:[r.jsx(Xe,{k:"Session ID",v:r.jsx(Ft,{children:c.session.sessionId})}),r.jsx(Xe,{k:"Provider",v:`${c.session.providerName||c.session.providerType} (${c.session.providerType})`}),c.session.transport&&r.jsx(Xe,{k:"Transport",v:c.session.transport}),c.session.workspace&&r.jsx(Xe,{k:"Workspace",v:r.jsx(Ft,{children:c.session.workspace})}),r.jsx(Xe,{k:"Spawned at",v:r.jsxs(r.Fragment,{children:[mh(c.session.spawnedAtMs),c.session.spawnedAtMs?r.jsx("span",{className:"text-text-secondary ml-2",children:fh(c.session.spawnedAtMs)}):null]})}),c.session.providerSessionId&&r.jsx(Xe,{k:"Provider session ID",v:r.jsx(Ft,{children:c.session.providerSessionId})}),!c.session.workspace&&(s==null?void 0:s.workspacePath)&&r.jsx(Xe,{k:"Workspace",v:r.jsx(Ft,{children:s.workspacePath})}),(s==null?void 0:s.machineName)&&r.jsx(Xe,{k:"Machine",v:s.machineName}),(s==null?void 0:s.connectionState)&&r.jsx(Xe,{k:"Connection",v:s.connectionState}),(s==null?void 0:s.git)&&r.jsx(Xe,{k:"Workspace git",v:r.jsxs("span",{children:[s.git.branch||"(detached)",s.git.ahead?` ↑${s.git.ahead}`:"",s.git.behind?` ↓${s.git.behind}`:"",s.git.dirty?" · dirty":" · clean"]})})]}),((k=c==null?void 0:c.session)==null?void 0:k.launch)&&r.jsxs(tn,{title:"Launch",children:[c.session.launch.command&&r.jsx(Xe,{k:"Command",v:r.jsx(Ft,{children:c.session.launch.command})}),c.session.launch.cwd&&r.jsx(Xe,{k:"Working directory",v:r.jsx(Ft,{children:c.session.launch.cwd})}),Array.isArray(c.session.launch.args)&&c.session.launch.args.length>0&&r.jsx(Xe,{k:"Args",v:r.jsx(Ft,{children:c.session.launch.args.join(" ")})}),Array.isArray(c.session.launch.extraArgs)&&c.session.launch.extraArgs.length>0&&r.jsx(Xe,{k:"Extra args",v:r.jsx(Ft,{children:c.session.launch.extraArgs.join(" ")})}),Array.isArray(c.session.launch.extraEnvKeys)&&c.session.launch.extraEnvKeys.length>0&&r.jsx(Xe,{k:"Extra env",v:r.jsx(Ft,{children:c.session.launch.extraEnvKeys.join(", ")})})]}),m&&r.jsxs(tn,{title:"Mesh node",children:[m.nodeId&&r.jsx(Xe,{k:"Node ID",v:r.jsx(Ft,{children:m.nodeId})}),m.workspace&&r.jsx(Xe,{k:"Workspace",v:r.jsx(Ft,{children:m.workspace})}),m.repoRoot&&m.repoRoot!==m.workspace&&r.jsx(Xe,{k:"Repo root",v:r.jsx(Ft,{children:m.repoRoot})}),m.daemonId&&r.jsx(Xe,{k:"Daemon ID",v:r.jsx(Ft,{children:m.daemonId})}),m.role&&r.jsx(Xe,{k:"Role",v:m.role}),m.machineStatus&&r.jsx(Xe,{k:"Machine status",v:m.machineStatus}),m.health&&r.jsx(Xe,{k:"Health",v:m.health}),m.isLocalWorktree&&r.jsx(Xe,{k:"Worktree",v:m.worktreeBranch?r.jsx(Ft,{children:m.worktreeBranch}):"yes"}),typeof m.launchReady=="boolean"&&r.jsx(Xe,{k:"Launch ready",v:m.launchReady?"yes":"no"}),m.git&&r.jsx(Xe,{k:"Git",v:r.jsxs("span",{children:[m.git.branch||"(detached)",m.git.headCommit?` @ ${String(m.git.headCommit).slice(0,10)}`:"",m.git.ahead?` ↑${m.git.ahead}`:"",m.git.behind?` ↓${m.git.behind}`:"",m.git.dirty?" · dirty":" · clean",m.git.upstream?` · ${m.git.upstream}`:""]})}),m.connection&&r.jsx(Xe,{k:"Connection",v:r.jsxs("span",{children:[m.connection.transport||"—",m.connection.state?` · ${m.connection.state}`:"",typeof m.connection.rttMs=="number"?` · ${m.connection.rttMs}ms RTT`:""]})}),Array.isArray(m.providers)&&m.providers.length>0&&r.jsx(Xe,{k:"Providers",v:r.jsx(Ft,{children:m.providers.join(", ")})}),Array.isArray(m.providerPriority)&&m.providerPriority.length>0&&r.jsx(Xe,{k:"Provider priority",v:r.jsx(Ft,{children:m.providerPriority.join(" › ")})})]}),!m&&b&&(v||w)&&r.jsx(tn,{title:"Mesh node",children:r.jsx("div",{className:"text-text-secondary italic",children:b})}),(c==null?void 0:c.coordinator)&&r.jsxs(tn,{title:"Mesh coordinator",children:[r.jsx(Xe,{k:"Mesh ID",v:r.jsx(Ft,{children:c.coordinator.meshId})}),c.coordinator.cliType&&r.jsx(Xe,{k:"Coordinator CLI",v:c.coordinator.cliType}),r.jsx(Xe,{k:"Started at",v:r.jsxs(r.Fragment,{children:[mh(c.coordinator.startedAt),c.coordinator.startedAt?r.jsx("span",{className:"text-text-secondary ml-2",children:fh(c.coordinator.startedAt)}):null]})}),c.coordinator.injection&&r.jsx(Xe,{k:"Prompt injection",v:`${c.coordinator.injection.mode}${c.coordinator.injection.target?` → ${c.coordinator.injection.target}`:""}`}),c.coordinator.mcpConfigPath&&r.jsx(Xe,{k:"MCP config",v:r.jsx(Ft,{children:c.coordinator.mcpConfigPath})}),c.coordinator.extraSystemPrompt&&r.jsx(td,{title:"Per-launch extra prompt",body:c.coordinator.extraSystemPrompt,defaultOpen:!0}),c.coordinator.systemPrompt&&r.jsx(td,{title:"Final system prompt (click to expand)",body:c.coordinator.systemPrompt})]}),((j=c==null?void 0:c.session)==null?void 0:j.runtimeMetadata)!=null&&r.jsx(nN,{meta:c.session.runtimeMetadata}),c&&!c.coordinator&&r.jsx("div",{className:"text-text-secondary italic",children:"This isn't a mesh coordinator session, so no coordinator-specific prompt was injected. The agent runs with whatever defaults its CLI ships with."})]}),r.jsxs("div",{className:"border-t border-border-subtle px-4 py-2 flex justify-end gap-2",children:[r.jsx("button",{type:"button",onClick:()=>void x(),className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:"Refresh"}),r.jsx("button",{type:"button",onClick:n,className:"px-3 py-1 text-sm rounded bg-accent text-white hover:opacity-90",children:"Close"})]})]})})}function tn({title:e,children:t}){return r.jsxs("div",{children:[r.jsx("h3",{className:"text-xs uppercase tracking-wide text-text-secondary mb-1",children:e}),r.jsx("div",{className:"space-y-1",children:t})]})}function Xe({k:e,v:t}){return r.jsxs("div",{className:"flex gap-3",children:[r.jsx("div",{className:"w-44 shrink-0 text-text-secondary",children:e}),r.jsx("div",{className:"min-w-0 break-all",children:t})]})}function Ft({children:e}){return r.jsx("code",{className:"font-mono text-xs",children:e})}function nN({meta:e}){if(!e||typeof e!="object")return null;const t=e,s=c=>typeof c=="string"&&c.trim()?c:null,n=s(t.runtimeId),i=s(t.lifecycle),a=s(t.surfaceKind),o=s(t.recoveryState),l=Array.isArray(t.attachedClients)?t.attachedClients.length:null;return r.jsxs(tn,{title:"Runtime",children:[n&&r.jsx(Xe,{k:"Runtime ID",v:r.jsx(Ft,{children:n})}),i&&r.jsx(Xe,{k:"Lifecycle",v:i}),a&&r.jsx(Xe,{k:"Surface",v:a}),o&&r.jsx(Xe,{k:"Recovery state",v:o}),typeof t.restoredFromStorage=="boolean"&&r.jsx(Xe,{k:"Restored from storage",v:t.restoredFromStorage?"yes":"no"}),l!=null&&r.jsx(Xe,{k:"Attached clients",v:String(l)}),r.jsx(td,{title:"Raw runtime metadata (click to expand)",body:iN(e)})]})}function iN(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function td({title:e,body:t,defaultOpen:s=!1}){const[n,i]=u.useState(s);return r.jsxs("div",{className:"mt-2",children:[r.jsxs("button",{type:"button",onClick:()=>i(a=>!a),className:"text-xs uppercase tracking-wide text-text-secondary hover:text-text-primary",style:{pointerEvents:"auto"},children:[n?"▾":"▸"," ",e]}),n&&r.jsx("pre",{className:"mt-1 p-2 bg-[var(--surface-secondary)] border border-border-subtle rounded text-xs whitespace-pre-wrap overflow-x-auto max-h-96 overflow-y-auto",children:t})]})}function aN({sessionId:e,daemonId:t,conv:s}){const[n,i]=u.useState(!1);return!e||!t?null:r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button",onClick:()=>i(!0),title:"Session info — launch args, mesh node, system prompt, …","aria-label":"Session info",className:"inline-flex items-center justify-center w-6 h-6 rounded-full text-text-secondary hover:text-text-primary hover:bg-surface-secondary text-sm leading-none",style:{pointerEvents:"auto"},children:"ⓘ"}),n&&r.jsx(rN,{sessionId:e,daemonId:t,conv:s,onClose:()=>i(!1)})]})}const dt=e=>e.transport==="pty",Tn=(e,t)=>dt(e)?e.mode||"terminal":"chat",Ng=(e,t)=>dt(e)&&Tn(e)==="terminal",at=e=>e.transport==="acp",oN=180;function dr(e){return e.streamSource!=="agent-stream"}function Kr(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function _g(e){return e.machineName||""}function Vi(e){return Kr(e)}function $s(e){return e.agentType||""}function So(e){return e.hostIdeType||""}function ou(e){return e.displayPrimary||e.agentName||"Agent"}function Cg(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function lN(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Ig(e){const t=lN(e),s=xn(t==null?void 0:t.content),n=xn(e.lastMessagePreview);return s||n||""}function cN(e,t=oN){const s=xn(e);if(!s||t<=0)return"";const n=Array.from(s);return n.length<=t?s:`${n.slice(0,Math.max(0,t-1)).join("").trimEnd()}…`}function dN(e){return cN(Ig(e)||e.displaySecondary||"")}function Ag(e){return[e.displaySecondary,_g(e)].filter(Boolean)}function wn(e){return e.agentName||Vt($s(e))}function uN(e){var t,s;if(!dr(e)){const n=(s=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:s.trim();if(n)return n}return Vt(So(e)||$s(e))}function Tg(e){return dr(e)?e.sessionId:e.nativeSessionId}function gh(e){return dr(e)?"native":e.tabKey}function pN(e){return e.sessionId}function hN(e,t){if(t)return dr(e)||!t.childSessions?t:t.childSessions.find(s=>s.id===e.sessionId||s.providerType===e.agentType)||t}function mN(e,t){const s=$s(e),n=dr(e),i=dt(e)||at(e),a=n?i?wn(e)||(t==null?void 0:t.cliName)||Vt(So(e)||s):t!=null&&t.type?Vt(t.type):Vt(So(e)||s):wn(e);return{isNativeConversation:n,isCli:dt(e),isAcp:at(e),isCliTerminal:Ng(e),providerType:s,displayLabel:a,targetEntry:hN(e,t)}}function Nr(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:dt(e)||at(e)?{agentType:$s(e)}:e.streamSource==="agent-stream"?{agentType:$s(e)}:t}function _r(e){return e?Vi(e):""}function Fn(e,t){e(s=>[...s,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function lu(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function xh(e){const t=e instanceof Error?e.message:String(e||""),s=t.toLowerCase();return s.includes("still processing the previous prompt")?"Message queued and will send after the current reply finishes.":s.includes("awaiting confirmation")?"Resolve the pending approval prompt before sending another message.":s.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":s.includes("not running")?"Runtime is not available right now.":t||"Unable to send message right now."}function Mg(){return"select_session"}function fN(){return"open_panel"}function gN({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function bh(e,t,s=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<s:!1}function Ca(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function li(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function cu(e){return e instanceof Error?e.message:String(e||"")}function yh(e){const t=cu(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function vh(e,t){const s=cu(t);return s?s.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${s}`:`⚠️ **${e}** unavailable`}function wh(e,t,s,n={}){const i=Nr(s);if(!t||t.length===0)return{message:e,...n.force?{force:!0}:{},...i};const a=t.map(o=>({type:"image",mimeType:o.mimeType,data:o.data,alt:o.name}));return e&&a.push({type:"text",text:e}),{message:e,input:{parts:a,textFallback:e},...n.force?{force:!0}:{},...i}}function cl({sendDaemonCommand:e,activeConv:t,setActionLogs:s,isStandalone:n}){const[i,a]=u.useState(!1),[o,l]=u.useState(!1),[c,d]=u.useState(null),p=u.useRef(!1),h=u.useRef(null);u.useEffect(()=>{d(null)},[t==null?void 0:t.tabKey]);const m=u.useCallback(async(w,x)=>{if(!t||p.current)return!1;const S=w.trim(),k=lu(t);if(gN({hasMessage:!!S,blockedMessage:k,sendInFlight:p.current}))return k&&d(k),!1;const j=Date.now(),y={tabKey:t.tabKey,message:S,timestamp:j};if(bh(h.current,y))return d(null),!0;p.current=!0,l(!0),d(null),h.current=y;try{const N=_r(t);if(!N)return h.current=Ca(h.current,y),d("Unable to send message right now."),!1;const _=await e(N,"send_chat",wh(S,x,t)),C=li(_);if(C!=null&&C.deduplicated)return d(null),!0;if((C==null?void 0:C.sent)===!1)throw new Error((C==null?void 0:C.error)||"Send failed");if((C==null?void 0:C.success)===!1)throw new Error((C==null?void 0:C.error)||"Send failed");return d(null),!0}catch(N){const _=cu(N);return _.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",_):console.warn("Send blocked/failed",N),h.current=Ca(h.current,y),d(xh(N)),!1}finally{p.current=!1,l(!1)}},[t,e]),g=u.useCallback(async(w,x)=>{if(!t||p.current)return!1;const S=w.trim();if(!S&&(!x||x.length===0))return!1;const k=Date.now(),j={tabKey:t.tabKey,message:`force:${S}`,timestamp:k};if(bh(h.current,j))return d(null),!0;p.current=!0,l(!0),d(null),h.current=j;try{const y=_r(t);if(!y)return h.current=Ca(h.current,j),d("Unable to send message right now."),!1;const N=await e(y,"send_chat",wh(S,x,t,{force:!0})),_=li(N);if((_==null?void 0:_.success)===!1||(_==null?void 0:_.sent)===!1)throw new Error((_==null?void 0:_.error)||"Send failed");return d(null),!0}catch(y){return console.warn("Force send blocked/failed",y),h.current=Ca(h.current,j),d(xh(y)),!1}finally{p.current=!1,l(!1)}},[t,e]),b=u.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(w){console.error("Relaunch failed",w)}},[t,e]),f=u.useCallback(async w=>{if(t)try{const S=(t.modalButtons||[]).indexOf(w),k=w.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),j=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(k),y=_r(t);if(!y)return;const N=await e(y,"resolve_action",{button:w,action:j?"approve":"reject",...S>=0&&{buttonIndex:S},...Nr(t)}),_=li(N);_.success||s(C=>[...C,{routeId:t.tabKey,text:vh(w,_==null?void 0:_.error),timestamp:Date.now()}])}catch(x){yh(x)||console.error("[ModalButton] Error:",x),s(S=>[...S,{routeId:t.tabKey,text:yh(x)?vh(w,x):`❌ **${w}** error`,timestamp:Date.now()}])}},[t,e,s]),v=u.useCallback(async()=>{if(!(!t||i)){a(!0);try{await e(t.routeId,fN(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(w){console.error("Focus agent failed",w)}finally{a(!1)}}},[t,i,e]);return{isSendingChat:o,sendFeedbackMessage:c,isFocusingAgent:i,handleSendChat:m,handleForceSendChat:g,handleRelaunch:b,handleModalButton:f,handleFocusAgent:v}}const xN=10,bN=8e3,yN=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function vN(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 sd(e,t="",s=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(yN.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=vN(e);return n.length>8e3?`${n.slice(0,8e3)}…[truncated ${n.length-8e3} chars]`:n}if(typeof e!="object")return String(e);if(s>=6)return"[MaxDepth]";if(Array.isArray(e)){const n=e.slice(-20).map(i=>sd(i,t,s+1));return e.length>20?[{truncatedBefore:e.length-20},...n]:n}return Object.fromEntries(Object.entries(e).slice(0,80).map(([n,i])=>[n,sd(i,n,s+1)]))}function Bn(e,t){return Array.isArray(e)?e.slice(-t):[]}function wN(e,t=Date.now()){const s=e&&t-e.firstAt<=bN,n=s?e.count+1:1;return n>=xN?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:s?e.firstAt:t},shouldCollect:!1}}function Eg(e){var n,i;const{activeConv:t}=e,s={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:((i=e.chatTailState.historyMessages)==null?void 0:i.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:Bn(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:Bn(t.messages,10),visibleMessagesTail:Bn(e.visibleMessages,5),historyMessagesTail:Bn(e.chatTailState.historyMessages,5),actionLogsTail:Bn(e.actionLogs.filter(a=>a.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 sd(s)}function Rg(e,t={}){const s=e&&typeof e=="object"?e:{},n=t.locatorCopyStatus??(t.locatorCopied===!1?"failed":"copied"),i=n==="copied"?"locator copied":n==="manual"?"locator shown for manual copy":"locator copy failed";return s.delivery==="daemon_file"?`Chat debug signal sent${typeof s.bundleId=="string"&&s.bundleId.trim()?` (${s.bundleId})`:""}; saved on daemon, ${i}.`:`Chat debug signal sent; ${i}.`}async function Pg(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(s){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",s)}if(typeof document<"u"&&document.body){let s=null;try{if(s=document.createElement("textarea"),s.value=e,s.setAttribute("readonly","true"),s.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(s),s.focus(),s.select(),document.execCommand("copy"))return"copied"}catch{}finally{s==null||s.remove()}}if(typeof window<"u"&&typeof window.prompt=="function")try{return window.prompt("Copy ADHDev chat debug locator:",e),"manual"}catch{}return"failed"}function Dg(e){const t=e&&typeof e=="object"?e:{};if(t.delivery==="daemon_file"){const s=["# 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"&&s.push("","summary:",JSON.stringify(t.summary,null,2)),Array.isArray(t.warnings)&&t.warnings.length>0&&s.push("","warnings:",...t.warnings.map(n=>`- ${String(n)}`)),s.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 Kl(e,t){return`${e}:${t}`}function SN(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function kN(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Qr(e,t){kN()&&console.debug(`[subscription-manager] ${e}`,t)}class jN{constructor(){re(this,"active",new Map);re(this,"retryTimers",new Map)}subscribe(t,s,n,i,a){var p,h;const o=Kl(n.topic,n.key),l=this.active.get(o);let c=!0;if(l)l.handlers.add(i),(!SN(l.request,n)||l.daemonId!==s)&&(l.daemonId=s,l.request=n,c=((p=t.sendData)==null?void 0:p.call(t,s,n))??!1,!c&&(a!=null&&a.retryIntervalMs)?this.scheduleRetry(o,t,a.retryIntervalMs):c&&this.clearRetry(o),Qr("subscribe_update",{daemonId:s,topic:n.topic,key:n.key,accepted:c})),l.lastUpdate&&i(l.lastUpdate);else{const m={daemonId:s,request:n,handlers:new Set([i])};this.active.set(o,m),Qr("subscribe",{daemonId:s,topic:n.topic,key:n.key}),c=((h=t.sendData)==null?void 0:h.call(t,s,n))??!1,!c&&(a!=null&&a.retryIntervalMs)&&this.scheduleRetry(o,t,a.retryIntervalMs)}const d=()=>{var b;this.clearRetry(o);const m=this.active.get(o);if(!m||(m.handlers.delete(i),m.handlers.size>0))return;this.active.delete(o);const g={type:"unsubscribe",topic:n.topic,key:n.key};Qr("unsubscribe",{daemonId:s,topic:n.topic,key:n.key}),(b=t.sendData)==null||b.call(t,s,g)};return d.initialSendAccepted=c,d}publish(t){const s=Kl(t.topic,t.key),n=this.active.get(s);n&&(this.clearRetry(s),n.lastUpdate=t,gn.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),n.handlers.forEach(i=>{i(t),gn.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,s,n){const i=Kl(t,s),a=this.active.get(i);a&&(a.request={...a.request,params:{...a.request.params,...n}})}resubscribeAll(t){var s;Qr("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())(s=t.sendData)==null||s.call(t,n.daemonId,n.request)}resubscribeForDaemon(t,s){var i;const n=Array.from(this.active.values()).filter(a=>a.daemonId===t);Qr("resubscribe_daemon",{daemonId:t,count:n.length,subscriptions:n.map(a=>({topic:a.request.topic,key:a.request.key}))});for(const a of n)(i=s.sendData)==null||i.call(s,a.daemonId,a.request)}scheduleRetry(t,s,n){if(this.retryTimers.has(t))return;const i=setTimeout(()=>{var l;this.retryTimers.delete(t);const a=this.active.get(t);if(!a)return;const o=((l=s.sendData)==null?void 0:l.call(s,a.daemonId,a.request))??!1;Qr("subscribe_retry",{id:t,accepted:o,topic:a.request.topic,key:a.request.key}),o||this.scheduleRetry(t,s,n)},n);this.retryTimers.set(t,i)}clearRetry(t){const s=this.retryTimers.get(t);s!==void 0&&(clearTimeout(s),this.retryTimers.delete(t))}}const Os=new jN;function NN(e,t){const s=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===t&&n.sessionId){s.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,activeInteractivePrompt:n.activeInteractivePrompt});for(const a of n.childSessions||[]){if(!(a!=null&&a.id))continue;const o=s.get(a.id)||{};s.set(a.id,{...o,...a})}}return s}function _N(e){const t=[],s=new Map;for(const n of e)if(n.parentId){const i=s.get(n.parentId)||[];i.push(n),s.set(n.parentId,i)}else t.push(n);return{topLevel:t,childrenByParent:s}}function Gl(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function CN(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function IN(e){CN()&&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 ko(e,t){const s=[],{daemonId:n,existingDaemon:i,existingEntries:a,timestamp:o}=t,l=o||e.timestamp||Date.now(),c=e.sessions||[],{topLevel:d,childrenByParent:p}=_N(c),h=NN(a,n),m=e.machine?{...(i==null?void 0:i.machine)||{},...e.machine}:i==null?void 0:i.machine,g=d.filter(v=>v.kind==="workspace"&&v.transport==="cdp-page"),b=d.filter(v=>v.kind==="agent"&&v.transport==="pty"),f=d.filter(v=>v.kind==="agent"&&v.transport==="acp");s.push({...i||{},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:g.some(v=>!!v.cdpConnected)});for(const v of g){const w=h.get(v.id),x=Jn(v,w),S=(p.get(v.id)||[]).map(k=>Jn(k,h.get(k.id)));s.push({id:`${n}:ide:${v.id}`,sessionId:v.id,providerSessionId:v.providerSessionId??(w==null?void 0:w.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,status:x.cdpConnected?"online":"detected",daemonId:n,instanceId:Gl(n,v.id),workspace:x.workspace,terminals:0,childSessions:S,agents:S.map(k=>({id:k.id,name:k.providerName||k.providerType,type:k.providerType,status:k.status})),activeChat:x.activeChat,...x.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:x.activeInteractivePrompt},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 v of b){const w=h.get(v.id),x=Jn(v,w);s.push({id:`${n}:cli:${v.id}`,sessionId:v.id,providerSessionId:v.providerSessionId??(w==null?void 0:w.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:Gl(n,v.id),cliName:x.providerName||x.providerType,mode:x.mode||(w==null?void 0:w.mode)||"terminal",workspace:x.workspace||"",activeChat:x.activeChat,...x.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:x.activeInteractivePrompt},...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 v of f){const w=h.get(v.id),x=Jn(v,w);s.push({id:`${n}:acp:${v.id}`,sessionId:v.id,providerSessionId:v.providerSessionId??(w==null?void 0:w.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:Gl(n,v.id),cliName:x.providerName||x.providerType,mode:"chat",workspace:x.workspace||"",activeChat:x.activeChat,...x.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:x.activeInteractivePrompt},...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 IN(s),s}const AN=15e3,TN=15e3,MN=6e4,EN=1200,Sh=12,RN=8e3,PN=4e3,ql=new Map,Vl=new Map,Ia=new Set,ci=new Map;function DN(e){if(!e||typeof e!="object")return null;const t=e,s=t.status;if(s&&typeof s=="object")return s;const n=t.result;if(n&&typeof n=="object"&&"status"in n){const i=n.status;if(i&&typeof i=="object")return i}return t}function kh(e,t){const s=ci.get(e);!s||s.size===0||(ci.delete(e),s.forEach(n=>n(t)))}function LN(e,t){return new Promise(s=>{const n=ci.get(e)||new Set;ci.set(e,n);const i=o=>{clearTimeout(a),n.delete(i),n.size===0&&ci.delete(e),s(o)},a=setTimeout(()=>i(!1),t);n.add(i)})}function Xi(){const{sendCommand:e,sendData:t}=jt(),{injectEntries:s,getIdes:n}=ji();return u.useCallback(async(i,a)=>{if(!i)return;const o=(a==null?void 0:a.minFreshMs)??MN,l=Vl.get(i)||0;if(!(a!=null&&a.force)&&Ia.has(i)&&l>0||!(a!=null&&a.force)&&l>0&&Date.now()-l<o)return;const c=ql.get(i);if(c)return c;const d=(async()=>{if(t&&!Ia.has(i)){const f=Os.subscribe({sendData:t},i,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${i}`,params:{includeSessions:!0}},v=>{const w=n(),x=w.find(k=>k.id===i),S=ko(v.status,{daemonId:i,existingDaemon:x,existingEntries:w,timestamp:v.timestamp});S.length>0&&s(S),Vl.set(i,Date.now()),kh(i,!0)});if(f.initialSendAccepted?Ia.add(i):Ia.delete(i),!(a!=null&&a.force)&&f.initialSendAccepted&&await LN(i,EN))return}const p=await e(i,"get_status_metadata"),h=DN(p);if(!h)return;const m=n(),g=m.find(f=>f.id===i),b=ko(h,{daemonId:i,existingDaemon:g,existingEntries:m,timestamp:h.timestamp||Date.now()});b.length>0&&s(b,{authoritativeDaemonIds:[i]}),Vl.set(i,Date.now()),kh(i,!0)})().finally(()=>{ql.delete(i)});return ql.set(i,d),d},[n,s,e,t])}function $N(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const ON=60,FN=50;function Lg(e={}){return e.isCliLike?FN:ON}function BN(e={}){return Lg(e)}function Yt(e){return(typeof e=="string"?e.trim():"")||void 0}function Gs(e,t){const s=Yt(t);return s?`${e}:${s}`:void 0}function ir(e,t,s){const n=Gs(t,s),i=Yt(s);n&&e.push(n),i&&e.push(i)}function cn(e){const t=[],s=new Set;for(const n of e)!n||s.has(n)||(s.add(n),t.push(n));return t}function $g(e){return Yt(e.providerSessionId)||Yt(e.sessionId)||Yt(e.tabKey)||Yt(e.routeId)}function dl(e){return cn([Yt(e.historySessionId),Yt(e.providerSessionId),Yt(e.sessionId)])}function Vs(e){const t=[];return ir(t,"provider",e.providerSessionId),ir(t,"session",e.sessionId),ir(t,"tab",e.tabKey),ir(t,"route",e.routeId),cn(t)}function WN(e){const t=[];return Yt(e.providerSessionId)?(ir(t,"provider",e.providerSessionId),cn(t)):Yt(e.sessionId)?(ir(t,"session",e.sessionId),cn(t)):Yt(e.tabKey)?(ir(t,"tab",e.tabKey),cn(t)):Yt(e.routeId)?(ir(t,"route",e.routeId),cn(t)):[]}function _i(e){return Gs("provider",e.providerSessionId)||Gs("session",e.sessionId)||Gs("tab",e.tabKey)||Gs("route",e.routeId)||"unknown:"}function Yi(e){return dl(e)[0]}function UN(e){const t=Yt(e.providerSessionId),s=Yt(e.sessionId),n=Yt(e.tabKey),i=Yt(e.routeId),a=[Gs("provider",t),Gs("session",s),Gs("tab",n),Gs("route",i)].filter(c=>typeof c=="string"),o=Vs({providerSessionId:t,sessionId:s,tabKey:n,routeId:i}),l=_i({providerSessionId:t,sessionId:s,tabKey:n,routeId:i});return{providerSessionId:t,sessionId:s,tabKey:n,routeId:i,canonicalKey:l,targetKey:l,targetValue:$g({providerSessionId:t,sessionId:s,tabKey:n,routeId:i}),historySessionId:Yi({providerSessionId:t,sessionId:s}),runtimeSessionId:s,allKeys:a,lookupKeys:o}}function rd(e,t){const s=UN(e);return WN(t).some(n=>s.lookupKeys.includes(n))}const Qi=60,HN=1e3,jh=500,du=12e4,zN=new Set(["generating","waiting_approval","starting","streaming","working"]),nd=new Map;function uu(e,t,s){return`${e}::${t}::${s||t}`}function jo(e=Qi){return{liveMessages:[],hasLiveSnapshot:!1,cursor:KN([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function KN(e,t=Qi){return{tailLimit:t}}function Nh(e,t){const s=e[e.length-1];if(!s)return"empty:";let n="";try{n=JSON.stringify(s.content??"")}catch{n=String(s.content??"")}return["",e.length,String(s.id||""),String(s.index??""),String(s.receivedAt??s.timestamp??""),n].join("|")}function id(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(id).join(`
|
|
41
|
+
`);if(typeof e=="object"){const t=e;return id(t.text??t.content??t.value??"")}return String(e)}function GN(e){return id(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function qN(e){return e.length===0||e.every(GN)}function VN(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="generating"||t==="long_generating"||t==="streaming"||t==="working"||t==="starting"}function Og(e,t){return Math.max(Math.max(0,t),Array.isArray(e.liveMessages)?e.liveMessages.length:0)}function XN(e,t,s,n,i){if(!VN(n))return!1;const a=Og(e,t);if(a<=0)return!1;if(qN(s))return!0;if(i&&typeof i=="object"){const o=i.selected,l=i.fallbackReason;if(o==="native-history"||typeof l=="string"&&l!==""&&!l.startsWith("native_history_"))return!1}return s.length<a}function YN(e,t,s,n){if(s.length!==0||Og(e,t)<=0||e.hasLiveSnapshot&&e.liveMessages.length===0||!n||typeof n!="object")return!1;const a=n.selected,o=n.fallbackReason,l=n.nativeSource;return a==="native-history"?!1:l==="native-unavailable"?!0:typeof o=="string"&&o.startsWith("native_history_")}function QN(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}function _h(e,t){const s=e[t];return typeof s=="string"?s:""}class JN{constructor(t){re(this,"manager");re(this,"sendData");re(this,"daemonId");re(this,"sessionId");re(this,"historySessionId");re(this,"subscriptionKey");re(this,"fallbackRecentCount");re(this,"snapshot");re(this,"transportSubscription",null);re(this,"listeners",new Set);re(this,"retainCount",0);re(this,"loadHistoryPromise",null);re(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=jo(Math.max(0,t.tailLimit??Qi))}updateOptions(t){const s=this.sendData,n=this.daemonId,i=this.sessionId;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 a=Math.max(0,t.tailLimit);a!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:a}},this.transportSubscription&&(this.disconnect(),this.connect()))}this.retainCount>0&&(s!==this.sendData||n!==this.daemonId||i!==this.sessionId)&&(this.disconnect(),this.connect())}getSnapshot(){return this.snapshot}clearLiveSnapshot(){this.snapshot={...jo(this.snapshot.cursor.tailLimit),hasLiveSnapshot:!0},this.emit()}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 s=(async()=>{try{const n=this.snapshot.hasLiveSnapshot,i=n?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),a=await t({offset:this.snapshot.historyOffset,excludeRecentCount:i}),o=Array.isArray(a.messages)?a.messages:[],l=!n&&o.length===0&&a.hasMore!==!0&&this.fallbackRecentCount>0,c=[...o,...this.snapshot.historyMessages],d=c.length>jh?c.slice(c.length-jh):c;this.snapshot={...this.snapshot,historyMessages:d,historyOffset:this.snapshot.historyOffset+o.length,hasMoreHistory:l?!0:a.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=s,s}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:HN}))}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 s=_h(t,"sessionId");if(s&&s!==this.sessionId)return;const n=_h(t,"historySessionId");if(n&&this.historySessionId&&n!==this.historySessionId)return;const i=QN(t),a=t.messageSource;if(XN(this.snapshot,this.fallbackRecentCount,i,t.status,a)||YN(this.snapshot,this.fallbackRecentCount,i,a))return;const o={tailLimit:this.snapshot.cursor.tailLimit};Nh(this.snapshot.liveMessages)===Nh(i)&&this.snapshot.cursor.tailLimit===o.tailLimit||(this.snapshot={...this.snapshot,liveMessages:i,hasLiveSnapshot:!0,cursor:o,messageSource:a},this.emit())}}function Fg(e){const t=uu(e.daemonId,e.sessionId,e.historySessionId),s=nd.get(t);if(s)return s.updateOptions(e),s;const n=new JN(e);return nd.set(t,n),n}function ZN(e,t,s){if(!e||!t)return;const n=`${e}::${t}::`,i=uu(e,t,s);for(const[a,o]of nd.entries())(a===i||a.startsWith(n))&&o.clearLiveSnapshot()}function e1(e,t){return{...e,loadHistoryPage:t}}function t1(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function s1(e,t={}){const s=String(e.status||"").trim().toLowerCase();if(zN.has(s)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=t.now??Date.now(),i=Math.max(0,Number(t.recentActivityMs??du)),a=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return a>0?n-a<=i:Array.isArray(e.messages)&&e.messages.length>0}function r1(e=du){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function n1(e,t={}){const s=new Set,n=[];for(const i of e){if(!s1(i,t))continue;const a=Vi(i),o=i.sessionId||"";if(!a||!o)continue;const l=Yi(i),c=uu(a,o,l||o);s.has(c)||(s.add(c),n.push({daemonId:a,sessionId:o,historySessionId:l||o,subscriptionKey:`daemon:${a}:session:${o}`}))}return n.sort(t1),{descriptors:n,signature:n.map(i=>`${i.subscriptionKey}|${i.historySessionId}`).join("||")}}function i1(e,t){const{sendData:s,sendCommand:n}=jt(),i=(t==null?void 0:t.enabled)!==!1,a=Vi(e),o=e.sessionId||"",l=Yi(e)||o,c=`daemon:${a}:session:${o}`,d=Math.max(0,(t==null?void 0:t.tailLimit)??Qi),p=e.messages.length,h=u.useMemo(()=>!i||!a||!o?null:Fg({daemonId:a,sessionId:o,historySessionId:l,subscriptionKey:c,sendData:s,tailLimit:d,fallbackRecentCount:p}),[a,i,l,s,o,c,d]);u.useEffect(()=>{h==null||h.updateOptions({fallbackRecentCount:p})},[h,p]);const[m,g]=u.useState(()=>(h==null?void 0:h.getSnapshot())||jo(d));u.useEffect(()=>{if(!h){g(jo(d));return}h.retain(),g(h.getSnapshot());const f=h.subscribe(v=>{g(v)});return()=>{f(),h.release()}},[h,d]);const b=u.useCallback(async()=>{!h||!a||!o||await h.loadHistoryPage(async({offset:f,excludeRecentCount:v})=>{const w=e.agentType,x=await n(a,"chat_history",{agentType:w,offset:f,limit:30,targetSessionId:o,historySessionId:l,excludeRecentCount:v}),S=x&&typeof x=="object"&&"result"in x?x.result||{}:x||{};return{messages:Array.isArray(S.messages)?S.messages:[],hasMore:S.hasMore===!0}})},[e.agentType,h,a,l,n,o]);return u.useMemo(()=>e1(m,b),[b,m])}function a1(e,t){const{sendData:s}=jt(),n=(t==null?void 0:t.enabled)!==!1,i=Math.max(0,(t==null?void 0:t.tailLimit)??Qi),a=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??du)),o=r1(a),[l,c]=u.useState(0);u.useEffect(()=>{if(!n||e.length===0)return;const p=setInterval(()=>{c(h=>h+1)},o);return()=>{clearInterval(p)}},[e.length,n,o]);const d=u.useMemo(()=>n1(e,{recentActivityMs:a}),[e,a,l]);u.useEffect(()=>{if(!n||!s||d.descriptors.length===0)return;const p=d.descriptors.map(h=>Fg({...h,sendData:s,tailLimit:i}));return p.forEach(h=>{h.retain()}),()=>{p.forEach(h=>h.release())}},[d.signature,n,s,i])}function o1(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function Ch(e){const t=String(e.role||"").toLowerCase();if(t!=="user"&&t!=="assistant")return!1;const s=String(e.kind||"standard").toLowerCase();return s===""||s==="standard"}function l1(e,t){if(e.length===0)return[];if(t.some(Ch))return[];const s=[],n=new Set;for(let i=e.length-1;i>=0&&s.length<2;i-=1){const a=e[i];if(!a||!Ch(a))continue;const o=String(a.role||"").toLowerCase();n.has(o)||(n.add(o),s.unshift(a))}return s}function c1(e){const{historyMessages:t,liveMessages:s,visibleLiveCount:n}=e,i=Math.max(0,s.length-n),a=i>0?s.slice(0,i):[],o=i>0?s.slice(-n):s,l=l1(a,o),c=l.length>0?[...l,...o]:o;return t.length===0?c:[...t,...c]}function d1(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function u1(e){return d1(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Za=new Map,ad=new Set;function Ih(e,t){!e||Za.get(e)===t||(t?Za.set(e,!0):Za.delete(e),ad.forEach(n=>n(e,t)))}function p1(e){return e?Za.get(e)===!0:!1}function h1(e){return ad.add(e),()=>{ad.delete(e)}}function m1(e,t,s=`${t}s`){return`${e} ${e===1?t:s}`}function f1(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function g1(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Bg(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function Wg(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 x1(e){return Bg(e)?!1:e.inboxBucket==="task_complete"&&Wg(e).length>0}function Ah(e){return e.branch||"detached HEAD"}function b1(e){if(e.error)return`${Ah(e)} · Git error: ${e.error}`;const t=[Ah(e)];return e.changedFiles>0?t.push(m1(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 y1(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${b1(t)}`}function v1(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function w1(e,t={}){if(t.enabled===!1)return[];if(!g1(e))return[];const s=Bg(e)?"working":x1(e)?"complete":null;if(!s)return[];const n=s==="complete"?Wg(e):"";return[{id:s==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${f1(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:y1(s,e.git),timestamp:v1(e,e.git),meta:{source:"git-system-bubble",phase:s,workspace:e.workspacePath,repoRoot:e.git.repoRoot,branch:e.git.branch,changedFiles:e.git.changedFiles,hasConflicts:e.git.hasConflicts}}]}const S1=60;function k1(e){return e.status==="long_generating"?"Agent has been generating for a long time. Send queues your message; Force sends it immediately.":e.status==="generating"||e.status==="streaming"?"Agent is generating. Send queues your message; Force sends it immediately.":e.status==="waiting_approval"&&(!e.modalButtons||e.modalButtons.length===0)?"Agent is waiting for approval. Approval controls will appear when available.":null}function od({activeConv:e,ideEntry:t,handleSendChat:s,handleForceSendChat:n,isSendingChat:i=!1,sendFeedbackMessage:a=null,handleFocusAgent:o,isFocusingAgent:l,actionLogs:c,userName:d,scrollToBottomRequestNonce:p,isInputActive:h=!0,isVisible:m=!0}){var le,Se,ge,G,W,Z,oe;const g=u.useRef(new Map),b=u.useRef(void 0),f=Xi(),{sendCommand:v}=jt(),{isVisible:w}=Jd();qi("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:c.length,isSendingChat:i});const x=Kt.useMemo(()=>An(e),[e.status,e.connectionState]);Kt.useEffect(()=>{const ue=e.sessionId;if(ue)return Ih(ue,x.isGenerating),()=>{Ih(ue,!1)}},[e.sessionId,x.isGenerating]);const S=u.useMemo(()=>mN(e,t),[e,t]),k=u.useMemo(()=>{var ue;return tu((ue=S.targetEntry)==null?void 0:ue.providerControls,{hostIdeType:e.hostIdeType,providerType:S.providerType})},[e.hostIdeType,S.providerType,(le=S.targetEntry)==null?void 0:le.providerControls]),j=Lg({isCliLike:S.isCli||S.isAcp}),y=BN({isCliLike:S.isCli||S.isAcp}),N=i1(e,{enabled:m&&!!e.sessionId,tailLimit:y}),[_,C]=u.useState(j),[D,T]=u.useState(()=>Yp()),A=e.tabKey,P=N.historyMessages,F=N.hasMoreHistory,J=N.historyError,R=o1(e,N),I=sg(R).length;u.useEffect(()=>{C(j)},[j,A]);const E=Math.max(0,R.length-_),$=ou(e),M=Vi(e),O=u1(e),H=lu(e),ae=k1(e),z=a||H||ae,X=!!H,[te,he]=u.useState(!1);u.useEffect(()=>{const ue=S.targetEntry;M&&(!ue||ue.providerControls===void 0||ue.controlValues===void 0)&&f(M,{minFreshMs:3e4}).catch(()=>{})},[M,S.isAcp,(Se=S.targetEntry)==null?void 0:Se.providerControls,(ge=S.targetEntry)==null?void 0:ge.controlValues,f]);const ke=u.useCallback(async()=>{if(!te){if(R.length>_){C(ue=>Math.min(R.length,ue+S1));return}he(!0);try{await N.loadHistoryPage()}finally{he(!1)}}},[N,te,R.length,_]),{allMessages:Q,receivedAtMap:q}=u.useMemo(()=>{const ue=c1({historyMessages:P,liveMessages:R,visibleLiveCount:_}),ce=w1(e),L=ce.length>0?[...ue,...ce]:ue,de={};return L.forEach((U,ie)=>{const Y=`${e.tabKey}:${bo(U,ie)}`;let Ae=$N(U)||g.current.get(Y)||0;Ae||(Ae=Date.now(),g.current.set(Y,Ae)),de[bo(U,ie)]=Ae}),{allMessages:L,receivedAtMap:de}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,E,P,R,_]),me=u.useMemo(()=>c.filter(ue=>ue.routeId===e.tabKey).sort((ue,ce)=>ue.timestamp-ce.timestamp),[c,e.tabKey]),we=u.useCallback(async()=>{var ie,Y;if(!M)return;const ue=Eg({activeConv:e,visibleMessages:Q,actionLogs:c,controls:(ie=S.targetEntry)==null?void 0:ie.providerControls,controlValues:(Y=S.targetEntry)==null?void 0:Y.controlValues,visibleBarControlCount:k.length,chatTailState:{liveMessages:N.liveMessages,hasLiveSnapshot:N.hasLiveSnapshot,hasMoreHistory:F,historyError:J,historyMessages:P},ui:{controlsVisible:w,visibleLiveCount:_,activityVisible:D,activityCount:I,hiddenLiveCount:E,isInputActive:h,isVisible:m}}),ce=await v(M,"get_chat_debug_bundle",{agentType:S.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:ue}),L=li(ce),de=Dg(L),U=await Pg(de);U==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),ht.showToast(Rg(L,{locatorCopyStatus:U}),U==="failed"?"warning":"success")},[e,c,I,Q,w,N.hasLiveSnapshot,N.liveMessages,S.providerType,(G=S.targetEntry)==null?void 0:G.controlValues,(W=S.targetEntry)==null?void 0:W.providerControls,M,F,E,P,h,m,J,v,D,k.length,_]);u.useEffect(()=>{const ue=ce=>{ce.key===eg&&T(Yp())};return window.addEventListener("storage",ue),()=>window.removeEventListener("storage",ue)},[]);const ye=u.useCallback(()=>{const ue=wN(b.current);b.current=ue.state,ue.shouldCollect&&we().catch(ce=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",ce),ht.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[we]),Te=u.useMemo(()=>{if(R.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return r.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[r.jsx("div",{className:"connecting-logo-float",children:r.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:r.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),r.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[r.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",r.jsx("span",{className:"connecting-dots"})]}),r.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((x.isGenerating||e.status==="streaming")&&he(!1),e.status==="not_monitored"&&O)return r.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[r.jsx("div",{className:"text-3xl opacity-60",children:r.jsx(vn,{size:28})}),r.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),r.jsx("button",{onClick:o,disabled:l,className:"btn btn-primary",children:l?"⌛ Switching...":r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(bn,{size:14})," Open ",$," Panel"]})}),r.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&O)return r.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[r.jsx("div",{className:"text-3xl opacity-60",children:r.jsx(Xf,{size:28})}),r.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),r.jsx("button",{onClick:o,disabled:l,className:"btn btn-primary",children:l?"⌛ Opening...":r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(bn,{size:14})," Open ",$," Panel"]})}),r.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"&&!te)return!F&&P.length===0?r.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[r.jsx("div",{className:"text-2xl opacity-40",children:"💬"}),r.jsx("div",{className:"text-[13px] opacity-40",children:"No messages yet"})]}):r.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[r.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),r.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,O,o,F,P.length,l,te,R.length,$,x.isGenerating]);return r.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col relative",children:[r.jsx("div",{className:"chat-activity-toggle-bar",children:r.jsx("div",{className:"ml-auto flex items-center gap-1",children:r.jsx(aN,{sessionId:e.sessionId,daemonId:e.daemonId,conv:e})})}),r.jsx(yk,{messages:Q,actionLogs:me,agentName:wn(e)||$||"Agent",userName:d,isCliMode:S.isCli||S.isAcp,isWorking:x.isGenerating,contextKey:e.tabKey,receivedAtMap:q,lastMessageHash:e.lastMessageHash,showActivityMessages:D,onLoadMore:ke,isLoadingMore:te,hasMoreHistory:F,hiddenLiveCount:E,loadError:J??void 0,emptyState:Te,scrollToBottomRequestNonce:p,isVisible:m}),r.jsx(_j,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:S.providerType,displayLabel:S.displayLabel,controls:(Z=S.targetEntry)==null?void 0:Z.providerControls,controlValues:(oe=S.targetEntry)==null?void 0:oe.controlValues,isActive:h,isCliTerminal:S.isCliTerminal}),!S.isCliTerminal&&r.jsx(wg,{contextKey:e.tabKey,panelLabel:$,isSending:i,isBusy:X,statusMessage:z,onSend:s,onForceSend:n,canForceSend:!!n&&x.isGenerating&&!X,isActive:h,showControlsToggle:k.length>0,onControlsToggle:ye,messageInput:e.messageInput})]})}let Ug=Fs;function Hg(){return Ug()}class j1{constructor(){re(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,s){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(s),()=>{var n;(n=this.listeners.get(t))==null||n.delete(s)}}emit(t,...s){var n;(n=this.listeners.get(t))==null||n.forEach(i=>i(...s))}}let zg=new j1;class N1{sendPtyInput(t,s,n){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,s){return!1}get(t){}onScreenshot(t,s){return()=>{}}onRuntimeEvent(t,s,n){return()=>{}}requestRuntimeSnapshot(t,s,n){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let At=new N1;function _1(e){e.dashboardWS&&(zg=e.dashboardWS),e.connectionManager&&(At=e.connectionManager),e.useDaemonsHook&&(Ug=e.useDaemonsHook)}const C1=.5,I1=1.25;function kt(e){return ou(e)}function Or(e){return Ag(e).join(" · ")}function A1(e){var i,a,o;const t=[],s=typeof((i=e.settings)==null?void 0:i.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0,n=!!((a=e.coordinator)!=null&&a.meshId)||typeof((o=e.settings)==null?void 0:o.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0;return s&&t.push("Mesh node"),n&&t.push("Coordinator"),t}function T1(e){var o,l,c;const t=[],s=typeof((o=e.settings)==null?void 0:o.meshNodeFor)=="string"?e.settings.meshNodeFor.trim():"",n=typeof((l=e.coordinator)==null?void 0:l.meshId)=="string"?e.coordinator.meshId.trim():"",i=typeof((c=e.settings)==null?void 0:c.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor.trim():"",a=n||i;if(s&&t.push(`Mesh node: ${s}`),a&&t.push(`Coordinator: ${a}`),e.meshQueueStats){const{pending:d,assigned:p,completed:h,failed:m}=e.meshQueueStats;t.push(`Queue: ${d} pending, ${p} assigned, ${h} completed, ${m} failed`)}return t.join(" · ")}function Kg(e){const t=Ig(e);return t||(e.title?e.title:Or(e)||"No messages yet")}function Gg(e,t){const{isReconnecting:s,isConnecting:n}=An(e);return s?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function M1(e,t){const s=["Chat",...Ag(e)];return t!=null&&t.timestampLabel&&s.push(t.timestampLabel),s.filter(Boolean).join(" · ")}function Cr(e){return Gg(e)||Or(e)}function E1(e){return`${kt(e)} · ${Kg(e)}`}function R1(e){const t=So(e),s=t?Vt(t):wn(e);return`${kt(e)} — ${s||"Agent"}`}function P1(e){return wn(e)||"CLI"}function qg(e){return Cg(e)}function Vg(e){return e?`Remote · ${kt(e)||e.workspaceName||"Session"}`:"Remote"}const Th=[{kind:"regex",label:"section matches",hint:"regex against a screen section",make:e=>({section:e[0],matches:""})},{kind:"elapsed",label:"elapsed_ms",hint:"N ms since state entered",make:()=>({elapsed_ms:1e3})},{kind:"stable",label:"stable_ms",hint:"region unchanged for N ms",make:()=>({stable_ms:1e3,cursor_above:5})},{kind:"changed",label:"changed",hint:"region changed vs prev frame",make:()=>({cursor_above:3,changed:!0})},{kind:"all",label:"all (AND)",hint:"every child must match",make:()=>({all:[]})},{kind:"any",label:"any (OR)",hint:"some child must match",make:()=>({any:[]})},{kind:"not",label:"not",hint:"invert a condition",make:()=>({not:{matches:""}})}],D1=[{label:"active spinner (busy)",cond:{section:"body",matches:"(?:^|\\n)\\s*[·✢✳✶✽✷✸✹]\\s+\\w.*?(?:…|\\.\\.\\.)"}},{label:"completion marker (done)",cond:{section:"body",matches:"✻\\s+\\w+ed\\s+for\\s+(?:\\d+h\\s+)?(?:\\d+m\\s+)?\\d+s"}},{label:"approval prompt (❯ 1.)",cond:{section:"footer",matches:"(?:^|\\n)\\s*[❯›>]\\s*1\\.\\s*.+"}},{label:"picker (Select a …)",cond:{section:"modal",matches:"Select (?:a |an )?(?:model|mode|option)\\b"}},{label:"stable 1.2s (settled)",cond:{stable_ms:1200,cursor_above:5}}];function L1(e){return"all"in e?"all":"any"in e?"any":"not"in e?"not":"elapsed_ms"in e?"elapsed":"stable_ms"in e&&!("changed"in e)?"stable":"changed"in e?"changed":"regex"}function pu({cond:e,path:t,sections:s,onChange:n,onRemove:i,onPreview:a,preview:o}){const l=L1(e),c=o[t],d=p=>{const h=Th.find(m=>m.kind===p);h&&n(h.make(s))};return r.jsxs("div",{className:"border border-zinc-700/60 rounded bg-zinc-800/30 p-1.5 space-y-1",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("select",{value:l,onChange:p=>d(p.target.value),className:"bg-zinc-900 text-zinc-200 text-[10px] font-mono rounded border border-zinc-700 px-1 py-0.5",children:Th.map(p=>r.jsx("option",{value:p.kind,children:p.label},p.kind))}),(l==="regex"||l==="stable"||l==="changed"||l==="elapsed")&&r.jsx("button",{type:"button",className:"text-[10px] text-sky-300 hover:text-sky-100 px-1.5 py-0.5 rounded border border-sky-700/40 hover:bg-sky-600/20",onClick:()=>a(t,e),children:"test"}),c&&c!=="loading"&&r.jsx("span",{className:`text-[10px] font-mono px-1.5 py-0.5 rounded ${c.result?"text-green-200 bg-green-600/25":"text-zinc-400 bg-zinc-700/40"}`,children:c.result?"match ✓":"no match"}),c==="loading"&&r.jsx("span",{className:"text-[10px] text-zinc-500",children:"testing…"}),i&&r.jsx("button",{type:"button",className:"ml-auto text-zinc-500 hover:text-red-300 text-xs px-1",onClick:i,children:"×"})]}),l==="regex"&&r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsxs("select",{value:e.section??"",onChange:p=>n({...e,section:p.target.value||void 0}),className:"bg-zinc-900 text-sky-300 text-[10px] font-mono rounded border border-zinc-700 px-1 py-0.5",children:[r.jsx("option",{value:"",children:"(whole screen)"}),s.map(p=>r.jsx("option",{value:p,children:p},p))]}),r.jsx("input",{value:e.matches??"",onChange:p=>n({...e,matches:p.target.value}),placeholder:"regex",spellCheck:!1,className:"flex-1 bg-black/40 text-zinc-200 text-[10px] font-mono rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"})]}),l==="elapsed"&&r.jsx(ar,{label:"elapsed_ms",value:e.elapsed_ms,onChange:p=>n({elapsed_ms:p})}),l==="stable"&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(ar,{label:"stable_ms",value:e.stable_ms,onChange:p=>n({...e,stable_ms:p})}),r.jsx(ar,{label:"cursor_above",value:e.cursor_above??0,onChange:p=>n({...e,cursor_above:p||void 0})})]}),l==="changed"&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(ar,{label:"cursor_above",value:e.cursor_above,onChange:p=>n({...e,cursor_above:p})}),r.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-zinc-400",children:[r.jsx("input",{type:"checkbox",checked:!!e.changed,onChange:p=>n({...e,changed:p.target.checked}),className:"accent-sky-500"}),"changed"]})]}),(l==="all"||l==="any")&&r.jsx($1,{kind:l,cond:e,path:t,sections:s,onChange:n,onPreview:a,preview:o}),l==="not"&&r.jsx("div",{className:"pl-2 border-l border-zinc-700",children:r.jsx(pu,{cond:e.not,path:`${t}.not`,sections:s,onChange:p=>n({not:p}),onPreview:a,preview:o})})]})}function $1({kind:e,cond:t,path:s,sections:n,onChange:i,onPreview:a,preview:o}){const l=(e==="all"?t.all:t.any)??[],c=d=>i(e==="all"?{all:d}:{any:d});return r.jsxs("div",{className:"pl-2 border-l border-zinc-700 space-y-1",children:[l.map((d,p)=>r.jsx(pu,{cond:d,path:`${s}.${e}[${p}]`,sections:n,onChange:h=>c(l.map((m,g)=>g===p?h:m)),onRemove:()=>c(l.filter((h,m)=>m!==p)),onPreview:a,preview:o},p)),r.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[r.jsx("button",{type:"button",className:"text-[10px] text-zinc-300 hover:text-white px-1.5 py-0.5 rounded border border-zinc-700 hover:bg-zinc-700/40",onClick:()=>c([...l,{section:n[0],matches:""}]),children:"+ condition"}),D1.map(d=>r.jsxs("button",{type:"button",className:"text-[10px] text-sky-300/80 hover:text-sky-100 px-1.5 py-0.5 rounded border border-sky-700/30 hover:bg-sky-600/15",onClick:()=>c([...l,JSON.parse(JSON.stringify(d.cond))]),title:"insert verified pattern",children:["+ ",d.label]},d.label))]})]})}function ar({label:e,value:t,onChange:s}){return r.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-zinc-400 font-mono",children:[e,r.jsx("input",{type:"number",value:Number.isFinite(t)?t:0,onChange:n=>s(Number(n.target.value)),className:"w-20 bg-black/40 text-zinc-200 rounded border border-zinc-700 px-1 py-0.5 outline-none focus:border-sky-500/50"})]})}function O1({sections:e,otherSectionIds:t,onChange:s,onTest:n,testResult:i}){const a=Object.keys(e),o=i&&i!=="loading"&&!("error"in i)?Object.fromEntries(i.sections.map(h=>[h.id,h])):{},l=(h,m)=>{if(!m||m===h||e[m])return;const g={};for(const[b,f]of Object.entries(e))g[b===h?m:b]=f;s(g)},c=(h,m)=>s({...e,[h]:m}),d=h=>{const m={...e};delete m[h],s(m)},p=()=>{let h="section",m=1;for(;e[h];)h=`section${m++}`;s({...e,[h]:{from_top:0}})};return r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[r.jsx("span",{className:"text-zinc-400 text-[10px] uppercase tracking-widest font-semibold",children:"Sections"}),r.jsx("span",{className:"text-zinc-600 text-[10px]",children:"— how the screen is split; conditions match against these"}),r.jsx("button",{type:"button",className:"ml-auto text-[10px] text-sky-300 hover:text-sky-100 px-1.5 py-0.5 rounded border border-sky-700/40 hover:bg-sky-600/20",onClick:n,title:"Resolve all sections against the live session screen",children:i==="loading"?"testing…":"test on live screen"}),r.jsx("button",{type:"button",className:"text-[10px] text-zinc-300 hover:text-white px-1.5 py-0.5 rounded border border-zinc-700 hover:bg-zinc-700/40",onClick:p,children:"+ section"})]}),i&&i!=="loading"&&"error"in i&&r.jsx("div",{className:"text-red-300 bg-red-900/30 border border-red-700/40 rounded p-1.5 text-[10px] mb-1",children:i.error}),r.jsx("div",{className:"space-y-1.5",children:a.map(h=>{var f;const m=e[h],g=m.anchor!=null?"anchor":"positional",b=v=>{v==="anchor"?c(h,{anchor:m.anchor??"^",anchor_last:m.anchor_last,until:m.until}):c(h,{from_top:m.from_top??0,until:m.until})};return r.jsxs("div",{className:"border border-zinc-700/60 rounded bg-zinc-800/30 p-2 space-y-1.5",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{value:h,onChange:v=>l(h,v.target.value.trim()),className:"w-28 bg-black/40 text-sky-300 font-mono text-[11px] rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"}),r.jsxs("div",{className:"inline-flex rounded border border-zinc-700 overflow-hidden text-[10px]",children:[r.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${g==="positional"?"bg-sky-600/30 text-sky-100":"text-zinc-400 hover:bg-zinc-700/40"}`,onClick:()=>b("positional"),children:"positional"}),r.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${g==="anchor"?"bg-sky-600/30 text-sky-100":"text-zinc-400 hover:bg-zinc-700/40"}`,onClick:()=>b("anchor"),children:"anchor"})]}),r.jsx("button",{type:"button",className:"ml-auto text-zinc-500 hover:text-red-300 text-sm px-1",onClick:()=>d(h),children:"×"})]}),g==="positional"?r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx(ar,{label:"from_top",value:typeof m.from_top=="number"?m.from_top:0,onChange:v=>c(h,{...m,from_top:v,from_bottom:void 0})}),r.jsx(ar,{label:"from_bottom",value:typeof m.from_bottom=="number"?m.from_bottom:0,onChange:v=>c(h,{...m,from_bottom:v||void 0})}),r.jsx(Mh,{def:m,otherIds:t(h),onChange:v=>c(h,v)})]}):r.jsxs("div",{className:"space-y-1",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"text-[10px] text-zinc-500 w-16",children:"anchor"}),r.jsx("input",{value:m.anchor??"",onChange:v=>c(h,{...m,anchor:v.target.value}),placeholder:"^regex locating section start",spellCheck:!1,className:"flex-1 bg-black/40 text-zinc-200 text-[10px] font-mono rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"}),r.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-zinc-400",children:[r.jsx("input",{type:"checkbox",checked:!!m.anchor_last,onChange:v=>c(h,{...m,anchor_last:v.target.checked||void 0}),className:"accent-sky-500"}),"last"]})]}),r.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:r.jsx(Mh,{def:m,otherIds:t(h),onChange:v=>c(h,v)})}),r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx("span",{className:"text-[10px] text-zinc-500 w-16",children:"ctx next"}),r.jsx("input",{value:((f=m.anchor_context)==null?void 0:f.next)??"",onChange:v=>c(h,{...m,anchor_context:{...m.anchor_context,next:v.target.value||void 0}}),placeholder:"optional: line after anchor must match",spellCheck:!1,className:"flex-1 bg-black/40 text-zinc-300 text-[10px] font-mono rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"})]})]}),o[h]&&r.jsxs("div",{className:"border-t border-zinc-700/50 pt-1",children:[r.jsxs("div",{className:"text-[9px] text-zinc-500 mb-0.5",children:["captured lines ",o[h].fromLine,"–",o[h].toLine,o[h].text.trim()===""&&r.jsx("span",{className:"text-amber-400 ml-1",children:"(empty — check bounds)"})]}),r.jsx("pre",{className:"font-mono text-[10px] text-zinc-300 whitespace-pre-wrap break-all bg-black/40 rounded border border-zinc-700/50 px-2 py-1 max-h-28 overflow-y-auto",children:o[h].text||"(empty)"})]})]},h)})})]})}function Mh({def:e,otherIds:t,onChange:s}){const n=e.until??"",i=n.startsWith("^");return r.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-zinc-400",children:["until",r.jsxs("select",{value:i?"__regex__":n,onChange:a=>{const o=a.target.value;s(o===""?{...e,until:void 0}:o==="__regex__"?{...e,until:n.startsWith("^")?n:"^"}:{...e,until:o})},className:"bg-zinc-900 text-sky-300 rounded border border-zinc-700 px-1 py-0.5",children:[r.jsx("option",{value:"",children:"(none)"}),t.map(a=>r.jsx("option",{value:a,children:a},a)),r.jsx("option",{value:"__regex__",children:"regex…"})]}),i&&r.jsx("input",{value:n,onChange:a=>s({...e,until:a.target.value}),spellCheck:!1,className:"w-40 bg-black/40 text-zinc-200 font-mono rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"})]})}function F1({model:e,onChange:t,onPreview:s,preview:n,onTestSections:i,sectionPreview:a}){const o=e.states.map(h=>h.id),l=Object.keys(e.sections??{}),c=u.useCallback(h=>t({...e,...h}),[e,t]),d=(h,m)=>c({states:e.states.map((g,b)=>b===h?{...g,...m}:g)}),p=(h,m)=>c({transitions:e.transitions.map((g,b)=>b===h?{...g,...m}:g)});return r.jsxs("div",{className:"space-y-3",children:[r.jsx(O1,{sections:e.sections??{},otherSectionIds:h=>l.filter(m=>m!==h),onChange:h=>c({sections:h}),onTest:()=>i(e.sections??{}),testResult:a}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[r.jsx("span",{className:"text-zinc-400 text-[10px] uppercase tracking-widest font-semibold",children:"States"}),r.jsx("button",{type:"button",className:"text-[10px] text-zinc-300 hover:text-white px-1.5 py-0.5 rounded border border-zinc-700 hover:bg-zinc-700/40",onClick:()=>c({states:[...e.states,{id:`state${e.states.length}`,label:"New"}]}),children:"+ state"})]}),r.jsx("div",{className:"space-y-1.5",children:e.states.map((h,m)=>r.jsxs("div",{className:"border border-zinc-700/60 rounded bg-zinc-800/30 p-2 space-y-1",children:[r.jsxs("div",{className:"flex items-end gap-2 flex-wrap",children:[r.jsxs("label",{className:"flex flex-col gap-0.5",children:[r.jsx("span",{className:"text-[9px] text-zinc-500 uppercase tracking-wide",children:"id (used by transitions)"}),r.jsx("input",{value:h.id,onChange:g=>d(m,{id:g.target.value}),placeholder:"idle",className:"w-32 bg-black/40 text-sky-300 font-mono text-[11px] rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"})]}),r.jsxs("label",{className:"flex flex-col gap-0.5 flex-1",children:[r.jsx("span",{className:"text-[9px] text-zinc-500 uppercase tracking-wide",children:"label (shown in dashboard)"}),r.jsx("input",{value:h.label,onChange:g=>d(m,{label:g.target.value}),placeholder:"Ready",className:"w-full bg-black/40 text-zinc-200 text-[11px] rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"})]}),r.jsx("button",{type:"button",className:"text-zinc-500 hover:text-red-300 text-sm px-1 pb-0.5",onClick:()=>c({states:e.states.filter((g,b)=>b!==m)}),children:"×"})]}),r.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-zinc-400 flex-wrap",children:[r.jsxs("label",{className:"flex items-center gap-1",children:[r.jsx("input",{type:"radio",name:"initial",checked:!!h.initial,onChange:()=>c({states:e.states.map((g,b)=>({...g,initial:b===m}))}),className:"accent-sky-500"}),"initial"]}),r.jsxs("label",{className:"flex items-center gap-1",children:[r.jsx("input",{type:"checkbox",checked:!!h.modal,onChange:g=>d(m,{modal:g.target.checked||void 0}),className:"accent-sky-500"}),"modal"]}),r.jsxs("label",{className:"flex items-center gap-1",children:["status",r.jsxs("select",{value:h.status??"",onChange:g=>d(m,{status:g.target.value||void 0}),className:"bg-zinc-900 text-zinc-200 rounded border border-zinc-700 px-1 py-0.5",children:[r.jsx("option",{value:"",children:"(auto)"}),r.jsx("option",{value:"idle",children:"idle"}),r.jsx("option",{value:"generating",children:"generating"}),r.jsx("option",{value:"approval",children:"approval"})]})]})]})]},m))})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[r.jsx("span",{className:"text-zinc-400 text-[10px] uppercase tracking-widest font-semibold",children:"Transitions"}),r.jsx("button",{type:"button",className:"text-[10px] text-zinc-300 hover:text-white px-1.5 py-0.5 rounded border border-zinc-700 hover:bg-zinc-700/40",onClick:()=>c({transitions:[...e.transitions,{from:o[0]??"",to:o[0]??""}]}),children:"+ transition"})]}),r.jsx("div",{className:"space-y-1.5",children:e.transitions.map((h,m)=>r.jsxs("div",{className:"border border-zinc-700/60 rounded bg-zinc-800/30 p-2 space-y-1.5",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("span",{className:"text-[10px] text-zinc-500",children:"from"}),r.jsx(B1,{value:h.from,states:o,onChange:g=>p(m,{from:g})}),r.jsx("span",{className:"text-[10px] text-zinc-500",children:"→"}),r.jsx("select",{value:h.to,onChange:g=>p(m,{to:g.target.value}),className:"bg-zinc-900 text-green-200 font-mono text-[10px] rounded border border-zinc-700 px-1 py-0.5",children:o.map(g=>r.jsx("option",{value:g,children:g},g))}),r.jsx("span",{className:"text-[10px] text-zinc-500 ml-1",children:"label"}),r.jsx("input",{value:h.label??"",onChange:g=>p(m,{label:g.target.value||void 0}),placeholder:"debug name only (optional)",title:"Display name shown in the debug history/transition table. Does not affect behaviour.",className:"flex-1 min-w-[120px] bg-black/40 text-zinc-300 text-[10px] rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"}),r.jsx("button",{type:"button",className:"text-zinc-500 hover:text-red-300 text-sm px-1",onClick:()=>c({transitions:e.transitions.filter((g,b)=>b!==m)}),children:"×"})]}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx(ar,{label:"min_hold_ms",value:h.min_hold_ms??0,onChange:g=>p(m,{min_hold_ms:g||void 0})}),r.jsx(ar,{label:"priority",value:h.priority??0,onChange:g=>p(m,{priority:g||void 0})})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[r.jsx("span",{className:"text-[10px] text-zinc-500",children:"when"}),!h.when&&r.jsx("button",{type:"button",className:"text-[10px] text-zinc-300 hover:text-white px-1.5 py-0.5 rounded border border-zinc-700 hover:bg-zinc-700/40",onClick:()=>p(m,{when:{section:l[0],matches:""}}),children:"+ guard condition"}),h.when&&r.jsx("button",{type:"button",className:"text-[10px] text-zinc-500 hover:text-red-300",onClick:()=>p(m,{when:void 0}),children:"remove guard"})]}),h.when&&r.jsx(pu,{cond:h.when,path:`t${m}`,sections:l,onChange:g=>p(m,{when:g}),onPreview:s,preview:n})]})]},m))})]})]})}function B1({value:e,states:t,onChange:s}){const n=new Set(Array.isArray(e)?e:e==="*"?t:[e]),i=e==="*",a=o=>{const l=new Set(n);l.has(o)?l.delete(o):l.add(o);const c=t.filter(d=>l.has(d));s(c.length===1?c[0]:c)};return r.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.map(o=>r.jsx("button",{type:"button",onClick:()=>a(o),className:`font-mono text-[10px] px-1 py-0.5 rounded border ${i||n.has(o)?"text-sky-200 bg-sky-600/25 border-sky-500/40":"text-zinc-500 border-zinc-700 hover:border-zinc-500"}`,children:o},o))})}function Wn(e){const t=Date.now()-e;if(t<0)return"just now";if(t<2e3)return`${t}ms ago`;if(t<6e4)return`${(t/1e3).toFixed(1)}s ago`;const s=Math.floor(t/6e4);return s<60?`${s}m ago`:`${Math.floor(s/60)}h ago`}function Eh(e){return e<=0?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}const W1={busy_hold_expired:"text-amber-200 bg-amber-500/20 border border-amber-500/30",idle_hold_committed:"text-green-200 bg-green-500/20 border border-green-500/30",completion_idle_after:"text-sky-200 bg-sky-500/20 border border-sky-500/30",forced_completion:"text-orange-200 bg-orange-500/20 border border-orange-500/30",forceEmit:"text-purple-200 bg-purple-500/20 border border-purple-500/30",spec_reload:"text-purple-200 bg-purple-500/20 border border-purple-500/30",eval_match:"text-zinc-300 bg-zinc-500/15 border border-zinc-500/20"},U1={idle:"text-green-100 bg-green-600/30 border border-green-500/40",busy:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",generating:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",waiting_approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",picker:"text-sky-100 bg-sky-600/30 border border-sky-500/40",signing_in:"text-sky-100 bg-sky-600/30 border border-sky-500/40"};function Xl(e){return U1[e]??"text-zinc-200 bg-zinc-600/20 border border-zinc-500/30"}function Aa({children:e}){return r.jsx("div",{className:"text-zinc-400 text-[10px] uppercase tracking-widest font-semibold mb-1.5 mt-0.5",children:e})}function Ta(){return r.jsx("div",{className:"border-t border-white/8 my-2"})}function Xg({node:e,depth:t=0}){var i;const s=e.result?"text-green-300":"text-zinc-500",n=e.result?"●":"○";return r.jsxs("div",{style:{marginLeft:t*10},className:"font-mono text-[10px] leading-relaxed",children:[r.jsxs("span",{className:s,children:[n," "]}),r.jsx("span",{className:"text-zinc-400",children:e.kind}),r.jsxs("span",{className:"text-zinc-500",children:[" ",e.detail]}),e.remainingMs!=null&&e.remainingMs>0&&r.jsxs("span",{className:"text-amber-300",children:[" (",e.remainingMs,"ms left)"]}),(i=e.children)==null?void 0:i.map((a,o)=>r.jsx(Xg,{node:a,depth:t+1},o))]})}function H1({t:e}){const[t,s]=u.useState(!1),n=e.fires?"text-green-200 bg-green-600/25 border-green-500/40":e.holdSatisfied?"text-zinc-400 bg-zinc-700/30 border-zinc-600/30":"text-amber-200 bg-amber-600/20 border-amber-500/30";return r.jsxs("div",{className:"border border-zinc-700/50 rounded bg-zinc-800/30 overflow-hidden",children:[r.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-1 hover:bg-zinc-700/30 text-left",onClick:()=>s(i=>!i),children:[r.jsx("span",{className:"text-[10px] text-zinc-500 w-3",children:e.cond?t?"▾":"▸":" "}),r.jsxs("span",{className:`font-mono text-[11px] px-1.5 py-0.5 rounded border ${n}`,children:["→ ",e.to]}),r.jsx("span",{className:"text-zinc-400 font-mono text-[10px] truncate",children:e.label}),r.jsxs("span",{className:"ml-auto flex items-center gap-1.5 shrink-0",children:[e.fires&&r.jsx("span",{className:"text-green-300 text-[10px] font-mono",children:"FIRES"}),!e.holdSatisfied&&r.jsxs("span",{className:"text-amber-300 text-[10px] font-mono",children:["hold ",e.holdRemainingMs,"ms"]}),r.jsx("span",{className:`text-[10px] font-mono ${e.condResult?"text-green-400":"text-zinc-600"}`,children:e.condResult?"cond✓":"cond✗"})]})]}),t&&e.cond&&r.jsx("div",{className:"px-3 pb-1.5 pt-0.5 bg-black/30 border-t border-zinc-700/50",children:r.jsx(Xg,{node:e.cond})})]})}function z1({activeConv:e,onClose:t}){var ye,Te,le,Se,ge;const{sendCommand:s}=jt(),[n,i]=u.useState(!0),[a,o]=u.useState(null),[l,c]=u.useState(null),[d,p]=u.useState(!1),[h,m]=u.useState(new Set(["footer"])),[g,b]=u.useState("Snapshot"),[f,v]=u.useState(!1),[w,x]=u.useState(null),[S,k]=u.useState(!1),[j,y]=u.useState(""),[N,_]=u.useState(!1),[C,D]=u.useState("idle"),[T,A]=u.useState(null),[P,F]=u.useState([]),[J,R]=u.useState({}),[I,E]=u.useState(null),[$,M]=u.useState(!1),O=e.daemonId||((ye=e.routeId)==null?void 0:ye.split(":")[0])||e.routeId||"",H=e.sessionId||"",ae=u.useCallback(async()=>{i(!0),c(null);try{const G=await s(O,"get_spec_debug",{targetSessionId:H}),W=G&&typeof G=="object"?G:{},Z=W.result&&typeof W.result=="object"?W.result:W;Z!=null&&Z.success?o(Z):(c((Z==null?void 0:Z.error)||"Failed to load spec debug"),o(null))}catch(G){c((G==null?void 0:G.message)||String(G)),o(null)}finally{i(!1)}},[s,O,H]);u.useEffect(()=>{ae()},[ae]),u.useEffect(()=>{if(!$)return;const G=setInterval(()=>{ae()},1e3);return()=>clearInterval(G)},[$,ae]),u.useEffect(()=>{const G=W=>{W.key==="Escape"&&!f&&t()};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[t,f]);const z=u.useCallback(async G=>{try{const W=await s(O,"validate_spec",{content:JSON.stringify(G)}),Z=W&&typeof W=="object"?W:{},oe=Z.result&&typeof Z.result=="object"?Z.result:Z;F(oe!=null&&oe.valid?[]:(oe==null?void 0:oe.errors)??["validation failed"])}catch(W){F([(W==null?void 0:W.message)||String(W)])}},[s,O]),X=u.useCallback(async()=>{A(null),D("idle"),R({});try{const G=await s(O,"get_spec_source",{targetSessionId:H}),W=G&&typeof G=="object"?G:{},Z=W.result&&typeof W.result=="object"?W.result:W;if(!(Z!=null&&Z.success)||typeof Z.content!="string"){A((Z==null?void 0:Z.error)||"Failed to load spec source");return}y(Z.content);let oe=null;try{oe=JSON.parse(Z.content)}catch{}oe&&oe.$schema==="adhdev:cli/spec@4"?(x(oe),k(!1),z(oe)):(x(null),k(!0)),_(!1),v(!0)}catch(G){A((G==null?void 0:G.message)||String(G))}},[s,O,H,z]),te=u.useCallback(G=>{x(G),y(JSON.stringify(G,null,2)),_(!0),D("idle"),z(G)},[z]),he=u.useCallback(async(G,W)=>{R(Z=>({...Z,[G]:"loading"}));try{const Z=await s(O,"eval_condition_preview",{targetSessionId:H,condition:W}),oe=Z&&typeof Z=="object"?Z:{},ue=oe.result&&typeof oe.result=="object"?oe.result:oe;!(ue!=null&&ue.success)||!ue.result?R(ce=>({...ce,[G]:{result:!1,detail:ue==null?void 0:ue.error}})):R(ce=>({...ce,[G]:{result:ue.result.result,detail:ue.result.detail}}))}catch(Z){R(oe=>({...oe,[G]:{result:!1,detail:Z==null?void 0:Z.message}}))}},[s,O,H]),ke=u.useCallback(async G=>{E("loading");try{const W=await s(O,"resolve_section_preview",{targetSessionId:H,sections:G}),Z=W&&typeof W=="object"?W:{},oe=Z.result&&typeof Z.result=="object"?Z.result:Z;!(oe!=null&&oe.success)||!Array.isArray(oe.sections)?E({error:(oe==null?void 0:oe.error)||"resolve failed"}):E({sections:oe.sections,screenLineCount:oe.screenLineCount??0})}catch(W){E({error:(W==null?void 0:W.message)||String(W)})}},[s,O,H]),Q=u.useCallback(async()=>{var Z,oe;const G=(Z=a==null?void 0:a.snapshot)==null?void 0:Z.specPath;if(!G){A("No spec path on this session");return}if(!S&&P.length>0){A("Fix validation errors before saving");return}const W=!S&&w?JSON.stringify(w,null,2):j;D("saving"),A(null);try{const ue=await s(O,"write_spec_source",{specPath:G,content:W}),ce=ue&&typeof ue=="object"?ue:{},L=ce.result&&typeof ce.result=="object"?ce.result:ce;if(!(L!=null&&L.success)){D("error"),A(((oe=L==null?void 0:L.validationErrors)==null?void 0:oe.join(`
|
|
42
|
+
`))||(L==null?void 0:L.error)||"Save failed");return}D("saved"),_(!1),setTimeout(()=>{ae()},400),setTimeout(()=>D("idle"),1500)}catch(ue){D("error"),A((ue==null?void 0:ue.message)||String(ue))}},[s,O,(Te=a==null?void 0:a.snapshot)==null?void 0:Te.specPath,j,w,S,P,ae]),q=a==null?void 0:a.snapshot,me=async()=>{var L,de,U;let G=a;G||(await ae(),G=a);const W=G==null?void 0:G.snapshot,Z=[];if(Z.push("# Spec Debug Snapshot"),Z.push(`Generated: ${new Date().toISOString()}`),Z.push(`Session: ${(G==null?void 0:G.sessionId)??""} (${(G==null?void 0:G.providerType)??""})`),Z.push(`Spec: ${(W==null?void 0:W.spec_id)??""} (${(W==null?void 0:W.specPath)??""})`),Z.push(`Provider: ${(W==null?void 0:W.name)??""} (${(W==null?void 0:W.cliType)??""})`),Z.push(`Working dir: ${(W==null?void 0:W.workingDir)??""}`),Z.push(`Spawned: ${W!=null&&W.spawnedAtMs?new Date(W.spawnedAtMs).toISOString():""}`),Z.push(""),Z.push("## Current State"),Z.push(`State: ${((L=W==null?void 0:W.current_state)==null?void 0:L.id)??"none"} (${((de=W==null?void 0:W.current_state)==null?void 0:de.label)??""})`),Z.push(`Status: ${(W==null?void 0:W.status)??""}`),Z.push(`Idle hold pending: ${(W==null?void 0:W.idleHoldPending)??!1}`),Z.push(`Exited: ${(W==null?void 0:W.exited)??!1}`),Z.push(`Last busy: ${W!=null&&W.lastBusyAt?Wn(W.lastBusyAt):""}`),Z.push(`Cursor: ${(W==null?void 0:W.cursorPosition)!=null?`(${W.cursorPosition.row},${W.cursorPosition.col})`:"n/a"}`),(U=W==null?void 0:W.completionIdleDebounce)!=null&&U.active){const ie=W.completionIdleDebounce;Z.push(`completion_idle_after: age=${ie.ageMs}ms hold=${ie.holdMs}ms force=${ie.forceAfterMs}ms remaining=${Math.max(0,ie.holdMs-ie.ageMs)}ms`)}if(Z.push(""),Z.push("## Modal"),W!=null&&W.current_modal){const ie=W.current_modal.buttons.map(Y=>Y.label).join(" / ");Z.push(`${W.current_modal.title??""} [${ie}]`)}else Z.push("none");Z.push(""),Z.push("## State History (last 20)");const oe=W!=null&&W.stateHistory?[...W.stateHistory].reverse().slice(0,20):[];for(const ie of oe){const Y=ie.reason!=null?typeof ie.reason=="string"?ie.reason:JSON.stringify(ie.reason):"",Ae=ie.debounceKind!=null?typeof ie.debounceKind=="string"?ie.debounceKind:JSON.stringify(ie.debounceKind):"",Ce=ie.matchedStateId!=null?String(ie.matchedStateId):"",je=(ie.matchedRules??[]).map(qe=>typeof qe=="string"?qe:JSON.stringify(qe)).join(", ");Z.push(`- ${ie.stateId} @ ${new Date(ie.at).toISOString()} held ${ie.durationMs}ms | reason: ${Y} | debounce: ${Ae} | eval→${Ce} | rules: ${je}`)}if(Z.push(""),Z.push("## Sections"),W!=null&&W.sections)for(const[ie,Y]of Object.entries(W.sections)){const Ae=Y.split(`
|
|
43
|
+
`).slice(0,3).join(`
|
|
44
|
+
`);Z.push(`${ie}: ${Ae}`)}Z.push(""),Z.push("## Last Assistant Message");const ce=[...(W==null?void 0:W.messages)??(W==null?void 0:W.committedMessages)??[]].reverse().find(ie=>ie.role==="assistant");Z.push(ce?ce.content.slice(0,400):""),Z.push(""),Z.push("## Screen (first 50 lines)"),Z.push(W!=null&&W.screen?W.screen.split(`
|
|
45
|
+
`).slice(0,50).join(`
|
|
46
|
+
`):"");try{await navigator.clipboard.writeText(Z.join(`
|
|
47
|
+
`)),b("Copied!"),setTimeout(()=>b("Snapshot"),1500)}catch(ie){console.error("[SpecDebugPanel] clipboard write failed",ie)}},we=G=>{m(W=>{const Z=new Set(W);return Z.has(G)?Z.delete(G):Z.add(G),Z})};return r.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Spec debug",className:"fixed inset-0 z-50 flex items-end justify-center bg-black/60 p-0 sm:items-center sm:p-4",onClick:t,style:{pointerEvents:"auto"},children:r.jsxs("div",{className:"bg-zinc-900 text-zinc-100 border border-zinc-700 rounded-t-xl sm:rounded-lg shadow-2xl max-w-2xl w-full max-h-[92vh] sm:max-h-[88vh] flex flex-col",onClick:G=>G.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between border-b border-zinc-700 px-4 py-2.5 shrink-0 gap-2 min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 overflow-hidden",children:[r.jsx("span",{className:"text-sm font-semibold text-zinc-100 shrink-0",children:"Spec Debug"}),q&&r.jsx("span",{className:"text-[11px] text-zinc-400 font-mono bg-zinc-800 px-1.5 py-0.5 rounded truncate",children:q.spec_id})]}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(q==null?void 0:q.specPath)&&r.jsx("button",{type:"button",className:`text-[11px] transition-colors px-2 py-1 rounded border ${f?"text-sky-200 bg-sky-600/25 border-sky-500/40":"text-zinc-300 hover:text-white hover:bg-zinc-700 border-transparent hover:border-zinc-600"}`,onClick:()=>{f?v(!1):X()},disabled:n,children:f?"Close Editor":"Edit Spec"}),r.jsx("button",{type:"button",className:"text-[11px] text-zinc-300 hover:text-white transition-colors px-2 py-1 rounded hover:bg-zinc-700 border border-transparent hover:border-zinc-600",onClick:()=>{me()},disabled:n,children:g}),r.jsx("button",{type:"button",className:"text-[11px] text-zinc-300 hover:text-white transition-colors px-2 py-1 rounded hover:bg-zinc-700 border border-transparent hover:border-zinc-600",onClick:()=>{ae()},disabled:n,children:n?"Loading…":"Refresh"}),r.jsx("button",{type:"button",className:"text-zinc-400 hover:text-zinc-100 transition-colors text-xl leading-none w-7 h-7 flex items-center justify-center rounded hover:bg-zinc-700",onClick:t,"aria-label":"Close",children:"×"})]})]}),f&&r.jsxs("div",{className:"flex-1 flex flex-col min-h-0 px-4 py-3 gap-2",children:[r.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[r.jsxs("div",{className:"inline-flex rounded border border-zinc-700 overflow-hidden text-[10px]",children:[r.jsx("button",{type:"button",className:`px-2 py-0.5 ${S?"text-zinc-400 hover:bg-zinc-700/40":"bg-sky-600/30 text-sky-100"}`,onClick:()=>{if(S)try{const G=JSON.parse(j);x(G),z(G)}catch{return}k(!1)},disabled:!w&&S,children:"Form"}),r.jsx("button",{type:"button",className:`px-2 py-0.5 ${S?"bg-sky-600/30 text-sky-100":"text-zinc-400 hover:bg-zinc-700/40"}`,onClick:()=>{w&&y(JSON.stringify(w,null,2)),k(!0)},children:"JSON"})]}),r.jsx("span",{className:"text-[10px] text-zinc-500 font-mono truncate flex-1",title:q==null?void 0:q.specPath,children:((q==null?void 0:q.specPath)??"").split("/").slice(-3).join("/")}),N&&r.jsx("span",{className:"text-amber-300 text-[10px]",children:"unsaved"}),!S&&P.length>0&&r.jsxs("span",{className:"text-red-300 text-[10px]",children:[P.length," error",P.length>1?"s":""]}),r.jsx("button",{type:"button",className:`text-[11px] px-2.5 py-1 rounded border transition-colors ${C==="saving"||!S&&P.length>0?"text-zinc-600 border-zinc-700 cursor-not-allowed":"text-green-200 bg-green-600/25 border-green-500/40 hover:bg-green-600/40"}`,onClick:()=>{Q()},disabled:C==="saving"||!S&&P.length>0,children:C==="saving"?"Saving…":C==="saved"?"Saved ✓ (reloading)":"Save & Apply"})]}),T&&r.jsx("pre",{className:"text-red-300 bg-red-900/40 border border-red-700/50 rounded p-2 text-[10px] whitespace-pre-wrap shrink-0 max-h-28 overflow-y-auto",children:T}),!S&&P.length>0&&r.jsx("div",{className:"text-red-300 bg-red-900/30 border border-red-700/40 rounded p-1.5 text-[10px] shrink-0 max-h-24 overflow-y-auto space-y-0.5",children:P.map((G,W)=>r.jsx("div",{className:"font-mono",children:G},W))}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:S||!w?r.jsx("textarea",{value:j,onChange:G=>{y(G.target.value),_(!0),D("idle")},spellCheck:!1,className:"w-full h-full min-h-[300px] font-mono text-[11px] leading-relaxed bg-black/40 text-zinc-200 border border-zinc-700 rounded p-3 resize-none outline-none focus:border-sky-500/50"}):r.jsx(F1,{model:w,onChange:te,onPreview:he,preview:J,onTestSections:ke,sectionPreview:I})}),r.jsx("div",{className:"text-[10px] text-zinc-500 shrink-0",children:S?"Raw JSON — validated on save.":'Build the FSM; from/to are constrained to existing states. "test" evaluates a condition against the live screen. Save hot-reloads the session.'})]}),!f&&r.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3 space-y-3 text-[12px]",children:[l&&r.jsx("div",{className:"text-red-300 bg-red-900/40 border border-red-700/50 rounded p-2",children:l}),n&&!a&&r.jsx("div",{className:"text-zinc-500 text-center py-6",children:"Loading…"}),a&&!a.isSpecProvider&&r.jsxs("div",{className:"text-zinc-500 text-center py-6",children:["Not a spec-driven provider (",a.providerType||"unknown",")."]}),q&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-[11px] bg-zinc-800/60 rounded-md px-3 py-2 border border-zinc-700/50",children:[q.name&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"text-zinc-500",children:"Provider"}),r.jsxs("span",{className:"font-mono text-zinc-200",children:[q.name," ",r.jsxs("span",{className:"text-zinc-500",children:["(",q.cliType,")"]})]})]}),q.workingDir&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"text-zinc-500",children:"Dir"}),r.jsx("span",{className:"font-mono text-zinc-300 truncate",title:q.workingDir,children:q.workingDir})]}),q.spawnedAtMs?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"text-zinc-500",children:"Spawned"}),r.jsx("span",{className:"text-zinc-400",children:Wn(q.spawnedAtMs)})]}):null,q.providerSessionId&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"text-zinc-500",children:"Session"}),r.jsx("span",{className:"font-mono text-zinc-500 text-[10px] truncate",title:q.providerSessionId,children:q.providerSessionId})]})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-wrap bg-zinc-800/40 rounded-md px-3 py-2 border border-zinc-700/50",children:[r.jsx("span",{className:`font-semibold font-mono text-[12px] px-2 py-0.5 rounded ${q.current_state?Xl(q.current_state.id):"text-zinc-500"}`,children:q.current_state?q.current_state.id:"none"}),((le=q.current_state)==null?void 0:le.label)&&q.current_state.label!==q.current_state.id&&r.jsx("span",{className:"text-zinc-400 text-[11px]",children:q.current_state.label}),q.status&&q.status!==((Se=q.current_state)==null?void 0:Se.id)&&r.jsxs("span",{className:"text-zinc-500 text-[11px]",children:["engine: ",r.jsx("span",{className:`font-mono ${Xl(q.status)} px-1 py-0.5 rounded text-[10px]`,children:q.status})]}),q.idleHoldPending&&r.jsx("span",{className:"text-yellow-200 text-[10px] bg-yellow-600/25 border border-yellow-500/35 px-1.5 py-0.5 rounded font-mono",children:"idle hold pending"}),q.exited&&r.jsx("span",{className:"text-red-200 text-[10px] bg-red-600/25 border border-red-500/35 px-1.5 py-0.5 rounded font-mono",children:"exited"}),q.cursorPosition!=null&&r.jsxs("span",{className:"text-zinc-500 text-[11px] font-mono",children:["cursor: ",r.jsxs("span",{className:"text-zinc-300",children:[q.cursorPosition.row,",",q.cursorPosition.col]})]}),q.lastBusyAt>0&&r.jsxs("span",{className:"text-zinc-500 text-[11px] ml-auto",children:["last busy: ",r.jsx("span",{className:"text-zinc-400",children:Wn(q.lastBusyAt)})]})]}),((ge=q.completionIdleDebounce)==null?void 0:ge.active)&&r.jsxs("div",{className:"flex items-center gap-2 text-[11px] bg-sky-900/20 border border-sky-700/30 rounded-md px-3 py-1.5 font-mono",children:[r.jsx("span",{className:"text-sky-400",children:"completion_idle_after"}),r.jsxs("span",{className:"text-zinc-400",children:["age: ",r.jsxs("span",{className:"text-sky-200",children:[q.completionIdleDebounce.ageMs,"ms"]})]}),r.jsx("span",{className:"text-zinc-500",children:"/"}),r.jsxs("span",{className:"text-zinc-400",children:["hold: ",r.jsxs("span",{className:"text-zinc-300",children:[q.completionIdleDebounce.holdMs,"ms"]})]}),r.jsxs("span",{className:"text-zinc-400",children:["force: ",r.jsxs("span",{className:"text-zinc-300",children:[q.completionIdleDebounce.forceAfterMs,"ms"]})]}),r.jsx("span",{className:"text-zinc-500 ml-auto",children:q.completionIdleDebounce.ageMs<q.completionIdleDebounce.holdMs?r.jsxs("span",{className:"text-amber-300",children:["hold remaining: ",q.completionIdleDebounce.holdMs-q.completionIdleDebounce.ageMs,"ms"]}):q.completionIdleDebounce.ageMs<q.completionIdleDebounce.forceAfterMs?r.jsxs("span",{className:"text-orange-300",children:["force in: ",q.completionIdleDebounce.forceAfterMs-q.completionIdleDebounce.ageMs,"ms"]}):r.jsx("span",{className:"text-red-300",children:"overdue"})})]}),q.current_modal&&r.jsxs("div",{className:"bg-orange-900/30 border border-orange-600/40 rounded-md p-2.5",children:[r.jsx("span",{className:"text-orange-200 font-semibold",children:"Modal: "}),r.jsx("span",{className:"text-zinc-300",children:q.current_modal.title||""}),q.current_modal.buttons.length>0&&r.jsxs("span",{className:"text-zinc-400 ml-2",children:["[",q.current_modal.buttons.map(G=>G.label).join(" / "),"]"]})]}),q.fsm&&r.jsxs(r.Fragment,{children:[r.jsx(Ta,{}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[r.jsxs(Aa,{children:["FSM — outgoing from ",r.jsx("span",{className:"text-sky-300 font-mono normal-case",children:q.fsm.currentState})," (held ",Eh(q.fsm.stateAgeMs),")"]}),r.jsxs("label",{className:"ml-auto flex items-center gap-1 text-[10px] text-zinc-500 cursor-pointer select-none mb-1.5",children:[r.jsx("input",{type:"checkbox",checked:$,onChange:G=>M(G.target.checked),className:"accent-sky-500"}),"live"]})]}),r.jsxs("div",{className:"space-y-1",children:[q.fsm.transitions.length===0&&r.jsx("div",{className:"text-zinc-600 text-[11px] italic px-1",children:"no outgoing transitions (terminal state)"}),q.fsm.transitions.map((G,W)=>r.jsx(H1,{t:G},W))]})]})]}),r.jsx(Ta,{}),q.sections&&Object.keys(q.sections).length>0&&r.jsxs("div",{children:[r.jsx(Aa,{children:"Sections"}),r.jsx("div",{className:"space-y-1",children:Object.entries(q.sections).map(([G,W])=>{var ce;const Z=h.has(G),oe=W.split(`
|
|
48
|
+
`),ue=((ce=oe[0])==null?void 0:ce.slice(0,80))||"(empty)";return r.jsxs("div",{className:"border border-zinc-700 rounded overflow-hidden bg-zinc-800/30",children:[r.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2.5 py-1.5 hover:bg-zinc-700/40 transition-colors text-left",onClick:()=>we(G),children:[r.jsx("span",{className:"text-[10px] text-zinc-500 w-3",children:Z?"▾":"▸"}),r.jsx("span",{className:"font-mono text-sky-300 w-20 shrink-0 text-[11px]",children:G}),!Z&&r.jsx("span",{className:"text-zinc-400 truncate font-mono text-[11px]",children:ue}),r.jsxs("span",{className:"ml-auto text-zinc-600 text-[10px] shrink-0",children:[oe.length,"L"]})]}),Z&&r.jsx("pre",{className:"px-3 pb-2.5 pt-1 font-mono text-[11px] text-zinc-300 whitespace-pre-wrap break-all bg-black/30 max-h-40 overflow-y-auto border-t border-zinc-700/50",children:W||"(empty)"})]},G)})})]}),r.jsx(Ta,{}),q.stateHistory&&q.stateHistory.length>0&&r.jsxs("div",{children:[r.jsxs(Aa,{children:["State History (",q.stateHistory.length,")"]}),r.jsx("div",{className:"space-y-px",children:[...q.stateHistory].reverse().slice(0,20).map((G,W)=>r.jsxs("div",{className:"rounded px-2 py-1 hover:bg-zinc-800/60 transition-colors",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("span",{className:`font-mono text-[11px] font-semibold px-1.5 py-0.5 rounded shrink-0 ${Xl(G.stateId)}`,children:G.stateId}),r.jsx("span",{className:"text-zinc-400 text-[11px] shrink-0 tabular-nums",children:Wn(G.at)}),G.durationMs>0&&r.jsxs("span",{className:"text-zinc-500 text-[11px]",children:["held ",r.jsx("span",{className:"text-zinc-400",children:Eh(G.durationMs)})]}),G.reason&&r.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${W1[String(G.reason)]??"text-zinc-400 bg-zinc-700/50 border border-zinc-600/30"}`,children:String(G.reason)}),G.debounceKind&&String(G.debounceKind)!=="none"&&r.jsxs("span",{className:"text-zinc-500 text-[10px] font-mono",children:["debounce:",String(G.debounceKind)]}),G.matchedStateId&&String(G.matchedStateId)!==G.stateId&&r.jsxs("span",{className:"text-zinc-500 text-[10px] font-mono",children:["eval→",r.jsx("span",{className:"text-zinc-300",children:String(G.matchedStateId)})]})]}),G.matchedRules&&G.matchedRules.length>0&&r.jsxs("div",{className:"flex items-start gap-1 flex-wrap mt-0.5 ml-1 pl-1 border-l border-zinc-700",children:[G.matchedRules.slice(0,3).map((Z,oe)=>r.jsx("span",{className:"font-mono text-[10px] text-sky-200 bg-sky-900/40 border border-sky-700/40 px-1.5 py-0.5 rounded break-all",children:typeof Z=="string"?Z:JSON.stringify(Z)},oe)),G.matchedRules.length>3&&r.jsxs("span",{className:"text-[10px] text-zinc-500",children:["+",G.matchedRules.length-3," more"]})]})]},W))})]}),r.jsx(Ta,{}),(()=>{const G=q.messages??q.committedMessages??[];if(G.length===0)return null;const W=G.filter(ue=>ue.role==="user").length,Z=G.filter(ue=>ue.role==="assistant").length,oe=[...G].reverse().find(ue=>ue.role==="assistant");return r.jsxs("div",{children:[r.jsxs(Aa,{children:["Transcript (",G.length," — ",W,"u / ",Z,"a)"]}),oe&&r.jsxs("div",{className:"bg-zinc-800/50 border border-zinc-700 rounded-md p-2.5 text-[11px]",children:[r.jsxs("div",{className:"text-zinc-500 mb-1 text-[10px]",children:["Last assistant ",oe.receivedAt?Wn(oe.receivedAt):""]}),r.jsxs("div",{className:"text-zinc-300 font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[oe.content.slice(0,400),oe.content.length>400?"…":""]})]})]})})(),q.specPath&&r.jsx("div",{className:"text-[10px] text-zinc-600 font-mono truncate border-t border-zinc-800 pt-2 mt-1",title:q.specPath,children:q.specPath}),r.jsxs("div",{children:[r.jsxs("button",{type:"button",className:"text-[11px] text-zinc-400 hover:text-zinc-200 transition-colors flex items-center gap-1.5",onClick:()=>p(G=>!G),children:[r.jsx("span",{className:"text-zinc-600",children:d?"▾":"▸"}),r.jsxs("span",{children:["Raw screen (",q.screen?q.screen.split(`
|
|
49
|
+
`).length:0," lines)"]})]}),d&&r.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-[11px] text-zinc-300 whitespace-pre bg-black/40 rounded-md border border-zinc-700 max-h-64 overflow-auto",children:q.screen||"(empty)"})]})]})]})]})})}function K1({activeConv:e,clearToken:t=0,terminalRef:s,handleSendChat:n,isSendingChat:i=!1,sendFeedbackMessage:a=null,isVisible:o=!0,isInputActive:l=!0}){var Ne;Fs();const{sendPtyInput:c}=jt(),[d,p]=u.useState(!1),h=u.useRef(!1);h.current=d;const[m,g]=u.useState("Runtime terminal unavailable"),[b,f]=u.useState(!1),[v,w]=u.useState(null),[x,S]=u.useState(!1),[k,j]=u.useState(!1),[y,N]=u.useState(1),[_,C]=u.useState(!1),[D,T]=u.useState(!1),[A,P]=u.useState({width:0,height:0}),[F,J]=u.useState({width:0,height:0}),[R,I]=u.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[E,$]=u.useState(null),M=u.useRef(null),O=u.useRef(null),H=u.useRef(!1),ae=u.useRef(!1),z=u.useRef(o),X=u.useRef(0),te=u.useRef(!1),he=u.useRef(""),ke=u.useRef(null),Q=u.useRef(!1),q=u.useRef(!1),me=u.useRef(null),we=u.useRef(null),ye=u.useRef(null),Te=32*1024,le=()=>{var ee,se,be,Me;return((se=(ee=M.current)==null?void 0:ee.ownerDocument)==null?void 0:se.defaultView)||((Me=(be=O.current)==null?void 0:be.ownerDocument)==null?void 0:Me.defaultView)||window},Se=ee=>{const se=le();return{ownerWindow:se,frameId:se.requestAnimationFrame(ee)}},ge=()=>{const ee=me.current;if(ee){try{ee.ownerWindow.cancelAnimationFrame(ee.frameId)}catch{}me.current=null}},G=()=>{const ee=we.current;if(ee){try{ee.ownerWindow.clearTimeout(ee.timeoutId)}catch{}we.current=null}},W=()=>{const ee=ye.current;if(ee){try{ee.ownerWindow.clearTimeout(ee.timeoutId)}catch{}ye.current=null}},Z=()=>{o&&me.current===null&&(me.current=Se(()=>{Mt()}))},oe=e.tabKey,ue=e.sessionId||"",ce=e.daemonId||((Ne=e.routeId)==null?void 0:Ne.split(":")[0])||e.routeId||"",L=lu(e),de=d?a||L:m,U=C1,ie=I1,Y=.05,Ae=()=>{const ee=F.width,se=F.height;if(!Number.isFinite(A.width)||A.width<=0||!Number.isFinite(A.height)||A.height<=0||!Number.isFinite(ee)||ee<=0||!Number.isFinite(se)||se<=0)return 1;const be=A.width/ee,Me=A.height/se;return Number(Math.min(ie,Math.max(U,Math.min(be,Me))).toFixed(2))},Ce=Ae(),je=H.current&&y>Ce,qe=Number.isFinite(F.width)&&F.width>0?Math.max(A.width,Math.round(F.width*y)):A.width,it=Number.isFinite(F.height)&&F.height>0?Math.max(A.height,Math.round(F.height*y)):A.height,lt=()=>{Se(()=>{const ee=O.current;ee&&(ee.scrollLeft=0,ee.scrollTop=ee.scrollHeight-ee.clientHeight)})},ft=()=>{var ee,se;X.current=0,te.current=!1,he.current="",ke.current=null,Q.current=!1,q.current=!1,H.current||(ae.current=!1,N(1)),me.current!==null&&ge(),p(!1),g("Runtime terminal unavailable"),W(),G(),w(null),$(null),C(!1),f(!1),S(!1),j(!1),(se=(ee=s.current)==null?void 0:ee.reset)==null||se.call(ee)},ct=()=>{var ee,se;X.current=0,te.current=!1,he.current="",ke.current=null,Q.current=!1,q.current=!1,me.current!==null&&ge(),p(!0),g(""),W(),G(),w(null),$(null),C(!1),f(!1),S(!1),j(!1),(se=(ee=s.current)==null?void 0:ee.reset)==null||se.call(ee)},_t=()=>{q.current&&(q.current=!1,Se(()=>{var ee,se;(se=(ee=s.current)==null?void 0:ee.scrollToTop)==null||se.call(ee)}))},Mt=()=>{if(me.current=null,!o)return;const ee=he.current;if(!ee)return;const se=ee.slice(0,Te);he.current=ee.slice(se.length);const be=s.current;if(!be){he.current=se+he.current,Z();return}be.write(se,()=>{if(he.current.length>0){Z();return}_t()})},Et=ee=>{ee&&(he.current+=ee,Z())},De=(ee,se=0,be,Me,$e={})=>{var Oe,ze,Le,Ye;const Re=!!$e.force;!Re&&se>0&&X.current>=se||!Re&&se===0&&te.current||(X.current=se,se>0&&S(!0),p(!0),g(""),typeof be=="number"&&typeof Me=="number"&&be>0&&Me>0&&((ze=(Oe=s.current)==null?void 0:Oe.resize)==null||ze.call(Oe,be,Me)),he.current="",(Ye=(Le=s.current)==null?void 0:Le.reset)==null||Ye.call(Le),ee?Et(ee):_t())};u.useEffect(()=>{ft()},[ue]),u.useEffect(()=>{var se;if(!ue)return;const ee=((se=At.onRuntimeEvent)==null?void 0:se.call(At,ue,be=>{if(!(!be||be.sessionId!==ue)){if(be.type==="runtime_snapshot"){if(!o){ke.current={text:be.text||"",seq:be.seq||0,cols:be.cols,rows:be.rows,force:!!be.force};return}De(be.text||"",be.seq||0,be.cols,be.rows,{force:!!be.force});return}if(be.type==="session_output"){te.current=!0,typeof be.seq=="number"&&(X.current=Math.max(X.current,be.seq),be.seq>0&&S(!0)),h.current||p(!0),h.current||g(""),typeof be.data=="string"&&Et(be.data);return}if(be.type==="session_cleared"){if(!o){Q.current=!0,he.current="",ke.current=null;return}ct();return}if(be.type==="session_io_error"){const Me=typeof be.error=="string"&&be.error?be.error:typeof be.reason=="string"&&be.reason?be.reason:"unknown error";p(!1),g(`Runtime input failed: ${Me}`);return}}},ce))||(()=>{});return()=>{ee()}},[ce,ue,s,o]);const He=async(ee={})=>{var se;if(!ce||!ue)return{success:!1,error:"daemonId and sessionId are required"};ee.preserveStatus||g(ee.loadingMessage||"Loading runtime terminal...");try{const be=await((se=At.requestRuntimeSnapshot)==null?void 0:se.call(At,ce,ue,{sinceSeq:ee.sinceSeq,force:ee.force}));return be&&be.success===!1?(ee.preserveStatus||(p(!1),g(`Runtime terminal unavailable: ${be.error}`)),be):be||{success:!0}}catch(be){const Me=(be==null?void 0:be.message)||String(be);return ee.preserveStatus||(p(!1),g(`Runtime terminal unavailable: ${Me}`)),{success:!1,error:Me}}},pt=async ee=>{var Re,Oe;const se=((Re=M.current)==null?void 0:Re.ownerDocument)||document,be=se.defaultView||window,Me=(Oe=be.navigator)==null?void 0:Oe.clipboard;if(Me!=null&&Me.writeText&&be.isSecureContext)try{return await Me.writeText(ee),!0}catch{}let $e=null;try{return $e=se.createElement("textarea"),$e.value=ee,$e.setAttribute("readonly","true"),$e.style.position="fixed",$e.style.left="-9999px",$e.style.top="0",se.body.appendChild($e),$e.focus(),$e.select(),se.execCommand("copy")}catch{return!1}finally{$e==null||$e.remove()}},Ze=ee=>{G(),$(ee);const se=le();we.current={ownerWindow:se,timeoutId:se.setTimeout(()=>{we.current=null,$(be=>be===ee?null:be)},2200)}},Lt=ee=>{W(),w(ee);const se=le();ye.current={ownerWindow:se,timeoutId:se.setTimeout(()=>{ye.current=null,w(be=>be===ee?null:be)},2200)}},B=async()=>{var $e,Re,Oe,ze;const ee=((Re=($e=s.current)==null?void 0:$e.getSelection)==null?void 0:Re.call($e))||"",se=((ze=(Oe=s.current)==null?void 0:Oe.getVisibleText)==null?void 0:ze.call(Oe))||"",be=ee.trimEnd()||se.trimEnd();if(!be){Ze("Nothing to copy");return}if(!await pt(be)){Ze("Copy failed");return}Ze(ee.trimEnd()?"Copied selection":"Copied visible terminal")},V=ee=>{if(!d||!o)return;((c==null?void 0:c(ce,ue,ee))??!1)||Ze("Terminal input failed")},ne=async()=>{if(b)return;f(!0),w("Loading older terminal output..."),q.current=!0;const ee=await He({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:d});if(f(!1),(ee==null?void 0:ee.success)===!1){q.current=!1,w(`Older terminal output unavailable: ${ee.error}`);return}j(!0),Lt("Older terminal output loaded"),Se(()=>{var se;(se=s.current)==null||se.bumpResize()})};u.useEffect(()=>{var se,be;if(!ue)return;ce&&((se=At.getState)==null?void 0:se.call(At,ce))==="connected"&&He();const ee=(be=At.onStateChange)==null?void 0:be.call(At,(Me,$e)=>{Me!==ce||$e!=="connected"||He()});return()=>{ee==null||ee()}},[ce,ue,s]),u.useEffect(()=>{t&&ft()},[t,oe,s]),u.useEffect(()=>{var Me,$e;const ee=M.current,se=($e=(Me=ee==null?void 0:ee.ownerDocument)==null?void 0:Me.defaultView)==null?void 0:$e.ResizeObserver;if(!ee||!se)return;const be=new se(Re=>{const Oe=Re[0];if(!Oe)return;const{width:ze,height:Le}=Oe.contentRect;P(Ye=>{const rt=Math.round(ze),Ct=Math.round(Le);return Ye.width===rt&&Ye.height===Ct?Ye:{width:rt,height:Ct}})});return be.observe(ee),()=>be.disconnect()},[]),u.useEffect(()=>{if(H.current)return;const ee=Ae();!Number.isFinite(ee)||ee<=0||N(se=>ae.current?ee<se-Y?ee:se:(ae.current=!0,ee))},[F.height,F.width,A.height,A.width]),u.useEffect(()=>{je&<()},[je,it,qe]),u.useEffect(()=>{var be;const ee=z.current;if(z.current=o,!o)return;ee||j(!1),Q.current&&(Q.current=!1,ct());const se=ke.current;se&&(ke.current=null,De(se.text,se.seq,se.cols,se.rows,{force:!!se.force})),ce&&ue&&((be=At.getState)==null?void 0:be.call(At,ce))==="connected"&&He(),he.current&&me.current===null&&Z(),Se(()=>{var Me;(Me=s.current)==null||Me.bumpResize()})},[ce,o,ue]),u.useEffect(()=>()=>{me.current!==null&&ge(),G(),W()},[]),u.useEffect(()=>{const ee=Me=>{var Re;const $e=Me.detail;$e!=null&&$e.sessionId&&$e.sessionId!==ue||d&&((Re=s.current)==null||Re.bumpResize())},se=le(),be=se===window?[window]:[window,se];for(const Me of be)Me.addEventListener("adhdev:fit-cli-terminal",ee);return()=>{for(const Me of be)Me.removeEventListener("adhdev:fit-cli-terminal",ee)}},[d,ue,s]);const ve=d&&x&&!k&&(R.atTop||!R.canScroll)||b||!!v;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{ref:M,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[ve&&r.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[r.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:()=>{ne()},disabled:!ue||b,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:b?"Loading older...":"Load older terminal output"}),v&&r.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:v})]}),r.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[E&&r.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:E}),r.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",onClick:()=>T(ee=>!ee),title:"Spec debug — inspect current state, sections, and transition history",children:"Debug"}),r.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:()=>{B()},disabled:!d,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),r.jsxs("div",{className:"relative",children:[r.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:()=>C(ee=>!ee),disabled:!d,"aria-label":"Open terminal control keys","aria-expanded":_,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),_&&r.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:[r.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[r.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),r.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:()=>C(!1),"aria-label":"Close terminal control keys",children:"×"})]}),r.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[r.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:()=>V("\x1B"),children:"Esc"}),r.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:()=>V(" "),children:"Tab"}),r.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:()=>V("\r"),children:"Enter"}),r.jsx("span",{"aria-hidden":"true"}),r.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:()=>V("\x1B[A"),"aria-label":"Arrow up",children:"↑"}),r.jsx("span",{"aria-hidden":"true"}),r.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:()=>V("\x1B[D"),"aria-label":"Arrow left",children:"←"}),r.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:()=>V("\x1B[B"),"aria-label":"Arrow down",children:"↓"}),r.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:()=>V("\x1B[C"),"aria-label":"Arrow right",children:"→"}),r.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:()=>V(""),children:"Ctrl-C"}),r.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:()=>V(""),children:"Ctrl-D"}),r.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:()=>V(""),children:"Bksp"})]})]})]}),r.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:()=>{H.current=!0,N(ee=>{const se=Math.max(Ce,Number((ee-.1).toFixed(2)));return se>Ce&<(),se})},title:"Shrink terminal viewport",children:"-"}),r.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:()=>{H.current=!0,N(ee=>{const se=Math.min(ie,Number((ee+.1).toFixed(2)));return se>Ce&<(),se})},title:"Increase terminal viewport",children:"+"})]}),r.jsx("div",{ref:O,className:je?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:r.jsx("div",{style:{width:qe>0?`${qe}px`:"100%",height:it>0?`${it}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:r.jsx("div",{style:{width:F.width>0?`${F.width}px`:"100%",height:F.height>0?`${F.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:y},children:r.jsx(og,{ref:s,readOnly:!d||!o,sizingMode:"measured",onViewportMetrics:J,onScrollMetrics:I,onInput:ee=>{!d||(c==null||c(ce,ue,ee))}})})})}),!d&&r.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})]}),r.jsx(wg,{contextKey:e.tabKey,panelLabel:kt(e),isSending:i,isBusy:!!L,statusMessage:de,onSend:async ee=>L?!1:n(ee),isActive:l&&o,showControlsToggle:!1,animateVisibility:!1}),D&&r.jsx(z1,{activeConv:e,onClose:()=>T(!1)})]})}const G1=5e3,q1=12e3;function V1(e){return e==="disconnected"||e==="reconnecting"}function X1({wsStatus:e,showReconnected:t,loginUrl:s,onReconnect:n,reconnectDelayMs:i=G1,reconnectActionDelayMs:a=q1}){const o=V1(e),[l,c]=u.useState(()=>!o||i<=0),[d,p]=u.useState(()=>!o||a<=0),h=u.useRef(!1);u.useEffect(()=>{if(!o){c(!1);return}if(h.current=!1,i<=0){h.current=!0,c(!0);return}c(!1);const j=setTimeout(()=>{h.current=!0,c(!0)},i);return()=>clearTimeout(j)},[i,o]),u.useEffect(()=>{if(!o){p(!1);return}if(a<=0){p(!0);return}p(!1);const j=setTimeout(()=>{p(!0)},a);return()=>clearTimeout(j)},[a,o]);const m=o?l:e==="offline"||e==="auth_failed",g=!!(n&&e!=="auth_failed"&&(!o||d)),b=u.useMemo(()=>!t||e!=="connected"?!1:i<=0||h.current,[i,t,e]),f=e==="auth_failed"?"red":e==="offline"?"orange":"accent",v={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))"},w={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)"},S="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",k={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return r.jsxs(r.Fragment,{children:[m&&r.jsx("div",{className:S,style:k,children:r.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:v[f],border:w[f],color:x[f]},children:[r.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}}),r.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&"Network offline",e==="disconnected"&&"Reconnecting",e==="reconnecting"&&"Reconnecting",e==="auth_failed"&&(s?r.jsxs(r.Fragment,{children:["Session expired."," ",r.jsx("a",{href:s,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),g&&r.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&&r.jsx("div",{className:S,style:k,children:r.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:[r.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function Yg({mode:e,onChange:t,compact:s=!1}){const n=s?14:15;return r.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"?r.jsx(Vd,{size:n}):r.jsx(zr,{size:n})})}const Ps="New session",Qg="A connected machine is ready. Start a new session with any installed provider — CLI, ACP, or IDE.";function Y1(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 Q1(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 J1(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 No({git:e,className:t="",compact:s=!1}){const n=Y1(e),i=Q1(e);if(!n||!i)return null;const a=[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 r.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 ${J1(i)} ${t}`.trim(),title:a.join(" · ")||n,"data-git-tone":i,children:[r.jsx("span",{"aria-hidden":"true",children:"⑂"}),r.jsx("span",{className:"truncate",children:n})]})}function Z1({wsStatus:e,isConnected:t,daemonCount:s,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const i=Object.values(n),a=i.filter(l=>l==="connected").length,o=i.filter(l=>l==="connecting"||l==="new"||l==="checking").length;return s>0&&o>0&&a===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 Rh({value:e}){return e?r.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Ph({notification:e,shortcutIndex:t,onOpen:s,onMarkRead:n,onMarkUnread:i,onDelete:a}){const o=al(e.updatedAt),l=!e.readAt;return r.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[r.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:s,children:[r.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),r.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?r.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",o].filter(Boolean).join(" · ")]}),e.preview?r.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),r.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?r.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:c=>{c.stopPropagation(),n()},children:"Mark read"}):r.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:c=>{c.stopPropagation(),i()},children:"Mark unread"}),r.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:c=>{c.stopPropagation(),a()},children:"Delete"})]})]})}function e_({activeConv:e,wsStatus:t,isConnected:s,conversations:n,onOpenHistory:i,onOpenRemote:a,onStopCli:o,activeCliViewMode:l,onSetCliViewMode:c,onHideConversation:d,hiddenConversations:p=[],onShowConversation:h,onShowAllHidden:m,onResetPanelsToMain:g,inboxOpen:b,onInboxOpenChange:f,hiddenOpen:v,onHiddenOpenChange:w,onOpenNewSession:x,onOpenDashboardGuide:S,guideNudgeVisible:k=!1,actionShortcuts:j,notifications:y,notificationUnreadCount:N,onOpenNotification:_,onMarkNotificationRead:C,onMarkNotificationUnread:D,onDeleteNotification:T,onOpenGitDialog:A,onOpenMeshGraph:P}){var Te;const{ides:F,p2pStates:J={}}=Fs(),R=!!e&&dt(e)&&!at(e),I=!!e&&at(e),E=!!(e!=null&&e.daemonId)&&!!((Te=e==null?void 0:e.coordinator)!=null&&Te.meshId),$=l||(e?Ng(e)?"terminal":"chat":null),[M,O]=u.useState(!1),H=u.useRef(null),ae=u.useRef(null),z=F.filter(le=>le.type==="adhdev-daemon"),X=Z1({wsStatus:t,isConnected:s,daemonCount:z.length,p2pStates:J}),te=X.subtitle,he=X.tone==="connected"?"#22c55e":X.tone==="limited"?"#eab308":"#ef4444",ke=X.tone==="connected"?"0 0 4px #22c55e80":X.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",Q=u.useMemo(()=>y.filter(le=>!le.readAt),[y]),q=u.useMemo(()=>y.filter(le=>!!le.readAt),[y]),me=u.useMemo(()=>Q.slice(0,9),[Q]),we=N;u.useEffect(()=>{if(!b)return;const le=Se=>{var ge;(ge=H.current)!=null&&ge.contains(Se.target)||f(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[b,f]),u.useEffect(()=>{if(!v)return;const le=Se=>{var ge;(ge=ae.current)!=null&&ge.contains(Se.target)||w(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[v,w]),u.useEffect(()=>{if(!v&&!b)return;const le=Se=>{if(!Se.altKey)return;const ge=Se.code.match(/^Digit([1-9])$/);if(!ge)return;const G=Number(ge[1])-1,W=v?p[G]:void 0,Z=b?me[G]:void 0;if(!(!W&&!Z)){if(Se.preventDefault(),Se.stopPropagation(),W){h==null||h(W),w(!1);return}Z&&(_(Z),f(!1))}};return window.addEventListener("keydown",le,!0),()=>window.removeEventListener("keydown",le,!0)},[p,v,b,me,w,f,_,h]);const ye=le=>{if(!le)return;const Se=n.find(ge=>ge.tabKey===le);Se&&(d==null||d(Se))};return r.jsxs("div",{className:"dashboard-header",children:[r.jsx("div",{className:"flex items-center gap-3",children:r.jsx("div",{className:"header-title-block",children:r.jsxs("div",{className:"header-title-row",children:[r.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[r.jsx(zr,{size:18}),r.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),r.jsx("span",{className:"header-title-mobile",children:e?kt(e):"Dashboard"}),r.jsx("span",{title:X.title,"aria-label":X.title,className:"header-title-status-dot",style:{background:he,boxShadow:ke}}),r.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:r.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:he,boxShadow:ke}})})]}),r.jsxs("div",{className:"header-subtitle flex items-center",children:[te&&r.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",te]}),x&&r.jsx("button",{type:"button",onClick:x,className:"btn btn-secondary btn-sm ml-2",title:`${Ps}${j!=null&&j.openNewSession?` (${j.openNewSession})`:""}`,"aria-label":Ps,children:r.jsx(Jf,{size:14})})]})]})})}),r.jsxs("div",{className:"flex gap-2 items-center",children:[S&&r.jsxs("button",{type:"button",onClick:S,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:[r.jsx("span",{className:"font-semibold leading-none",children:"?"}),k&&r.jsx("span",{children:"Guide"})]}),e&&(R||I||!at(e))&&r.jsxs("div",{className:"dashboard-header-actions-group",children:[r.jsx("span",{className:"dashboard-header-action-target",title:Or(e)||kt(e),children:kt(e)}),A&&e.git&&e.daemonId&&e.workspacePath?r.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:()=>A(e.daemonId,e.workspacePath),children:r.jsx(No,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):r.jsx(No,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),E&&P&&r.jsxs("button",{type:"button",onClick:()=>P(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:"Open live repo mesh graph",children:[r.jsx(qs,{size:14}),r.jsx("span",{className:"hidden lg:inline",children:"Mesh graph"})]}),(R||I)&&o&&r.jsxs(r.Fragment,{children:[R&&c&&$&&r.jsx(Yg,{mode:$,onChange:c,compact:!0}),r.jsx("button",{onClick:()=>o(e),className:"btn btn-secondary btn-sm",title:I?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:r.jsx(Ot,{size:14})})]}),!at(e)&&r.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:r.jsx(Gd,{size:14})}),!R&&!at(e)&&r.jsx("button",{onClick:a,className:"btn btn-secondary btn-sm",title:"Remote Control",children:r.jsx(_s,{size:14})})]}),r.jsxs("div",{className:"dashboard-header-inbox",ref:H,children:[r.jsxs("div",{className:`dashboard-header-hidden${M?" is-drop-target":""}`,ref:ae,onDragEnter:le=>{le.dataTransfer.types.includes("text/tab-key")&&(le.preventDefault(),O(!0))},onDragOver:le=>{le.dataTransfer.types.includes("text/tab-key")&&(le.preventDefault(),le.dataTransfer.dropEffect="move",O(!0))},onDragLeave:le=>{le.currentTarget.contains(le.relatedTarget)||O(!1)},onDrop:le=>{const Se=le.dataTransfer.getData("text/tab-key");le.preventDefault(),O(!1),ye(Se)},children:[r.jsxs("button",{type:"button",onClick:()=>w(!v),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${j!=null&&j.toggleHiddenTabs?` (${j.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[r.jsx(qd,{size:16}),p.length>0&&r.jsx("span",{className:"dashboard-header-hidden-badge",children:p.length})]}),v&&r.jsxs("div",{className:"dashboard-header-hidden-popover",children:[r.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),r.jsx(Rh,{value:j==null?void 0:j.toggleHiddenTabs})]}),r.jsxs("div",{className:"dashboard-header-hidden-actions",children:[g&&r.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:g,children:"Reset panels"}),p.length>0&&m&&r.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{m(),w(!1)},children:"Restore all"})]})]}),e&&d&&r.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>d(e),children:[r.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[r.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),r.jsx(Rh,{value:j==null?void 0:j.hideCurrentTab})]}),r.jsx("span",{className:"dashboard-header-hidden-current-title",children:kt(e)})]}),p.length>0?r.jsx("div",{className:"dashboard-header-hidden-list",children:p.map(le=>r.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(le),w(!1)},children:[r.jsx("span",{className:"dashboard-header-inbox-item-title",children:kt(le)}),r.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[p.indexOf(le)<9?r.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",p.indexOf(le)+1]}):null,Or(le)]})]},le.tabKey))}):r.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),r.jsxs("button",{type:"button",onClick:()=>f(!b),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[r.jsx(Gi,{size:16}),we>0&&r.jsx("span",{className:"dashboard-header-inbox-badge",children:we})]}),b&&r.jsxs("div",{className:"dashboard-header-inbox-popover",children:[Q.length>0&&r.jsxs("div",{className:"dashboard-header-inbox-section",children:[r.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),Q.map(le=>r.jsx(Ph,{notification:le,shortcutIndex:me.indexOf(le)>=0?me.indexOf(le)+1:void 0,onOpen:()=>_(le),onMarkRead:()=>C(le.id),onMarkUnread:()=>D(le.id),onDelete:()=>T(le.id)},le.id))]}),q.length>0&&r.jsxs("div",{className:"dashboard-header-inbox-section",children:[r.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),q.map(le=>r.jsx(Ph,{notification:le,onOpen:()=>_(le),onMarkRead:()=>C(le.id),onMarkUnread:()=>D(le.id),onDelete:()=>T(le.id)},le.id))]}),y.length===0&&r.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function Jt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function t_(e,t){return String(e||"")!==String(t||"")}function s_(e,t={}){const s=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),i=String(t.modelQuery||"").trim().toLowerCase(),a=!!t.resumableOnly;return!s&&!n&&!i&&!a?e:e.filter(o=>!(a&&!o.canResume||s&&![o.title,o.preview].map(c=>String(c||"").toLowerCase()).join(`
|
|
50
|
+
`).includes(s)||n&&!String(o.workspace||"").toLowerCase().includes(n)||i&&!fg(o.summaryMetadata).map(c=>c.toLowerCase()).join(`
|
|
51
|
+
`).includes(i)))}function r_(e,t="recent"){const s=e.slice();return s.sort((n,i)=>{if(t==="oldest")return(Number(n.lastMessageAt)||0)-(Number(i.lastMessageAt)||0);if(t==="messages"){const a=(Number(i.messageCount)||0)-(Number(n.messageCount)||0);if(a!==0)return a}return(Number(i.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),s}function Jg(e,t={}){return r_(s_(e,t),t.sortMode||"recent")}function _o(e){return e?"Resume saved history":"Start fresh"}function hu(e){return e?"Resuming saved history…":"Starting fresh…"}function n_(){return"Start fresh"}function i_(e,t=!1){return e==="cli"?_o(t):e==="ide"?"Start IDE":"Start ACP session"}function a_(e,t=!1){return e==="cli"?hu(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function o_(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function l_(){return"Open saved history"}function c_(){return"Saved History"}function mu(){return"Use saved history when you want continuity in the same provider conversation."}function d_(){return"No saved history found yet."}function u_(){return"Refresh saved history"}function p_(){return"Refreshing saved history…"}function Co(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function Io(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 Ao(e){return e==="start-fresh"?"Start fresh":"Restart"}function To(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Zg(e){return`Resume saved history with ${e}?`}function ex(){return"Review or change the target workspace before resuming saved history."}function h_(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 tx({activeConv:e,ides:t,isCreatingChat:s,isRefreshingHistory:n,savedSessions:i=[],isSavedSessionsLoading:a=!1,isResumingSavedSessionId:o=null,savedHistoryFilters:l,missingWorkspaceResumePath:c,onSavedHistoryFiltersChange:d,onClose:p,onNewChat:h,onSwitchSession:m,onRefreshHistory:g,onResumeSavedSession:b}){var T;const f=t.find(A=>A.id===e.routeId),v=(f==null?void 0:f.chats)||[],w=(T=f==null?void 0:f.activeChat)==null?void 0:T.id,x=dt(e)&&!at(e),[S,k]=u.useState(()=>Jt()),j=l||S,y=String(c||"").trim(),N=A=>{if(d){d(A);return}k(A)},_=u.useMemo(()=>i.map(A=>{const P=String(A.workspace||"").trim();return A.canResume||P||!y?A:{...A,workspace:y,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[y,i]),C=u.useMemo(()=>Jg(_,{textQuery:j.textQuery,workspaceQuery:j.workspaceQuery,modelQuery:j.modelQuery,resumableOnly:j.resumableOnly,sortMode:j.sortMode}),[_,j.modelQuery,j.resumableOnly,j.sortMode,j.textQuery,j.workspaceQuery]),D=r.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:[r.jsx("div",{onClick:p,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),r.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:[r.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:[r.jsxs("div",{children:[r.jsx("h3",{className:"m-0 text-lg font-extrabold",children:x?c_():"Chat History"}),r.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:R1(e)}),x&&r.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:mu()})]}),r.jsx("button",{onClick:p,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:r.jsx(Ot,{size:16})})]}),r.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!x&&r.jsx("button",{onClick:h,disabled:s,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:s?"⌛ Creating...":"+ Start New Chat Session"}),x?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[r.jsx("input",{type:"text",value:j.textQuery,onChange:A=>N({...j,textQuery:A.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"}),r.jsx("input",{type:"text",value:j.workspaceQuery,onChange:A=>N({...j,workspaceQuery:A.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"}),r.jsx("input",{type:"text",value:j.modelQuery,onChange:A=>N({...j,modelQuery:A.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"}),r.jsxs("select",{value:j.sortMode,onChange:A=>N({...j,sortMode:A.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[r.jsx("option",{value:"recent",children:"Most recent"}),r.jsx("option",{value:"oldest",children:"Oldest first"}),r.jsx("option",{value:"messages",children:"Most messages"})]})]}),r.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[r.jsx("input",{type:"checkbox",checked:j.resumableOnly,onChange:A=>N({...j,resumableOnly:A.target.checked})}),"Resume-ready only"]})]}),C.map(A=>{const P=e.providerSessionId===A.providerSessionId,F=P||!A.canResume||!!o,J=A.workspaceFallbackSource==="selected-workspace";return r.jsxs("button",{type:"button",onClick:()=>{F||!b||b(A)},disabled:F,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${P?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${F?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[r.jsxs("div",{className:"flex items-start justify-between gap-3",children:[r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("div",{className:`font-bold text-sm mb-1 truncate ${P?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:A.title||"Untitled Session"}),r.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:A.providerSessionId})]}),r.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:h_(A.lastMessageAt)})]}),r.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:A.preview||"No saved preview yet"}),r.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[r.jsxs("div",{className:"truncate",children:[A.workspace||"Workspace unknown",J?" · selected workspace":"",$r(A.summaryMetadata)?` · ${$r(A.summaryMetadata)}`:"",A.messageCount>0?` · ${A.messageCount} msgs`:""]}),r.jsx("div",{className:"shrink-0",children:P?"ACTIVE":A.canResume?J?"RESUME IN SELECTED WORKSPACE":o===A.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},A.id)})]}):v.map(A=>r.jsxs("div",{onClick:()=>{m(e.routeId,A.id),p()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${w===A.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[r.jsx("div",{className:`font-bold text-sm mb-1 ${w===A.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:A.title||"Untitled Session"}),r.jsxs("div",{className:"flex justify-between items-center",children:[r.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[A.id.substring(0,12),"..."]}),w===A.id&&r.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},A.id)),(x&&!a&&C.length===0||!x&&v.length===0)&&r.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[r.jsx("div",{className:"text-3xl mb-3 opacity-60",children:r.jsx(OS,{size:32})}),r.jsx("div",{className:"text-[13px]",children:x?i.length>0?"No saved history matches these filters.":d_():"No recent chat sessions found."})]}),x&&a&&r.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:r.jsx("div",{className:"text-[13px]",children:p_()})})]}),r.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:r.jsx("button",{onClick:g,disabled:n||a,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||a?"⌛ Refreshing...":r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(il,{size:13})," ",x?u_():"Refresh History"]})})})]})]});return typeof document>"u"?D:Si.createPortal(D,document.body)}const Dh={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 sx({toasts:e,onDismiss:t,onClickToast:s}){return r.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 i=Dh[n.type]||Dh.info;return r.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 a;(a=n.actions)!=null&&a.length||s&&s(n)},children:[r.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${i.accent}, color-mix(in srgb, ${i.accent} 55%, transparent))`}}),r.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:a=>{a.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:r.jsx(Ot,{size:14})}),r.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[r.jsx("div",{className:"flex items-center gap-2 pr-8",children:r.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:i.chipBg,color:i.chipText,border:`1px solid color-mix(in srgb, ${i.accent} 22%, transparent)`},children:i.label})}),r.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&r.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((a,o)=>r.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${a.variant==="primary"||a.variant==="danger",""}`,style:a.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)"}:a.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(),a.onClick(),t(n.id)},children:a.label},o))})]})]},n.id)})})}const m_=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function f_(e){const t=e.workspace||"";if(!t)return"";const s=t.split(/[/\\]/).filter(Boolean);return s.length>0?s[s.length-1]:t}function g_(e){return e.sessionId||e.instanceId||e.agentType}function Yl(e,t){return t||e||"unknown"}function rx(e=[]){const t={};for(const s of e)s.type==="adhdev-daemon"&&(t[s.id]=hs(s,{fallbackId:s.id}));return t}function nx(e,t={}){var n,i;const s=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((i=t.machineNames)==null?void 0:i[e.daemonId])||void 0,connectionState:t.connectionStates?t.connectionStates[s]||t.defaultConnectionState||"new":t.defaultConnectionState}}function fu(e,t={}){return x_(e,nx(e,t))}function x_(e,t={}){var h,m,g,b,f,v,w,x,S;const s=[],n=t.machineName,i=t.connectionState,a=f_(e),o=e.workspace||"",l=zk(e.type,{agentName:e.cliName}),c=dt(e)||at(e)?l:Vt(e.type),d=Array.isArray(e.childSessions)?e.childSessions.map(k=>{var j,y,N;return{sessionId:k.id,instanceId:k.id,providerSessionId:k.providerSessionId,activeChatId:(j=k.activeChat)==null?void 0:j.id,transport:k.transport,sessionCapabilities:k.capabilities,agentType:k.providerType,agentName:k.providerName||Vt(k.providerType),status:k.status,title:k.title,lastMessagePreview:k.lastMessagePreview,lastMessageRole:k.lastMessageRole,lastMessageAt:k.lastMessageAt,lastMessageHash:k.lastMessageHash,messages:((y=k.activeChat)==null?void 0:y.messages)||[],activeModal:((N=k.activeChat)==null?void 0:N.activeModal)||void 0,unread:k.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,inboxBucket:k.inboxBucket,completionMarker:k.completionMarker,surfaceHidden:k.surfaceHidden,git:k.git,settings:k.settings,coordinator:k.coordinator,messageInput:k.messageInput}}):[],p=m_(e);if(p){const k=e.sessionId||e.instanceId,j=(h=e.settings)==null?void 0:h.meshCoordinatorFor,y=((m=e.settings)==null?void 0:m.meshNodeFor)||!((g=e.settings)!=null&&g.meshCoordinatorFor)&&((b=e.settings)==null?void 0:b.launchedByCoordinator),N=j?" (Coordinator)":y?" (Mesh Node)":"",_=l+N,C=(f=e.activeChat)==null?void 0:f.activeModal,D=C&&Array.isArray(C.buttons)&&C.buttons.length>0,T=Kk(e.activeChat,[{status:e.status,activeModal:(v=e.activeChat)==null?void 0:v.activeModal}],e.agents||[]),A=e.activeChat||{title:"",messages:[]};let P=A.title&&String(A.title).trim()?String(A.title).trim():"";const F=(w=e.activeChat)==null?void 0:w.id,J=e.chats;if(F&&Array.isArray(J)&&J.length>0){const ae=J.find(z=>z.id===F||z.id&&String(z.id)===String(F));ae!=null&&ae.title&&String(ae.title).trim()&&(P=String(ae.title).trim())}const R=(dt(e)||at(e),e.type),I=(dt(e)||at(e))&&lh(P,_,R)?"":P,E=A.messages||[],$=typeof F=="string"?F.trim():"",M=(dt(e)||at(e))&&$===String(e.type||"").trim(),O=$&&!M?$:e.providerSessionId,H=e.coordinator||(typeof((x=e.settings)==null?void 0:x.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);s.push({routeId:e.id,sessionId:k,providerSessionId:e.providerSessionId,historySessionId:O,nativeSessionId:k,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:dt(e)?e.mode||"terminal":"chat",agentName:_,agentType:R,status:T,title:I,messages:E,resume:e.resume,hostIdeType:!dt(e)&&!at(e)?e.type:void 0,workspaceName:a,workspacePath:o,git:e.git,displayPrimary:I||a||(dt(e)?e.mode==="chat"?_:`Terminal${N}`:_),displaySecondary:dt(e)&&a?_:c,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:D?C.buttons:void 0,modalMessage:D?C.message:void 0,streamSource:"native",tabKey:Yl(k,e.id),machineName:n,connectionState:i,settings:e.settings,coordinator:H,messageInput:e.messageInput})}if(p&&(dt(e)||at(e)))return s;for(const k of d){const j=k.activeModal&&Array.isArray(k.activeModal.buttons)&&k.activeModal.buttons.length>0,y=Gk(k),N=g_(k),_=`${e.id}:${N}`,C=k.title&&String(k.title).trim()||"",D=lh(C,k.agentName,k.agentType)?"":C,T=k.messages||[];if(!(k.transport==="cdp-webview"||!!k.sessionId||!!k.providerSessionId||T.length>0||j||!!D||!["idle","panel_hidden","disconnected","not_monitored"].includes(y)))continue;const P=k.coordinator||(typeof((S=k.settings)==null?void 0:S.meshCoordinatorFor)=="string"&&k.settings.meshCoordinatorFor?{meshId:k.settings.meshCoordinatorFor,role:"coordinator"}:void 0);s.push({routeId:e.id,sessionId:k.sessionId||k.instanceId,providerSessionId:k.providerSessionId,historySessionId:k.activeChatId||k.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:k.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:k.sessionCapabilities,mode:"chat",agentName:k.agentName,agentType:k.agentType,status:y,title:D,messages:T,hostIdeType:e.type,workspaceName:a,workspacePath:o,git:k.git||e.git,displayPrimary:D||a||k.agentName||c,displaySecondary:`${c} · ${k.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:k.lastMessagePreview,lastMessageRole:k.lastMessageRole,lastMessageAt:k.lastMessageAt,lastMessageHash:k.lastMessageHash,lastUpdated:k.lastUpdated||e.lastUpdated,inboxBucket:k.inboxBucket,completionMarker:k.completionMarker,modalButtons:j?k.activeModal.buttons:void 0,modalMessage:j?k.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Yl(k.sessionId||k.instanceId,_),machineName:n,connectionState:i,settings:k.settings,coordinator:P,messageInput:k.messageInput})}return s.length===0&&s.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:a,workspacePath:o,git:e.git,displayPrimary:a||c,displaySecondary:c,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Yl(e.sessionId||e.instanceId,e.id),connectionState:i,settings:e.settings,messageInput:e.messageInput}),s}function ix(e){return String(e.type||e.id||"").trim()}function b_(e){var t;return e.category!=="cli"||!ix(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 Sn(e){var n;const t=new Set,s=[];for(const i of e||[]){if(!b_(i))continue;const a=ix(i);if(!a||t.has(a))continue;t.add(a);const o=String(i.displayName||i.name||a),l=i.detectedPath||((n=i.lastDetection)==null?void 0:n.path)||null;s.push({type:a,label:o,icon:i.icon,statusLabel:l?`Detected at ${l}`:"Detected on this machine",detectedPath:l})}return s}function Ji(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],s=new Set,n=[];for(const i of t){const a=typeof i=="string"?i.trim():"";!a||s.has(a)||(s.add(a),n.push(a))}return n}function eo(e,t){const s=new Set(t.map(n=>n.type));return Ji(e).filter(n=>s.has(n))}function Ci(e){return e.map(t=>t.type)}function y_(e,t){const s=Ji(e),n=t.trim();return!n||s.includes(n)?s:[...s,n]}function v_(e,t){return Ji(e).filter(s=>s!==t)}function Lh(e,t,s){const n=Ji(e),i=n.indexOf(t);if(i<0)return n;const a=n.filter(l=>l!==t);if(s==="top")return[t,...a];if(s==="bottom")return[...a,t];const o=s==="up"?Math.max(0,i-1):Math.min(a.length,i+1);return a.splice(o,0,t),a}function $h({direction:e}){return r.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"?r.jsx("polyline",{points:"18 15 12 9 6 15"}):r.jsx("polyline",{points:"6 9 12 15 18 9"})})}function Oh({value:e,availableProviders:t,onChange:s,disabled:n=!1,saveButton:i}){const[a,o]=u.useState(""),l=u.useMemo(()=>new Map(t.map(m=>[m.type,m])),[t]),c=u.useMemo(()=>eo(e,t),[e,t]),d=e.length-c.length,p=t.filter(m=>!c.includes(m.type)),h=()=>{a&&(s(y_(c,a)),o(""))};return r.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[r.jsx("div",{className:"flex flex-col gap-2",children:c.length===0?r.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."}):c.map((m,g)=>{const b=l.get(m);return r.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:[r.jsxs("div",{className:"min-w-0",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",g+1]}),(b==null?void 0:b.icon)&&r.jsx("span",{"aria-hidden":"true",children:b.icon}),r.jsx("span",{className:"font-mono text-[12px] text-text-primary",children:m}),r.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"})]}),r.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:b?`${b.label} · ${b.statusLabel}`:m})]}),r.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[r.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||g===0,title:"Move up",onClick:()=>s(Lh(c,m,"up")),children:r.jsx($h,{direction:"up"})}),r.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||g===c.length-1,title:"Move down",onClick:()=>s(Lh(c,m,"down")),children:r.jsx($h,{direction:"down"})}),r.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>s(v_(c,m)),children:"Remove"})]})]},m)})}),r.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[r.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[r.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:"Add available CLI provider"}),r.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:a,onChange:m=>o(m.target.value),disabled:n||p.length===0,children:[r.jsx("option",{value:"",children:p.length?"Select provider…":"No additional detected CLI providers"}),p.map(m=>r.jsxs("option",{value:m.type,children:[m.label," (",m.type,")"]},m.type))]})]}),r.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!a,onClick:h,children:"Add provider"}),i]}),r.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.",d>0?` ${d} provider${d===1?"":"s"} from the saved policy are not detected now and will be omitted when saved.`:""]})]})}function w_(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 ax(e,t){const s=w_(e);return{daemonId:s.daemonId,payload:{...t,...s.targetSessionId&&!t.targetSessionId?{targetSessionId:s.targetSessionId}:{}}}}const ox=[{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:"🏄"}],lx=[{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:"🧩"}],cx=[{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:"🟠"}],S_=ox,k_=lx,j_=cx;function ks(...e){return xw(bw(e))}function N_({icon:e,title:t,subtitle:s,badge:n,actions:i,className:a}){return r.jsxs("div",{className:ks("dashboard-header",a),children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"header-title flex items-center gap-2",children:[r.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&r.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]})]}),s&&r.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:s})]}),i&&r.jsx("div",{className:"flex gap-2",children:i})]})}function Zi({icon:e,title:t,subtitle:s,badge:n,actions:i,widthClassName:a="max-w-6xl",contentClassName:o,children:l}){return r.jsxs("div",{className:"flex flex-col h-full",children:[r.jsx(N_,{icon:e,title:t,subtitle:s,badge:n,actions:i}),r.jsx("div",{className:"page-content",children:r.jsx("div",{className:ks("mx-auto flex w-full flex-col gap-4",a,o),children:l})})]})}const ld="adhdev:themechange";function __(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function sn(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function rn(e){return e==="system"?__():e}function dx(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function to(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(ld,{detail:{preference:e,theme:t}}))}function C_(){const e=sn(),t=rn(e);dx(t),to(e,t)}function Gr(){const[e,t]=u.useState(sn),[s,n]=u.useState(()=>rn(sn()));u.useEffect(()=>{dx(s)},[s]),u.useEffect(()=>{const o=window.matchMedia("(prefers-color-scheme: light)"),l=c=>{if(e==="system"){const d=c.matches?"light":"dark";n(d),to("system",d)}};return o.addEventListener("change",l),()=>o.removeEventListener("change",l)},[e]),u.useEffect(()=>{const o=c=>{const d=c.detail||{},p=d.preference,h=d.theme;t(p==="dark"||p==="light"||p==="system"?p:sn()),n(h==="dark"||h==="light"?h:rn(sn()))},l=c=>{if(c.key!=="theme")return;const d=sn(),p=rn(d);t(d),n(p)};return window.addEventListener(ld,o),window.addEventListener("storage",l),()=>{window.removeEventListener(ld,o),window.removeEventListener("storage",l)}},[]);const i=u.useCallback(o=>{const l=rn(o);t(o),n(l);try{localStorage.setItem("theme",o)}catch{}to(o,l)},[]),a=u.useCallback(()=>{t(o=>{const l=o==="dark"?"light":o==="light"?"system":"dark",c=rn(l);n(c);try{localStorage.setItem("theme",l)}catch{}return to(l,c),l})},[]);return{theme:s,preference:e,setPreference:i,cycleTheme:a,isDark:s==="dark"}}const Fh={dark:"Dark",light:"Light",system:"System"};function I_({collapsed:e}){const{preference:t,cycleTheme:s}=Gr(),n=t==="dark"?r.jsx(BS,{size:16}):t==="light"?r.jsx(FS,{size:16}):r.jsx(WS,{size:16});return r.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:s,title:`Theme: ${Fh[t]} (click to cycle)`,children:[r.jsx("span",{className:"nav-icon",children:n}),!e&&r.jsx("span",{className:"text-xs",children:Fh[t]})]})}function Ql(e,t){return e?typeof e=="function"?e(t):e:null}function A_({children:e,brand:t,navItems:s,sidebarSections:n=[],footerItems:i=[],footerInfo:a,footerActions:o,preMainContent:l,collapsedStorageKey:c="sidebar-collapsed"}){const[d,p]=u.useState(!1),[h,m]=u.useState(()=>{try{return localStorage.getItem(c)==="1"}catch{return!1}}),g=()=>p(!0),b=()=>p(!1),f=()=>{m(S=>{const k=!S;try{localStorage.setItem(c,k?"1":"0")}catch{}return k})},v=u.useMemo(()=>({collapsed:h,mobileMenuOpen:d,openMobileMenu:g,closeMobileMenu:b,toggleCollapsed:f}),[h,d]),w=S=>`nav-item${S.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${S.className?` ${S.className}`:""}`,x=S=>r.jsxs("div",{className:w(S),id:`nav-${S.id}`,onClick:()=>{S.onSelect(),b()},title:h?S.title??(typeof S.label=="string"?S.label:void 0):S.title,children:[r.jsx("span",{className:"nav-icon",children:S.icon}),!h&&S.label]},S.id);return r.jsxs("div",{className:`app-layout${d?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[r.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:g,children:[r.jsx("span",{className:"mobile-menu-icon"}),r.jsx("span",{className:"mobile-menu-icon"}),r.jsx("span",{className:"mobile-menu-icon"})]}),d&&r.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:b,onKeyDown:S=>S.key==="Escape"&&b()}),r.jsxs("aside",{className:`sidebar ${d?"sidebar-open":""}`,children:[r.jsxs("div",{className:"sidebar-header",children:[r.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:Ql(t,v)}),r.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:b,children:r.jsx(Ot,{size:16})})]}),r.jsx("nav",{className:"sidebar-nav",children:s.map(x)}),n.map(S=>r.jsxs("div",{className:S.className??"border-t border-border-subtle pt-2 mt-2",children:[!h&&S.title?r.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:S.title}):null,S.items.map(x)]},S.key)),r.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[i.map(x),Ql(a,v),r.jsx(I_,{collapsed:h}),Ql(o,v)]})]}),r.jsx("main",{className:"main-content relative",children:r.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function wt({title:e,icon:t,description:s,accentColor:n,className:i,collapsible:a,defaultOpen:o=!0,badge:l,children:c}){const[d,p]=u.useState(o),h=a?d:!0,m=(e||s)&&r.jsxs("div",{className:ks("flex items-start justify-between gap-3",h&&"mb-4"),children:[r.jsxs("div",{className:"min-w-0",children:[e&&r.jsxs("h3",{className:"text-base font-semibold text-text-primary flex items-center gap-1.5",children:[t&&r.jsx("span",{children:t}),r.jsx("span",{children:e}),l]}),s&&r.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:s})]}),a&&r.jsx("span",{className:ks("mt-0.5 shrink-0 text-text-muted transition-transform select-none",h?"rotate-90":"rotate-0"),"aria-hidden":!0,children:"▸"})]});return r.jsxs("div",{className:ks("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]",i),style:n?{borderLeftColor:n}:void 0,children:[a&&m?r.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>p(g=>!g),"aria-expanded":h,children:m}):m,h&&c]})}function ul({icon:e,title:t,description:s,action:n,className:i}){return r.jsxs("div",{className:ks("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",i),children:[r.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),r.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),r.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:s}),n]})}const T_={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"},M_={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function or({variant:e,children:t,onDismiss:s,className:n}){return r.jsxs("div",{className:ks("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",T_[e],n),children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{children:M_[e]}),r.jsx("span",{children:t})]}),s&&r.jsx("button",{onClick:s,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function Wt({label:e,hint:t,children:s,className:n}){return r.jsxs("div",{className:ks("mb-5",n),children:[r.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),s,t&&r.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function di(e){const{className:t,...s}=e;return r.jsx("input",{...s,className:ks("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 E_={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"},R_={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function P_({status:e,label:t,className:s}){const n=t||e;return r.jsxs("span",{className:ks("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",E_[e],s),children:[r.jsx("span",{className:ks("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",R_[e])}),n]})}function kr({label:e,description:t,checked:s,disabled:n,onChange:i,extra:a}){return r.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[r.jsxs("div",{className:"pr-4",children:[r.jsx("div",{className:"font-medium text-sm",children:e}),r.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),r.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[a,r.jsxs("button",{type:"button",role:"switch","aria-checked":s,"aria-disabled":n,disabled:n,onClick:()=>i(!s),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[r.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:s?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),r.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)] ${s?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function D_({onPrefChange:e}){const[t,s]=sj(),[n,i]=u.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);u.useEffect(()=>{const o=()=>{if(typeof window>"u"||!("Notification"in window)){i("unsupported");return}i(Notification.permission)};return o(),window.addEventListener("focus",o),document.addEventListener("visibilitychange",o),()=>{window.removeEventListener("focus",o),document.removeEventListener("visibilitychange",o)}},[]);const a=(o,l)=>{s({[o]:l}),e==null||e(o,l)};return r.jsxs("div",{className:"flex flex-col gap-3",children:[r.jsx(kr,{label:r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(Gi,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:o=>a("globalEnabled",o)}),t.globalEnabled&&r.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&r.jsx(kr,{label:r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(_s,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:o=>a("browserNotifications",o)}),t.globalEnabled&&r.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[r.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"&&r.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[r.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),r.jsx("button",{onClick:()=>{bg().then(i)},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"&&r.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"&&r.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&&r.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[r.jsx(kr,{label:r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(Zf,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:o=>a("completionAlert",o)}),r.jsx(kr,{label:r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(US,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:o=>a("approvalAlert",o)}),r.jsx(kr,{label:r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(vn,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:o=>a("disconnectAlert",o)})]}),!t.globalEnabled&&r.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function Mo(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function L_(e,t){const s=Mo(e),n=Mo(t);if(!s||!n)return e.localeCompare(t);for(let i=0;i<3;i+=1){if(s[i]<n[i])return-1;if(s[i]>n[i])return 1}return 0}function gu(e,t){const s=e.version||null;return e.versionMismatch===!0?!0:!s||!t?!1:s!==t}function ui(e,t){if(e.versionUpdateRequired===!0)return!0;const s=e.version||null;if(!s||!t||s===t||L_(s,t)>=0)return!1;const n=Mo(s),i=Mo(t);return!n||!i?!1:n[0]!==i[0]||n[1]!==i[1]}function $_(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Jl(e,t){return e instanceof Error?e.message:t}function O_({ides:e,emptyMessage:t,sendDaemonCommand:s,onDisconnect:n,onRevokeToken:i}){const a=e.filter(o=>o.type==="adhdev-daemon");return a.length===0?r.jsx(ul,{icon:r.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."}):r.jsx("div",{className:"flex flex-col gap-2",children:a.map(o=>r.jsx(B_,{ide:o,allIdes:e,sendDaemonCommand:s,onDisconnect:n,onRevokeToken:i},o.id))})}function Bh({title:e,message:t,confirmLabel:s,confirmColor:n,onConfirm:i,onCancel:a}){const o=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return Si.createPortal(r.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:a,children:r.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:[r.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),r.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),r.jsxs("div",{className:"flex gap-2 justify-end",children:[r.jsx("button",{onClick:a,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"}),r.jsx("button",{onClick:i,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:s})]})]})}),document.body)}function F_(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...S_,...k_,...j_].find(i=>i.id===t||t.includes(i.id)||i.id.includes(t));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function B_({ide:e,allIdes:t,sendDaemonCommand:s,onDisconnect:n,onRevokeToken:i}){var F,J;const[a,o]=u.useState("idle"),[l,c]=u.useState(""),[d,p]=u.useState(null),[h,m]=u.useState("idle"),[g,b]=u.useState(""),f=e.version||null,v=((F=e.machine)==null?void 0:F.platform)||((J=e.system)==null?void 0:J.platform)||"",w=hs(e,{fallbackId:e.id}),x=v==="win32"?"🪟":v==="darwin"?"🍎":"🐧",S=t.filter(R=>R.daemonId===e.id&&R.transport==="cdp-page"),k=t.filter(R=>R.daemonId===e.id&&R.transport==="pty"),j=t.filter(R=>R.daemonId===e.id&&R.transport==="acp"),y=e.p2p,N=async()=>{if(s){o("upgrading"),c("Starting upgrade...");try{const R=$_(await s(e.id,"daemon_upgrade",{}));R.alreadyLatest?(o("done"),c(`Already on v${R.version||"latest"}.`)):R.upgraded||R.success?(o("done"),c(`Upgrade to v${R.version||"latest"} started. Daemon is restarting...`)):(o("error"),c(R.error||"Upgrade failed"))}catch(R){o("error"),c(Jl(R,"Connection lost during upgrade"))}}},_=async()=>{if(p(null),!!n){m("loading");try{await n(e.id),m("done"),b("Machine disconnected.")}catch(R){m("error"),b(Jl(R,"Failed to disconnect"))}}},C=async()=>{if(p(null),!!i){m("loading");try{await i(e.id),m("done"),b("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(R){m("error"),b(Jl(R,"Failed to revoke token"))}}},D="0.9.82",T=gu(e,D),A=ui(e,D),P=S.length+k.length+j.length;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[r.jsxs("div",{className:"flex justify-between items-center",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("span",{className:"text-xl",children:x}),r.jsxs("div",{children:[r.jsx("div",{className:"font-medium text-sm",children:w}),r.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[r.jsxs("span",{children:[e.id.substring(0,12),"…"]}),f&&r.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${T?"":"bg-bg-secondary"}`,style:T?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",f,!T&&" ✓"]})]})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[s&&T&&r.jsx("button",{onClick:N,disabled:a==="upgrading"||a==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${D}`,children:a==="upgrading"?r.jsxs("span",{className:"flex items-center gap-1",children:[r.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):a==="done"?"✓ Updated":`${A?"↑ Update now":`↑ Update${` to v${D}`}`}`}),n&&r.jsx("button",{onClick:()=>p("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),i&&r.jsx("button",{onClick:()=>p("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),r.jsx(P_,{status:e.status==="online"?"online":"error"})]})]}),r.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[y&&r.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[r.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${y.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${y.state==="connecting"||y.state==="new"?"animate-pulse":""}`,style:y.state==="connecting"||y.state==="new"?{background:"var(--status-warning)"}:void 0}),r.jsxs("span",{className:"text-text-muted",children:["P2P ",y.state==="connected"?"connected":y.state==="connecting"||y.state==="new"?"connecting...":y.state||"off"]}),y.peers!==void 0&&y.peers>0&&r.jsxs("span",{className:"text-text-muted/60",children:["(",y.peers," peer",y.peers!==1?"s":"",")"]})]}),y&&P>0&&r.jsx("span",{className:"text-border-subtle",children:"·"}),P>0?r.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[S.map(R=>{const I=F_(R.type),E=R.cdpConnected;return r.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[r.jsx("span",{children:I.icon}),r.jsx("span",{children:I.name}),E!==void 0&&r.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${E?"bg-green-400":"animate-pulse"}`,style:E?void 0:{background:"var(--status-warning)"},title:E?"CDP connected":"CDP connecting..."})]},R.id)}),k.map(R=>r.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[r.jsx("span",{children:"⌨️"}),r.jsx("span",{children:R.cliName||"CLI"})]},R.id)),j.map(R=>r.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[r.jsx("span",{children:"🔗"}),r.jsx("span",{children:R.cliName||"ACP"})]},R.id))]}):r.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||g)&&r.jsx("div",{className:`text-xs mt-2 px-1 ${a==="error"||h==="error"?"text-red-400":a==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:g||l})]}),d==="disconnect"&&r.jsx(Bh,{title:"🔌 Disconnect Machine",message:`Disconnect "${w}" from ADHDev?
|
|
52
|
+
|
|
53
|
+
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
54
|
+
|
|
55
|
+
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:_,onCancel:()=>p(null)}),d==="revoke"&&r.jsx(Bh,{title:"⚠️ Remove Machine",message:`Remove "${w}" from your dashboard?
|
|
56
|
+
|
|
57
|
+
This will:
|
|
58
|
+
• Immediately disconnect the machine
|
|
59
|
+
• Delete the machine registration
|
|
60
|
+
• Require restarting ADHDev on that machine
|
|
61
|
+
|
|
62
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:C,onCancel:()=>p(null)})]})}const W_=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function U_({daemonId:e,knownCliTypes:t=W_}){const{sendCommand:s}=jt(),[n,i]=u.useState({}),[a,o]=u.useState({}),[l,c]=u.useState(!0),[d,p]=u.useState(null),[h,m]=u.useState(null),[g,b]=u.useState(""),f=u.useCallback(async()=>{if(e){c(!0),m(null);try{const x=await s(e,"list_coordinator_prompts",{}),S=x!=null&&x.result&&typeof x.result=="object"?x.result:x;if(!(S!=null&&S.success)){m((S==null?void 0:S.error)||"Failed to load");return}const k=S.entries||{};b(S.dir||"");const j={};for(const y of t)j[y]=k[y]||{override:"",append:""};for(const y of Object.keys(k))j[y]||(j[y]=k[y]);i(j),o(JSON.parse(JSON.stringify(j)))}catch(x){m((x==null?void 0:x.message)||String(x))}finally{c(!1)}}},[s,e,t]);u.useEffect(()=>{f()},[f]);const v=u.useCallback(async(x,S)=>{var k;if(e){p(`${x}:${S}`),m(null);try{const j=((k=n[x])==null?void 0:k[S])||"",y=await s(e,"write_coordinator_prompt",{key:x,kind:S,content:j}),N=y!=null&&y.result&&typeof y.result=="object"?y.result:y;if(!(N!=null&&N.success)){m((N==null?void 0:N.error)||"Save failed");return}o(_=>({..._,[x]:{..._[x]||{override:"",append:""},[S]:j}}))}catch(j){m((j==null?void 0:j.message)||String(j))}finally{p(null)}}},[s,e,n]),w=u.useMemo(()=>(x,S)=>{var k,j;return(((k=n[x])==null?void 0:k[S])||"")!==(((j=a[x])==null?void 0:j[S])||"")},[n,a]);return e?r.jsxs("div",{className:"flex flex-col gap-4",children:[r.jsxs("div",{className:"text-[12px] text-text-muted",children:[r.jsxs("p",{children:["Customize the coordinator prompt this daemon's mesh coordinator sessions get. ",r.jsx("span",{className:"font-mono text-[11px]",children:g||"~/.adhdev/coordinator-prompts/"})]}),r.jsxs("p",{className:"mt-1",children:[r.jsx("strong",{children:"Override"})," replaces the daemon's built-in base prompt for that CLI."," ",r.jsx("strong",{children:"Append"})," stacks after whichever base wins. Leave a field empty + Save to remove it (reset to default). Supports placeholders: ","{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}",", etc."]})]}),h&&r.jsx("div",{className:"text-[12px] text-red-400 bg-red-500/10 border border-red-500/20 rounded px-3 py-2",children:h}),l&&r.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),r.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(n).map(([x,S])=>r.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[r.jsx("div",{className:"text-[13px] font-semibold mb-2",children:x}),r.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Override"}),r.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:4,value:S.override,onChange:k=>i(j=>({...j,[x]:{...j[x],override:k.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:d===`${x}:override`}),r.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:r.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void v(x,"override"),disabled:d===`${x}:override`||!w(x,"override"),children:d===`${x}:override`?"Saving…":w(x,"override")?"Save override":"Saved"})}),r.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Append"}),r.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:3,value:S.append,onChange:k=>i(j=>({...j,[x]:{...j[x],append:k.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:d===`${x}:append`}),r.jsx("div",{className:"mt-1 flex justify-end",children:r.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void v(x,"append"),disabled:d===`${x}:append`||!w(x,"append"),children:d===`${x}:append`?"Saving…":w(x,"append")?"Save append":"Saved"})})]},x))})]}):r.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const H_=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function z_(){const{preference:e,setPreference:t}=Gr();return r.jsx("div",{className:"flex gap-2",children:H_.map(s=>r.jsxs("button",{onClick:()=>t(s.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===s.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===s.id?{color:"var(--accent-on-primary)"}:void 0,children:[r.jsx("span",{children:s.icon}),s.label]},s.id))})}function K_(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 G_(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Zl(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Wh(e){const{r:t,g:s,b:n}=G_(e);return .2126*Zl(t)+.7152*Zl(s)+.0722*Zl(n)}function Uh(e,t){const s=Wh(e),n=Wh(t),i=Math.max(s,n),a=Math.min(s,n);return(i+.05)/(a+.05)}function ux(e){const t=K_(e);if(!t)return"#111827";const s="#111827",n="#ffffff";return Uh(t,s)>=Uh(t,n)?s:n}const cd={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},dd={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},q_=[{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"}}}],px="adhdev-chat-theme",hx="adhdev-chat-theme-custom";function so(){if(typeof window>"u")return"ember";try{return localStorage.getItem(px)||"ember"}catch{return"ember"}}function ws(e){try{const t=localStorage.getItem(hx);if(t){const s=JSON.parse(t);return{...e==="dark"?cd:dd,...s[e]}}}catch{}return e==="dark"?cd:dd}function Ma(e,t){try{localStorage.setItem(hx,JSON.stringify({dark:e,light:t}))}catch{}}function cs(e,t){const s=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),i=parseInt(e.slice(5,7),16);return`rgba(${s}, ${n}, ${i}, ${t})`}function Eo(e,t){const s=Math.min(255,parseInt(e.slice(1,3),16)+t),n=Math.min(255,parseInt(e.slice(3,5),16)+t),i=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${s.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}const V_={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function pi(e,t){var i;const s=(i=V_[e])==null?void 0:i[t];if(!s)return;const n=document.documentElement;n.style.setProperty("--accent-primary",s),n.style.setProperty("--accent-primary-light",Eo(s,24)),n.style.setProperty("--accent-on-primary",ux(s)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${s}, ${Eo(s,18)})`),n.style.setProperty("--border-accent",cs(s,.35)),n.style.setProperty("--nav-active-bg",cs(s,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${s}, 0 0 12px ${cs(s,.06)}`)}function Ir(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",cs(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",cs(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",cs(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",cs(e.borderSubtle,.5)),t.style.setProperty("--border-default",cs(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Eo(e.accentColor,30)),t.style.setProperty("--accent-on-primary",ux(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Eo(e.accentColor,40)})`),t.style.setProperty("--border-accent",cs(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",cs(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${cs(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 ${cs(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 xu(){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(s=>e.style.removeProperty(s))}function X_(e){try{localStorage.setItem(px,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Ar()?"dark":"light";Ir(ws(t))}else xu(),pi(e,Ar()?"dark":"light")}function Y_(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=so();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Ar()?"dark":"light";Ir(ws(t))}else xu(),pi(e,Ar()?"dark":"light")}function Ar(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Qt({label:e,value:t,onChange:s}){return r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[r.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[r.jsx("input",{type:"color",value:t,onChange:n=>s(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),r.jsx("input",{type:"text",value:t,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&s(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 Un({title:e,children:t}){return r.jsxs("div",{style:{marginBottom:14},children:[r.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}),r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function Q_({dark:e,onColorsChange:t}){const s=e?"dark":"light",[n,i]=u.useState(()=>ws(s));u.useEffect(()=>{i(ws(s))},[s]);const a=u.useCallback((o,l)=>{i(c=>{const d={...c,[o]:l},h=ws(s==="dark"?"light":"dark");return s==="dark"?Ma(d,h):Ma(h,d),Ir(d),t(d),d})},[s,t]);return r.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[r.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",r.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"]})]}),r.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[r.jsxs("div",{children:[r.jsxs(Un,{title:"App Background",children:[r.jsx(Qt,{label:"Background",value:n.bgPrimary,onChange:o=>a("bgPrimary",o)}),r.jsx(Qt,{label:"Surface",value:n.bgSecondary,onChange:o=>a("bgSecondary",o)}),r.jsx(Qt,{label:"Card",value:n.surfacePrimary,onChange:o=>a("surfacePrimary",o)})]}),r.jsxs(Un,{title:"App Text",children:[r.jsx(Qt,{label:"Primary",value:n.textPrimary,onChange:o=>a("textPrimary",o)}),r.jsx(Qt,{label:"Secondary",value:n.textSecondary,onChange:o=>a("textSecondary",o)}),r.jsx(Qt,{label:"Muted",value:n.textMuted,onChange:o=>a("textMuted",o)})]}),r.jsxs(Un,{title:"Borders & Accent",children:[r.jsx(Qt,{label:"Border subtle",value:n.borderSubtle,onChange:o=>a("borderSubtle",o)}),r.jsx(Qt,{label:"Border default",value:n.borderDefault,onChange:o=>a("borderDefault",o)}),r.jsx(Qt,{label:"Accent",value:n.accentColor,onChange:o=>a("accentColor",o)})]})]}),r.jsxs("div",{children:[r.jsxs(Un,{title:"Chat Bubbles",children:[r.jsx(Qt,{label:"User bubble",value:n.userBubble,onChange:o=>a("userBubble",o)}),r.jsx(Qt,{label:"User text",value:n.userText,onChange:o=>a("userText",o)}),r.jsx(Qt,{label:"Agent bubble",value:n.assistantBubble,onChange:o=>a("assistantBubble",o)}),r.jsx(Qt,{label:"Agent text",value:n.assistantText,onChange:o=>a("assistantText",o)})]}),r.jsxs(Un,{title:"Chat Layout",children:[r.jsx(Qt,{label:"Chat BG",value:n.containerBg,onChange:o=>a("containerBg",o)}),r.jsx(Qt,{label:"Send button",value:n.sendButton,onChange:o=>a("sendButton",o)}),r.jsx(Qt,{label:"Input border",value:n.inputBorder,onChange:o=>a("inputBorder",o)}),r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[r.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[r.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:o=>a("bubbleRadius",Number(o.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),r.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),r.jsx("button",{onClick:()=>{const o=e?cd:dd,c=ws(e?"light":"dark");e?Ma(o,c):Ma(c,o),i(o),Ir(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 J_(){const[e,t]=u.useState(so),[s,n]=u.useState(!0),[i,a]=u.useState(()=>ws("dark"));u.useEffect(()=>{n(Ar());const c=new MutationObserver(()=>{const h=Ar();n(h);const m=so();m==="custom"?Ir(ws(h?"dark":"light")):pi(m,h?"dark":"light")});c.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const d=window.matchMedia("(prefers-color-scheme: dark)"),p=()=>{const h=Ar();n(h);const m=so();m==="custom"?Ir(ws(h?"dark":"light")):pi(m,h?"dark":"light")};return d.addEventListener("change",p),()=>{c.disconnect(),d.removeEventListener("change",p)}},[]),u.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?Ir(ws(s?"dark":"light")):(xu(),pi(e,s?"dark":"light"))},[e,s]),u.useEffect(()=>{a(ws(s?"dark":"light"))},[s]);const o=c=>{t(c),X_(c)},l=[...q_,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:i.userBubble,assistantBubble:i.assistantBubble,assistantBorder:`1px solid ${i.accentColor}22`,containerBg:i.containerBg,textColor:i.assistantText},light:{userBubble:i.userBubble,assistantBubble:i.assistantBubble,assistantBorder:`1px solid ${i.accentColor}22`,containerBg:i.containerBg,textColor:i.assistantText}}}];return r.jsxs("div",{children:[r.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(c=>{const d=e===c.id,p=s?c.preview.dark:c.preview.light,h=c.id==="honey"||c.id==="ember"?"#1a1a1a":c.id==="custom"?i.userText:"#fff";return r.jsxs("button",{onClick:()=>o(c.id),className:"text-left rounded-xl p-3 transition-all",style:{background:d?"var(--bg-glass-hover)":"var(--bg-glass)",border:d?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:d?1:.75},children:[r.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:p.containerBg},children:[r.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:p.assistantBubble,border:p.assistantBorder,color:p.textColor},children:"Hello! How can I help?"}),r.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:p.userBubble,color:h},children:"Fix the bug please"}),r.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:p.assistantBubble,border:p.assistantBorder,color:p.textColor},children:"On it! ✨"})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[d&&r.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),r.jsxs("div",{children:[r.jsx("div",{className:"text-sm font-bold text-text-primary",children:c.id==="custom"?"🎨 Custom":c.name}),r.jsx("div",{className:"text-[10px] text-text-muted",children:c.description})]})]})]},c.id)})}),e==="custom"&&r.jsx(Q_,{dark:s,onColorsChange:c=>a(c)})]})}const bu="adhdev_mobileDashboardMode_v1",ud="adhdev:mobile-dashboard-mode-change";function yu(){try{return localStorage.getItem(bu)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Z_(e){if(typeof window>"u")return()=>{};const t=i=>{e(i??yu())},s=i=>{const a=i.detail;t(a)},n=i=>{i.key&&i.key!==bu||t()};return window.addEventListener(ud,s),window.addEventListener("storage",n),()=>{window.removeEventListener(ud,s),window.removeEventListener("storage",n)}}function eC(e){try{localStorage.setItem(bu,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ud,{detail:e}))}function tC(){const[e,t]=u.useState(!0);return u.useEffect(()=>{t(yu()==="chat")},[]),r.jsx(kr,{label:r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(zr,{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:s=>{t(s),eC(s?"chat":"workspace")},extra:r.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const ec=new Map,Hh=new Map;function sC(e){if(!e||typeof e!="object")return null;const t=e,s=t.result&&typeof t.result=="object"?t.result:t,n=s.machine;return!n||typeof n!="object"?null:{machine:n,timestamp:typeof s.timestamp=="number"?s.timestamp:void 0}}function rC(e,t,s,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:s.platform,machine:s}}function mx(){const{sendCommand:e}=jt(),{injectEntries:t,getIdes:s}=ji();return u.useCallback(async(n,i)=>{if(!n)return;const a=(i==null?void 0:i.minFreshMs)??TN,o=Hh.get(n)||0;if(!(i!=null&&i.force)&&o>0&&Date.now()-o<a)return;const l=ec.get(n);if(l)return l;const c=(async()=>{const d=await e(n,"get_machine_runtime_stats"),p=sC(d);if(!p)return;const h=s().find(g=>g.id===n),m=rC(h,n,p.machine,p.timestamp||Date.now());t([m]),Hh.set(n,Date.now())})().finally(()=>{ec.delete(n)});return ec.set(n,c),c},[s,t,e])}function nC(e,t,s){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:s.timestamp,platform:s.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...s.machine}}}function iC(e,t){const{sendData:s}=jt(),{injectEntries:n,getIdes:i}=ji(),a=Array.from(new Set(e.filter(Boolean))).join("|");u.useEffect(()=>{if(!(t!=null&&t.enabled)||!s)return;const o=a?a.split("|"):[];if(o.length===0)return;const l=o.map(c=>Os.subscribe({sendData:s},c,{type:"subscribe",topic:"machine.runtime",key:`machine:${c}`,params:{intervalMs:t==null?void 0:t.intervalMs}},p=>{const h=i().find(g=>g.id===c),m=nC(h,c,p);n([m])}));return()=>{l.forEach(c=>c())}},[a,i,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,s])}function aC(e,t){const{sendData:s}=jt(),[n,i]=u.useState(null),[a,o]=u.useState(!1);return u.useEffect(()=>{if(!e){i(null),o(!1);return}if(!(t!=null&&t.enabled)||!s){o(!1);return}i(null),o(!0);let l=null;const c=Os.subscribe({sendData:s},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}:{}}},d=>{l&&(clearTimeout(l),l=null),i(d.diagnostics),o(!1)});return c.initialSendAccepted?l=setTimeout(()=>{o(!1)},PN):o(!1),()=>{l&&clearTimeout(l),c()}},[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,s]),{diagnostics:n,loading:a,applyDiagnostics:i}}function oC(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function fx(e){const{sendData:t}=jt(),[s,n]=u.useState({});return u.useEffect(()=>{const i=oC(e);if(!i||!e.sessionId||!t){n({});return}const a=Os.subscribe({sendData:t},i,{type:"subscribe",topic:"session.modal",key:`daemon:${i}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},o=>{n({status:o.status,modalMessage:o.modalMessage,modalButtons:o.modalButtons}),gn.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 a.initialSendAccepted||n({}),()=>{a()}},[e.daemonId,e.routeId,e.sessionId,t]),s}const gx="adhdev_hiddenTabs",xx="adhdev_autoHiddenMeshTabs";function lC(){try{const e=localStorage.getItem(gx);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function yr(e){try{localStorage.setItem(gx,JSON.stringify([...e]))}catch{}}function cC(){try{const e=localStorage.getItem(xx);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function zh(e){try{localStorage.setItem(xx,JSON.stringify([...e]))}catch{}}function ei(e){return _i(e)}function pl(e,t){return Vs(t).some(s=>e.has(s))}function bx(e){var t,s,n;return((t=e.settings)==null?void 0:t.launchedByCoordinator)===!0&&typeof((s=e.settings)==null?void 0:s.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0&&((n=e.settings)==null?void 0:n.spawnedSessionVisibility)==="hidden"}function dC(e,t,s=new Set){return e.filter(n=>{if(!bx(n))return!1;const i=ei(n);return s.has(i)?!1:!pl(t,n)})}function uC(){const[e,t]=u.useState(lC),[s,n]=u.useState(cC),i=u.useCallback(m=>{const g=ei(m);t(b=>{const f=new Set(b);return f.has(g)?f.delete(g):f.add(g),yr(f),f})},[]),a=u.useCallback(m=>{const g=ei(m);t(b=>{if(b.has(g))return b;const f=new Set(b);return f.add(g),yr(f),f})},[]),o=u.useCallback(m=>{const g=ei(m);t(b=>{if(b.has(g))return b;const f=new Set(b);return f.add(g),yr(f),f}),n(b=>{if(b.has(g))return b;const f=new Set(b);return f.add(g),zh(f),f})},[]),l=u.useCallback(m=>{const g=ei(m);t(b=>{if(!b.has(g))return b;const f=new Set(b);return f.delete(g),yr(f),f}),n(b=>{if(b.has(g))return b;const f=new Set(b);return f.add(g),zh(f),f})},[]),c=u.useCallback(()=>{t(m=>{if(m.size===0)return m;const g=new Set;return yr(g),g})},[]),d=u.useCallback((m,g)=>{t(b=>{const f=new Set(b);for(const v of g)f.add(v);return yr(f),f})},[]),p=u.useCallback((m,g)=>{t(b=>{const f=new Set(b);for(const v of g)f.delete(v);return yr(f),f})},[]),h=u.useCallback(m=>pl(e,m),[e]);return{hiddenTabs:e,autoHiddenTabs:s,toggleTarget:i,hideTarget:a,autoHideTarget:o,showTarget:l,showAllTabs:c,hideAllForDaemon:d,showAllForDaemon:p,isHidden:h}}const Ea="adhdev_mutedConversations",tc="adhdev_autoMutedMeshConversations";function Kh(e){try{const t=localStorage.getItem(e);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function Hn(e,t){try{localStorage.setItem(e,JSON.stringify([...t]))}catch{}}function pC(e,t){return Vs(t).some(s=>e.has(s))}function hC(){const[e,t]=u.useState(()=>Kh(Ea)),[s,n]=u.useState(()=>Kh(tc)),i=u.useCallback(d=>{const p=_i(d);t(h=>{if(h.has(p))return h;const m=new Set(h);return m.add(p),Hn(Ea,m),m})},[]),a=u.useCallback(d=>{const p=Vs(d);t(h=>{let m=!1;const g=new Set(h);for(const b of p)g.delete(b)&&(m=!0);return m?(Hn(Ea,g),g):h}),n(h=>{let m=!1;const g=new Set(h);for(const b of p)g.delete(b)&&(m=!0);return m?(Hn(tc,g),g):h})},[]),o=u.useCallback(d=>{Vs(d).some(m=>e.has(m))?a(d):i(d)},[e,i,a]),l=u.useCallback(d=>{if(!bx(d))return;const p=_i(d);s.has(p)||(n(h=>{if(h.has(p))return h;const m=new Set(h);return m.add(p),Hn(tc,m),m}),t(h=>{if(h.has(p))return h;const m=new Set(h);return m.add(p),Hn(Ea,m),m}))},[s]),c=u.useCallback(d=>pC(e,d),[e]);return{mutedTargets:e,autoMutedTargets:s,muteTarget:i,unmuteTarget:a,toggleTarget:o,autoMuteIfCoordinator:l,isMuted:c}}function mC(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function fC(e){const t=(e==null?void 0:e.result)??e;return typeof(t==null?void 0:t.error)=="string"?t.error:"Interactive prompt response failed"}async function gC(e,t,s){const n=await s(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let i=`HTTP ${n.status}`;try{const a=await n.json();typeof(a==null?void 0:a.error)=="string"&&(i=a.error)}catch{}throw new Error(i)}}async function xC({promptSession:e,response:t,useP2PCommand:s,sendCommand:n,fetchImpl:i=fetch}){if(s){const a=await n(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!mC(a))throw new Error(fC(a));return}await gC(e.sessionId,t,i)}function yx(e){const{ides:t,isP2PActive:s,p2pStates:n}=Fs(),{sendCommand:i}=jt(),[a,o]=u.useState(null),[l,c]=u.useState(!1),[d,p]=u.useState(null),h=u.useMemo(()=>Tk(t,e),[t,e]),m=!!h,g=u.useMemo(()=>h?h.prompt.promptId===a?null:h:null,[a,h]),b=u.useCallback(async w=>{if(!g)return;const x=cg(g.prompt,w);c(!0),p(null);try{const S=(n==null?void 0:n[g.daemonId])==="connected"||s===!0;await xC({promptSession:g,response:x,useP2PCommand:S,sendCommand:i}),o(g.prompt.promptId)}catch(S){throw p(S instanceof Error?S.message:String(S)),S}finally{c(!1)}},[s,n,g,i]),f=u.useCallback(()=>{g&&o(g.prompt.promptId)},[g]),v=u.useCallback(()=>{o(null),p(null)},[]);return{promptSession:g,hasActivePrompt:m,responseError:d,isSubmitting:l,submit:b,cancel:f,reopen:v}}function vx(e){return e instanceof Error?e.message:String(e||"")}function bC(e){const t=vx(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 yC(e){const t=vx(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function wx({conversation:e,mode:t,ides:s,sendDaemonCommand:n,setCliViewModeOverrides:i}){if(!e||!dt(e)||at(e))return;const a=Tn(e);if(a===t)return;const o=e.sessionId;o&&i(l=>({...l,[o]:t}));try{await n(Kr(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:$s(e),mode:t})}catch(l){const c=yC(l);o&&!c&&i(d=>{const p={...d};return a===Sx(s,o)?delete p[o]:p[o]=a,p}),bC(l)?console.warn(c?"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 Gh(e,t){const s=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!s||e.transport!=="pty")return e;const n=t[s];return!n||e.mode===n?e:{...e,mode:n}}function vC(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let s=!1;const n=e.map(i=>{const a=Gh(i,t),o=Array.isArray(i.childSessions)?i.childSessions.map(c=>Gh(c,t)):i.childSessions,l=o!==i.childSessions;return a!==i||l?(s=!0,{...a,...l?{childSessions:o}:{}}):i});return s?n:e}function Sx(e,t){if(!t)return null;for(const s of e){if(s.sessionId===t&&s.transport==="pty")return s.mode==="chat"?"chat":"terminal";for(const n of s.childSessions||[])if(n.id===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function wC(e,t){if(!e||Object.keys(e).length===0)return e;let s=!1;const n={...e};for(const[i,a]of Object.entries(e))Sx(t,i)===a&&(delete n[i],s=!0);return s?n:e}function SC({visibleConversations:e,clearedTabs:t,setClearedTabs:s,setActionLogs:n}){u.useEffect(()=>{bg()},[]);const i=u.useMemo(()=>e.map(a=>({id:a.tabKey,name:qg(a),status:a.status,activeModal:a.modalMessage?{message:a.modalMessage,buttons:a.modalButtons}:null})),[e]);return aj(i),u.useEffect(()=>{if(Object.keys(t).length===0)return;const o=setTimeout(()=>{s(l=>{const c=Date.now(),d={};for(const[p,h]of Object.entries(l))c-h<5e3&&(d[p]=h);return Object.keys(d).length===Object.keys(l).length?l:d})},5500);return()=>clearTimeout(o)},[t,s]),u.useEffect(()=>{const a=setInterval(()=>{const o=Date.now()-3e5;n(l=>{const c=l.filter(d=>d.timestamp>o).slice(-100);return c.length===l.length?l:c})},6e4);return()=>clearInterval(a)},[n]),null}function qh(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 Tr(e){const t=[...e.messages].reverse().find(i=>!(i!=null&&i._localId))||e.messages[e.messages.length-1],s=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,n=qh(t==null?void 0:t.receivedAt)||qh(t==null?void 0:t.timestamp)||0;return Math.max(s,n)}function pd(e,t=0){return Tr(e)||e.lastUpdated||t||0}function kx(e){return Tr(e)||e.lastUpdated||0}function jx(e,t,s=kx){const n=s(t)-s(e);if(n!==0)return n;const i=(e.machineName||"").localeCompare(t.machineName||"");if(i!==0)return i;const a=e.displayPrimary.localeCompare(t.displayPrimary);if(a!==0)return a;const o=e.displaySecondary.localeCompare(t.displaySecondary);return o!==0?o:e.tabKey.localeCompare(t.tabKey)}function hd(e){var s;const t=us(e.status,{activeModal:(s=e.modalButtons)!=null&&s.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function kC(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!hd(e)&&!e.title.trim()}function jC(e){return e.length===0?null:[...e].sort((t,s)=>{const n=Number(hd(s))-Number(hd(t));if(n!==0)return n;const i=s.messages.length-t.messages.length;return i!==0?i:jx(t,s)})[0]||null}function js(e,t){const s=e.filter(o=>o.routeId===t);if(s.length===0)return null;const n=s.find(o=>o.streamSource==="native")||null,i=s.filter(o=>o.streamSource==="agent-stream"),a=jC(i);return n?a&&kC(n)?a:n:a||s[0]||null}function NC(e){const t=String(e.daemonId||"").trim(),s=String(e.id||"").trim();return!t||s.startsWith(`${t}:`)?s:`${t}:${s}`}function _C(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),s=new Map;for(const n of t){const i=NC(n),a=s.get(i);if(!a){s.set(i,n);continue}const o=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>o||(n.timestamp||0)>(a.timestamp||0))&&s.set(i,n)}return Array.from(s.values())}function sc(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s]!==t[s])return!1;return!0}function CC(e){let t=2166136261;for(let s=0;s<e.length;s+=1)t^=e.charCodeAt(s),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function Vh(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],s=t[t.length-1],n=s?CC(xn(s.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((s==null?void 0:s.id)||""),String((s==null?void 0:s.index)??""),String((s==null?void 0:s.receivedAt)??(s==null?void 0:s.timestamp)??""),n].join(":")}function IC(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||""),Vh(e.activeChat),...t.map(s=>[s.id||"",s.providerSessionId||"",s.transport||"",s.mode||"",s.status||"",s.title||"",s.lastMessageHash||"",String(s.lastMessageAt||""),s.lastMessagePreview||"",s.lastMessageRole||"",String(s.lastUpdated||""),Vh(s.activeChat)].join(":"))].join("|")}function AC(e,t){const s=Date.now();return e.map(n=>{const i=t[n.tabKey];return i&&s-i<5e3?{...n,messages:[],title:""}:n})}function TC(e,t){const s=new Map;for(const n of e){const i=t.get(n.routeId)||n;for(const a of Vs({routeId:n.routeId}))s.set(a,i);for(const a of Vs({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))s.set(a,n.streamSource==="native"?i:n);for(const a of Vs({tabKey:n.tabKey}))s.set(a,n)}return s}function MC(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function EC(e){const t=MC(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 s=String(t.role||""),n=xn(t.content).slice(0,240);return`${e.messages.length}:${s}:${n}`}function RC({ides:e,connectionStates:t,clearedTabs:s,hiddenTabs:n}){const i=u.useMemo(()=>_C(e),[e]),a=u.useMemo(()=>rx(e),[e]),o=u.useRef([]),l=u.useRef([]),c=u.useRef([]),d=u.useRef(new Map),p=u.useRef(new Map),h=u.useMemo(()=>{const k=new Map,j=[];for(const C of i){const{connectionState:D="new",machineName:T}=nx(C,{machineNames:a,connectionStates:t,defaultConnectionState:"new"}),A=IC(C),P=d.current.get(C.id);if(P&&P.ide===C&&P.sourceSignature===A&&P.connectionState===D&&P.machineName===T){k.set(C.id,P),j.push(...P.conversations);continue}const F=fu(C,{machineNames:a,connectionStates:t,defaultConnectionState:"new"}),J={ide:C,sourceSignature:A,connectionState:D,machineName:T,conversations:F};k.set(C.id,J),j.push(...F)}d.current=k;const y=new Map,N=C=>{const D=EC(C),T=p.current.get(C.tabKey);if(T&&T.signature===D)return y.set(C.tabKey,T),T.timestamp;const A={signature:D,timestamp:kx(C)||(T==null?void 0:T.timestamp)||0};return y.set(C.tabKey,A),A.timestamp},_=[...j].sort((C,D)=>jx(C,D,N));return p.current=y,_},[i,t,a]),m=u.useMemo(()=>{const k=AC(h,s);return sc(o.current,k)?o.current:(o.current=k,k)},[h,s]),g=u.useMemo(()=>{const k=new Map,j=Array.from(new Set(m.map(y=>y.routeId)));for(const y of j){const N=js(m,y);N&&k.set(y,N)}return k},[m]),b=u.useMemo(()=>{const k=new Map;for(const j of m){const y=g.get(j.routeId),N=j.streamSource==="native"&&y?y:j;for(const _ of Vs({providerSessionId:j.providerSessionId,sessionId:j.sessionId,tabKey:j.tabKey}))k.set(_,N)}return k},[m,g]),f=u.useMemo(()=>TC(m,g),[m,g]),v=u.useCallback(k=>{if(k)return b.get(k)},[b]),w=u.useCallback(k=>{if(k)return f.get(k)},[f]),x=u.useMemo(()=>{const k=m.filter(j=>!pl(n,j));return sc(l.current,k)?l.current:(l.current=k,k)},[m,n]),S=u.useMemo(()=>{const k=x.map(j=>j.tabKey);return sc(c.current,k)?c.current:(c.current=k,k)},[x]);return{chatIdes:i,conversations:m,visibleConversations:x,visibleTabKeys:S,resolveConversationBySessionId:v,resolveConversationByTarget:w}}function PC({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:s,setSearchParams:n}){const i=u.useMemo(()=>{var l;return e||!t?null:((l=s(t))==null?void 0:l.tabKey)??null},[e,s,t]),a=u.useMemo(()=>{var l;return!e||!t?null:((l=s(t))==null?void 0:l.tabKey)??null},[e,s,t]),o=u.useCallback(()=>{t&&n(l=>{const c=new URLSearchParams(l);return c.delete("activeTab"),c},{replace:!0})},[n,t]);return{requestedDesktopTabKey:i,requestedMobileTabKey:a,consumeRequestedActiveTab:o}}function DC({ides:e,sendDaemonCommand:t,setToasts:s,resolveConversationByTarget:n}){u.useEffect(()=>{ht.setIdes(e)},[e]),u.useEffect(()=>{ht.setResolveAction((i,a,o)=>{t(i,a,o).catch(()=>{})})},[t]),u.useEffect(()=>{const i=ht.onToast(a=>{s(l=>l.some(d=>d.message===a.message&&a.timestamp-d.timestamp<3e3)?l:[...l.slice(-4),{id:a.id,message:a.message,type:a.type,timestamp:a.timestamp,targetKey:a.targetKey,actions:a.actions}]);const o=a.duration||5e3;setTimeout(()=>s(l=>l.filter(c=>c.id!==a.id)),o)});return()=>{i()}},[s]),u.useEffect(()=>{const i=zg.on("status_event",a=>{ht.handleRawEvent(a,"ws")});return()=>{i()}},[]),u.useEffect(()=>{var a;const i=o=>{var f;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 c=l.targetSessionId||l.targetKey||l.daemonId,d=n(c),p=(d==null?void 0:d.routeId)||l.daemonId;if(!p)return;const h=Number(l.buttonIndex),m=l.button||((f=d==null?void 0:d.modalButtons)==null?void 0:f[h])||"Approve",g=String(m).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),b=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(p,"resolve_action",{action:b?"approve":"reject",button:m,...Number.isFinite(h)&&{buttonIndex:h},...(d==null?void 0:d.sessionId)&&{targetSessionId:d.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(v=>console.error("[SW Action] approval failed:",v))};return(a=navigator.serviceWorker)==null||a.addEventListener("message",i),()=>{var o;return(o=navigator.serviceWorker)==null?void 0:o.removeEventListener("message",i)}},[n,t])}const LC="adhdev_dashboardLayout_v1",$C="adhdev_dashboardDockview_v1",OC="adhdev_dashboardDockviewHiddenRestore_v1",zn={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function vu(e,t){try{const s=localStorage.getItem(e);return s?JSON.parse(s):t}catch{return t}}function FC(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Nx(e){return`${LC}:${e}`}function BC(e){const t=Nx(e);return vu(t,null)}function WC(e,t){try{const s=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,n=Nx(e);if(s){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function _x(e){return`${$C}:${e}`}function UC(e){const t=_x(e);return vu(t,null)}function HC(e,t){try{const s=_x(e);if(!t){localStorage.removeItem(s);return}localStorage.setItem(s,JSON.stringify(t))}catch{}}function Cx(e){return`${OC}:${e}`}function zC(e){const t=Cx(e);return vu(t,{})}function KC(e,t){try{const s=Cx(e);if(Object.keys(t).length===0){localStorage.removeItem(s);return}localStorage.setItem(s,JSON.stringify(t))}catch{}}function GC(){return{groupAssignments:[...zn.groupAssignments],focusedGroup:zn.focusedGroup,groupActiveTabIds:{...zn.groupActiveTabIds},groupTabOrders:{...zn.groupTabOrders},groupSizes:[...zn.groupSizes]}}function qC(e,t){return e?e.length===t.length&&e.every((s,n)=>s===t[n]):t.length===0}function VC(){const[e]=u.useState(()=>FC(typeof window<"u"?window.innerWidth:1280)),[t,s]=u.useState(()=>new Map),[n,i]=u.useState(0),[a,o]=u.useState({}),[l,c]=u.useState({}),[d,p]=u.useState([]),[h,m]=u.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,b]=u.useState(!1),f=u.useCallback(()=>{if(g)return;const C=BC(e)??GC();s(new Map(C.groupAssignments)),i(C.focusedGroup),o(C.groupActiveTabIds),c(C.groupTabOrders),p(C.groupSizes),b(!0)},[g,e]);u.useEffect(()=>{g&&WC(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:a,groupTabOrders:l,groupSizes:d})},[g,e,t,n,a,l,d]),u.useEffect(()=>{const C=window.matchMedia("(max-width: 767px)"),D=T=>m(T.matches);return C.addEventListener("change",D),()=>C.removeEventListener("change",D)},[]);const v=u.useCallback(C=>{s(C)},[]),w=u.useCallback(C=>{i(C)},[]),x=u.useCallback(C=>{o(C)},[]),S=u.useCallback(C=>{c(C)},[]),k=u.useCallback(C=>{p(C)},[]),j=u.useCallback(C=>{w(C)},[w]),y=u.useCallback((C,D)=>{o(T=>(T[C]??null)===(D??null)?T:{...T,[C]:D})},[]),N=u.useCallback((C,D)=>{c(T=>{const A=T[C];return qC(A,D)?T:{...T,[C]:D}})},[]),_=u.useCallback((C,D)=>{const T=D.get(C)??0;return y(T,C),j(T),T},[j,y]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:v,focusedGroup:n,updateFocusedGroup:w,focusGroup:j,groupActiveTabIds:a,updateGroupActiveTabIds:x,setGroupActiveTab:y,groupTabOrders:l,updateGroupTabOrders:S,setGroupTabOrder:N,groupSizes:d,updateGroupSizes:k,isMobile:h,hasHydratedStoredLayout:g,hydrateStoredLayout:f,focusConversationTab:_}}function XC(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const s=e[0],n=dl(t);return typeof(s==null?void 0:s.id)=="string"&&n.includes(s.id)}function YC({urlActiveTab:e,conversations:t,resolveConversationBySessionId:s,normalizedGroupAssignments:n,hasHydratedStoredLayout:i,hydrateStoredLayout:a,focusConversationTab:o,setSearchParams:l,historyModalOpen:c,activeConv:d,isRefreshingHistory:p,ides:h,handleRefreshHistory:m}){const g=u.useRef(!1),b=u.useRef(!1),f=u.useRef(null),v=u.useRef(!1);u.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!i){a();return}const w=s(e);w&&(o(w.tabKey,n),g.current=!0,b.current=!0,f.current!=null&&(window.clearTimeout(f.current),f.current=null),l(x=>{const S=new URLSearchParams(x);return S.delete("activeTab"),S},{replace:!0}))},[e,t,s,n,i,a,o,l]),u.useEffect(()=>{if(!(b.current||i)&&t.length!==0){if(!e){a(),b.current=!0;return}if(g.current){b.current=!0;return}if(f.current==null)return f.current=window.setTimeout(()=>{f.current=null,!(b.current||i)&&(a(),b.current=!0)},1500),()=>{f.current!=null&&(window.clearTimeout(f.current),f.current=null)}}},[e,t.length,i,a]),u.useEffect(()=>{if(!c){v.current=!1;return}if(!d||v.current||p)return;const w=h.find(x=>x.id===d.routeId);w&&(!w.chats||w.chats.length===0||XC(w.chats,d))&&(v.current=!0,m())},[c,d,p,h,m])}function rc(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const s=e[0];if((s==null?void 0:s.active)===!0)return!0;const n=dl(t);return typeof(s==null?void 0:s.id)=="string"&&n.includes(s.id)}function Ix({sendDaemonCommand:e,activeConv:t,chats:s,updateRouteChats:n,setToasts:i,setClearedTabs:a}){const[o,l]=u.useState(!1),[c,d]=u.useState(!1),p=u.useCallback(async b=>{try{await e("standalone","launch_ide",{ideType:b,enableCdp:!0})}catch(f){console.error("Launch failed",f)}},[e]),h=u.useCallback(async(b,f)=>{try{const v=b||(t==null?void 0:t.daemonId)||"",w=await e(v,"switch_chat",{id:f,sessionId:f,...Nr(t)}),x=w==null?void 0:w.result;if((w==null?void 0:w.success)===!0||x==="switched"||x==="switched-by-title")return;x===!1||x==="not_found"?Fn(i,"⚠️ Session tab not found — try refreshing history"):typeof x=="string"&&x.startsWith("error:")?Fn(i,`⚠️ Switch error: ${x}`):Fn(i,"⚠️ Session switch failed")}catch(v){console.error("Switch failed",v),Fn(i,`❌ Switch failed: ${v.message||"connection error"}`)}},[t,e,i]),m=u.useCallback(async()=>{if(!(!t||o)){l(!0);try{const b=_r(t);await e(b,"new_chat",{...Nr(t)}),ZN(b,t.sessionId,dl(t)[0]),a(f=>({...f,[t.tabKey]:Date.now()}))}catch(b){console.error("New chat failed",b)}finally{l(!1)}}},[t,o,e,a]),g=u.useCallback(async()=>{var b,f;if(!(!t||c)){d(!0);try{const v=_r(t),w=async()=>e(v,"list_chats",{forceExpand:!0,...Nr(t)});let x=await w(),S=(x==null?void 0:x.chats)||((b=x==null?void 0:x.result)==null?void 0:b.chats);rc(S,t)&&(await new Promise(k=>setTimeout(k,450)),x=await w(),S=(x==null?void 0:x.chats)||((f=x==null?void 0:x.result)==null?void 0:f.chats)),x!=null&&x.success&&Array.isArray(S)&&(n(t.routeId,S),rc(S,t)&&!rc(s,t)&&Fn(i,"⚠️ History dialog did not fully open — try once more"))}catch(v){console.error("Refresh history failed",v)}finally{d(!1)}}},[t,s,c,e,n,i]);return{isCreatingChat:o,isRefreshingHistory:c,handleLaunchIde:p,handleSwitchSession:h,handleNewChat:m,handleRefreshHistory:g}}function QC(e,t){if(e.size!==t.size)return!1;for(const[s,n]of e)if(t.get(s)!==n)return!1;return!0}function JC(e,t){return e.length!==t.length?!1:e.every((s,n)=>s===t[n])}function Xh(e,t){const s=Object.keys(e),n=Object.keys(t);return s.length!==n.length?!1:s.every(i=>t[Number(i)]===e[Number(i)])}function Ra(e,t){const s=new Set(t),n=t.length>0?[0]:[];for(const[o,l]of e)!s.has(o)||l<=0||n.includes(l)||n.push(l);n.sort((o,l)=>o-l);const i={};n.forEach((o,l)=>{i[o]=l}),n.length===0&&(i[0]=0);const a=new Map;for(const[o,l]of e){if(!s.has(o)||l<=0)continue;const c=i[l];typeof c=="number"&&c>0&&a.set(o,c)}return{assignments:a,groupCount:Math.max(1,n.length),mapping:i,usedGroups:n}}function Yh(e,t){const s={};for(const[n,i]of Object.entries(e)){const a=t[Number(n)];typeof a=="number"&&(s[a]=i)}return s}function ZC(e,t,s){if(t.length===0)return 0;if(typeof s[e]=="number")return s[e];const n=[...t].reverse().find(i=>i<e)??t[0];return s[n]??0}function eI(e,t,s){if(t.length<=1)return[];const n=t.map(o=>e[o]).filter(o=>Number.isFinite(o)),i=n.length===t.length?n:Array(s).fill(100/s),a=i.reduce((o,l)=>o+l,0);return a>0?i.map(o=>o/a*100):Array(s).fill(100/s)}function Qh(e,t){const s={};for(const[n,i]of Object.entries(e)){const a=Number(n);s[a>=t?a+1:a]=i}return s}function Jh(e){return Array(e).fill(100/e)}function tI({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:s,updateGroupActiveTabIds:n,updateGroupTabOrders:i,groupSizes:a,updateGroupSizes:o,isMobile:l,visibleConversations:c,visibleTabKeys:d}){const p=u.useRef(null),h=u.useMemo(()=>Ra(e,d),[e,d]),m=h.assignments,g=u.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),b=g>1,f=u.useCallback((j,y)=>{t(N=>{const _=new Map(Ra(N,d).assignments);return y===0?_.delete(j):_.set(j,y),_}),n(N=>({...N,[y]:j})),s(y)},[t,d,n,s]),v=u.useCallback(j=>{t(y=>{const N=Ra(y,d).assignments,_=new Map;for(const[C,D]of N)D!==j&&(D>j?_.set(C,D-1):_.set(C,D));return _}),o(y=>{if(y.length<=1)return[];const N=[...y];N.splice(j,1);const _=N.reduce((C,D)=>C+D,0);return _>0?N.map(C=>C/_*100):[]}),s(0)},[t,d,o,s]),w=u.useCallback((j,y)=>{y.preventDefault();const N=p.current;if(!N)return;const _=y.clientX,C=N.offsetWidth,D=a.length===g?[...a]:Jh(g),T=P=>{const J=(P.clientX-_)/C*100,R=[...D];R[j]=Math.max(15,D[j]+J),R[j+1]=Math.max(15,D[j+1]-J),o(R)},A=()=>{document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",A),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",T),document.addEventListener("mouseup",A)},[a,g,o]),x=u.useCallback((j,y,N)=>{if(g>=4)return;const _=N==="left"?y:y+1;t(C=>{const D=Ra(C,d).assignments,T=new Map;for(const A of c){const P=D.get(A.tabKey)??0,F=P>=_?P+1:P;F>0&&T.set(A.tabKey,F)}return _>0&&T.set(j,_),T}),o(C=>{const D=C.length===g?[...C]:Jh(g),T=D[y]??100/g,A=Math.max(15,T/2),P=Math.max(15,T/2),F=[...D];F[y]=A,F.splice(_,0,P);const J=F.reduce((R,I)=>R+I,0);return F.map(R=>R/J*100)}),n(C=>{const D=Qh(C,_);return D[_]=j,D}),i(C=>{const D=Qh(C,_);return D[_]=[j],D}),s(_)},[g,t,d,c,o,n,i,s]);u.useEffect(()=>{QC(e,m)||t(m)},[e,m,t]),u.useEffect(()=>{const{mapping:j,usedGroups:y}=h;n(N=>{const _=Yh(N,j);return Xh(N,_)?N:_}),i(N=>{const _=Yh(N,j);return Xh(N,_)?N:_}),s(N=>{const _=l?0:ZC(N,y,j);return N===_?N:_}),o(N=>{const _=l?[]:eI(N,y,h.groupCount);return JC(N,_)?N:_})},[h,l,n,i,s,o]);const S=u.useMemo(()=>{const j=Array.from({length:g},()=>[]);for(const y of c){const N=m.get(y.tabKey)??0,_=Math.min(N,g-1);j[_].push(y)}return j},[c,m,g]),k=u.useCallback(()=>{t(new Map),s(0)},[t,s]);return{containerRef:p,normalizedGroupAssignments:m,numGroups:g,isSplitMode:b,groupedConvs:S,moveTabToGroup:f,closeGroup:v,handleResizeStart:w,splitTabRelative:x,clearAllSplits:k}}function nc(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 sI(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 Pa(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function wu(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},s=nc(t.channel)||nc(e.updateChannel)||nc(e.releaseChannel)||void 0,n=sI(t.npmTag)||(s==="preview"?"next":s==="stable"?"latest":void 0),i=Pa(t.targetVersion)||Pa(e.serverVersion)||void 0,a=Pa(t.minVersion)||void 0,o=Pa(t.updateCommand)||(s?`adhdev update --channel ${s}`:void 0);return{...s?{channel:s}:{},...n?{npmTag:n}:{},...i?{targetVersion:i}:{},...a?{minVersion:a}:{},...o?{updateCommand:o}:{}}}function nn(e,t=null){return wu(e).targetVersion||t}function Ax(e){return wu(e).channel||null}function Tx(e){const t=wu(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 rI({ides:e,sendDaemonCommand:t}){const s="0.9.82",n=u.useMemo(()=>e.filter(h=>h.type!=="adhdev-daemon"?!1:gu(h,nn(h,s))).sort((h,m)=>Number(ui(m,nn(m,s)))-Number(ui(h,nn(h,s)))),[s,e]),i=u.useMemo(()=>n.some(h=>ui(h,nn(h,s))),[s,n]),a=u.useMemo(()=>n.map(h=>nn(h,s)).find(h=>typeof h=="string"&&h.trim().length>0)||s,[s,n]),[o,l]=u.useState(!1),[c,d]=u.useState({}),p=u.useCallback(async h=>{var g,b;const m=e.find(f=>f.id===h);if(m){d(f=>({...f,[h]:"upgrading"}));try{const f=await t(h,"daemon_upgrade",Tx(m));(g=f==null?void 0:f.result)!=null&&g.upgraded||(b=f==null?void 0:f.result)!=null&&b.success?d(v=>({...v,[h]:"done"})):d(v=>({...v,[h]:"error"}))}catch{d(f=>({...f,[h]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:i,targetVersion:a,versionBannerDismissed:o,setVersionBannerDismissed:l,upgradingDaemons:c,handleBannerUpgrade:p}}const Mx=80;function ro(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function nI(e){return{...e,createdAt:ro(e.createdAt),updatedAt:ro(e.updatedAt,e.createdAt),lastEventAt:ro(e.lastEventAt,e.updatedAt||e.createdAt)}}function iI(e){const t=_i(e);return t==="unknown:"?e.id:t}function aI(e){return[e.type,$g(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function oI(e,t=Mx){const s=new Map;for(const n of e){if(n.deletedAt)continue;const i=iI(n),a=s.get(i);if(!a){s.set(i,n);continue}(n.updatedAt>a.updatedAt||n.updatedAt===a.updatedAt&&n.createdAt>a.createdAt)&&s.set(i,n)}return Array.from(s.values()).sort((n,i)=>{const a=i.updatedAt-n.updatedAt;return a!==0?a:i.createdAt-n.createdAt}).slice(0,Math.max(0,t))}function lI(e,t){const s=Date.now(),n=[];for(const i of e){const a=i.sessionId?t.get(i.sessionId):void 0;if(a!=null&&a.surfaceHidden)continue;const o=ol(i,t),l=o.inboxBucket==="needs_attention"?"needs_attention":o.inboxBucket==="task_complete"&&o.unread?"task_complete":null;if(!l)continue;const c=ro(i.lastMessageAt||(a==null?void 0:a.lastUpdated)||i.lastUpdated,s),d=aI({type:l,sessionId:i.sessionId,providerSessionId:i.providerSessionId,tabKey:i.tabKey,lastMessageHash:i.lastMessageHash,lastMessageAt:i.lastMessageAt,lastUpdated:(a==null?void 0:a.lastUpdated)||i.lastUpdated});n.push(nI({id:d,dedupKey:d,type:l,routeId:i.routeId,machineId:i.daemonId||i.routeId,sessionId:i.sessionId,providerSessionId:i.providerSessionId,tabKey:i.tabKey,title:Cg(i),preview:dN(i),createdAt:c,updatedAt:c,lastEventAt:c}))}return oI(n)}function cI(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function dI(e){const{conversations:t,liveSessionInboxState:s,maxItems:n=Mx}=e,i=u.useMemo(()=>lI(t,s).slice(0,Math.max(0,n)),[t,s,n]),a=u.useMemo(()=>cI(i),[i]);return{notifications:i,unreadCount:a}}function uI({notifications:e,sendDaemonCommand:t}){const s=u.useCallback(a=>{const o=e.find(c=>c.id===a),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=u.useCallback(a=>{const o=e.find(l=>l.id===a);o!=null&&o.sessionId&&t(o.machineId||o.routeId,"mark_notification_unread",{sessionId:o.sessionId,notificationId:o.id}).catch(()=>{})},[e,t]),i=u.useCallback(a=>{const o=e.find(l=>l.id===a);o!=null&&o.sessionId&&t(o.machineId||o.routeId,"delete_notification",{sessionId:o.sessionId,notificationId:o.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:s,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:i}}function Su(...e){const t=new Set,s=[],n=i=>{const a=typeof i=="string"?i.trim():"";if(!a)return;const o=a.toLowerCase();t.has(o)||(t.add(o),s.push(a))};for(const i of e){if(Array.isArray(i)){for(const a of i)n(a);continue}n(i)}return s}function pI(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 s=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(s){const n=s[1].toUpperCase(),i=(s[2]||"").replace(/[\\/]+/g,"\\");return i?`${n}:\\${i}`:`${n}:\\`}return null}function ku(e,t=[]){if(e==="win32"){for(const s of t){if(typeof s!="string")continue;const n=pI(s);if(n)return n}return"C:\\"}for(const s of t){const n=typeof s=="string"?s.trim():"";if(n)return n}return"~"}function hI(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const s=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?s:n.slice(0,-1).join(s)||s}function mI(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function ju(e,t,s){const n=await e(t,"file_list_browse",{path:s}),i=mI(n);if(!(i!=null&&i.success))throw new Error((i==null?void 0:i.error)||(n==null?void 0:n.error)||"Could not browse folder");const a=typeof(i==null?void 0:i.path)=="string"?i.path:s,o=a.includes("\\")?"\\":"/",l=(d,p)=>/^[A-Za-z]:\\?$/.test(d)?`${d.replace(/\\?$/,"\\")}${p}`:d==="/"||d==="\\"?`${o}${p}`:`${d.replace(/[\\/]+$/,"")}${o}${p}`,c=Array.isArray(i==null?void 0:i.files)?i.files.filter(d=>(d==null?void 0:d.type)==="directory"&&typeof(d==null?void 0:d.name)=="string").map(d=>({name:d.name,path:typeof(d==null?void 0:d.path)=="string"&&d.path.trim()?d.path:l(a,d.name)})).sort((d,p)=>d.name.localeCompare(p.name)):[];return{path:a,directories:c}}function fI(e,t){const s=t.meshId||"",n={meshId:s,workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp",adhdevMcpArgs:t.adhdevMcpArgs||`mcp --mode ipc --repo-mesh ${s}`};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(i,a)=>n[a]||"")}function Ex(e,t={}){const s=e==null?void 0:e.mcpConfig;return(s==null?void 0:s.mode)!=="manual"?null:{serverName:s.serverName||"adhdev-mesh",configFormat:s.format,configPathCommand:s.configPathCommand,requiresRestart:s.requiresRestart===!0,instructions:s.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:fI(s.template||"",{...t,serverName:s.serverName||"adhdev-mesh"})}}function gI(e){if(!e||typeof e!="object")return null;const t=e,s=typeof t.instructions=="string"?t.instructions:"",n=typeof t.template=="string"?t.template:"";return!s&&!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:s||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:n}}function Ii(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Rx(e){return Yi(e)||e.tabKey||e.routeId||null}function Px(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",s=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",i=e.conversations.find(a=>{if(n&&a.routeId!==n)return!1;const o=[a.providerSessionId,a.sessionId,a.nativeSessionId,a.tabKey].map(l=>typeof l=="string"?l.trim():"").filter(Boolean);return!!(t&&o.includes(t)||s&&o.includes(s)||n&&a.routeId===n)});if(i!=null&&i.tabKey)return i.tabKey;if(n){const a=js(e.conversations,n)||e.conversations.find(o=>o.routeId===n);if(a!=null&&a.tabKey)return a.tabKey}return t||s||n||null}function rr(e){return String(e||"").trim()}function Dx(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Ro(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function xI(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function bI(e,t){const s=rr(e.providerSessionId),n=rr(e.targetSessionId),i=t.find(a=>{const o=[a.providerSessionId,a.sessionId,a.nativeSessionId,a.tabKey,a.routeId].map(rr).filter(Boolean);return!!(s&&o.includes(s)||n&&o.includes(n))});return i?i.tabKey:n||s||null}function yI(e,t,s){if(t.event!=="agent:generating_completed")return null;const n=Dx(t.daemonId);if(n&&n!==e.machineId)return null;const i=rr(t.providerType);if(e.providerType&&i!==e.providerType)return null;const a=rr(e.resumeSessionId),o=rr(e.launchedSessionId),l=rr(t.providerSessionId),c=rr(t.targetSessionId);if(a&&a!==l&&a!==c||o&&o!==l&&o!==c)return null;const d=Ro(e.workspacePath);if(d){const p=Ro(t.workspaceName);if(p&&!xI(p,d))return null}return bI(t,s)}function Zh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function vI({ides:e,conversations:t,onOpenSession:s}){const[n,i]=u.useState(null),a=u.useRef(null),o=u.useCallback(()=>{a.current=null,i(null)},[]),l=u.useCallback(c=>{a.current=c,i(c)},[]);return u.useEffect(()=>{if(!n)return;const c=Ro(n.workspacePath),d=e.find(h=>{var v,w,x,S;if(!h||h.type==="adhdev-daemon"||Dx(h.daemonId||h.id)!==n.machineId||(Ni(h)?"cli":un(h)?"acp":"ide")!==n.kind)return!1;const b=String(h.agentType||h.type||"");if(n.providerType&&b!==n.providerType)return!1;if(n.resumeSessionId)return String(h.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const k=String(n.launchedSessionId||"");return[h.providerSessionId,h.sessionId,h.instanceId,h.id].map(y=>String(y||"")).filter(Boolean).includes(k)}if(c){const k=Ro(h.workspace||h.runtimeWorkspaceLabel);return k?k===c:!1}return Number(h.lastUpdated||h._lastUpdate||h.timestamp||((S=(x=(w=(v=h.activeChat)==null?void 0:v.messages)==null?void 0:w.at)==null?void 0:x.call(w,-1))==null?void 0:S.timestamp)||0)>=n.startedAt-5e3});if(!d)return;const p=Px({entrySessionId:d.sessionId,entryInstanceId:d.instanceId,entryRouteId:d.id,conversations:t});p&&(o(),s(p))},[o,t,e,s,n]),u.useEffect(()=>ht.onStatusEvent(c=>{const d=a.current;if(!d)return;const p=yI(d,c,t);p&&(o(),s(p))}),[o,t,s]),u.useEffect(()=>{if(!n)return;const c=window.setTimeout(()=>{i(d=>!d||d.startedAt!==n.startedAt?d:(a.current=null,null))},45e3);return()=>window.clearTimeout(c)},[n]),{trackPendingLaunch:l}}function wI({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:s,activeConv:n,ides:i,setCliViewModeOverrides:a}){const o=su(),{launchCli:l}=rl(),c=u.useCallback(async(v,w)=>ju(e,v,w),[e]),d=u.useCallback(async(v,w)=>{if(!w.trim())return{ok:!1,error:"Choose a workspace path first."};try{const x=await e(v,"workspace_add",{path:w.trim()});return x!=null&&x.success?{ok:!0}:{ok:!1,error:(x==null?void 0:x.error)||"Could not save workspace"}}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Could not save workspace"}}},[e]),p=u.useCallback(async(v,w,x)=>{var S;try{const k={ideType:w,enableCdp:!0};(S=x==null?void 0:x.workspacePath)!=null&&S.trim()&&(k.workspace=x.workspacePath.trim());const j=await e(v,"launch_ide",k);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:v,kind:"ide",providerType:w,workspacePath:(x==null?void 0:x.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(k){return{ok:!1,error:k instanceof Error?k.message:"Could not launch IDE"}}},[e,t]),h=u.useCallback(async(v,w,x,S)=>{var j,y,N;const k=Date.now();try{const _={cliType:x};(j=S==null?void 0:S.workspacePath)!=null&&j.trim()?_.dir=S.workspacePath.trim():S!=null&&S.workspaceId&&(_.workspaceId=S.workspaceId),(y=S==null?void 0:S.resumeSessionId)!=null&&y.trim()&&(_.resumeSessionId=S.resumeSessionId.trim()),Array.isArray(S==null?void 0:S.cliArgs)&&S.cliArgs.length>0&&(_.cliArgs=S.cliArgs),(N=S==null?void 0:S.initialModel)!=null&&N.trim()&&(_.initialModel=S.initialModel.trim());const C=await l(v,_),D=(C==null?void 0:C.result)||C,T=(D==null?void 0:D.sessionId)||(D==null?void 0:D.id);return C!=null&&C.success&&T?(t({machineId:v,kind:w,providerType:x,workspacePath:(S==null?void 0:S.workspacePath)||null,resumeSessionId:(S==null?void 0:S.resumeSessionId)||null,launchedSessionId:T,startedAt:k}),{ok:!0}):C!=null&&C.success?(t({machineId:v,kind:w,providerType:x,workspacePath:(S==null?void 0:S.workspacePath)||null,resumeSessionId:(S==null?void 0:S.resumeSessionId)||null,startedAt:k}),{ok:!0}):{ok:!1,error:(C==null?void 0:C.error)||(D==null?void 0:D.error)||`Could not launch ${w.toUpperCase()} session`}}catch(_){return Zh(_)?(t({machineId:v,kind:w,providerType:x,workspacePath:(S==null?void 0:S.workspacePath)||null,resumeSessionId:(S==null?void 0:S.resumeSessionId)||null,startedAt:k}),{ok:!0}):{ok:!1,error:_ instanceof Error?_.message:`Could not launch ${w.toUpperCase()} session`}}},[l,e,t]),m=u.useCallback(async v=>{var w;if(o!=null&&o.listMeshes)return o.listMeshes(v);if(!v)return[];try{const x=await e(v,"list_meshes",{}),S=(x==null?void 0:x.result)??x;if((S==null?void 0:S.success)===!1)throw new Error((S==null?void 0:S.error)||"Could not load meshes");return(Array.isArray(S==null?void 0:S.meshes)?S.meshes:Array.isArray((w=S==null?void 0:S.result)==null?void 0:w.meshes)?S.result.meshes:[]).map(j=>{var y;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(((y=j.nodes[0])==null?void 0:y.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(x){throw console.error("List meshes failed",x),x}},[o,e]),g=u.useCallback(async(v,w,x)=>{if(!w.trim())return{ok:!1,error:"Choose a mesh first."};if(o!=null&&o.launchMeshCoordinator)return o.launchMeshCoordinator(v,w,x);const S=Date.now();try{const k={meshId:w.trim()};x.trim()&&(k.cliType=x.trim());const j=await e(v,"launch_mesh_coordinator",k),y=(j==null?void 0:j.result)??j;if((y==null?void 0:y.success)===!1||(j==null?void 0:j.success)===!1){const _=String((y==null?void 0:y.code)||(j==null?void 0:j.code)||""),C=gI((y==null?void 0:y.meshCoordinatorSetup)||(y==null?void 0:y.manualSetup)||(j==null?void 0:j.meshCoordinatorSetup)||(j==null?void 0:j.manualSetup));return{ok:!1,error:(y==null?void 0:y.error)||(j==null?void 0:j.error)||"Could not launch mesh coordinator",code:_||void 0,manualSetup:C}}const N=(y==null?void 0:y.sessionId)||(y==null?void 0:y.id);return N?s(N):t({machineId:v,kind:"cli",providerType:(y==null?void 0:y.cliType)||x.trim()||void 0,workspacePath:(y==null?void 0:y.workspace)||null,startedAt:S}),{ok:!0}}catch(k){return Zh(k)?(t({machineId:v,kind:"cli",providerType:x.trim()||void 0,startedAt:S}),{ok:!0}):{ok:!1,error:k instanceof Error?k.message:"Could not launch mesh coordinator"}}},[o,s,e,t]),b=u.useCallback(async(v,w)=>{if(!v||!w)return[];try{const x=await e(v,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),S=(x==null?void 0:x.result)??x;return Array.isArray(S==null?void 0:S.sessions)?S.sessions:[]}catch(x){return console.error("List saved sessions failed",x),[]}},[e]),f=u.useCallback(async v=>{await wx({conversation:n,mode:v,ides:i,sendDaemonCommand:e,setCliViewModeOverrides:a})},[n,i,e,a]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:d,handleLaunchMachineIde:p,handleLaunchMachineProvider:h,handleListMachineMeshes:m,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:b,setActiveCliViewMode:f}}function SI(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 kI(e,t,s=Date.now()){return!e||!SI(t)?null:{tabKey:e,nonce:s}}function jI({isMobile:e,conversations:t,visibleConversations:s,groupActiveTabIds:n,focusedGroup:i,groupedConvs:a,setSearchParams:o}){const[l,c]=u.useState(null),[d,p]=u.useState(null),h=u.useMemo(()=>{var v,w;if(!e){if(l){const x=t.find(S=>S.tabKey===l);if(x)return x}return s[0]}const f=n[i];if(f){const x=t.find(S=>S.tabKey===f);if(x)return x}return((v=a[i])==null?void 0:v[0])||((w=a[0])==null?void 0:w[0])},[t,l,i,n,a,e,s]),m=u.useCallback(f=>{c(f)},[]),g=u.useCallback(f=>{c(f.tabKey),o(v=>{const w=new URLSearchParams(v),x=pN(f);return x?w.set("activeTab",x):w.delete("activeTab"),w},{replace:!0})},[o]),b=u.useCallback((f,v)=>{const w=kI(f,v);w&&p(w)},[]);return{activeConv:h,openDesktopConversation:g,requestScrollToBottom:b,scrollToBottomRequest:d,setDesktopActiveTab:m}}function NI(e){const t=e.completedKey||null,s=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:s!==null&&s!==e.autoReadKey,nextPendingKey:s===e.autoReadKey?s:null}:s===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:s}:{shouldSchedule:!0,shouldCancelPending:s!==null&&s!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!s,nextPendingKey:null}}function _I(e){const t=String(e.liveState.completionMarker||""),s=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),i=!!e.liveState.unread,a=[e.tabKey,e.historySessionId||"",t,s,n,i?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&i&&(!t||t!==s)),autoReadKey:a,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function CI({activeConv:e,isMobile:t,liveSessionInboxState:s,sendDaemonCommand:n}){const i=u.useRef(null),a=u.useRef(null),o=u.useRef(null),l=u.useRef(null),c=u.useRef(null);u.useEffect(()=>{const d=()=>{o.current&&(clearTimeout(o.current),o.current=null),l.current&&(clearTimeout(l.current),l.current=null),c.current&&(document.removeEventListener("visibilitychange",c.current),c.current=null),a.current=null};if(t){d(),i.current=null;return}if(!(e!=null&&e.sessionId)){d(),i.current=null;return}const p=yo(e,s),h=_I({tabKey:e.tabKey,historySessionId:Yi(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Tr(e),liveState:p}),m=h.autoReadKey,g=NI({autoReadKey:m,shouldMarkSeen:h.shouldMarkSeen,completedKey:i.current,pendingKey:a.current});if(!h.shouldMarkSeen){g.shouldCancelPending&&d(),i.current=m;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&d();const b=()=>{if(document.visibilityState!=="visible"||i.current===m)return;i.current=m,a.current=null,o.current=null,l.current=null,c.current&&(document.removeEventListener("visibilitychange",c.current),c.current=null);const v=h.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:v,completionMarker:h.completionMarker}).catch(()=>{})};if(a.current=g.nextPendingKey,document.visibilityState==="visible"){o.current=setTimeout(b,1500);const v=()=>{document.visibilityState!=="visible"&&o.current&&(clearTimeout(o.current),o.current=null)};c.current=v,document.addEventListener("visibilitychange",v);return}const f=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(b,800),c.current&&(document.removeEventListener("visibilitychange",c.current),c.current=null))};c.current=f,document.addEventListener("visibilitychange",f)},[e,t,s,n]),u.useEffect(()=>()=>{o.current&&clearTimeout(o.current),l.current&&clearTimeout(l.current),c.current&&document.removeEventListener("visibilitychange",c.current)},[])}function ic(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const s=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(s)?s:""}function II({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:s,ides:n,sendDaemonCommand:i,updateRouteChats:a,setToasts:o,setClearedTabs:l,setSearchParams:c}){var E;const{launchCli:d}=rl(),[p,h]=u.useState(!1),[m,g]=u.useState([]),[b,f]=u.useState(()=>Jt()),[v,w]=u.useState(!1),[x,S]=u.useState(null),k=u.useRef(null),j=u.useMemo(()=>s||t||e,[e,s,t]),y=!!j&&dt(j)&&!at(j),N=u.useMemo(()=>{if(!j||!y)return null;const $=j.daemonId||j.routeId||"",M=$s(j),O=ic(j);return`${$}:${M}:${j.providerSessionId||""}:${O}`},[j,y]),_=u.useMemo(()=>!j||!y?"":ic(j),[j,y]),{isCreatingChat:C,isRefreshingHistory:D,handleSwitchSession:T,handleNewChat:A,handleRefreshHistory:P}=Ix({sendDaemonCommand:i,activeConv:j,chats:(E=n.find($=>$.id===(j==null?void 0:j.routeId)))==null?void 0:E.chats,updateRouteChats:a,setToasts:o,setClearedTabs:l}),F=u.useCallback(()=>{h(!0)},[]),J=u.useCallback(()=>{h(!1)},[]),R=u.useCallback(async()=>{if(!(!j||!y||v)){w(!0);try{const $=j.daemonId||j.routeId,M=$s(j),O=ic(j),H=await i($,"list_saved_sessions",{agentType:M,providerType:M,kind:"cli",limit:50,...j.providerSessionId?{providerSessionId:j.providerSessionId}:{},...O?{workspace:O}:{}}),ae=(H==null?void 0:H.result)??H;g(Array.isArray(ae==null?void 0:ae.sessions)?ae.sessions:[])}catch($){console.error("Refresh saved sessions failed",$),g([])}finally{w(!1)}}},[j,v,y,i]);u.useEffect(()=>{if(!p){k.current=null;return}if(!y){k.current=null,g([]),w(!1);return}!N||v||k.current!==N&&(k.current=N,R())},[R,p,v,y,N]);const I=u.useCallback(async $=>{if(!j||!y||!$.providerSessionId||!$.workspace)return;const M=j.daemonId||j.routeId,O=$s(j);try{S($.providerSessionId);const H=await d(M,{cliType:O,dir:$.workspace,resumeSessionId:$.providerSessionId,initialModel:gg($.summaryMetadata,"model",{preferShortValue:!0})||void 0}),ae=(H==null?void 0:H.result)??H,z=typeof(ae==null?void 0:ae.sessionId)=="string"?ae.sessionId:typeof(ae==null?void 0:ae.id)=="string"?ae.id:"";z&&c(X=>{const te=new URLSearchParams(X);return te.set("activeTab",z),te},{replace:!0}),J()}catch(H){console.error("Resume saved session failed",H)}finally{S(null)}},[J,j,y,i,c]);return{historyModalOpen:p,openHistoryModal:F,closeHistoryModal:J,historyTargetConv:j,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:C,isHistoryRefreshingHistory:D,handleHistorySwitchSession:T,handleHistoryNewChat:A,handleHistoryRefresh:P,savedHistorySessions:m,savedHistoryFilters:b,setSavedHistoryFilters:f,missingWorkspaceResumePath:_,isSavedHistoryLoading:v,resumingSavedHistorySessionId:x,handleRefreshSavedHistory:R,handleResumeSavedHistorySession:I}}function AI({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:n,requestedDesktopTabKey:i,conversations:a,ides:o,resolveConversationByTarget:l}){const[c,d]=u.useState(null),[p,h]=u.useState(null),m=u.useMemo(()=>{if(e||!n)return null;const w=l(n);return w&&!dt(w)&&!at(w)?w:null},[e,n,l]),g=u.useMemo(()=>{const w=c==null?void 0:c.routeId;if(!w)return null;const x=c!=null&&c.tabKey?a.find(S=>S.tabKey===c.tabKey):i?a.find(S=>S.tabKey===i):null;return(x==null?void 0:x.routeId)===w?x:js(a,w)},[a,c,i]),b=u.useMemo(()=>{if(g)return o.find(w=>w.id===g.routeId)},[o,g]);u.useEffect(()=>{m&&(d({routeId:m.routeId,tabKey:gh(m)}),h(m),s({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,s,m]);const f=u.useCallback(w=>{w&&(d({routeId:w.routeId,tabKey:gh(w)}),h(w))},[]),v=u.useCallback(()=>{d(null),h(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:b,remoteDialogActiveConv:p,setRemoteDialogActiveConv:h,openRemoteDialog:f,closeRemoteDialog:v}}function TI({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:n,requestedDesktopTabKey:i,conversations:a,ides:o,resolveConversationByTarget:l,activeConv:c,sendDaemonCommand:d}){const{remoteDialogConv:p,remoteDialogIdeEntry:h,remoteDialogActiveConv:m,setRemoteDialogActiveConv:g,openRemoteDialog:b,closeRemoteDialog:f}=AI({isMobile:e,location:t,navigate:s,requestedRemoteTabTarget:n,requestedDesktopTabKey:i,conversations:a,ides:o,resolveConversationByTarget:l}),[v,w]=u.useState(!1),[x,S]=u.useState(null),k=u.useCallback(async N=>{const _=N||c;!_||!dt(_)&&!at(_)||(S(_),w(!0))},[c]),j=u.useCallback(()=>{w(!1),S(null)},[]),y=u.useCallback(async N=>{const _=x||c;if(!_||!dt(_)&&!at(_)){j();return}w(!1);try{const C=$s(_),D=_.routeId||_.daemonId||"";await d(D,"stop_cli",{cliType:C,targetSessionId:_.sessionId,mode:N})}catch(C){console.error("Stop CLI failed:",C)}finally{S(null)}},[c,j,x,d]);return{remoteDialogConv:p,remoteDialogIdeEntry:h,remoteDialogActiveConv:m,setRemoteDialogActiveConv:g,openRemoteDialog:b,closeRemoteDialog:f,cliStopDialogOpen:v,cliStopTargetConv:x,requestCliStop:k,cancelCliStop:j,confirmCliStop:y}}function ac(e,t=!0){return(e??!0)&&t}const Nu=u.memo(function({activeConv:t,clearToken:s,isCliTerminal:n,ideEntry:i,terminalRef:a,handleModalButton:o,handleRelaunch:l,handleSendChat:c,handleForceSendChat:d,isSendingChat:p,sendFeedbackMessage:h=null,handleFocusAgent:m,isFocusingAgent:g,actionLogs:b,userName:f,scrollToBottomRequestNonce:v,isInputActive:w=!0,isVisible:x=!0}){const S=n,k=!n,j=ac(x,S),y=ac(x,k),N=ac(x),_=fx(t),C=_.status||_.modalMessage||_.modalButtons?{...t,..._.status?{status:_.status}:{},..._.modalMessage!==void 0?{modalMessage:_.modalMessage}:{},..._.modalButtons!==void 0?{modalButtons:_.modalButtons}:{}}:t;return r.jsxs(r.Fragment,{children:[r.jsx(pg,{activeConv:C,onModalButton:o}),C.transport!=="pty"&&C.transport!=="acp"&&C.cdpConnected===!1?r.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:r.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:[r.jsx("span",{className:"text-sm",children:r.jsx(yn,{size:14})}),r.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),r.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,C.transport==="pty"?r.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[r.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:S?"visible":"hidden",pointerEvents:S?"auto":"none"},children:r.jsx(K1,{activeConv:C,clearToken:s,terminalRef:a,handleSendChat:c,isSendingChat:p,sendFeedbackMessage:h,isVisible:j,isInputActive:w&&j})}),r.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:k?"visible":"hidden",pointerEvents:k?"auto":"none"},children:r.jsx(od,{activeConv:C,ideEntry:i,handleSendChat:c,isSendingChat:p,sendFeedbackMessage:h,handleFocusAgent:m,isFocusingAgent:g,actionLogs:b,userName:f,scrollToBottomRequestNonce:v,isInputActive:w&&y,isVisible:y})})]}):r.jsx(od,{activeConv:C,ideEntry:i,handleSendChat:c,handleForceSendChat:d,isSendingChat:p,sendFeedbackMessage:h,handleFocusAgent:m,isFocusingAgent:g,actionLogs:b,userName:f,scrollToBottomRequestNonce:v,isInputActive:w&&N,isVisible:N})]})},(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.handleForceSendChat===t.handleForceSendChat&&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 MI({conversation:e,className:t="",onOpenNativeConversation:s,onOpenMachine:n,interactive:i=!0,meshOnly:a=!1}){var S,k,j;const o=zi(),l=Kr(e),c=a?null:_g(e),d=!a&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),p=!a&&e.streamSource==="agent-stream"&&!!e.agentName,h=!a&&!p&&(e.transport==="pty"||e.transport==="acp"),m=wn(e),g=uN(e),b=(S=e.settings)==null?void 0:S.meshNodeFor,f=e.meshQueueStats,v=((k=e.coordinator)==null?void 0:k.meshId)||((j=e.settings)==null?void 0:j.meshCoordinatorFor),w=u.useCallback(()=>{if(n){n();return}l&&o("/dashboard",{state:{openMachineId:l}})},[l,o,n]),x=u.useCallback(()=>{if(s){s();return}const y=Rx(e);y&&o(Ii(y))},[e,o,s]);return!d&&!p&&!h&&!c&&!b&&!f?null:r.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[d&&(i?r.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:x,title:g,children:[r.jsx(_s,{size:12}),r.jsx("span",{children:g})]}):r.jsxs("span",{className:"conversation-meta-chip",title:g,children:[r.jsx(_s,{size:12}),r.jsx("span",{children:g})]})),p&&r.jsxs("span",{className:"conversation-meta-chip is-active",title:m,children:[r.jsx(vn,{size:12}),r.jsx("span",{children:m})]}),h&&r.jsxs("span",{className:"conversation-meta-chip is-active",title:m,children:[r.jsx(vn,{size:12}),r.jsx("span",{children:m})]}),c&&(i?r.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:w,title:c,children:[r.jsx(cr,{size:12}),r.jsx("span",{children:c})]}):r.jsxs("span",{className:"conversation-meta-chip",title:c,children:[r.jsx(cr,{size:12}),r.jsx("span",{children:c})]})),b&&r.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[r.jsx(cr,{size:12}),r.jsx("span",{children:"Mesh Node"})]}),v&&f&&r.jsxs("span",{className:`conversation-meta-chip ${f.pending>0?"is-active":""}`,style:f.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${f.pending} pending, ${f.assigned} assigned, ${f.completed} completed, ${f.failed} failed`,children:[r.jsx(ES,{size:12}),r.jsxs("span",{children:[f.pending," Pending"]})]})]})}function EI({selectedConversation:e,isAcp:t,isStandalone:s,selectedIdeEntry:n,actionLogs:i,userName:a,isSendingChat:o,sendFeedbackMessage:l=null,isFocusingAgent:c,onBack:d,onOpenNativeConversation:p,onOpenMachine:h,onOpenHistory:m,onOpenRemote:g,onOpenMeshGraph:b,onStopCli:f,cliViewMode:v,onSetCliViewMode:w,handleSendChat:x,handleForceSendChat:S,handleFocusAgent:k,handleModalButton:j,handleRelaunch:y}){var A,P;const N=u.useRef(null),_=dt(e)&&!t,C=_&&v==="terminal",D=!!e.daemonId&&!!((A=e.coordinator)!=null&&A.meshId||(P=e.settings)!=null&&P.meshCoordinatorFor),T=s?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`flex items-center justify-between gap-3 ${T} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[r.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[r.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:d,type:"button","aria-label":"Back",children:r.jsx(Kd,{size:18})}),r.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[r.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:kt(e)}),r.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:r.jsx(MI,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>p(e),onOpenMachine:()=>h(e)})})]})]}),r.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[_&&v&&r.jsx(Yg,{mode:v,onChange:w,compact:!0}),_&&f&&r.jsx("button",{onClick:()=>{f(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:r.jsx(Ot,{size:14})}),D&&b&&r.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>b(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:r.jsx(qs,{size:14})}),r.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(e),type:"button",children:r.jsx(Gd,{size:14})}),!t&&!_&&r.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:r.jsx(_s,{size:14})})]})]}),r.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:r.jsx(Nu,{activeConv:e,clearToken:0,isCliTerminal:C,ideEntry:n,terminalRef:N,handleModalButton:j,handleRelaunch:y,handleSendChat:x,handleForceSendChat:S,isSendingChat:o,sendFeedbackMessage:l,handleFocusAgent:k,isFocusingAgent:c,actionLogs:i,userName:a})})]})}const oc={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 RI(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Lx(){const[e,t]=u.useState("unix"),[s,n]=u.useState("powershell"),[i,a]=u.useState(!1),o=e==="unix"?"unix":s;u.useEffect(()=>{t(RI())},[]);const l=u.useCallback(()=>{navigator.clipboard.writeText(oc[o].cmd).catch(()=>{}),a(!0),setTimeout(()=>a(!1),2e3)},[o]);return r.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:[r.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[r.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"}),r.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"&&r.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[r.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${s==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),r.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${s==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),r.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[r.jsx("span",{className:"text-text-muted select-none",children:oc[o].prompt}),r.jsx("span",{className:"flex-1 break-all",children:oc[o].cmd}),r.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:i?"✓":"📋"})]}),r.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",r.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function $x({section:e,onSectionChange:t}){const s=[{key:"machines",label:"Machines",icon:_s},{key:"chats",label:"Chats",icon:zr}];return r.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:r.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:s.map(({key:n,label:i,icon:a})=>{const o=e===n;return r.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:[r.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:r.jsx(a,{size:15})}),r.jsx("span",{children:i})]},n)})})})}function Da({title:e,className:t=""}){return r.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:r.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function Jr({children:e,className:t=""}){return r.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 Kn({icon:e,title:t,subtitle:s,children:n}){return r.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:[r.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}),r.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),r.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:s}),n]})}function PI({conversation:e,onCancel:t,onConfirm:s}){const n=kt(e),i=Or(e);return r.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:[r.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),r.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:[r.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border-subtle bg-[var(--surface-primary)] px-4 py-4",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base font-extrabold text-text-primary",children:"Hide this chat from the inbox?"}),r.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."})]}),r.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:r.jsx(Ot,{size:16})})]}),r.jsx("div",{className:"px-4 py-4",children:r.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary/60 px-3.5 py-3",children:[r.jsx("div",{className:"truncate text-sm font-bold text-text-primary",children:n}),r.jsx("div",{className:"mt-1 truncate text-xs text-text-muted",children:i})]})}),r.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:[r.jsx("button",{type:"button",className:"btn btn-secondary min-h-[40px] px-4 text-sm",onClick:t,children:"Cancel"}),r.jsx("button",{type:"button",className:"btn btn-primary min-h-[40px] px-4 text-sm",onClick:s,children:"Hide tab"})]})]})]})}function La({item:e,type:t,getAvatarText:s,onOpenConversation:n,onRequestHideConversation:i,onOpenMeshGraph:a,onCollectChatDebugBundle:o,isMuted:l,onToggleMute:c}){var A,P;const d=t==="needs_attention"||t==="task_complete",p=t==="working",h=t==="earlier",m=t==="task_complete",{isReconnecting:g,isConnecting:b}=An(e.conversation),f=kt(e.conversation),v=Or(e.conversation),w=Gg(e.conversation,{requiresAction:t==="needs_attention"}),x=d?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":p?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":h?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",S=d?"bg-accent-primary shadow-glow":p?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":h?"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",k=h?"text-text-secondary":"text-text-primary",j=h?"text-text-muted":"text-text-secondary",y=h?"text-text-secondary opacity-80":"text-text-muted",N=h?"text-text-muted opacity-80":"text-text-muted",_=!p&&!m,C=!!e.conversation.daemonId&&!!((A=e.conversation.coordinator)!=null&&A.meshId||(P=e.conversation.settings)!=null&&P.meshCoordinatorFor),D="text-[color:var(--status-warning)]",T=F=>{if(!o)return;F.preventDefault(),F.stopPropagation();const J=o==null?void 0:o(e.conversation);Promise.resolve(J).catch(R=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",R)})};return r.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${x}`,children:r.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[d||p?r.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,r.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[r.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${S}`,style:d?{color:"var(--accent-on-primary)"}:void 0,children:s(f)}),i&&r.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:F=>{F.preventDefault(),F.stopPropagation(),i()},"aria-label":`Hide ${f}`,title:"Hide conversation",children:[r.jsx(qd,{size:11}),r.jsx("span",{children:"Hide"})]}),c&&r.jsxs("button",{type:"button",className:`mobile-inbox-mute-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border px-2 text-[10px] font-semibold transition-colors ${l?"border-amber-500/40 bg-amber-500/10 text-amber-300 hover:bg-amber-500/20":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:F=>{F.preventDefault(),F.stopPropagation(),c()},"aria-label":l?`Unmute ${f}`:`Mute ${f}`,title:l?"Unmute (resume notifications)":"Mute notifications",children:[r.jsx(Gi,{size:11}),r.jsx("span",{children:l?"Muted":"Mute"})]}),C&&a&&r.jsxs("button",{type:"button",className:"mobile-inbox-mesh-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:F=>{F.preventDefault(),F.stopPropagation(),a(e.conversation)},"aria-label":`Open mesh graph for ${f}`,title:"Open live repo mesh graph",children:[r.jsx(qs,{size:11}),r.jsx("span",{children:"Graph"})]})]}),r.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:T,type:"button",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${k}`,children:f}),_&&r.jsx("span",{className:`text-[11px] font-medium shrink-0 ${N}`,children:ug(e.timestamp)})]}),r.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${j}`,children:[r.jsx("span",{className:"truncate",children:v}),r.jsx(No,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),g?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"mx-1 opacity-50",children:"·"}),r.jsx("span",{className:`${D} animate-pulse`,children:"Reconnecting…"})]}):b?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"mx-1 opacity-50",children:"·"}),r.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):w==="Action needed"&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"mx-1 opacity-50",children:"·"}),r.jsx("span",{className:D,children:"Action needed"})]})]}),r.jsx("div",{className:`mt-0.5 truncate text-[13px] ${y}`,children:e.preview})]}),d&&!m&&r.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),m&&r.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"}),p&&r.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 em({size:e=32}){return r.jsx("div",{className:"flex flex-col items-center gap-2.5",children:r.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 DI({section:e,attentionItems:t,unreadItems:s,workingItems:n,completedItems:i,hiddenConversations:a,machineCards:o,getAvatarText:l,actionLogs:c,sendDaemonCommand:d,onOpenConversation:p,onShowAllHidden:h,onHideConversation:m,onOpenMeshGraph:g,onOpenNewSession:b,onOpenMachine:f,onOpenSettings:v,onSectionChange:w,wsStatus:x="connected",isStandalone:S=!1,onCollectChatDebugBundle:k,isConversationMuted:j,onToggleMuteConversation:y}){const[N,_]=u.useState(null),C=x==="disconnected"||x==="reconnecting"||x==="offline"||x==="auth_failed",D=o.length>0,T=t.length>0||s.length>0||n.length>0||i.length>0,A=e==="machines"?"Machines":"Chats",P=S?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",F=S?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",J=u.useCallback(async E=>{const $=_r(E);if(!$)return;const M=Array.isArray(E.messages)?E.messages:[],O=Eg({activeConv:E,visibleMessages:M,actionLogs:c,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:M.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),H=await d($,"get_chat_debug_bundle",{...Nr(E),delivery:"daemon_file",frontendSnapshot:O}),ae=li(H),z=Dg(ae),X=await Pg(z);X==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ht.showToast(Rg(ae,{locatorCopyStatus:X}),X==="failed"?"warning":"success")},[c,d]),R=k||J,I=u.useCallback(()=>{N&&(m==null||m(N),_(null))},[N,m]);return r.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[r.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${P}`,children:r.jsxs("div",{className:"flex items-center justify-between gap-3",children:[r.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:A}),r.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||s.length>0)&&r.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:[r.jsx(Gi,{size:13}),r.jsx("span",{children:t.length+s.length})]}),r.jsx("button",{onClick:v,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:r.jsx(nl,{size:18})})]})]})}),r.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] ${F}`,children:[e==="machines"&&r.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:C?r.jsx(Kn,{icon:r.jsx(em,{}),title:x==="offline"?"Network offline":x==="auth_failed"?"Session expired":"Reconnecting",subtitle:x==="offline"?"Waiting for network…":x==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):o.length===0?r.jsx(Kn,{icon:r.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:S?"Waiting for your daemon":"Connect your machines",subtitle:S?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can launch sessions with any installed provider.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!S&&r.jsx("div",{className:"w-full max-w-[360px] mt-4",children:r.jsx(Lx,{})})}):r.jsx(Jr,{children:o.map((E,$)=>r.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${$>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(E.id),type:"button",children:[r.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(E.label)}),r.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:E.label}),r.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:E.unread>0?r.jsxs("span",{className:"text-accent-primary",children:[E.unread," new"]}):E.total>0?`${E.total} chats`:"Idle"})]}),r.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:E.subtitle}),E.total>0?r.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[E.total," chat",E.total!==1?"s":"",E.unread>0?` · ${E.unread} unread`:""]}):r.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},E.id))})}),e==="chats"&&t.length>0&&r.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[r.jsx(Da,{title:"Needs attention",className:"mb-0"}),r.jsx(Jr,{children:t.map((E,$)=>r.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:r.jsx(La,{item:E,type:"needs_attention",getAvatarText:l,onOpenConversation:p,onRequestHideConversation:m?()=>_(E.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:R,isMuted:j==null?void 0:j(E.conversation),onToggleMute:y?()=>y(E.conversation):void 0})},E.conversation.tabKey))})]}),e==="chats"&&s.length>0&&r.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[r.jsx(Da,{title:"Task complete",className:"mb-0 mt-2"}),r.jsx(Jr,{children:s.map((E,$)=>r.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:r.jsx(La,{item:E,type:"task_complete",getAvatarText:l,onOpenConversation:p,onRequestHideConversation:m?()=>_(E.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:R,isMuted:j==null?void 0:j(E.conversation),onToggleMute:y?()=>y(E.conversation):void 0})},E.conversation.tabKey))})]}),e==="chats"&&n.length>0&&r.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[r.jsx(Da,{title:"Working now",className:"mb-0 mt-2"}),r.jsx(Jr,{children:n.map((E,$)=>r.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:r.jsx(La,{item:E,type:"working",getAvatarText:l,onOpenConversation:p,onRequestHideConversation:m?()=>_(E.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:R,isMuted:j==null?void 0:j(E.conversation),onToggleMute:y?()=>y(E.conversation):void 0})},E.conversation.tabKey))})]}),e==="chats"&&r.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[i.length>0&&r.jsx(Da,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),i.length>0?r.jsx(Jr,{children:i.map((E,$)=>r.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:r.jsx(La,{item:E,type:"earlier",getAvatarText:l,onOpenConversation:p,onRequestHideConversation:m?()=>_(E.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:R,isMuted:j==null?void 0:j(E.conversation),onToggleMute:y?()=>y(E.conversation):void 0})},E.conversation.tabKey))}):T?r.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):C?r.jsx(Kn,{icon:r.jsx(em,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):D?r.jsx(Kn,{icon:r.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:r.jsx(zr,{size:20})}),title:"No conversations yet",subtitle:Qg,children:b&&r.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:b,"aria-label":Ps,title:Ps,children:[r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),r.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),r.jsx("span",{children:Ps})]})}):r.jsx(Kn,{icon:r.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"&&a.length>0&&r.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:r.jsx(Jr,{className:"mt-4 border-dashed bg-bg-secondary/20",children:r.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),r.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[a.length," collapsed ",a.length===1?"conversation":"conversations"]})]}),r.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:h,children:"Restore all"})]})})})]}),e==="chats"&&b&&T&&r.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:b,"aria-label":Ps,title:Ps,children:r.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),r.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),N&&r.jsx(PI,{conversation:N,onCancel:()=>_(null),onConfirm:I}),r.jsx($x,{section:e,onSectionChange:w})]})}function LI(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 Ox(e){const t=[e.workspace||"Workspace unknown"],s=$r(e.summaryMetadata);s&&t.push(s),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=LI(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function _u({title:e,description:t,currentPath:s,directories:n,busy:i=!1,error:a="",confirmLabel:o="Use this folder",onClose:l,onNavigate:c,onConfirm:d}){const[p,h]=u.useState(s);u.useEffect(()=>{h(s)},[s]);const m=hI(s),g=p.trim();return r.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:r.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:[r.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),r.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),r.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:r.jsx(Ot,{size:16})})]}),r.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[r.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||i||c(m)},disabled:!m||i,children:[r.jsx(Kd,{size:15}),"Parent"]}),r.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[r.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"text",value:p,onChange:b=>h(b.target.value),onKeyDown:b=>{b.key!=="Enter"||!g||i||(b.preventDefault(),c(g))},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"}),r.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:()=>{!g||i||c(g)},disabled:!g||i,children:"Go"})]})]})]}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:i?r.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):a?r.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:a}):n.length===0?r.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):r.jsx("div",{className:"p-3",children:n.map(b=>r.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:()=>c(b.path),children:[r.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:r.jsx(bn,{size:17})}),r.jsxs("span",{className:"min-w-0 flex-1",children:[r.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:b.name}),r.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:b.path})]})]},b.path))})}),r.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:[r.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),r.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>d(g||s),disabled:!g&&!s||i,children:o})]})]})})}function Fx({title:e,description:t,details:s,workspaceOptions:n,selectedWorkspaceKey:i,onWorkspaceChange:a,confirmLabel:o="Launch",busyLabel:l="Launching…",busy:c=!1,showArgsInput:d,argsValue:p,onArgsChange:h,showModelInput:m,modelValue:g,onModelChange:b,historyProviderNode:f,onConfirm:v,onCancel:w}){const x=n==null?void 0:n.find(S=>S.key===i);return r.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:r.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:[r.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),r.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),r.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:w,"aria-label":"Close launch confirmation",children:r.jsx(Ot,{size:16})})]}),r.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&&a&&r.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[r.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),r.jsx("select",{value:i||"",onChange:S=>a(S.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:c,children:n.map(S=>r.jsx("option",{value:S.key,children:S.label},S.key))}),(x==null?void 0:x.description)&&r.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:x.description})]}),f,s.map(S=>r.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[r.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:S.label}),r.jsx("div",{className:"text-sm text-text-primary break-all",children:S.value})]},`${S.label}:${S.value}`)),m&&b&&r.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[r.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),r.jsx("input",{type:"text",value:g||"",onChange:S=>b(S.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:c})]}),d&&h&&r.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[r.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),r.jsx("input",{type:"text",value:p||"",onChange:S=>h(S.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:c})]})]}),r.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:[r.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:w,disabled:c,children:"Cancel"}),r.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:v,disabled:c,children:[r.jsx(Qf,{size:14}),c?l:o]})]})]})})}function tm(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Bx(e){const{machine:t,currentWorkspacePath:s,currentWorkspaceId:n,includeHome:i=!0}=e,a=[];i&&a.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const c of t.workspaces||[])a.push({key:`saved:${c.id}`,label:`${c.id===t.defaultWorkspaceId?"⭐ ":""}${tm(c.path,c.label)}`,description:c.path,workspaceId:c.id,workspacePath:c.path});const o=(s==null?void 0:s.trim())||"",l=o?(t.workspaces||[]).find(c=>c.path===o):null;if(o&&!l&&a.push({key:`custom:${o}`,label:tm(o),description:o,workspaceId:null,workspacePath:o}),n){const c=`saved:${n}`;if(a.some(d=>d.key===c))return{options:a,selectedKey:c}}return l?{options:a,selectedKey:`saved:${l.id}`}:o?{options:a,selectedKey:`custom:${o}`}:{options:a,selectedKey:"__home__"}}function $I(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function OI(e){return[$I(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function FI(e){return e.lastLaunchedAt?al(e.lastLaunchedAt):""}function Wx(e){return{metaText:OI(e),updatedLabel:FI(e)}}function lc(e,t,s){return e?"ide":t>0?"cli":s>0?"acp":null}function BI({selectedMachineEntry:e,cliProviders:t,acpProviders:s,machineAction:n,onBrowseDirectory:i,onListSavedSessions:a}){var ct,_t,Mt,Et;const o=Xi(),[l,c]=u.useState(!1),d=(((ct=e.detectedIdes)==null?void 0:ct.length)||0)>0,p=u.useMemo(()=>(e.workspaces||[]).map(De=>({id:De.id,path:De.path,label:De.label})),[e]),h=e.defaultWorkspaceId||null,[m,g]=u.useState(h||((_t=p[0])==null?void 0:_t.id)||""),[b,f]=u.useState(""),[v,w]=u.useState(""),[x,S]=u.useState([]),[k,j]=u.useState(!1),[y,N]=u.useState(""),[_,C]=u.useState(!1),[D,T]=u.useState(lc(d,t.length,s.length)),A=u.useRef(null),[P,F]=u.useState(null),J=u.useRef("__home__"),[R,I]=u.useState("__home__"),[E,$]=u.useState(""),[M,O]=u.useState(""),[H,ae]=u.useState(""),[z,X]=u.useState([]),[te,he]=u.useState(()=>Jt().textQuery),[ke,Q]=u.useState(()=>Jt().workspaceQuery),[q,me]=u.useState(()=>Jt().modelQuery),[we,ye]=u.useState(()=>Jt().resumableOnly),[Te,le]=u.useState(()=>Jt().sortMode),[Se,ge]=u.useState(!1),[G,W]=u.useState(!1),Z=u.useRef(null),oe=u.useRef(null);u.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&o(e.id,{minFreshMs:3e4}).catch(()=>{})},[o,e]);const ue=m==="__custom__"?b.trim():((Mt=p.find(De=>De.id===m))==null?void 0:Mt.path)||"",ce=m==="__custom__"&&!!ue&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),L=m!=="__custom__"&&((Et=p.find(De=>De.id===m))==null?void 0:Et.path)||"",de=u.useMemo(()=>(e.recentLaunches||[]).map(De=>De.workspace),[e]),U=u.useCallback(async De=>{j(!0),N("");try{const He=await i(De);w(He.path),f(He.path),S(He.directories)}catch(He){N(He instanceof Error?He.message:"Could not load folder")}finally{j(!1)}},[i]),ie=u.useCallback(()=>{var He;g("__custom__"),C(!0);const De=ku(e.platform,Su(b.trim(),L,de,e.defaultWorkspacePath,(He=p.find(pt=>pt.id===h))==null?void 0:He.path,p.map(pt=>pt.path)));U(De)},[b,h,U,de,L,e.platform,p]),Y=u.useCallback(De=>{if(De!=null&&De.workspaceId){g(De.workspaceId),f("");return}if(De!=null&&De.workspacePath){g("__custom__"),f(De.workspacePath);return}g(""),f("")},[]),Ae=u.useCallback(De=>{if(g(De),De==="__custom__"){ie();return}f("")},[ie]),Ce=u.useCallback(De=>{g("__custom__"),f(De)},[]),je=u.useCallback((De,He)=>{A.current=He,J.current=De.selectedWorkspaceKey||"__home__",I(De.selectedWorkspaceKey||"__home__"),$(De.initialArgs||""),O(De.initialModel||""),ae(""),X([]);const pt=De.providerType?`${e.id}:${De.providerType}`:null;if(t_(oe.current,pt)){const Ze=Jt();he(Ze.textQuery),Q(Ze.workspaceQuery),me(Ze.modelQuery),ye(Ze.resumableOnly),le(Ze.sortMode)}oe.current=pt,F(De),De.providerType&&a&&(ge(!0),a(De.providerType).then(Ze=>X(Ze||[])).catch(Ze=>console.warn("Failed to load saved sessions",Ze)).finally(()=>ge(!1)))},[a,e.id]),qe=u.useMemo(()=>Jg(z,{textQuery:te,workspaceQuery:ke,modelQuery:q,resumableOnly:we,sortMode:Te}),[q,we,z,Te,te,ke]);u.useEffect(()=>{H&&(qe.some(De=>De.providerSessionId===H)||ae(""))},[qe,H]);const it=u.useCallback(()=>{A.current&&(W(!0),A.current().finally(()=>{A.current=null,W(!1),F(null)}))},[]),lt=u.useCallback(()=>{A.current=null,F(null)},[]),ft=u.useCallback(De=>{J.current=De,I(De)},[]);return u.useEffect(()=>{var De;Z.current!==e.id&&(Z.current=e.id,g(h||((De=p[0])==null?void 0:De.id)||"__custom__"),f(""),w(""),S([]),N(""),C(!1),he(Jt().textQuery),Q(Jt().workspaceQuery),me(Jt().modelQuery),ye(Jt().resumableOnly),le(Jt().sortMode),oe.current=null,T(lc(d,t.length,s.length)))},[s.length,t.length,h,d,e.id,p]),u.useEffect(()=>{var De;m!=="__custom__"&&(m&&p.some(He=>He.id===m)||g(h||((De=p[0])==null?void 0:De.id)||"__custom__"))},[h,m,p]),u.useEffect(()=>{D==="ide"&&d||D==="cli"&&t.length>0||D==="acp"&&s.length>0||T(lc(d,t.length,s.length))},[D,s.length,t.length,d]),{showAllRecent:l,setShowAllRecent:c,hasIdeOptions:d,workspaceRows:p,defaultWorkspaceId:h,workspaceChoice:m,customWorkspacePath:b,browseCurrentPath:v,browseDirectories:x,browseBusy:k,browseError:y,browseDialogOpen:_,activeLauncherKind:D,launchConfirm:P,launchConfirmWorkspaceKeyRef:J,launchConfirmWorkspaceKey:R,launchConfirmArgs:E,launchConfirmModel:M,launchConfirmResumeId:H,launchConfirmSavedSessions:z,launchConfirmTextFilter:te,launchConfirmWorkspaceFilter:ke,launchConfirmModelFilter:q,launchConfirmResumableOnly:we,launchConfirmSortMode:Te,filteredLaunchConfirmSavedSessions:qe,launchConfirmSessionsLoading:Se,launchConfirmBusy:G,resolvedWorkspacePath:ue,canCreateMissingWorkspace:ce,openBrowseDialog:ie,loadBrowsePath:U,handleWorkspaceChoiceChange:Ae,chooseCustomWorkspacePath:Ce,setCustomWorkspacePath:f,setBrowseDialogOpen:C,setActiveLauncherKind:T,openLaunchConfirm:je,handleConfirmLaunch:it,closeLaunchConfirm:lt,setWorkspaceSelectionFromOption:Y,setLaunchConfirmWorkspaceKeyAndSync:ft,setLaunchConfirmArgs:$,setLaunchConfirmModel:O,setLaunchConfirmResumeId:ae,setLaunchConfirmTextFilter:he,setLaunchConfirmWorkspaceFilter:Q,setLaunchConfirmModelFilter:me,setLaunchConfirmResumableOnly:ye,setLaunchConfirmSortMode:le}}function WI({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:s,cliProviders:n,acpProviders:i,selectedMachineNeedsUpgrade:a,appVersion:o,machineAction:l,isStandalone:c,section:d,showBottomNav:p,onBack:h,onSectionChange:m,onOpenConversation:g,onOpenRecent:b,onOpenMachineDetails:f,onMachineUpgrade:v,onLaunchDetectedIde:w,onAddWorkspace:x,onBrowseDirectory:S,onLaunchWorkspaceProvider:k,onListSavedSessions:j}){const y=R=>R==="ide"?"Workspace":R==="cli"?"CLI":"ACP",N=s.slice(0,4),_=t.slice(0,3),C=BI({selectedMachineEntry:e,cliProviders:n,acpProviders:i,machineAction:l,onBrowseDirectory:S,onListSavedSessions:j}),D=u.useMemo(()=>N.map(R=>{const{metaText:I,updatedLabel:E}=Wx(R);return{key:`recent-launch:${R.id}`,primary:R.label,secondary:I,updatedLabel:E,onClick:()=>{const{options:$,selectedKey:M}=Bx({machine:{workspaces:C.workspaceRows,defaultWorkspaceId:C.defaultWorkspaceId},currentWorkspacePath:R.workspace});C.openLaunchConfirm({title:R.kind==="ide"?Co("restart-ide",R.label):R.providerSessionId?Zg(R.label):Co("start-fresh",R.label),description:R.kind==="ide"?Io("restart-ide"):R.providerSessionId?ex():Io("start-fresh"),confirmLabel:R.kind==="ide"?Ao("restart-ide"):R.providerSessionId?_o(!0):Ao("start-fresh"),busyLabel:R.kind==="ide"?To("restart-ide"):R.providerSessionId?hu(!0):To("start-fresh"),workspaceOptions:$,selectedWorkspaceKey:M,details:[{label:"Mode",value:y(R.kind)},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]},async()=>{const O=$.find(H=>H.key===C.launchConfirmWorkspaceKeyRef.current);C.setWorkspaceSelectionFromOption(O),await b({...R,workspace:(O==null?void 0:O.workspacePath)??null})})}}}),[C,b,N]),T=u.useMemo(()=>_.map(R=>({key:`recent-chat:${R.conversation.tabKey}`,primary:kt(R.conversation),secondary:M1(R.conversation,{timestampLabel:R.timestamp?ug(R.timestamp):null}),unread:R.unread,onClick:()=>g(R.conversation)})),[g,_]),A=C.showAllRecent?D:D.slice(0,4),P=D.length>0,F=T.length>0,J=c?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`flex items-center justify-between gap-3 ${J} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:r.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[r.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":"Back",children:r.jsx(Kd,{size:18})}),r.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[r.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:hs(e,{fallbackId:e.id})}),r.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}`:""]})]})]})}),r.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[F&&r.jsxs("section",{className:"flex flex-col gap-0",children:[r.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),r.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:T.map(R=>r.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${R.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:R.onClick,children:[r.jsx("span",{className:"text-sm font-bold text-text-primary",children:R.primary}),r.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))})]}),P&&r.jsxs("section",{className:"flex flex-col gap-0",children:[r.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),r.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:A.map(R=>r.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:R.onClick,children:[r.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[r.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:R.primary}),R.updatedLabel&&r.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:R.updatedLabel})]}),r.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))}),D.length>4&&r.jsx("div",{className:"flex justify-center px-4 pt-2",children:r.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:()=>C.setShowAllRecent(R=>!R),children:C.showAllRecent?"Show fewer":`Show ${D.length-4} more`})})]}),!1,r.jsxs("section",{className:"flex flex-col gap-0",children:[r.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),r.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[a&&r.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:v,children:[r.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",o]}),r.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),r.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:f,children:[r.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),r.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),C.browseDialogOpen&&r.jsx(_u,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:C.browseCurrentPath,directories:C.browseDirectories,busy:C.browseBusy,error:C.browseError,confirmLabel:"Use this folder",onClose:()=>C.setBrowseDialogOpen(!1),onNavigate:R=>{C.loadBrowsePath(R)},onConfirm:R=>{C.chooseCustomWorkspacePath(R),C.setBrowseDialogOpen(!1)}}),C.launchConfirm&&r.jsx(Fx,{title:C.launchConfirm.title,description:C.launchConfirm.description,details:C.launchConfirm.details,workspaceOptions:C.launchConfirm.workspaceOptions,selectedWorkspaceKey:C.launchConfirmWorkspaceKey,onWorkspaceChange:C.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:C.launchConfirm.providerType?_o(!!C.launchConfirmResumeId):C.launchConfirm.confirmLabel,busyLabel:C.launchConfirm.providerType?void 0:C.launchConfirm.busyLabel,busy:C.launchConfirmBusy,showArgsInput:C.launchConfirm.showArgsInput,argsValue:C.launchConfirmArgs,onArgsChange:C.setLaunchConfirmArgs,showModelInput:C.launchConfirm.showModelInput,modelValue:C.launchConfirmModel,onModelChange:C.setLaunchConfirmModel,historyProviderNode:C.launchConfirm.providerType&&(C.launchConfirmSessionsLoading||C.launchConfirmSavedSessions.length>0)&&r.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[r.jsxs("div",{className:"flex items-center justify-between mb-1",children:[r.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),C.launchConfirmSessionsLoading&&r.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),r.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:mu()}),r.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[r.jsx("input",{type:"text",value:C.launchConfirmTextFilter,onChange:R=>C.setLaunchConfirmTextFilter(R.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:C.launchConfirmBusy||C.launchConfirmSessionsLoading}),r.jsx("input",{type:"text",value:C.launchConfirmWorkspaceFilter,onChange:R=>C.setLaunchConfirmWorkspaceFilter(R.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:C.launchConfirmBusy||C.launchConfirmSessionsLoading}),r.jsx("input",{type:"text",value:C.launchConfirmModelFilter,onChange:R=>C.setLaunchConfirmModelFilter(R.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:C.launchConfirmBusy||C.launchConfirmSessionsLoading}),r.jsxs("select",{value:C.launchConfirmSortMode,onChange:R=>C.setLaunchConfirmSortMode(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:C.launchConfirmBusy||C.launchConfirmSessionsLoading,children:[r.jsx("option",{value:"recent",children:"Most recent"}),r.jsx("option",{value:"oldest",children:"Oldest first"}),r.jsx("option",{value:"messages",children:"Most messages"})]})]}),r.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[r.jsx("input",{type:"checkbox",checked:C.launchConfirmResumableOnly,onChange:R=>C.setLaunchConfirmResumableOnly(R.target.checked),disabled:C.launchConfirmBusy||C.launchConfirmSessionsLoading}),"Resume-ready only"]}),r.jsxs("select",{value:C.launchConfirmResumeId,onChange:R=>C.setLaunchConfirmResumeId(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:C.launchConfirmBusy||C.launchConfirmSessionsLoading,children:[r.jsx("option",{value:"",children:n_()}),C.filteredLaunchConfirmSavedSessions.map(R=>r.jsxs("option",{value:R.providerSessionId,disabled:!R.canResume,children:[R.title||R.providerSessionId," ",R.canResume?"":"(workspace missing)"]},R.providerSessionId))]}),!C.launchConfirmSessionsLoading&&C.launchConfirmSavedSessions.length>0&&C.filteredLaunchConfirmSavedSessions.length===0&&r.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),C.launchConfirmResumeId&&(()=>{const R=C.filteredLaunchConfirmSavedSessions.find(E=>E.providerSessionId===C.launchConfirmResumeId);if(!R)return null;const I=Ox(R);return r.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:[r.jsx("div",{className:"font-semibold text-text-primary truncate",children:I.title}),r.jsx("div",{className:"font-mono break-all mt-0.5",children:I.providerSessionId}),r.jsx("div",{className:"mt-1",children:I.metaLine}),I.updatedLabel&&r.jsx("div",{className:"mt-1 text-text-secondary",children:I.updatedLabel}),I.preview&&r.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:I.preview})]})})()]}),onConfirm:C.handleConfirmLaunch,onCancel:C.closeLaunchConfirm}),p&&r.jsx($x,{section:d,onSectionChange:m})]})}function no(e){return[...e].sort((t,s)=>{const n=s.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(s.conversation.tabKey)})}function UI(e,t=[]){const s=new Map(e.map(i=>[i.conversation.tabKey,i])),n=t.map(i=>s.get(i)).filter(i=>!!i);return n.length===e.length?n:no(e)}function HI(e){var s;const t=((s=e.p2p)==null?void 0:s.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":"Offline"}function zI(e,t){if(!e)return[];const s=e.recentLaunches||[];return s.length>0?s.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:$r(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 i=Ni(n)?"cli":un(n)?"acp":"ide",a=$r(n.summaryMetadata);return{id:`${i}:${n.type}:${n.workspace||""}`,label:((o=n.activeChat)==null?void 0:o.title)||(Ni(n)?n.cliName||n.type:un(n)&&n.cliName||n.type),kind:i,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:un(n)?a||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:n.lastMessageAt||0}}).sort((n,i)=>i.timestamp-n.timestamp).map(({timestamp:n,...i})=>i)}function KI(e,t){const s=new Map;for(const n of t){const i=Kr(n.conversation),a=s.get(i);a?a.push(n):s.set(i,[n])}return e.map(n=>{const i=s.get(n.id)||[],a=[...i].sort((h,m)=>m.timestamp-h.timestamp)[0]||null,o=(a==null?void 0:a.conversation)||null,l=Jc(n),c=i.filter(h=>h.unread||h.requiresAction).length,d=HI(n),p=[n.platform||"machine",d].filter(Boolean);return{id:n.id,label:hs(n,{fallbackId:n.id}),subtitle:p.join(" · "),unread:c,total:i.length,latestConversation:o,latestTimestamp:(a==null?void 0:a.timestamp)||0,fallbackActivityAt:l,preview:o?E1(o):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,i)=>{const a=n.latestTimestamp||n.fallbackActivityAt||0,o=i.latestTimestamp||i.fallbackActivityAt||0;return o!==a?o-a:n.label.localeCompare(i.label)})}function GI(e){return e==="chat"}function $a(e,t){var s;if(!(typeof window>"u"))try{if(!(!!((s=import.meta.env)!=null&&s.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function qI({conversations:e,machineEntries:t,items:s,selectedConversation:n,selectedTabKey:i,screen:a,liveSessionInboxState:o,sendDaemonCommand:l,requestedActiveTabKey:c,onRequestedActiveTabConsumed:d,requestedMachineId:p,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:g,setSelectedTabKey:b,setScreen:f,setSelectedMachineId:v,setSection:w,setMachineBackTarget:x,resetMachineAction:S}){const k=u.useRef(null),j=u.useCallback(y=>{if(!(y!=null&&y.sessionId))return;const N=yo(y,o),_=Math.max(Date.now(),Tr(y),N.lastUpdated||0);$a("mark_read:start",{tabKey:y.tabKey,sessionId:y.sessionId,displayPrimary:kt(y),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:Tr(y),readAt:_}),l(Kr(y)||y.routeId,"mark_session_seen",{sessionId:y.sessionId,providerSessionId:y.providerSessionId,seenAt:_,completionMarker:N.completionMarker}).then(C=>{$a("mark_read:result",{tabKey:y.tabKey,sessionId:y.sessionId,result:C})}).catch(C=>{$a("mark_read:error",{tabKey:y.tabKey,sessionId:y.sessionId,error:C instanceof Error?C.message:String(C)})})},[o,l]);return u.useEffect(()=>{var N;if(!n){GI(a)&&f("inbox"),b(((N=e[0])==null?void 0:N.tabKey)||null),k.current=null;return}if(a!=="chat"){k.current=null;return}const y=`${n.tabKey}:${n.sessionId||""}`;k.current!==y&&(k.current=y,j(n))},[e,j,a,n,f,b]),u.useEffect(()=>{if(!c)return;const y=e.find(N=>N.tabKey===c);y&&(b(y.tabKey),f("chat"),d==null||d())},[e,d,c,f,b]),u.useEffect(()=>{if(!p)return;const y=t.find(N=>N.id===p);y&&(v(y.id),S(),w("machines"),x("inbox"),f("machine"),h==null||h())},[t,h,p,S,x,f,w,v]),u.useEffect(()=>{m&&(w(m),f("inbox"),g==null||g())},[g,m,f,w]),u.useEffect(()=>{const y=s.filter(N=>N.inboxBucket==="task_complete"||N.unread);y.length!==0&&$a("inbox_state",{screen:a,selectedTabKey:i,items:y.map(N=>{const _=yo(N.conversation,o);return{liveState:_,tabKey:N.conversation.tabKey,sessionId:N.conversation.sessionId,displayPrimary:kt(N.conversation),serverBucket:_.inboxBucket,computedBucket:N.inboxBucket,serverUnread:_.unread,computedUnread:N.unread,lastSeenAt:_.lastSeenAt,lastUpdated:_.lastUpdated,activityAt:Tr(N.conversation)}})})},[s,o,a,i]),{markConversationRead:j}}function VI(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function sm(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function XI(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function YI({sendDaemonCommand:e,navigate:t,ides:s,conversations:n}){const{launchCli:i}=rl(),[a,o]=u.useState("idle"),[l,c]=u.useState(""),[d,p]=u.useState(null),h=u.useCallback(()=>{o("idle"),c(""),p(null)},[]),m=u.useCallback(async(S,k,j)=>{var y;try{o("loading"),c(`Launching ${k}…`);const N={ideType:k,enableCdp:!0};(y=j==null?void 0:j.workspacePath)!=null&&y.trim()&&(N.workspace=j.workspacePath.trim()),await e(S,"launch_ide",N),o("done"),c(`${k} launch requested`)}catch(N){o("error"),c(N instanceof Error?N.message:"Launch IDE failed"),console.error("Launch IDE failed",N)}},[e]),g=u.useCallback(async(S,k,j)=>{if(k.trim())try{o("loading"),c(j!=null&&j.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(S,"workspace_add",{path:k.trim(),createIfMissing:(j==null?void 0:j.createIfMissing)===!0});if(y!=null&&y.success){o("done"),c(j!=null&&j.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}o("error"),c((y==null?void 0:y.error)||"Could not save workspace")}catch(y){o("error"),c(y instanceof Error?y.message:"Could not save workspace")}},[e]),b=u.useCallback(async S=>{var k,j,y,N,_,C;try{o("loading"),c("Starting daemon upgrade…");const D=await e(S,"daemon_upgrade",{});if((k=D==null?void 0:D.result)!=null&&k.alreadyLatest){o("done"),c(`Already on v${((j=D==null?void 0:D.result)==null?void 0:j.version)||"latest"}.`);return}if((y=D==null?void 0:D.result)!=null&&y.upgraded||(N=D==null?void 0:D.result)!=null&&N.success){o("done"),c(`Upgrade to v${((_=D==null?void 0:D.result)==null?void 0:_.version)||"latest"} started. Daemon is restarting…`);return}o("error"),c(((C=D==null?void 0:D.result)==null?void 0:C.error)||"Upgrade failed")}catch(D){o("error"),c(D instanceof Error?D.message:"Upgrade failed")}},[e]),f=u.useCallback(async(S,k,j,y)=>{var C,D,T;const N=Date.now(),_={machineId:S,kind:k,providerType:j,workspaceId:(y==null?void 0:y.workspaceId)||null,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:N};try{o("loading"),c(`Launching ${j}…`),p(_);const A={cliType:j};(C=y==null?void 0:y.workspacePath)!=null&&C.trim()?A.dir=y.workspacePath.trim():y!=null&&y.workspaceId&&(A.workspaceId=y.workspaceId),y!=null&&y.resumeSessionId&&(A.resumeSessionId=y.resumeSessionId),(D=y==null?void 0:y.args)!=null&&D.trim()&&(A.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(T=y==null?void 0:y.model)!=null&&T.trim()&&(A.initialModel=y.model.trim());const P=await i(S,A),F=(P==null?void 0:P.result)||P,J=(F==null?void 0:F.sessionId)||(F==null?void 0:F.id);if(P!=null&&P.success&&J){p(null),o("done"),c(`${j} launched`),t(Ii(J));return}if(P!=null&&P.success){o("loading"),c(`${j} launch requested — waiting for session…`);return}p(null),o("error"),c((P==null?void 0:P.error)||(F==null?void 0:F.error)||`Could not launch ${k.toUpperCase()} workspace`)}catch(A){if(XI(A)){o("loading"),c(`${j} launch requested — waiting for session…`);return}p(null),o("error"),c(A instanceof Error?A.message:`Could not launch ${k.toUpperCase()} workspace`)}},[t,e]),v=u.useCallback(async(S,k)=>{try{const j=await e(S,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),y=(j==null?void 0:j.result)??j;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(j){return console.error("Failed to list saved sessions on mobile:",j),[]}},[e]),w=u.useCallback(async(S,k)=>ju(e,S,k),[e]);u.useEffect(()=>{if(!d)return;const S=sm(d.workspacePath),k=s.find(y=>{var A,P,F,J;if(!y||y.type==="adhdev-daemon"||VI(y.daemonId||y.id)!==d.machineId||(y.transport==="acp"?"acp":y.transport==="pty"?"cli":null)!==d.kind||String(y.agentType||y.type||"")!==d.providerType)return!1;const D=String(y.providerSessionId||"");if(d.resumeSessionId&&D)return D===d.resumeSessionId;if(S){const R=sm(y.workspace||y.runtimeWorkspaceLabel);return R?R===S:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((J=(F=(P=(A=y.activeChat)==null?void 0:A.messages)==null?void 0:P.at)==null?void 0:F.call(P,-1))==null?void 0:J.timestamp)||0)>=d.startedAt-5e3});if(!k)return;const j=Px({entrySessionId:k.sessionId,entryInstanceId:k.instanceId,entryRouteId:k.id,conversations:n});j&&(p(null),o("done"),c(`${d.providerType} launched`),t(Ii(j)))},[n,s,t,d]),u.useEffect(()=>{if(!d)return;const S=window.setTimeout(()=>{p(k=>!k||k.startedAt!==d.startedAt?k:(o("error"),c("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(S)},[d]);const x=u.useCallback(async(S,k)=>{if(k.kind==="ide"&&k.providerType){await m(S,k.providerType,{workspacePath:k.workspace||null});return}(k.kind==="cli"||k.kind==="acp")&&k.providerType&&await f(S,k.kind,k.providerType,{workspacePath:k.workspace||null,resumeSessionId:k.providerSessionId||null})},[m,f]);return{machineAction:{state:a,message:l},resetMachineAction:h,handleLaunchDetectedIde:m,handleAddWorkspace:g,handleMachineUpgrade:b,handleLaunchWorkspaceProvider:f,handleListSavedSessions:v,handleBrowseDirectory:w,handleOpenRecent:x}}function QI({conversations:e,selectedConversation:t,machineBackTarget:s,markConversationRead:n,resetMachineAction:i,setSelectedTabKey:a,setScreen:o,setSelectedMachineId:l,setSection:c,setMachineBackTarget:d}){const p=u.useCallback(w=>{a(w.tabKey),o("chat"),n(w)},[n,o,a]),h=u.useCallback(w=>{const x=e.find(S=>S.routeId===w.routeId&&S.streamSource==="native");x&&(a(x.tabKey),o("chat"),n(x))},[e,n,o,a]),m=u.useCallback(()=>{n(t),o("inbox")},[n,t,o]),g=u.useCallback((w,x="inbox")=>{l(w),i(),c("machines"),d(x),o("machine")},[i,d,o,c,l]),b=u.useCallback(w=>{const x=Kr(w);x&&g(x,"chat")},[g]),f=u.useCallback(()=>{i(),o(s)},[s,i,o]),v=u.useCallback(w=>{c(w),o("inbox")},[o,c]);return{openConversation:p,openNativeConversation:h,backFromConversation:m,openMachine:g,openConversationMachine:b,backFromMachine:f,changeMachineSection:v}}function kn(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function JI(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function ZI({conversations:e,hiddenConversations:t,ides:s,actionLogs:n,sendDaemonCommand:i,setActionLogs:a,isStandalone:o,userName:l,requestedActiveTabKey:c,onRequestedActiveTabConsumed:d,requestedMachineId:p,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:g,onOpenHistory:b,onOpenRemote:f,onStopCli:v,wsStatus:w,isConnected:x,onShowAllHiddenConversations:S,onHideConversation:k,onOpenMeshGraph:j,onOpenNewSession:y,liveSessionInboxState:N,setCliViewModeOverrides:_}){const[C,D]=u.useState(()=>{var Y;return((Y=e[0])==null?void 0:Y.tabKey)||null}),[T,A]=u.useState(()=>e[0]?"chat":"inbox"),[P,F]=u.useState("chats"),[J,R]=u.useState(null),[I,E]=u.useState("inbox"),$=u.useRef([]),M=zi(),O="0.9.82",H=u.useMemo(()=>e.find(Y=>Y.tabKey===C)||e[0]||null,[e,C]),ae=u.useMemo(()=>H?s.find(Y=>Y.id===H.routeId):void 0,[s,H]),z=u.useMemo(()=>!H||at(H)||!dt(H)?null:Tn(H),[H]),X=u.useMemo(()=>s.filter(Y=>Y.type==="adhdev-daemon").sort(Zd),[s]),te=u.useMemo(()=>X.find(Y=>Y.id===J)||null,[X,J]),he=cl({sendDaemonCommand:i,activeConv:H||void 0,setActionLogs:a,isStandalone:o}),ke=YI({sendDaemonCommand:i,navigate:M,ides:s,conversations:e}),Q=u.useMemo(()=>e.map(Y=>{const Ae=T==="chat"&&(H==null?void 0:H.tabKey)===Y.tabKey,Ce=ol(Y,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ae}),je=Tr(Y),qe=Kg(Y);return{conversation:Y,timestamp:je,preview:qe,unread:Ce.unread,requiresAction:Ce.requiresAction,isWorking:Ce.isWorking,inboxBucket:Ce.inboxBucket}}),[e,N,T,H]),{markConversationRead:q}=qI({conversations:e,machineEntries:X,items:Q,selectedConversation:H,selectedTabKey:C,screen:T,liveSessionInboxState:N,sendDaemonCommand:i,requestedActiveTabKey:c,onRequestedActiveTabConsumed:d,requestedMachineId:p,onRequestedMachineConsumed:h,requestedMobileSection:m,onRequestedMobileSectionConsumed:g,setSelectedTabKey:D,setScreen:A,setSelectedMachineId:R,setSection:F,setMachineBackTarget:E,resetMachineAction:ke.resetMachineAction}),me=QI({conversations:e,selectedConversation:H,machineBackTarget:I,markConversationRead:q,resetMachineAction:ke.resetMachineAction,setSelectedTabKey:D,setScreen:A,setSelectedMachineId:R,setSection:F,setMachineBackTarget:E}),{isMuted:we,autoMuteIfCoordinator:ye,toggleTarget:Te}=hC();u.useEffect(()=>{if(o)for(const Y of Q)ye(Y.conversation)},[Q,o,ye]);const le=u.useMemo(()=>no(Q.filter(Y=>Y.requiresAction&&!we(Y.conversation))),[Q,we]),Se=u.useMemo(()=>no(Q.filter(Y=>Y.unread&&!Y.requiresAction&&!we(Y.conversation))),[Q,we]),ge=u.useMemo(()=>UI(Q.filter(Y=>!Y.unread&&!Y.requiresAction&&Y.isWorking),$.current),[Q]);u.useEffect(()=>{$.current=ge.map(Y=>Y.conversation.tabKey)},[ge]);const G=u.useMemo(()=>no(Q.filter(Y=>!Y.unread&&!Y.requiresAction&&!Y.isWorking)),[Q]),W=u.useMemo(()=>te?Q.filter(Y=>Kr(Y.conversation)===te.id):[],[Q,te]),Z=u.useMemo(()=>zI(te,s),[s,te]),oe=(te==null?void 0:te.version)||null,ue=!!te&&!!oe&&!0&&oe!==O,ce=u.useMemo(()=>(te==null?void 0:te.availableProviders)||[],[te]),L=u.useMemo(()=>ce.filter(Y=>kn(Y,"cli")).map(Y=>({type:Y.type,displayName:Y.displayName||Y.type,icon:Y.icon})),[ce]),de=u.useMemo(()=>ce.filter(Y=>kn(Y,"acp")).map(Y=>({type:Y.type,displayName:Y.displayName||Y.type,icon:Y.icon})),[ce]),U=u.useMemo(()=>KI(X,Q),[Q,X]),ie=u.useCallback(async Y=>{te&&await ke.handleOpenRecent(te.id,Y)},[ke,te]);return r.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:T==="chat"&&H?r.jsx(EI,{selectedConversation:H,isAcp:at(H),isStandalone:o,selectedIdeEntry:ae,actionLogs:n,userName:l,isSendingChat:he.isSendingChat,sendFeedbackMessage:he.sendFeedbackMessage,isFocusingAgent:he.isFocusingAgent,handleModalButton:he.handleModalButton,handleRelaunch:he.handleRelaunch,onBack:me.backFromConversation,onOpenNativeConversation:me.openNativeConversation,onOpenMachine:me.openConversationMachine,onOpenHistory:b,onOpenRemote:f,onOpenMeshGraph:j,onStopCli:v,cliViewMode:z,onSetCliViewMode:async Y=>{await wx({conversation:H,mode:Y,ides:s,sendDaemonCommand:i,setCliViewModeOverrides:_})},handleSendChat:he.handleSendChat,handleForceSendChat:he.handleForceSendChat,handleFocusAgent:he.handleFocusAgent}):T==="machine"&&te?r.jsx(WI,{selectedMachineEntry:te,selectedMachineConversations:W,selectedMachineRecentLaunches:Z,cliProviders:L,acpProviders:de,selectedMachineNeedsUpgrade:ue,appVersion:O,machineAction:ke.machineAction,isStandalone:o,section:P,showBottomNav:I==="inbox",onBack:me.backFromMachine,onSectionChange:me.changeMachineSection,onOpenConversation:me.openConversation,onOpenRecent:ie,onOpenMachineDetails:()=>M(`/machines/${te.id}`),onMachineUpgrade:()=>ke.handleMachineUpgrade(te.id),onLaunchDetectedIde:(Y,Ae)=>ke.handleLaunchDetectedIde(te.id,Y,Ae),onAddWorkspace:(Y,Ae)=>ke.handleAddWorkspace(te.id,Y,Ae),onBrowseDirectory:Y=>ke.handleBrowseDirectory(te.id,Y),onLaunchWorkspaceProvider:(Y,Ae,Ce)=>ke.handleLaunchWorkspaceProvider(te.id,Y,Ae,Ce),onListSavedSessions:Y=>ke.handleListSavedSessions(te.id,Y)}):r.jsx(DI,{section:P,attentionItems:le,unreadItems:Se,workingItems:ge,completedItems:G,hiddenConversations:t,machineCards:U,getAvatarText:JI,actionLogs:n,sendDaemonCommand:i,onOpenConversation:me.openConversation,onShowAllHidden:S,onHideConversation:k,onOpenMeshGraph:j,onOpenNewSession:y,onOpenMachine:me.openMachine,onOpenSettings:()=>M("/settings"),onSectionChange:F,wsStatus:w,isConnected:x,isStandalone:o,isConversationMuted:o?we:void 0,onToggleMuteConversation:o?Te:void 0})})}function cc(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function eA({conversations:e,numGroups:t,onMoveTab:s,onReceiveTab:n,onOwnTabDrop:i,onClearPreviewOrder:a}){const o=u.useRef(0),[l,c]=u.useState(!1),[d,p]=u.useState(null),h=u.useCallback(()=>{o.current=0,c(!1),p(null)},[]);u.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const m=u.useCallback(v=>{v.dataTransfer.types.includes("text/tab-key")&&(o.current+=1,c(!0))},[]),g=u.useCallback(v=>{if(!v.dataTransfer.types.includes("text/tab-key"))return;if(v.preventDefault(),!cc(t,s)){p("merge");return}const w=v.currentTarget.getBoundingClientRect(),x=v.clientX-w.left,S=w.width/3;x<S?p("split-left"):x>S*2?p("split-right"):p("merge")},[t,s]),b=u.useCallback(()=>{o.current-=1,!(o.current>0)&&(o.current=0,c(!1),p(null))},[]),f=u.useCallback(v=>{o.current=0,c(!1);const w=v.dataTransfer.getData("text/tab-key"),x=w?e.some(k=>k.tabKey===w):!1,S=d;if(p(null),a(),!!w){if(v.preventDefault(),S==="split-left"&&cc(t,s)){s==null||s(w,"split-left");return}if(S==="split-right"&&cc(t,s)){s==null||s(w,"split-right");return}if(x){i(w);return}n==null||n(w)}},[e,d,t,s,n,i,a]);return{dragOver:l,dropAction:d,resetDragState:h,handleDragEnter:m,handleDragOver:g,handleDragLeave:b,handleDrop:f}}function tA(e,t){const s=new Set(t.map(a=>a.tabKey)),n=e.filter(a=>s.has(a)),i=t.filter(a=>!e.includes(a.tabKey)).map(a=>a.tabKey);return[...n,...i]}function sA({conversations:e,initialActiveTabId:t,initialTabOrder:s,onActiveTabChange:n,onTabOrderChange:i}){const[a,o]=u.useState(t??null),[l,c]=u.useState(s??[]),[d,p]=u.useState(null),h=u.useRef(null),m=u.useRef(null),g=u.useRef(n),b=u.useRef(i);u.useEffect(()=>{g.current=n},[n]),u.useEffect(()=>{b.current=i},[i]),u.useEffect(()=>{t&&t!==a&&o(t)},[t,a]),u.useEffect(()=>{c(N=>{const _=tA(N,e);return _.length===N.length&&_.every((C,D)=>C===N[D])?N:_})},[e]);const f=u.useMemo(()=>{const N=d??l;if(N.length===0)return e;const _=new Map(N.map((C,D)=>[C,D]));return[...e].sort((C,D)=>{const T=_.get(C.tabKey)??999,A=_.get(D.tabKey)??999;return T-A})},[e,d,l]);u.useEffect(()=>{var _,C;if(f.length===0){a!==null&&(o(null),(_=g.current)==null||_.call(g,null));return}if(a&&f.some(D=>D.tabKey===a))return;const N=f[0].tabKey;N!==a&&(o(N),(C=g.current)==null||C.call(g,N))},[f,a]);const v=u.useMemo(()=>f.find(N=>N.tabKey===a),[f,a]),w=u.useCallback(N=>{var _;o(N),(_=g.current)==null||_.call(g,N)},[]),x=u.useCallback((N,_,C)=>{c(D=>{var F;const T=D.filter(J=>J!==N),A=T.indexOf(_);if(A<0)return D;const P=C==="left"?A:A+1;return T.splice(P,0,N),(F=b.current)==null||F.call(b,T),T}),p(null)},[]),S=u.useCallback((N,_,C)=>{const T=(l.length>0?l:e.map(F=>F.tabKey)).filter(F=>F!==N),A=T.indexOf(_);if(A<0)return;const P=C==="left"?A:A+1;T.splice(P,0,N),h.current=T,p(T)},[l,e]),k=u.useCallback(()=>{var _;const N=h.current;N&&(c(N),(_=b.current)==null||_.call(b,N))},[]),j=u.useCallback(()=>{h.current=null,p(null)},[]),y=u.useCallback(N=>{c(_=>{var D;const C=_.filter(T=>T!==N);return C.push(N),(D=b.current)==null||D.call(b,C),C})},[]);return{activeTabId:a,activeConv:v,sortedConversations:f,previewOrderRef:h,draggingTabRef:m,selectTab:w,handleTabReorder:x,updatePreviewOrder:S,commitPreviewOrder:k,clearPreviewOrder:j,moveTabToEnd:y,setDraggingTabKey:N=>{m.current=N}}}function rA({dropAction:e,canSplit:t}){return r.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[r.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:r.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"})}),r.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:r.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"})}),r.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:r.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 Cu({conversationsCount:e,isSplitMode:t,isStandalone:s,hasRegisteredMachines:n=!1,suppressGuide:i=!1,onOpenNewSession:a}){if(i)return r.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const o=!s&&!n,l=n&&!!a,c=n?"No conversations yet":s?"Waiting for your daemon":"Connect your machines",d=n?Qg:s?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can launch sessions with any installed provider.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!t?r.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[r.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:r.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),r.jsxs("div",{className:"text-center max-w-lg",children:[r.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:c}),r.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:d}),l&&r.jsx("div",{className:"flex items-center justify-center mb-4",children:r.jsxs("button",{type:"button",onClick:a,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Ps,"aria-label":Ps,children:[r.jsx(Jf,{size:14}),r.jsx("span",{children:Ps})]})}),o&&r.jsx(Lx,{}),o&&r.jsx("div",{className:"mt-8",children:r.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 →"})})]})]}):r.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const Ux="adhdev-tab-shortcuts";function Hx(){try{return JSON.parse(localStorage.getItem(Ux)||"{}")}catch{return{}}}function zx({enabled:e=!0,sortedTabKeys:t,onFocus:s,onSelectTab:n}){const i=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[a,o]=u.useState(()=>Hx()),[l,c]=u.useState(null),d=u.useCallback(h=>{const m=[];return h.metaKey&&m.push(i?"⌘":"Meta"),h.ctrlKey&&m.push("Ctrl"),h.altKey&&m.push(i?"⌥":"Alt"),h.shiftKey&&m.push(i?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(m.push(h.key.length===1?h.key.toUpperCase():h.key),m.join("+"))},[i]),p=u.useCallback(h=>{o(h);try{localStorage.setItem(Ux,JSON.stringify(h))}catch{}},[]);return u.useEffect(()=>{if(!e||!l)return;const h=m=>{if(m.preventDefault(),m.stopPropagation(),m.key==="Escape"){c(null);return}const g=d(m);if(!g)return;const b={...a};for(const[f,v]of Object.entries(b))v===g&&delete b[f];b[l]=g,p(b),c(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,a,p,d]),u.useEffect(()=>{if(!e)return;const h=m=>{if(!(!m.ctrlKey&&!m.metaKey&&!m.altKey)){for(const[g,b]of Object.entries(a))if(t.includes(g)&&d(m)===b){m.preventDefault(),s(),n(g);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,a,t,s,n,d]),{isMac:i,tabShortcuts:a,shortcutListening:l,setShortcutListening:c,saveShortcuts:p}}const dc=e=>{e.preventDefault()},nA=u.memo(function({conv:t,isActive:s,isDraggedTab:n,isTaskCompleteUnread:i,shortcut:a,conversationKeys:o,draggingTabRef:l,onFocus:c,onSelectTab:d,onConversationActivated:p,onPreviewReorder:h,onReorderTab:m,onCommitPreviewOrder:g,onClearPreviewOrder:b,onDragStateReset:f,onDragTabKeyChange:v,onReceiveTab:w,onOpenContextMenu:x,longPressTimer:S,isGroupActive:k}){const j=An(t),y=j.isGenerating?"agent-tab-generating":j.isWaiting?"agent-tab-waiting":"",N=j.isReconnecting,_=A1(t),C=T1(t),D=u.useCallback($=>{l.current=t.tabKey,v(t.tabKey),$.dataTransfer.setData("text/tab-key",t.tabKey),$.dataTransfer.effectAllowed="move"},[t.tabKey,l,v]),T=u.useCallback(()=>{l.current=null,v(null),g(),b(),f()},[l,v,g,b,f]),A=u.useCallback($=>{const M=l.current;if(!(!M||M===t.tabKey)&&$.dataTransfer.types.includes("text/tab-key")){$.preventDefault(),$.stopPropagation();const O=$.currentTarget.getBoundingClientRect(),H=$.clientX<O.left+O.width/2?"left":"right";h(M,t.tabKey,H)}},[t.tabKey,l,h]),P=u.useCallback($=>{$.preventDefault(),$.stopPropagation();const M=$.dataTransfer.getData("text/tab-key");if(M&&M!==t.tabKey){const O=$.currentTarget.getBoundingClientRect(),H=$.clientX<O.left+O.width/2?"left":"right";o.includes(M)?m(M,t.tabKey,H):w&&w(M)}b()},[t.tabKey,o,m,w,b]),F=u.useCallback($=>{$.stopPropagation(),c(),d(t.tabKey),p(t)},[t,p,c,d]),J=u.useCallback($=>{$.preventDefault(),x($.clientX,$.clientY,t.tabKey)},[t.tabKey,x]),R=u.useCallback($=>{const M=$.touches[0];S.current=setTimeout(()=>{x(M.clientX,M.clientY,t.tabKey)},600)},[t.tabKey,S,x]),I=u.useCallback(()=>{S.current&&clearTimeout(S.current)},[S]),E=["adhdev-dockview-tab",y,s&&"is-active",k&&"is-group-active",N&&"is-reconnecting"].filter(Boolean).join(" ");return r.jsxs("div",{"data-tabkey":t.tabKey,className:E,draggable:!0,onDragStart:D,onDragEnd:T,onDragOver:A,onDrop:P,onClick:F,onContextMenu:J,onTouchStart:R,onTouchEnd:I,onTouchMove:I,style:{cursor:"pointer",opacity:n?.4:void 0},children:[i&&r.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),r.jsx("div",{className:"adhdev-dockview-tab-status",children:j.isGenerating?r.jsx("div",{className:"tab-spinner"}):j.isWaiting?r.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?r.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):j.isConnecting?r.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?r.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):r.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),_.length>0&&r.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:C,"aria-label":C||_.join(" · "),children:_.join(" · ")}),r.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[r.jsx("span",{className:"adhdev-dockview-tab-primary",title:kt(t),children:kt(t)}),r.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[N?r.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Cr(t)}):j.isConnecting?r.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Cr(t),r.jsx("span",{className:"connecting-dots"})]}):r.jsx("span",{className:"truncate",children:Cr(t)}),r.jsx(No,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),a&&r.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${a}`,children:a})]})},(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 iA({conversations:e,activeTabId:t,groupIndex:s,unreadTabKeys:n,draggingTabRef:i,onFocus:a,onSelectTab:o,onConversationActivated:l,onPreviewReorder:c,onReorderTab:d,onCommitPreviewOrder:p,onClearPreviewOrder:h,onDragStateReset:m,onDragTabKeyChange:g,onReceiveTab:b,onHideTab:f,isGroupActive:v,allowTabShortcuts:w=!0}){const[x,S]=u.useState(null),k=u.useRef(null),j=u.useRef(null),y=u.useMemo(()=>e.map(P=>P.tabKey),[e]);qi("PaneGroupTabBar",{groupIndex:s,activeTabId:t,tabCount:e.length,ctxMenuTab:(x==null?void 0:x.tabKey)||null});const{isMac:N,tabShortcuts:_,shortcutListening:C,setShortcutListening:D,saveShortcuts:T}=zx({enabled:w,sortedTabKeys:e.map(P=>P.tabKey),onFocus:a,onSelectTab:o});u.useEffect(()=>{if(!x)return;const P=F=>{const J=document.querySelector("[data-pane-context-menu]");J&&J.contains(F.target)||S(null)};return window.addEventListener("mousedown",P,!0),()=>window.removeEventListener("mousedown",P,!0)},[x]),u.useEffect(()=>{const P=j.current;if(!P)return;const F=J=>{Math.abs(J.deltaY)<=Math.abs(J.deltaX)||(J.preventDefault(),P.scrollLeft+=J.deltaY)};return P.addEventListener("wheel",F,{passive:!1}),()=>P.removeEventListener("wheel",F)},[]);const A=u.useCallback((P,F,J)=>{S({x:P,y:F,tabKey:J})},[]);return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:r.jsxs("div",{ref:j,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(P=>r.jsx(nA,{conv:P,isActive:t===P.tabKey,isDraggedTab:i.current===P.tabKey,isTaskCompleteUnread:n.has(P.tabKey),shortcut:w?_[P.tabKey]:void 0,conversationKeys:y,draggingTabRef:i,onFocus:a,onSelectTab:o,onConversationActivated:l,onPreviewReorder:c,onReorderTab:d,onCommitPreviewOrder:p,onClearPreviewOrder:h,onDragStateReset:m,onDragTabKeyChange:g,onReceiveTab:b,onOpenContextMenu:A,longPressTimer:k,isGroupActive:v},P.tabKey)),e.length===0&&r.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),x&&r.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:[w&&r.jsxs(r.Fragment,{children:[r.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:dc,onClick:P=>{P.stopPropagation(),D(x.tabKey),S(null)},children:["⌨ ",_[x.tabKey]?`Change shortcut (${_[x.tabKey]})`:"Set shortcut"]}),_[x.tabKey]&&r.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:dc,onClick:()=>{const P={..._};delete P[x.tabKey],T(P),S(null)},children:"✕ Remove shortcut"})]}),f&&r.jsxs(r.Fragment,{children:[w&&r.jsx("div",{className:"border-t border-border-subtle my-1"}),r.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:dc,onClick:()=>{f(x.tabKey),S(null)},children:"🚫 Hide from Dashboard"})]})]}),w&&C&&r.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:()=>D(null),children:r.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:P=>P.stopPropagation(),children:[r.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),r.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",N?"⌘+1":"Ctrl+1",", ",N?"⌥+A":"Alt+A",")"]}),r.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),r.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function aA({conversations:e,ides:t,clearedTabs:s,actionLogs:n,sendDaemonCommand:i,setActionLogs:a,isStandalone:o,hasRegisteredMachines:l,userName:c,groupIndex:d,onFocus:p,isSplitMode:h,numGroups:m,onMoveTab:g,onReceiveTab:b,style:f,onActiveTabChange:v,initialActiveTabId:w,initialTabOrder:x,onTabOrderChange:S,onHideTab:k,isFocused:j,allowTabShortcuts:y=!0,onOpenNewSession:N,liveSessionInboxState:_}){const{sendCommand:C}=jt(),D=u.useRef(null),{activeTabId:T,activeConv:A,sortedConversations:P,draggingTabRef:F,selectTab:J,handleTabReorder:R,updatePreviewOrder:I,commitPreviewOrder:E,clearPreviewOrder:$,moveTabToEnd:M,setDraggingTabKey:O}=sA({conversations:e,initialActiveTabId:w,initialTabOrder:x,onActiveTabChange:v,onTabOrderChange:S}),H=cl({sendDaemonCommand:i,activeConv:A,setActionLogs:a,isStandalone:o}),{dragOver:ae,dropAction:z,resetDragState:X,handleDragEnter:te,handleDragOver:he,handleDragLeave:ke,handleDrop:Q}=eA({conversations:e,numGroups:m,onMoveTab:g,onReceiveTab:b,onOwnTabDrop:M,onClearPreviewOrder:$}),q=A&&!at(A)&&Tn(A)==="terminal",me=u.useMemo(()=>A?t.find(le=>le.id===A.routeId):void 0,[t,A]),we=u.useMemo(()=>A?n.filter(le=>le.routeId===A.tabKey):[],[n,A]),ye=u.useMemo(()=>new Set(P.filter(le=>Pk(le,_,{isOpenConversation:le.tabKey===T})).map(le=>le.tabKey)),[T,_,P]);qi("PaneGroup",{groupIndex:d,conversationCount:e.length,activeTabId:T,dragOver:ae});const Te=u.useCallback(le=>{le.streamSource==="agent-stream"&&le.agentType&&C(le.routeId,Mg(),{agentType:le.agentType,...le.sessionId&&{targetSessionId:le.sessionId}}).catch(()=>{})},[C]);return r.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:p,style:{...f,outline:ae?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[r.jsx(iA,{conversations:P,activeTabId:T,groupIndex:d,numGroups:m,unreadTabKeys:ye,draggingTabRef:F,onFocus:p,onSelectTab:J,onConversationActivated:Te,onPreviewReorder:I,onReorderTab:R,onCommitPreviewOrder:E,onClearPreviewOrder:$,onDragStateReset:X,onDragTabKeyChange:O,onMoveTab:g,onReceiveTab:b,onHideTab:k,isGroupActive:j??!1,allowTabShortcuts:y}),r.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:te,onDragOver:he,onDragLeave:ke,onDrop:Q,children:[ae&&r.jsx(rA,{dropAction:z,canSplit:!!(m<4&&g)}),A?r.jsx(Nu,{activeConv:A,clearToken:s[A.tabKey]||0,isCliTerminal:!!q,ideEntry:me,terminalRef:D,handleModalButton:H.handleModalButton,handleRelaunch:H.handleRelaunch,handleSendChat:H.handleSendChat,handleForceSendChat:H.handleForceSendChat,isSendingChat:H.isSendingChat,sendFeedbackMessage:H.sendFeedbackMessage,handleFocusAgent:H.handleFocusAgent,isFocusingAgent:H.isFocusingAgent,actionLogs:we,userName:c,isInputActive:!h||!!j}):r.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:r.jsx(Cu,{conversationsCount:e.length,isSplitMode:h,isStandalone:o,hasRegisteredMachines:l,onOpenNewSession:N})})]})]})}function oA({containerRef:e,isSplitMode:t,numGroups:s,groupSizes:n,groupedConvs:i,clearedTabs:a,ides:o,actionLogs:l,sendDaemonCommand:c,setActionLogs:d,isStandalone:p,hasRegisteredMachines:h,userName:m,focusedGroup:g,focusGroup:b,moveTabToGroup:f,splitTabRelative:v,closeGroup:w,handleResizeStart:x,groupActiveTabIds:S,setGroupActiveTab:k,groupTabOrders:j,setGroupTabOrder:y,toggleHiddenTab:N,onOpenNewSession:_,allowTabShortcuts:C=!0,liveSessionInboxState:D}){return r.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:i.map((T,A)=>{const P=t&&n.length===s?`${n[A]}%`:void 0;return r.jsxs(Kt.Fragment,{children:[t&&A>0&&r.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:F=>x(A-1,F),onDoubleClick:()=>w(A),title:"Drag to resize · Double-click to merge",children:r.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),r.jsx(aA,{style:t?{flexBasis:P??`${100/s}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:T,clearedTabs:a,ides:o,actionLogs:l,sendDaemonCommand:c,setActionLogs:d,isStandalone:p,hasRegisteredMachines:h,userName:m,groupIndex:A,isFocused:t&&g===A,onFocus:()=>b(A),isSplitMode:t,numGroups:s,onMoveTab:(F,J)=>{J==="left"&&A>0?f(F,A-1):J==="right"&&A<s-1?f(F,A+1):J==="split-left"&&s<4?v(F,A,"left"):J==="split-right"&&s<4&&v(F,A,"right")},onReceiveTab:F=>f(F,A),onActiveTabChange:F=>k(A,F),initialActiveTabId:S[A],initialTabOrder:j[A],onTabOrderChange:F=>y(A,F),onHideTab:N,onOpenNewSession:_,allowTabShortcuts:C,liveSessionInboxState:D})]},A)})})}function Kx({doId:e,targetSessionId:t,connState:s,viewMode:n}){const[i,a]=u.useState(null),[o,l]=u.useState(null);u.useEffect(()=>e?At.onScreenshot("ide-page",(p,h)=>{if(p!==e)return;const m=new FileReader;m.onload=()=>a(m.result),m.readAsDataURL(h)}):void 0,[e]),u.useEffect(()=>{s!=="connected"&&a(null)},[s]),u.useEffect(()=>{var p;return e?((p=At.onStatus)==null?void 0:p.call(At,(h,m)=>{h===e&&m!=null&&m.screenshotUsage&&l(m.screenshotUsage)}))||(()=>{}):void 0},[e]),u.useEffect(()=>{a(null)},[e,t]),u.useEffect(()=>{const d=e?At.get(e):null;if(!(!d||s!=="connected"))return n!=="chat"&&t?d.startScreenshots(t):d.stopScreenshots(t),()=>{d.stopScreenshots(t)}},[n,s,t,e]);const c=u.useCallback(async(d,p)=>{const h=e?At.get(e):null;return!h||s!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(d,p,t)},[e,s,t]);return{connScreenshot:i,screenshotUsage:o,handleRemoteAction:c}}const Gx="adhdev-dashboard-action-shortcuts",lA=1200,cA=[["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 dA(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function gt(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 qx(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:gt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:gt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:gt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:gt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:gt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:gt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:gt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:gt("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:gt("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:gt("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:gt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:gt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:gt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:gt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:gt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:gt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:gt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:gt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:gt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:gt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:gt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:gt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:gt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:gt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:gt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:gt("toggleCliView",e)}]}function md(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Po(e){const t=Object.fromEntries(qx(e).map(s=>[s.id,s.defaultShortcut]));try{const s=JSON.parse(localStorage.getItem(Gx)||"{}"),n={...t,...s};for(const[i,a]of cA)n[i]===a&&(n[i]=t[i]);return n}catch{return t}}function Vx(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function uA({enabled:e=!0,onTrigger:t}){const s=dA(),[n,i]=u.useState(()=>Po(s)),[a,o]=u.useState(null),[l,c]=u.useState([]),d=u.useRef({parts:[],timer:null}),p=u.useCallback(f=>{const v=[];return f.metaKey&&v.push(s?"⌘":"Meta"),f.ctrlKey&&v.push("Ctrl"),f.altKey&&v.push(s?"⌥":"Alt"),f.shiftKey&&f.key.length!==1&&v.push(s?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(v.push(Vx(f.key)),v.join("+"))},[s]),h=u.useCallback(f=>{i(f);try{localStorage.setItem(Gx,JSON.stringify(f))}catch{}},[]);u.useEffect(()=>{const f=Po(s),v=Object.entries(n),w=Object.entries(f);v.length===w.length&&v.every(([x,S])=>f[x]===S)||h(f)},[n,s,h]);const m=u.useCallback(()=>{typeof window<"u"&&d.current.timer!=null&&window.clearTimeout(d.current.timer),d.current={parts:[],timer:null}},[]),g=u.useCallback(()=>{typeof window>"u"||(d.current.timer!=null&&window.clearTimeout(d.current.timer),d.current.timer=window.setTimeout(()=>{d.current={parts:[],timer:null}},lA))},[]);u.useEffect(()=>{if(!a)return;const f=v=>{if(v.preventDefault(),v.stopPropagation(),v.key==="Escape"){o(null),c([]);return}const w=p(v);if(!w)return;const S=!(v.metaKey||v.ctrlKey||v.altKey)&&/^[A-Z0-9]$/.test(w);if(l.length===0&&S){c([w]);return}const j=[...l,w].slice(0,2).join(" "),y={...n};for(const[N,_]of Object.entries(y))_===j&&delete y[N];y[a]=j,h(y),o(null),c([])};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[n,p,h,a,l]),u.useEffect(()=>{if(!e||a)return;const f=v=>{if(v.defaultPrevented)return;const w=p(v);if(!w)return;const x=v.metaKey||v.ctrlKey||v.altKey;if(md(v.target))return;const S=d.current.parts,k=x?[w]:[...S.slice(-1),w].slice(-2),j=k.join(" "),y=k[k.length-1],N=Object.entries(n).filter(([,A])=>!!A),_=N.find(([,A])=>A===j);if(_){v.preventDefault(),m(),t(_[0]);return}if(N.some(([,A])=>A.startsWith(`${j} `))){v.preventDefault(),d.current.parts=k,g();return}const D=N.find(([,A])=>A===y);if(D){v.preventDefault(),m(),t(D[0]);return}if(N.some(([,A])=>A.startsWith(`${y} `))){v.preventDefault(),d.current.parts=[y],g();return}m()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[n,g,e,p,t,m,a]),u.useEffect(()=>()=>m(),[m]);const b=u.useMemo(()=>qx(s),[s]);return{isMac:s,actionDefinitions:b,actionShortcuts:n,shortcutListening:a,shortcutListeningDraft:l,setShortcutListening:o,setShortcutListeningDraft:c,saveShortcuts:h}}function pA({isTabInPopout:e,isTabFloating:t,tabShortcut:s,actionShortcuts:n}){const i=[];return e?(t&&i.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),i.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):t?i.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):i.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),i.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:s?`Change shortcut (${s})`:"Set shortcut",shortcut:n.setActiveTabShortcut}),s&&i.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),i.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:n.hideCurrentTab,tone:"muted"}),i}function Xx(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function rm({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:s,ides:n}){return!e||s>0?!1:t?!Xx(n):!0}function hA({previousVisibleConversationCount:e,visibleConversationCount:t,ides:s}){return t>0||e<=0?!1:Xx(s)}const Yx=1e3,mA=4;function nm(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function im(e,t,s){return Math.abs(t.clientX-e.clientX)>s||Math.abs(t.clientY-e.clientY)>s}function fA({detachDelayMs:e=Yx,stillnessThresholdPx:t=mA,onDetach:s,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:i=globalThis.clearTimeout.bind(globalThis)}){let a=null,o=null,l=null,c=null,d=null,p=!1;const h=()=>{d!=null&&(i(d),d=null)},m=()=>{h(),l=null},g=()=>{h(),a=null,o=null,l=null,c=null,p=!1},b=()=>{!a||!l||!c||p||d!=null||(d=n(()=>{d=null,!(!a||!l||!c||p)&&nm(c,o)&&(im(l,c,t)||(p=!0,s({panelId:a,clientX:c.clientX,clientY:c.clientY})))},e))},f=w=>{if(!(!a||p)){if(!nm(w,o)){c={clientX:w.clientX,clientY:w.clientY},m();return}(!l||im(l,w,t))&&(h(),l={clientX:w.clientX,clientY:w.clientY}),c={clientX:w.clientX,clientY:w.clientY},b()}},v=w=>{!a||p||(w&&(c={clientX:w.clientX,clientY:w.clientY}),m())};return{startDrag:w=>{h(),a=w.panelId,o=w.selfPanelBounds??null,l=null,c={clientX:w.clientX,clientY:w.clientY},p=!1},markSelfPanel:f,markNonSelfPanel:v,markNoDropTarget:v,markDockTarget:v,endDrag:g,isDragging:()=>a!=null,hasDetached:()=>p,dispose:g}}function gA(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Oa(e){return e.isActive}function am(e){return e.isVisible}const Qx=u.createContext(null);function hl(){const e=u.useContext(Qx);if(!e)throw new Error("DashboardDockviewContext missing");return e}function io(e){return kt(e)||e.tabKey}function xA(e){return`remote:${e}`}function ys(e){return e.startsWith("remote:")}function om(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function bA(e){e.preventDefault()}function uc(e){var n;const t=e==null?void 0:e.defaultView;if(!t)return;const s=i=>{if(i)try{i.focus({preventScroll:!0})}catch{try{i.focus()}catch{}}};try{t.focus(),s(e==null?void 0:e.body),s(e==null?void 0:e.documentElement),(n=t.requestAnimationFrame)==null||n.call(t,()=>{try{t.focus(),s(e==null?void 0:e.body)}catch{}})}catch{}}function pc(e,t){e.classList.remove(Hc.className,zc.className),e.classList.add(t==="light"?Hc.className:zc.className)}function lm(e){return e?Array.from(new Set(e.groups.map(t=>{var s,n;return(n=(s=t.element)==null?void 0:s.ownerDocument)==null?void 0:n.defaultView}).filter(t=>!!t&&t!==window))):[]}function yA(e){const[,t]=u.useState(0);u.useEffect(()=>{const s=()=>t(i=>i+1),n=[e.api.onDidActiveGroupChange(s),e.api.onDidTitleChange(s),e.api.onDidGroupChange(s),e.containerApi.onDidActivePanelChange(s)];return()=>{for(const i of n)i.dispose()}},[e.api,e.containerApi])}function vA(e,t,s){var o;const n=[t];let i;for(const l of n){let c;for(const d of l){const p=e.addPanel({id:d.tabKey,component:"conversation",title:io(d),params:{kind:"conversation",tabKey:d.tabKey},...c?{position:{referencePanel:c,direction:"within"},inactive:!0}:i?{position:{referencePanel:i,direction:"right"},inactive:!0}:{}});c||(c=p.id)}i=c??i}return s??((o=t[0])==null?void 0:o.tabKey)??null}function cm(e,t){const s=new Set(t.map(i=>i.tabKey)),n=new Map;for(const i of t)n.set(i.tabKey,(n.get(i.tabKey)||0)+1);for(const i of[...e.panels])ys(i.id)||s.has(i.id)||e.removePanel(i);for(const i of t){const a=e.getPanel(i.tabKey);if(a){(n.get(i.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:i.tabKey,daemonId:i.daemonId,sessionId:i.sessionId,providerSessionId:i.providerSessionId,panelId:a.id}),a.update({params:{tabKey:i.tabKey}}),a.title!==io(i)&&a.api.setTitle(io(i));continue}e.addPanel({id:i.tabKey,component:"conversation",title:io(i),params:{kind:"conversation",tabKey:i.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 dm(e,t,s){var c,d;const n=s?xA(s):null;for(const p of[...e.panels])ys(p.id)&&(!n||p.id!==n)&&e.removePanel(p);if(!s||!n)return;const i=js(t,s);if(!i&&e.totalPanels===0)return;const a=e.getPanel(n),o=Vg(i);if(a){a.title!==o&&a.api.setTitle(o);return}const l=(i==null?void 0:i.tabKey)??((c=e.activePanel)==null?void 0:c.id)??((d=e.panels.find(p=>!ys(p.id)))==null?void 0:d.id);e.addPanel({id:n,component:"remote",title:o,params:{kind:"remote",routeId:s},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function wA({params:e,api:t}){var g;const s=hl(),n=u.useRef(null),[i,a]=u.useState(()=>Oa(t)),[o,l]=u.useState(()=>am(t)),c=s.conversationsByTabKey.get(e.tabKey),d=cl({sendDaemonCommand:s.sendDaemonCommand,activeConv:c,setActionLogs:s.setActionLogs,isStandalone:s.isStandalone});u.useEffect(()=>{a(Oa(t)),l(am(t));const b=[t.onDidActiveChange(f=>a(f.isActive)),t.onDidActiveGroupChange(f=>{if(!Oa(t)&&!f.isActive){a(!1);return}a(Oa(t))}),t.onDidVisibilityChange(f=>l(f.isVisible))];return()=>{for(const f of b)f.dispose()}},[t]);const p=u.useMemo(()=>c?s.ides.find(b=>b.id===c.routeId):void 0,[s.ides,c]),h=u.useMemo(()=>c?s.actionLogs.filter(b=>b.routeId===c.tabKey):[],[s.actionLogs,c]);if(!c)return r.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:r.jsx(Cu,{conversationsCount:0,isSplitMode:!1,isStandalone:s.isStandalone,hasRegisteredMachines:s.hasRegisteredMachines,onOpenNewSession:s.onOpenNewSession,suppressGuide:s.hasDetachedConversationPanels})});const m=!at(c)&&Tn(c)==="terminal";return r.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:r.jsx(Nu,{activeConv:c,clearToken:s.clearedTabs[c.tabKey]||0,isCliTerminal:m,ideEntry:p,terminalRef:n,handleModalButton:d.handleModalButton,handleRelaunch:d.handleRelaunch,handleSendChat:d.handleSendChat,handleForceSendChat:d.handleForceSendChat,isSendingChat:d.isSendingChat,handleFocusAgent:d.handleFocusAgent,isFocusingAgent:d.isFocusingAgent,actionLogs:h,userName:s.userName,scrollToBottomRequestNonce:((g=s.scrollToBottomRequest)==null?void 0:g.tabKey)===c.tabKey?s.scrollToBottomRequest.nonce:void 0,isInputActive:i,isVisible:o})})}function SA({params:e}){var c;const t=hl(),s=u.useMemo(()=>js([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=u.useMemo(()=>t.ides.find(d=>d.id===e.routeId),[t.ides,e.routeId]),i=(s==null?void 0:s.daemonId)||((c=s==null?void 0:s.routeId)==null?void 0:c.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:a,screenshotUsage:o,handleRemoteAction:l}=Kx({doId:i,targetSessionId:s?Tg(s):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(s==null?void 0:s.connectionState)||"new",viewMode:"remote"});return s?r.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:r.jsx(lg,{addLog:()=>{},connState:s.connectionState||"new",connScreenshot:a,screenshotUsage:o,transportType:s.transport,onAction:l})}):r.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 kA(){const e=hl();return r.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:r.jsx(Cu,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function jA(e){var x,S;yA(e);const t=hl(),s=u.useCallback(k=>{"button"in k&&k.button!==0||e.api.setActive()},[e.api]),n=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),i=n==null?void 0:n.sessionId,a=u.useCallback(k=>h1(k),[]),o=u.useCallback(()=>p1(i),[i]),l=u.useSyncExternalStore(a,o,o);if(e.params.kind==="remote"){const k=js([...t.conversationsByTabKey.values()],e.params.routeId),j=((x=e.api.group.activePanel)==null?void 0:x.id)===e.api.id,y=e.api.isGroupActive;return r.jsxs("div",{className:`adhdev-dockview-tab${j?" is-active":""}${y?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(k==null?void 0:k.tabKey)||"",onMouseDown:s,onTouchStart:s,children:[r.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:r.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),r.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[r.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),r.jsx("div",{className:"adhdev-dockview-tab-meta",children:k!=null&&k.machineName?r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"Live remote view"}),r.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),r.jsx("span",{className:"adhdev-dockview-tab-machine",children:k.machineName})]}):r.jsx("span",{children:"Live remote view"})})]})]})}const c=t.conversationsByTabKey.get(e.params.tabKey);if(!c)return r.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:r.jsx("div",{className:"adhdev-dockview-tab-copy",children:r.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const d=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,p=e.api.isGroupActive,h=ol(c,t.liveSessionInboxState,{isOpenConversation:d}),m=h.isReconnecting,g=h.isConnecting,b=h.isGenerating||l,f=h.isWaiting,v=h.unread,w=t.tabShortcuts[c.tabKey];return r.jsxs("div",{className:`adhdev-dockview-tab${d?" is-active":""}${p?" is-group-active":""}${m?" is-reconnecting":""}`,title:kt(c),"data-tab-key":e.params.tabKey,onMouseDown:s,onTouchStart:s,onContextMenu:k=>{var j;k.preventDefault(),s(k),t.openTabContextMenu({x:k.clientX,y:k.clientY,tabKey:c.tabKey,sourceDocument:((j=k.target)==null?void 0:j.ownerDocument)??document})},children:[v&&r.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),r.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:b?r.jsx("div",{className:"tab-spinner"}):f?r.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):m?r.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):g?r.jsx("div",{className:"tab-connecting-spinner"}):c.connectionState==="connected"?r.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):r.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),r.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[r.jsx("div",{className:"adhdev-dockview-tab-primary",children:kt(c)}),r.jsx("div",{className:"adhdev-dockview-tab-meta",children:m?r.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Cr(c)}):g?r.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Cr(c)}):r.jsx("span",{children:Cr(c)})})]}),w&&r.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:w,children:w})]})}function NA({visibleConversations:e,clearedTabs:t,ides:s,actionLogs:n,sendDaemonCommand:i,setActionLogs:a,isStandalone:o,hasRegisteredMachines:l,initialDataLoaded:c,userName:d,toggleHiddenTab:p,actionShortcuts:h,registerActionHandlers:m,onActiveTabChange:g,onOpenNewSession:b,onRequestScrollToBottom:f,requestedActiveTabKey:v,requestedRemoteIdeId:w,onRequestedActiveTabConsumed:x,scrollToBottomRequest:S,liveSessionInboxState:k,layoutProfile:j}){var pt,Ze,Lt;const{theme:y}=Gr(),{sendCommand:N}=jt(),_=u.useRef(null),C=u.useRef(null),D=u.useRef(null),T=u.useRef(!1),A=u.useRef(!1),P=u.useRef(!1),F=u.useRef(null),J=u.useRef([]),[R,I]=u.useState(null),[E,$]=u.useState(0),M=u.useRef(typeof window>"u"?{}:zC(j)),O=u.useMemo(()=>new Map(e.map(B=>[B.tabKey,B])),[e]),H=u.useMemo(()=>{const B=_.current;return B?B.groups.some(V=>{try{const ne=V.model.location.type;return ne!=="floating"&&ne!=="popout"?!1:V.panels.some(xe=>O.has(xe.id))}catch{return!1}}):!1},[O,E,e]),ae=u.useCallback(()=>{var B;(B=_.current)==null||B.focus()},[]),z=u.useCallback((B,V)=>{f==null||f(B,V)},[f]),X=u.useCallback(B=>{const V=document,ne=B.document;for(const se of V.querySelectorAll('link[rel="stylesheet"]')){const be=ne.createElement("link");be.rel="stylesheet",be.href=se.href,se.crossOrigin&&(be.crossOrigin=se.crossOrigin),ne.head.appendChild(be)}for(const se of V.querySelectorAll("style")){const be=ne.createElement("style");be.textContent=se.textContent,ne.head.appendChild(be)}const xe=[];for(const se of V.styleSheets)try{for(const be of se.cssRules)be instanceof CSSStyleRule&&(be.selectorText===":root"||be.selectorText==="html")&&xe.push(be.cssText)}catch{}if(xe.length>0){const se=ne.createElement("style");se.textContent=xe.join(`
|
|
63
|
+
`),ne.head.appendChild(se)}const ve=V.documentElement.getAttribute("data-theme");ve&&ne.documentElement.setAttribute("data-theme",ve),ne.documentElement.style.colorScheme=ve==="light"?"light":"dark",ne.body.className=V.body.className;const Ne=V.documentElement.getAttribute("style");Ne&&ne.documentElement.setAttribute("style",Ne);const ee=ne.getElementById("dv-popout-window");ee instanceof HTMLElement&&(ee.classList.add("adhdev-dockview"),pc(ee,y))},[y]),te=u.useCallback(()=>{var V;const B=_.current;if(B)for(const ne of B.groups)try{const xe=(V=ne.element)==null?void 0:V.ownerDocument;if(!xe||xe===document)continue;const ve=xe.getElementById("dv-popout-window");ve instanceof HTMLElement&&(ve.classList.add("adhdev-dockview"),pc(ve,y));const Ne=document.documentElement.getAttribute("data-theme");Ne&&xe.documentElement.setAttribute("data-theme",Ne),xe.documentElement.style.colorScheme=Ne==="light"?"light":"dark",xe.body.className=document.body.className;const ee=document.documentElement.getAttribute("style");ee?xe.documentElement.setAttribute("style",ee):xe.documentElement.removeAttribute("style")}catch{}},[y]),he=u.useCallback(B=>{const V=_.current;if(!V)return;const ne=V.getPanel(B);ne&&V.addPopoutGroup(ne,{popoutUrl:"/popout.html",onDidOpen:({window:xe})=>{X(xe),Se();const ve=O.get(B);xe.document.title=ve?`${kt(ve)} — ADHDev`:"ADHDev — Popout"}})},[O,X]),ke=u.useCallback(B=>{const V=_.current,ne=V==null?void 0:V.getPanel(B);if(!V||!ne)return;const xe=V.groups.filter(ve=>{var Ne;try{return((Ne=ve.element)==null?void 0:Ne.ownerDocument)===document}catch{return!0}});xe.length>0?ne.api.moveTo({group:xe[0],position:"center"}):ne.api.moveTo({position:"center"}),ne.api.setActive()},[]),Q=u.useCallback(B=>{var xe;const V=_.current;if(!V)return!1;const ne=V.getPanel(B);if(!ne)return!1;try{return((xe=ne.group.element)==null?void 0:xe.ownerDocument)!==document}catch{return!1}},[]),q=u.useCallback(B=>{Q(B)&&ke(B),p(B)},[Q,ke,p]),me=u.useCallback(B=>{const V=_.current,ne=V==null?void 0:V.getPanel(B);!V||!ne||V.addFloatingGroup(ne,{width:600,height:500})},[]),we=u.useCallback(B=>{var ne;const V=(ne=_.current)==null?void 0:ne.getPanel(B);if(!V)return!1;try{return V.group.model.location.type==="floating"}catch{return!1}},[]),ye=u.useCallback(()=>{var V,ne;const B=(ne=(V=_.current)==null?void 0:V.activePanel)==null?void 0:ne.id;return!B||ys(B)?null:O.has(B)?B:null},[O]),Te=u.useCallback(B=>{const V=_.current,ne=V==null?void 0:V.getPanel(B);if(!V||!ne)return;const xe=V.groups.filter(ve=>{try{return ve.model.location.type==="grid"}catch{return!0}});xe.length>0?ne.api.moveTo({group:xe[0],position:"center"}):ne.api.moveTo({position:"center"}),ne.api.setActive()},[]),le=u.useCallback(()=>{var Ne;const B=_.current;if(!B)return;const ne=B.groups.filter(ee=>{var se;try{return((se=ee.element)==null?void 0:se.ownerDocument)===document&&ee.model.location.type==="grid"}catch{return!1}})[0]||null,xe=[...B.panels];for(const ee of xe){const se=(Ne=ee.group.element)==null?void 0:Ne.ownerDocument,be=ee.group.model.location.type;se===document&&be==="grid"||(ne&&ne.id!==ee.group.id?ee.api.moveTo({group:ne,position:"center"}):ee.api.moveTo({position:"center"}))}const ve=B.activePanel;ve&&(ve.group.model.openPanel(ve),ve.api.setActive()),uc(document)},[]),Se=u.useCallback(()=>{var V,ne;const B=_.current;if(B)for(const xe of B.groups){const ve=(V=xe.element)==null?void 0:V.ownerDocument;if(!ve||ve===document)continue;const Ne=ve.getElementById("dv-popout-window");if(!(Ne instanceof HTMLElement))continue;let ee=null,se=ve.title||"ADHDev",be="Popout workspace";const Me=xe.activePanel;if(Me)if(ee=Me.id,ys(Me.id)){const Le=((ne=Me.params)==null?void 0:ne.routeId)||Me.id.slice(7),Ye=js([...O.values()],Le);se=Vg(Ye),be=Ye!=null&&Ye.machineName?`Remote view · ${Ye.machineName}`:"Remote view"}else{const Le=O.get(Me.id);se=Le?kt(Le):Me.title||Me.id,be=Le?Cr(Le):"Dockview panel"}ve.title=`${se} — ADHDev`;const $e=Array.from(ve.querySelectorAll("#adhdev-popout-header"));for(const Le of $e)Le.remove();const Re=ve.createElement("div");Re.id="adhdev-popout-header",ve.body.appendChild(Re),Re.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(";")),Re.innerHTML=`
|
|
64
|
+
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
65
|
+
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
66
|
+
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${om(se)}</div>
|
|
67
|
+
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${om(be)}</div>
|
|
68
|
+
</div>
|
|
69
|
+
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
70
|
+
<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>
|
|
71
|
+
<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>
|
|
72
|
+
</div>
|
|
73
|
+
`,Ne.style.top="52px",Ne.style.height="calc(100% - 52px)";const Oe=Re.querySelector("[data-adhdev-popout-focus]");Oe&&(Oe.onclick=()=>{window.focus()});const ze=Re.querySelector("[data-adhdev-popout-dock]");ze&&(ze.disabled=!ee,ze.style.opacity=ee?"1":"0.5",ze.style.cursor=ee?"pointer":"default",ze.onclick=()=>{var Le;ee&&ke(ee),(Le=ve.defaultView)==null||Le.focus()})}},[O,ke]),ge=u.useCallback(B=>{var xe;const V=_.current,ne=V==null?void 0:V.getPanel(B);if(!(!V||!ne)){ne.group.model.openPanel(ne),ne.api.setActive(),z(B,"dockview-shortcut");try{const ve=ne.group.model.location;ve.type==="popout"?ve.getWindow().focus():uc((xe=ne.group.element)==null?void 0:xe.ownerDocument)}catch{}}},[z]),G=u.useCallback(B=>{const V=_.current,ne=V==null?void 0:V.activePanel,xe=(V==null?void 0:V.activeGroup)||(ne==null?void 0:ne.group);if(!V||!ne||!xe)return;const ve=xe.panels||[];if(ve.length<=1)return;const Ne=ve.findIndex(be=>be.id===ne.id);if(Ne<0)return;const ee=(Ne+B+ve.length)%ve.length,se=ve[ee];se&&(se.group.model.openPanel(se),se.api.setActive(),ys(se.id)||z(se.id,"dockview-shortcut"))},[z]),W=u.useCallback(B=>{var Oe;const V=_.current,ne=(V==null?void 0:V.activeGroup)||((Oe=V==null?void 0:V.activePanel)==null?void 0:Oe.group);if(!V||!ne)return;const xe=V.groups||[],ve=xe.find(ze=>ze.id===ne.id);if(!ve)return;const Ne=ve.element.getBoundingClientRect(),ee=Ne.left+Ne.width/2,se=Ne.top+Ne.height/2,be=(ze,Le,Ye,rt)=>Math.max(0,Math.min(Le,rt)-Math.max(ze,Ye)),Me=ze=>{const Le=ze.element.getBoundingClientRect(),Ye=Le.left+Le.width/2,rt=Le.top+Le.height/2;let Ct=0,Ut=0,Rt=0,It=!1;if(B==="left"?(It=Ye<ee,Ct=Math.max(0,Ne.left-Le.right),Ut=Math.abs(rt-se),Rt=be(Ne.top,Ne.bottom,Le.top,Le.bottom)):B==="right"?(It=Ye>ee,Ct=Math.max(0,Le.left-Ne.right),Ut=Math.abs(rt-se),Rt=be(Ne.top,Ne.bottom,Le.top,Le.bottom)):B==="above"?(It=rt<se,Ct=Math.max(0,Ne.top-Le.bottom),Ut=Math.abs(Ye-ee),Rt=be(Ne.left,Ne.right,Le.left,Le.right)):(It=rt>se,Ct=Math.max(0,Le.top-Ne.bottom),Ut=Math.abs(Ye-ee),Rt=be(Ne.left,Ne.right,Le.left,Le.right)),!It)return Number.POSITIVE_INFINITY;const Ge=Rt>0?0:120;return Ct*3+Ut+Ge};let $e=null,Re=Number.POSITIVE_INFINITY;for(const ze of xe){if(ze.id===ve.id)continue;const Le=Me(ze);Number.isFinite(Le)&&(Le>=Re||(Re=Le,$e=ze))}return $e||void 0},[]),Z=u.useCallback(B=>{var xe;const V=W(B);if(!V)return;const ne=V.activePanel||V.panels[0];ne&&(V.model.openPanel(ne),ne.api.setActive(),ys(ne.id)||z(ne.id,"dockview-focus"),uc((xe=V.element)==null?void 0:xe.ownerDocument))},[W,z]),oe=u.useCallback((B,V)=>{const ne=_.current,xe=ne==null?void 0:ne.activePanel,ve=(ne==null?void 0:ne.activeGroup)||(xe==null?void 0:xe.group);if(!ne||!xe||!ve)return;let Ne=W(B);!Ne&&(V!=null&&V.createGroupIfMissing)&&(Ne=ne.addGroup({referenceGroup:ve,direction:B})),Ne&&(xe.api.moveTo({group:Ne,position:"center"}),xe.group.model.openPanel(xe),xe.api.setActive(),ys(xe.id)||z(xe.id,V!=null&&V.createGroupIfMissing?"dockview-split":"dockview-move"))},[W,z]),{isMac:ue,tabShortcuts:ce,shortcutListening:L,setShortcutListening:de,saveShortcuts:U}=zx({sortedTabKeys:e.map(B=>B.tabKey),onFocus:ae,onSelectTab:ge}),ie=u.useCallback(()=>{var ne;const B=_.current;if(!B)return;const V=B.activePanel;if(V){if(ys(V.id)){const xe=((ne=V.params)==null?void 0:ne.routeId)||V.id.slice(7),ve=js(e,xe);ve!=null&&ve.tabKey&&de(ve.tabKey);return}O.has(V.id)&&de(V.id)}},[O,ge,de,e]),Y=u.useCallback(B=>{const V=[];return B.metaKey&&V.push(ue?"⌘":"Meta"),B.ctrlKey&&V.push("Ctrl"),B.altKey&&V.push(ue?"⌥":"Alt"),B.shiftKey&&B.key.length!==1&&V.push(ue?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(B.key)?null:(V.push(Vx(B.key)),V.join("+"))},[ue]),Ae=u.useCallback(B=>{var V,ne;switch(B){case"splitActiveTabRight":oe("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":oe("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const xe=ye();xe&&me(xe);return}case"popoutActiveTab":{const xe=ye();xe&&he(xe);return}case"dockActiveTab":{const xe=ye();if(!xe)return;Q(xe)?ke(xe):we(xe)&&Te(xe);return}case"focusLeftPane":Z("left");return;case"focusRightPane":Z("right");return;case"focusUpPane":Z("above");return;case"focusDownPane":Z("below");return;case"moveActiveTabToLeftPane":oe("left");return;case"moveActiveTabToRightPane":oe("right");return;case"moveActiveTabToUpPane":oe("above");return;case"moveActiveTabToDownPane":oe("below");return;case"selectPreviousGroupTab":G(-1);return;case"selectNextGroupTab":G(1);return;case"setActiveTabShortcut":ie();return;case"hideCurrentTab":{const xe=(ne=(V=_.current)==null?void 0:V.activePanel)==null?void 0:ne.id;xe&&!ys(xe)&&q(xe);return}default:return}},[G,Te,Z,me,ye,q,we,Q,ke,oe,he,ie]);u.useEffect(()=>{if(!R)return;const B=R.sourceDocument,V=B.defaultView??window,ne=xe=>{const ve=B.querySelector("[data-dockview-tab-context-menu]");ve&&ve.contains(xe.target)||I(null)};return V.addEventListener("mousedown",ne,!0),V!==window&&window.addEventListener("mousedown",()=>I(null),!0),()=>{V.removeEventListener("mousedown",ne,!0),V!==window&&window.removeEventListener("mousedown",()=>I(null),!0)}},[R]);const Ce=u.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:O,hasDetachedConversationPanels:H,ides:s,isStandalone:o,hasRegisteredMachines:l,onOpenNewSession:b,liveSessionInboxState:k,sendDaemonCommand:i,setActionLogs:a,toggleHiddenTab:q,userName:d,scrollToBottomRequest:S,tabShortcuts:ce,openTabContextMenu:({x:B,y:V,tabKey:ne,sourceDocument:xe})=>I({x:B,y:V,tabKey:ne,sourceDocument:xe??document}),popoutTab:he,moveTabBackToMain:ke,isTabInPopout:Q,floatTab:me,isTabFloating:we}),[n,t,O,H,s,o,l,b,k,i,a,q,d,S,ce,he,ke,Q,me,we]),je=R?pA({isTabInPopout:Q(R.tabKey),isTabFloating:we(R.tabKey),tabShortcut:ce[R.tabKey],actionShortcuts:h}):[],qe=u.useCallback(B=>{var xe;const V=_.current;if((((xe=V==null?void 0:V.activePanel)==null?void 0:xe.id)??null)===B.id){B.group.model.openPanel(B);return}B.group.model.openPanel(B),B.api.setActive()},[]),it=u.useCallback((B,V="requested-tab")=>{if(!B)return!1;const ne=_.current;if(!ne)return!1;const xe=ne.getPanel(B);return xe?(qe(xe),z(B,V),x==null||x(),!0):!1},[qe,x,z]),lt=u.useCallback(()=>{if(P.current)return!1;const B=it(F.current,"stored-layout-restore");return B&&(P.current=!0),B},[it]),ft=u.useCallback(()=>{var V;const B=_.current;B&&HC(j,{activeTabId:((V=B.activePanel)==null?void 0:V.id)??null,layout:B.toJSON()})},[j]),ct=u.useCallback(()=>{KC(j,M.current)},[j]),_t=u.useCallback(B=>{var xe,ve,Ne,ee;const V=_.current;if(!V)return{kind:"grid"};const ne=V.toJSON();for(const se of ne.floatingGroups||[])if((ve=(xe=se.data)==null?void 0:xe.views)!=null&&ve.includes(B)&&se.position)return{kind:"floating",position:se.position};for(const se of ne.popoutGroups||[])if((ee=(Ne=se.data)==null?void 0:Ne.views)!=null&&ee.includes(B))return{kind:"popout",position:se.position,popoutUrl:se.url};return{kind:"grid"}},[]),Mt=u.useCallback(B=>{const V=_.current;if(!V)return;const ne=V.getPanel(B),xe=M.current[B];if(!ne||!xe||xe.kind==="grid")return;if(ne.group.model.location.type===xe.kind){delete M.current[B],ct();return}if(xe.kind==="floating"){V.addFloatingGroup(ne,{x:xe.position.left??24,y:xe.position.top??24,width:xe.position.width,height:xe.position.height}),delete M.current[B],ct();return}delete M.current[B],ct()},[ct]);u.useEffect(()=>(m==null||m({setShortcutForActiveTab:ie,restoreHiddenTabToSavedLocation:Mt,activateConversationTab:ge,resetAllPanelsToMain:le,activatePreviousTabInGroup:()=>G(-1),activateNextTabInGroup:()=>G(1),floatActiveTab:()=>{const B=ye();B&&me(B)},popoutActiveTab:()=>{const B=ye();B&&he(B)},dockActiveTab:()=>{const B=ye();B&&(Q(B)?ke(B):we(B)&&Te(B))},splitActiveTabRight:()=>oe("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>oe("below",{createGroupIfMissing:!0}),focusLeftPane:()=>Z("left"),focusRightPane:()=>Z("right"),focusUpPane:()=>Z("above"),focusDownPane:()=>Z("below"),moveActiveTabToLeftPane:()=>oe("left"),moveActiveTabToRightPane:()=>oe("right"),moveActiveTabToUpPane:()=>oe("above"),moveActiveTabToDownPane:()=>oe("below")}),()=>m==null?void 0:m(null)),[G,Te,me,Z,ye,we,Q,oe,ke,he,m,le,Mt,ge,ie]),u.useEffect(()=>()=>{var B;(B=D.current)==null||B.call(D),D.current=null},[]);const Et=u.useCallback(B=>{var ne,xe;_.current=B.api,(ne=D.current)==null||ne.call(D),D.current=null;const V=UC(j);if(F.current=(V==null?void 0:V.activeTabId)??null,V!=null&&V.layout&&B.api.fromJSON(V.layout,{reuseExistingPanels:!1}),A.current=rm({hasStoredLayout:!!(V!=null&&V.layout),initialDataLoaded:c,visibleConversationCount:e.length,ides:s}),A.current||(cm(B.api,e),dm(B.api,e,w)),B.api.totalPanels===0&&e.length>0){const ve=vA(B.api,e,v);if(ve){const Ne=B.api.getPanel(ve);Ne&&qe(Ne)}}else!A.current&&!it(v)&<();if(T.current=!0,B.api.onDidActivePanelChange(ve=>{var ee;if(F.current=(ve==null?void 0:ve.id)??null,P.current=!0,Se(),ve&&ys(ve.id)){const se=((ee=ve.params)==null?void 0:ee.routeId)||ve.id.slice(7),be=js(e,se);g((be==null?void 0:be.tabKey)??null),ft();return}if(g((ve==null?void 0:ve.id)??null),ft(),!ve)return;const Ne=O.get(ve.id);(Ne==null?void 0:Ne.streamSource)==="agent-stream"&&Ne.agentType&&N(Ne.routeId,Mg(),{agentType:Ne.agentType,...Ne.sessionId&&{targetSessionId:Ne.sessionId}}).catch(()=>{})}),B.api.onDidLayoutChange(()=>{ft(),Se(),$(ve=>ve+1)}),gA()){const ve=Re=>({clientX:Re.clientX,clientY:Re.clientY}),Ne=Re=>{const Oe=Re==null?void 0:Re.getBoundingClientRect();return Oe?{left:Oe.left,right:Oe.right,top:Oe.top,bottom:Oe.bottom}:null},ee=Re=>{var ze;const Oe=(ze=C.current)==null?void 0:ze.getBoundingClientRect();return Oe?Re.clientX<Oe.left||Re.clientX>Oe.right||Re.clientY<Oe.top||Re.clientY>Oe.bottom:!1},se=fA({detachDelayMs:Yx,onDetach:({panelId:Re,clientX:Oe,clientY:ze})=>{var Rt,It;const Le=B.api.getPanel(Re);if(!Le)return;try{if(Le.group.model.location.type!=="grid")return}catch{return}const Ye=(Rt=C.current)==null?void 0:Rt.getBoundingClientRect(),rt=(It=Le.group.element)==null?void 0:It.getBoundingClientRect(),Ct=Math.round(Math.min(Math.max((rt==null?void 0:rt.width)??600,360),720)),Ut=Math.round(Math.min(Math.max((rt==null?void 0:rt.height)??500,260),640));B.api.addFloatingGroup(Le,{x:Ye?Math.max(0,Oe-Ye.left-32):void 0,y:Ye?Math.max(0,ze-Ye.top-18):void 0,width:Ct,height:Ut}),Le.api.setActive(),ft(),Se(),$(Ge=>Ge+1)}}),be=[B.api.onWillDragPanel(Re=>{if(!(Re.nativeEvent.defaultPrevented||Re.nativeEvent.shiftKey)){try{if(Re.panel.group.model.location.type!=="grid")return}catch{return}se.startDrag({panelId:Re.panel.id,selfPanelBounds:Ne(Re.panel.group.element),...ve(Re.nativeEvent)})}}),B.api.onWillShowOverlay(Re=>{if(se.hasDetached()){Re.preventDefault();return}se.markDockTarget(ve(Re.nativeEvent))}),B.api.onWillDrop(Re=>{if(se.hasDetached()){Re.preventDefault(),se.endDrag();return}se.markDockTarget(ve(Re.nativeEvent))}),B.api.onDidDrop(()=>se.endDrag()),B.api.onUnhandledDragOverEvent(Re=>{se.isDragging()&&se.markSelfPanel(ve(Re.nativeEvent))})],Me=Re=>{if(!se.isDragging())return;const Oe=ve(Re);ee(Oe)&&se.markNonSelfPanel(Oe)},$e=()=>se.endDrag();window.addEventListener("dragover",Me,!0),window.addEventListener("drop",$e,!0),window.addEventListener("dragend",$e,!0),D.current=()=>{se.dispose();for(const Re of be)Re.dispose();window.removeEventListener("dragover",Me,!0),window.removeEventListener("drop",$e,!0),window.removeEventListener("dragend",$e,!0)}}B.api.onDidAddGroup(ve=>{requestAnimationFrame(()=>{var Ne,ee;try{const se=(Ne=ve.element)==null?void 0:Ne.ownerDocument;if(!se||se===document)return;(ee=se.getElementById("dv-popout-window"))==null||ee.classList.add("adhdev-dockview");const be=document.documentElement.getAttribute("data-theme");be&&se.documentElement.setAttribute("data-theme",be),se.body.className=document.body.className;const Me=document.documentElement.getAttribute("style");Me&&se.documentElement.setAttribute("style",Me)}catch{}Se(),$(se=>se+1)})}),g(((xe=B.api.activePanel)==null?void 0:xe.id)??null)},[qe,it,O,s,c,j,g,ft,v,w,N,Se,e]);u.useLayoutEffect(()=>{const B=_.current;if(!B||!T.current||A.current&&rm({hasStoredLayout:!0,initialDataLoaded:c,visibleConversationCount:e.length,ides:s}))return;A.current&&(A.current=!1);const V=J.current,ne=new Set(V),xe=e.map($e=>$e.tabKey),ve=new Set(xe),Ne=hA({previousVisibleConversationCount:V.length,visibleConversationCount:e.length,ides:s});let ee=!1;for(const $e of V)ve.has($e)||Ne||(M.current[$e]=_t($e),ee=!0);ee&&ct(),Ne||(cm(B,e),dm(B,e,w));const se=xe.filter($e=>!ne.has($e));let be=!1;for(const $e of se){const Re=B.getPanel($e),Oe=M.current[$e];if(!Re||!Oe||Oe.kind==="grid")continue;if(Re.group.model.location.type===Oe.kind){delete M.current[$e],be=!0;continue}if(Oe.kind==="floating"){B.addFloatingGroup(Re,{x:Oe.position.left??24,y:Oe.position.top??24,width:Oe.position.width,height:Oe.position.height}),delete M.current[$e],be=!0;continue}}if(be&&ct(),J.current=xe,v&&it(v))return;!B.activePanel&&B.panels[0]&&qe(B.panels[0]),!!(B.activePanel&&B.getPanel(B.activePanel.id))||lt()},[qe,it,lt,s,c,ct,_t,v,w,e]),u.useEffect(()=>{T.current&&it(v)},[it,v]),u.useEffect(()=>{const B=ne=>{const xe=ne.target;if(!xe)return;const ve=xe.querySelector("[data-tab-key]")||xe.closest("[data-tab-key]");if(ve){const Ne=ve.getAttribute("data-tab-key");if(Ne&&ne.dataTransfer){const ee=xe.closest(".dv-tab")||ve.closest(".dv-tab")||ve;ne.dataTransfer.effectAllowed="move",ne.dataTransfer.setData("text/tab-key",Ne),ee instanceof HTMLElement&&ne.dataTransfer.setDragImage(ee,Math.max(12,Math.round(ee.clientWidth/2)),Math.max(10,Math.round(ee.clientHeight/2)))}}};window.addEventListener("dragstart",B);const V=lm(_.current);for(const ne of V)ne.addEventListener("dragstart",B);return()=>{window.removeEventListener("dragstart",B);for(const ne of V)ne.removeEventListener("dragstart",B)}},[E]),u.useEffect(()=>{var V;const B=(V=C.current)==null?void 0:V.querySelector(".adhdev-dockview");B instanceof HTMLElement&&pc(B,y),te(),Se()},[Se,te,y]),u.useEffect(()=>{Se()},[Se]),u.useEffect(()=>{const B=V=>{if(V.defaultPrevented||L)return;const ne=Y(V);if(!ne)return;const xe=V.metaKey||V.ctrlKey||V.altKey;md(V.target)&&!xe||Po(ue).setActiveTabShortcut!==ne||(V.preventDefault(),V.stopPropagation(),ie())};return window.addEventListener("keydown",B,!0),()=>window.removeEventListener("keydown",B,!0)},[Y,ue,L,ie]),u.useEffect(()=>{const B=C.current;if(!B)return;const V=ne=>{var se,be;if(!ne.isTrusted)return;const xe=(be=(se=ne.target)==null?void 0:se.closest)==null?void 0:be.call(se,".dv-scrollable");if(!xe)return;ne.preventDefault(),ne.stopPropagation();const ve=Math.abs(ne.deltaX),Ne=Math.abs(ne.deltaY),ee=ve>Ne?ne.deltaX:ne.deltaY;xe.dispatchEvent(new WheelEvent("wheel",{deltaY:ee,deltaMode:ne.deltaMode,bubbles:!1,cancelable:!0}))};return B.addEventListener("wheel",V,{passive:!1,capture:!0}),()=>B.removeEventListener("wheel",V,{capture:!0})},[]),u.useEffect(()=>{const B=lm(_.current);if(B.length===0)return;const V=B.map(ne=>{let xe=[],ve=null;const Ne=()=>{ve!=null&&ne.clearTimeout(ve),ve=null,xe=[]},ee=()=>{ve!=null&&ne.clearTimeout(ve),ve=ne.setTimeout(()=>{ve=null,xe=[]},1200)},se=Me=>{if(!Me.ctrlKey&&!Me.metaKey&&!Me.altKey)return;const $e=Y(Me);if(!$e)return;const Re=Hx();for(const[Oe,ze]of Object.entries(Re))if(e.some(Le=>Le.tabKey===Oe)&&ze===$e){Me.preventDefault(),ge(Oe);return}},be=Me=>{if(Me.defaultPrevented||L)return;const $e=Y(Me);if(!$e)return;const Re=Me.metaKey||Me.ctrlKey||Me.altKey;if(md(Me.target))return;const Oe=Po(ue),ze=Object.entries(Oe).filter(([Ge,gs])=>!!gs&&(Ge==="splitActiveTabRight"||Ge==="splitActiveTabDown"||Ge==="floatActiveTab"||Ge==="popoutActiveTab"||Ge==="dockActiveTab"||Ge==="focusLeftPane"||Ge==="focusRightPane"||Ge==="focusUpPane"||Ge==="focusDownPane"||Ge==="moveActiveTabToLeftPane"||Ge==="moveActiveTabToRightPane"||Ge==="moveActiveTabToUpPane"||Ge==="moveActiveTabToDownPane"||Ge==="selectPreviousGroupTab"||Ge==="selectNextGroupTab"||Ge==="setActiveTabShortcut"||Ge==="hideCurrentTab")),Le=Re?[$e]:[...xe.slice(-1),$e].slice(-2),Ye=Le.join(" "),rt=Le[Le.length-1],Ct=ze.find(([,Ge])=>Ge===Ye);if(Ct){Me.preventDefault(),Ne(),Ae(Ct[0]);return}if(ze.some(([,Ge])=>Ge.startsWith(`${Ye} `))){Me.preventDefault(),xe=Le,ee();return}const Rt=ze.find(([,Ge])=>Ge===rt);if(Rt){Me.preventDefault(),Ne(),Ae(Rt[0]);return}if(ze.some(([,Ge])=>Ge.startsWith(`${rt} `))){Me.preventDefault(),xe=[rt],ee();return}Ne()};return ne.addEventListener("keydown",se),ne.addEventListener("keydown",be),()=>{Ne(),ne.removeEventListener("keydown",se),ne.removeEventListener("keydown",be)}});return()=>{for(const ne of V)ne()}},[Y,ue,E,ge,L,Ae,e]);const De=y==="light"?Hc:zc,He=((Lt=(Ze=(pt=_.current)==null?void 0:pt.activePanel)==null?void 0:Ze.group.element)==null?void 0:Lt.ownerDocument)??document;return r.jsxs(Qx.Provider,{value:Ce,children:[r.jsx("div",{ref:C,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:r.jsx(yw,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:wA,remote:SA},defaultTabComponent:jA,watermarkComponent:kA,onReady:Et,singleTabMode:"default",tabAnimation:"smooth",theme:De,popoutUrl:"/popout.html"})}),R&&Si.createPortal(r.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:R.x,top:R.y},children:je.map(B=>{if(B.type==="separator")return r.jsx("div",{className:"border-t border-border-subtle my-1"},B.id);let V=r.jsx(qS,{size:13,className:"shrink-0 opacity-70"}),ne=()=>{};switch(B.id){case"dockInWindow":case"dockBackToGrid":V=r.jsx(XS,{size:13,className:"shrink-0 opacity-70"}),ne=()=>{Te(R.tabKey),I(null)};break;case"moveBackToMain":V=r.jsx(GS,{size:13,className:"shrink-0 opacity-70"}),ne=()=>{ke(R.tabKey),I(null)};break;case"floatAsPanel":V=r.jsx(VS,{size:13,className:"shrink-0 opacity-70"}),ne=()=>{me(R.tabKey),I(null)};break;case"openInNewWindow":V=r.jsx(KS,{size:13,className:"shrink-0 opacity-70"}),ne=()=>{he(R.tabKey),I(null)};break;case"setShortcut":ne=xe=>{xe.stopPropagation(),de(R.tabKey),I(null)};break;case"removeShortcut":V=r.jsx(Ot,{size:13,className:"shrink-0 opacity-70"}),ne=()=>{const xe={...ce};delete xe[R.tabKey],U(xe),I(null)};break;case"hideTab":V=r.jsx(qd,{size:13,className:"shrink-0 opacity-70"}),ne=()=>{q(R.tabKey),I(null)};break}return r.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 ${B.tone==="muted"?"text-text-muted":""}`,onMouseDown:bA,onClick:ne,children:[V,r.jsx("span",{className:"flex-1 min-w-0",children:B.label}),B.shortcut?r.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:B.shortcut}):null]},B.id)})}),R.sourceDocument.body),L&&Si.createPortal(r.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>de(null),children:r.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:B=>B.stopPropagation(),children:[r.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),r.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",ue?"⌘+1":"Ctrl+1",", ",ue?"⌥+A":"Alt+A",")"]}),r.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),r.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),He.body)]})}const Jx="adhdev-recent-launch-args-v1",_A=8;function CA(e){return String(e||"").trim().replace(/\s+/g," ")}function Zx(e,t){return`${e.trim()}::${t.trim()}`}function eb(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Jx)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function IA(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Jx,JSON.stringify(e))}catch{}}function AA(e,t){var a;const s=String(e||"").trim(),n=String(t||"").trim();return!s||!n?[]:((a=eb().byKey[Zx(s,n)])==null?void 0:a.items)||[]}function TA(e,t,s){var p;const n=String(e||"").trim(),i=String(t||"").trim(),a=CA(s);if(!n||!i||!a)return;const o=eb(),l=Zx(n,i),c=((p=o.byKey[l])==null?void 0:p.items)||[],d=[a,...c.filter(h=>h!==a)].slice(0,_A);o.byKey[l]={items:d},IA(o)}function MA(e){return!e.hasLoadedInitialResults&&!e.isLoading}function ao({title:e,description:t,action:s,children:n,className:i="",contentClassName:a=""}){return r.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${i}`.trim(),children:[r.jsxs("div",{className:"flex items-start justify-between gap-3",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),t&&r.jsx("div",{className:"text-xs text-text-secondary mt-1",children:t})]}),s?r.jsx("div",{className:"flex items-center gap-2",children:s}):null]}),n?r.jsx("div",{className:t||s?`mt-3 ${a}`.trim():a,children:n}):null]})}function EA({savedSessionsLoading:e,savedSessionsLoaded:t,savedSessionsCount:s=0}){return e?"Refreshing saved history…":t?s>0?`${s} saved ${s===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 RA({busy:e,savedSessionsLoading:t,savedSessionsError:s,savedSessionsLoaded:n,savedSessionsCount:i=0,selectedSession:a,onRefresh:o,onOpenHistory:l,onClearSelection:c}){const d=a?Ox(a):null,p=EA({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:i});return r.jsxs(ao,{title:"Saved history",description:mu(),action:r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:o,children:t?"Loading…":"Refresh"}),r.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:l,children:l_()})]}),children:[d?r.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:r.jsxs("div",{className:"flex items-start justify-between gap-2",children:[r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),r.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:d.title}),r.jsx("div",{className:"font-mono break-all mt-0.5",children:d.providerSessionId}),r.jsx("div",{className:"mt-1",children:d.metaLine}),d.updatedLabel&&r.jsx("div",{className:"mt-1 text-text-secondary",children:d.updatedLabel}),d.preview&&r.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:d.preview})]}),r.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:c,disabled:e,children:"Clear"})]})}):r.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:p}),s&&r.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:s})]})}function tb({setup:e,providerName:t,className:s=""}){return e?r.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${s}`,children:[r.jsxs("div",{className:"font-semibold",children:["Manual MCP setup required",t?` for ${t}`:""]}),e.instructions&&r.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),r.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-text-muted",children:[e.serverName&&r.jsxs("span",{children:["Server: ",r.jsx("code",{children:e.serverName})]}),e.configFormat&&r.jsxs("span",{children:["Format: ",r.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&r.jsxs("span",{children:["Config path: ",r.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&r.jsx("span",{children:"Start a fresh CLI session after editing config."})]}),e.template&&r.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 PA({workspaceMode:e,activeKind:t,cliEnabled:s,ideEnabled:n,acpEnabled:i,busy:a,onSelect:o}){return e==="mesh"?null:r.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[r.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),r.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:s},{id:"ide",label:"Workspace",enabled:n},{id:"acp",label:"ACP",enabled:i}].map(l=>r.jsx("button",{type:"button",className:`btn btn-sm ${t===l.id?"btn-primary":"btn-secondary"}`,onClick:()=>o(l.id),disabled:!l.enabled||a,children:l.label},l.id))})]})}function hc(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(i=>kn(i,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(i=>kn(i,"acp"))?"acp":null}function Fa(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function DA({machines:e,ides:t,onClose:s,onBrowseDirectory:n,onSaveWorkspace:i,onLaunchIde:a,onLaunchProvider:o,onListMeshes:l,onLaunchMeshCoordinator:c,onListSavedSessions:d}){var Ge,gs;const p=Xi(),h=u.useMemo(()=>[...e].sort(Zd),[e]),[m,g]=u.useState(((Ge=h[0])==null?void 0:Ge.id)||""),b=u.useMemo(()=>h.find(pe=>pe.id===m)||h[0],[m,h]),f=u.useMemo(()=>((b==null?void 0:b.workspaces)||[]).map(pe=>({id:pe.id,path:pe.path,label:pe.label})),[b]),v=(b==null?void 0:b.defaultWorkspaceId)||null,[w,x]=u.useState("workspace"),[S,k]=u.useState(""),[j,y]=u.useState(""),[N,_]=u.useState([]),[C,D]=u.useState(""),[T,A]=u.useState(!1),[P,F]=u.useState(null),[J,R]=u.useState(""),[I,E]=u.useState(hc(h[0])),[$,M]=u.useState(""),[O,H]=u.useState(""),[ae,z]=u.useState([]),[X,te]=u.useState(""),[he,ke]=u.useState([]),[Q,q]=u.useState(!1),[me,we]=u.useState(!1),[ye,Te]=u.useState(""),[le,Se]=u.useState(!1),[ge,G]=u.useState(()=>Jt()),[W,Z]=u.useState(null),[oe,ue]=u.useState(!1),[ce,L]=u.useState(""),[de,U]=u.useState(null),[ie,Y]=u.useState(!1),[Ae,Ce]=u.useState(""),[je,qe]=u.useState([]),[it,lt]=u.useState(!1),[ft,ct]=u.useState(""),[_t,Mt]=u.useState(!1),Et=u.useRef(null),De=u.useRef(0);u.useEffect(()=>{var pe;!m&&((pe=h[0])!=null&&pe.id)&&g(h[0].id)},[m,h]),u.useEffect(()=>{!b||!(!b.workspaces||!b.availableProviders||!b.detectedIdes||!b.recentLaunches)||p(b.id,{minFreshMs:3e4}).catch(()=>{})},[p,b]);const He=u.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(pe=>kn(pe,"cli")),[b]),pt=u.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(pe=>kn(pe,"acp")),[b]),Ze=u.useMemo(()=>((b==null?void 0:b.detectedIdes)||[]).map(pe=>({id:pe.type,label:pe.name||pe.type,meta:pe.running?"Detected locally":"Available to open"})),[b]),Lt=u.useMemo(()=>I==="cli"?He.map(pe=>({id:pe.type,label:pe.displayName||pe.type,meta:"CLI provider"})):I==="acp"?pt.map(pe=>({id:pe.type,label:pe.displayName||pe.type,meta:"ACP provider"})):Ze,[pt,I,He,Ze]),B=u.useMemo(()=>N.find(pe=>pe.id===C)||null,[N,C]),V=u.useMemo(()=>He.find(pe=>pe.type===$)||null,[He,$]),ne=u.useMemo(()=>Ex(V==null?void 0:V.meshCoordinator,{meshId:(B==null?void 0:B.id)||"",workspace:(B==null?void 0:B.workspace)||""}),[V,B]),xe=de||ne,ve=u.useCallback(async pe=>{A(!0),R("");try{const Be=await l(pe);_(Be),D(fe=>{var Fe;return Be.some(Gt=>Gt.id===fe)?fe:((Fe=Be[0])==null?void 0:Fe.id)||""}),F(pe)}catch(Be){_([]),D(""),F(pe),R(Be instanceof Error?Be.message:"Could not load meshes")}finally{A(!1)}},[l]);u.useEffect(()=>{var Be;if(!b)return;if(Et.current!==b.id){Et.current=b.id,x("workspace"),k(v||((Be=f[0])==null?void 0:Be.id)||"__home__"),y(""),_([]),D(""),F(null),R(""),E(hc(b)),M(""),H(""),te(""),ke([]),we(!1),Te(""),G(Jt()),L(""),U(null);return}k(fe=>{var Fe;return fe==="__custom__"||fe==="__home__"||f.some(Gt=>Gt.id===fe)?fe:v||((Fe=f[0])==null?void 0:Fe.id)||"__home__"}),E(fe=>fe==="ide"&&Ze.length>0||fe==="cli"&&He.length>0||fe==="acp"&&pt.length>0?fe:hc(b))},[pt.length,He.length,v,Ze.length,b,f]),u.useEffect(()=>{!b||w!=="mesh"||P===b.id||T||ve(b.id)},[ve,P,T,b,w]),u.useEffect(()=>{w==="mesh"&&I!=="cli"&&He.length>0&&E("cli")},[I,He.length,w]),u.useEffect(()=>{var pe;I&&(Lt.some(Be=>Be.id===$)||M(((pe=Lt[0])==null?void 0:pe.id)||""))},[I,Lt,$]),u.useEffect(()=>{U(null)},[b==null?void 0:b.id,C,$,w]);const Ne=u.useCallback(async(pe,Be)=>{const fe=De.current+1;return De.current=fe,q(!0),Te(""),d(pe,Be).then(Fe=>{De.current===fe&&ke(Fe)}).catch(Fe=>{De.current===fe&&(ke([]),Te(Fe instanceof Error?Fe.message:"Could not load saved sessions"))}).finally(()=>{De.current===fe&&(q(!1),we(!0))})},[d]),ee=u.useCallback((pe,Be)=>{z(AA(pe,Be))},[]);u.useEffect(()=>{De.current+=1,te(""),G(Jt()),!b||!$||I==="ide"?z([]):ee(b.id,$),we(!1),ke([]),Te(""),q(!1)},[I,ee,Ne,b,$]),u.useEffect(()=>{if(!X)return;const pe=he.find(Be=>Be.providerSessionId===X);pe!=null&&pe.canResume||te("")},[he,X]);const se=S==="__custom__"?j.trim():S==="__home__"?"":((gs=f.find(pe=>pe.id===S))==null?void 0:gs.path)||"",be=u.useMemo(()=>b?t.filter(pe=>pe.id!==b.id&&pe.daemonId===b.id).map(pe=>pe.workspace):[],[t,b]),Me=u.useMemo(()=>((b==null?void 0:b.recentLaunches)||[]).map(pe=>pe.workspace),[b]),$e=u.useCallback(pe=>{const Be=String(pe.workspace||"").trim();if(!Be)return;const fe=f.find(Fe=>Fa(Fe.path)===Fa(Be));if(fe){k(fe.id),y("");return}k("__custom__"),y(Be)},[f]),Re=u.useCallback(pe=>{const Be=String(pe.workspace||"").trim();if(!Be)return{workspaceId:null,workspacePath:null};const fe=f.find(Fe=>Fa(Fe.path)===Fa(Be));return fe?{workspaceId:fe.id,workspacePath:null}:{workspaceId:null,workspacePath:Be}},[f]),Oe=u.useMemo(()=>he.find(pe=>pe.providerSessionId===X)||null,[he,X]),ze=u.useMemo(()=>{var Be;if(I!=="cli"||!b||!$)return null;const pe=((Be=He.find(fe=>fe.type===$))==null?void 0:Be.displayName)||$;return{routeId:b.id,daemonId:b.id,providerSessionId:X||void 0,transport:"pty",mode:"chat",agentName:pe,agentType:$,status:"idle",title:pe,messages:[],ideType:$,workspaceName:se,workspacePath:se,displayPrimary:pe,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${b.id}:${$}`,machineName:hs(b,{fallbackId:b.id})}},[I,He,se,b,X,$]),Le=u.useCallback(()=>{var Be;if(!b)return;k("__custom__"),Y(!0),ct("");const pe=ku(b.platform,Su(j.trim(),se,be,Me,b.defaultWorkspacePath,(Be=f.find(fe=>fe.id===v))==null?void 0:Be.path,f.map(fe=>fe.path)));lt(!0),n(b.id,pe).then(fe=>{Ce(fe.path),y(fe.path),qe(fe.directories)}).catch(fe=>{ct(fe instanceof Error?fe.message:"Could not load folder")}).finally(()=>lt(!1))},[j,v,Me,be,n,se,b,f]),Ye=u.useCallback(pe=>{b&&(lt(!0),ct(""),n(b.id,pe).then(Be=>{Ce(Be.path),y(Be.path),qe(Be.directories)}).catch(Be=>{ct(Be instanceof Error?Be.message:"Could not load folder")}).finally(()=>lt(!1)))},[n,b]),rt=u.useCallback(async()=>{if(!b||!se)return;Mt(!0),L("");const pe=await i(b.id,se);if(Mt(!1),!pe.ok){L(pe.error||"Could not save workspace");return}L("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,se,b]),Ct=u.useCallback(async()=>{if(!b)return;if(w==="mesh"){if(!C||!$)return;ue(!0),L(""),U(null);const fe=await c(b.id,C,$);if(ue(!1),!fe.ok){if(fe.code==="mesh_coordinator_manual_mcp_setup_required"&&fe.manualSetup){U(fe.manualSetup),L("Manual MCP setup required before this provider can act as mesh coordinator.");return}L(fe.error||"Could not start mesh coordinator");return}s();return}if(!I||!$)return;ue(!0),L("");const pe=O.trim()?O.trim().split(/\s+/).filter(Boolean):[],Be=I==="ide"?await a(b.id,$,{workspacePath:se||null}):await o(b.id,I,$,{workspaceId:S!=="__home__"&&S!=="__custom__"?S:null,workspacePath:S==="__custom__"&&se||null,resumeSessionId:I==="cli"&&X?X:null,cliArgs:pe});if(ue(!1),!Be.ok){L(Be.error||"Could not start session");return}I!=="ide"&&O.trim()&&(TA(b.id,$,O),ee(b.id,$)),s()},[I,O,ee,s,a,c,o,se,b,C,X,$,S,w]),Ut=w==="mesh"?"Start mesh coordinator":I?i_(I,I==="cli"&&!!X):"Start",Rt=w==="mesh"?"Starting coordinator…":I?a_(I,I==="cli"&&!!X):"Starting…",It=h.length>5;return b?r.jsxs(r.Fragment,{children:[r.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:r.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:[r.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:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),r.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."})]}),r.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:s,"aria-label":"Close new session dialog",children:r.jsx(Ot,{size:16})})]}),r.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:[h.length>1&&r.jsx(ao,{title:"Machine",children:It?r.jsx("select",{"aria-label":"Machine",value:b.id,onChange:pe=>g(pe.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:oe,children:h.map(pe=>r.jsx("option",{value:pe.id,children:hs(pe,{fallbackId:pe.id})},pe.id))}):r.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:h.map(pe=>{const Be=hs(pe,{fallbackId:pe.id}),fe=b.id===pe.id;return r.jsxs("button",{type:"button","aria-label":`Select machine ${Be}`,"aria-pressed":fe,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${fe?"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:()=>g(pe.id),disabled:oe,title:Be,children:[r.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${pe.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),r.jsx("span",{className:"truncate",children:Be})]},pe.id)})})}),r.jsxs(ao,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:w==="workspace"?r.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Le,disabled:oe,children:"Browse…"}):void 0,children:[r.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(pe=>r.jsxs("button",{type:"button",role:"radio","aria-checked":w===pe.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${w===pe.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(pe.id),L(""),pe.id==="mesh"&&b&&P!==b.id&&!T&&ve(b.id)},disabled:oe,children:[r.jsx("div",{className:"text-sm font-semibold",children:pe.label}),r.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:pe.desc})]},pe.id))}),w==="workspace"?r.jsxs(r.Fragment,{children:[r.jsxs("select",{value:S,onChange:pe=>{const Be=pe.target.value;k(Be),Be==="__custom__"?Le():L("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:oe,children:[r.jsx("option",{value:"__home__",children:"Home directory"}),f.map(pe=>r.jsxs("option",{value:pe.id,children:[pe.id===v?"⭐ ":"",hg(pe.path,pe.label)||pe.path]},pe.id)),r.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),r.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:S==="__home__"?"Launch without a workspace.":se||"Select a workspace folder."}),S==="__custom__"&&se&&r.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[r.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Le,disabled:oe,children:[r.jsx(bn,{size:14}),"Select folder"]}),r.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:rt,disabled:oe||_t,children:_t?"Saving…":"Save workspace"})]})]}):r.jsxs("div",{className:"space-y-3",children:[T&&r.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!T&&J&&r.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:J}),!T&&!J&&N.length===0&&r.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."}),N.length>0&&r.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:N.map(pe=>r.jsxs("button",{type:"button",role:"radio","aria-checked":C===pe.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${C===pe.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>D(pe.id),disabled:oe,children:[r.jsx("div",{className:"text-sm font-semibold text-text-primary",children:pe.name}),r.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[pe.repoIdentity||"Repo mesh",typeof pe.nodesCount=="number"?` · ${pe.nodesCount} node${pe.nodesCount===1?"":"s"}`:""]}),pe.workspace&&r.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",pe.workspace]})]},pe.id))}),B&&r.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),r.jsx(PA,{workspaceMode:w,activeKind:I,cliEnabled:He.length>0,ideEnabled:Ze.length>0,acpEnabled:pt.length>0,busy:oe,onSelect:E}),r.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[r.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:I==="ide"?"Choose IDE":I==="cli"?"Choose CLI provider":"Choose ACP provider"}),r.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Lt.map(pe=>r.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${$===pe.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>M(pe.id),disabled:oe,children:[r.jsx("div",{className:"text-sm font-semibold text-text-primary",children:pe.label}),r.jsx("div",{className:"text-xs text-text-secondary mt-1",children:pe.meta})]},pe.id)),Lt.length===0&&r.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."})]})]}),w==="mesh"&&xe&&r.jsx(tb,{setup:xe,providerName:(V==null?void 0:V.displayName)||(V==null?void 0:V.name)||$}),w!=="mesh"&&I!=="ide"&&r.jsxs(ao,{title:"Startup arguments",children:[r.jsx("input",{type:"text",value:O,onChange:pe=>H(pe.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:oe}),ae.length>0&&r.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:ae.map(pe=>r.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>H(pe),disabled:oe,title:pe,children:pe},pe))})]}),w!=="mesh"&&I==="cli"&&r.jsx(RA,{busy:oe,savedSessionsLoading:Q,savedSessionsError:ye,selectedSession:Oe,onRefresh:()=>{!b||!$||Ne(b.id,$)},onOpenHistory:()=>{!b||!$||(Se(!0),MA({hasLoadedInitialResults:me,isLoading:Q})&&Ne(b.id,$))},onClearSelection:()=>te("")}),ce&&r.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ce.includes("saved")||ce.includes("requested")||ce.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:ce})]}),r.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:[r.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:s,disabled:oe,children:"Cancel"}),r.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:Ct,disabled:oe||(w==="mesh"?!C||!$||I!=="cli"||T:!I||!$||S==="__custom__"&&!se),children:[r.jsx(Qf,{size:14}),oe?Rt:Ut]})]})]})}),ie&&r.jsx(_u,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:Ae,directories:je,busy:it,error:ft,onClose:()=>Y(!1),onNavigate:Ye,onConfirm:pe=>{y(pe),Ce(pe),k("__custom__"),Y(!1)}}),le&&ze&&r.jsx(tx,{activeConv:ze,ides:[],isCreatingChat:!1,isRefreshingHistory:Q,savedSessions:he,isSavedSessionsLoading:Q,isResumingSavedSessionId:W,savedHistoryFilters:ge,missingWorkspaceResumePath:se||null,onSavedHistoryFiltersChange:G,onClose:()=>Se(!1),onNewChat:()=>{te(""),Se(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!b||!$||Ne(b.id,$)},onResumeSavedSession:pe=>{if(!b||!$||W||!pe.canResume)return;const Be=Re(pe);te(pe.providerSessionId),$e(pe),Z(pe.providerSessionId),Se(!1),ue(!0),L(""),o(b.id,"cli",$,{workspaceId:Be.workspaceId,workspacePath:Be.workspacePath,resumeSessionId:pe.providerSessionId}).then(fe=>{if(!fe.ok){L(fe.error||"Could not resume session");return}s()}).finally(()=>{ue(!1),Z(fe=>fe===pe.providerSessionId?null:fe)})}})]}):null}const LA=5*60*1e3;function sb(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function rb(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function $A(e){var t,s,n;return((t=e.connection)==null?void 0:t.state)==="self"||e.isLocalWorktree===!0?"local":((s=e.connection)==null?void 0:s.transport)==="direct"||((n=e.connection)==null?void 0:n.transport)==="relay"||sb(e)||rb(e)?"remote":"unknown"}function OA(e){const t=e.connection;if(!t)return{connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null};const s=t.rttMs,n=typeof s=="number"&&Number.isFinite(s)&&s>=0?s:null;return{connectionTransport:t.transport??null,connectionState:t.state??null,connectionReason:typeof t.reason=="string"&&t.reason.trim()?t.reason.trim():null,connectionReported:t.reported===!0,connectionRttMs:n}}function nb(e){const t=e.connectionTransport;if(t==="direct"||t==="relay"||t==="local")return t;const s=e.connectionState;return s==="connecting"?"connecting":s==="disconnected"?"disconnected":s==="failed"?"failed":s==="closed"?"closed":null}function FA(e){const t=nb(e)??"unknown";return typeof e.connectionRttMs=="number"?`${t} · ${Math.round(e.connectionRttMs)}ms`:t}function BA(e){return nu(e)}function ib(e){var t;return BA(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function ab(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function WA(e){return e.activeSessionDetails&&e.activeSessionDetails.length>0?e.activeSessionDetails:(e.activeSessions??[]).map(t=>({sessionId:t,workspace:e.workspace,isCached:!0}))}function ob(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function lb(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function Iu(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function UA(e){return Iu(e)?"degraded":lb(e)?"dirty":"online"}function HA(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function um(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":default:return 5}}function mc(e){return e.length===0?"unknown":e.reduce((t,s)=>um(s)>um(t)?s:t)}function zA(e){var a,o,l,c,d;const t=new Map,s=new Map;for(const p of e){const h=(o=(a=p.git)==null?void 0:a.branch)==null?void 0:o.trim();h&&(s.set(h,(s.get(h)??0)+1),(l=p.git)!=null&&l.upstream&&t.set(h,(t.get(h)??0)+1))}const n=[...t.entries()].sort((p,h)=>{if(h[1]!==p[1])return h[1]-p[1];const m=["main","master","develop","dev"],g=m.indexOf(p[0]),b=m.indexOf(h[0]);return g!==-1||b!==-1?g===-1?1:b===-1?-1:g-b:p[0].localeCompare(h[0])});return(c=n[0])!=null&&c[0]?n[0][0]:((d=[...s.entries()].sort((p,h)=>h[1]-p[1])[0])==null?void 0:d[0])??null}function KA(e,t){const s=[],n=e.git;return n?n.isGitRepo?(!n.branch&&n.headCommit&&s.push("Detached HEAD"),n.hasConflicts&&s.push("Merge conflicts need resolution"),n.branch&&t&&n.branch!==t&&!n.upstream&&s.push(`No upstream tracking for ${n.branch}`),n.upstream&&n.upstreamStatus&&n.upstreamStatus!=="fresh"&&s.push(`Upstream freshness unverified for ${n.branch??"workspace"}`),e.error&&s.push(e.error),s):(s.push("Not a git repository"),s):(s.push("No git status available"),s)}function pm(e){switch(e){case"merged_to_main":return 0;case"pushed_feature_branch_needs_merge":return 1;case"cleanup_candidate":return 2;case"blocked_review":return 3;case"not_mergeable":default:return 4}}function GA(e){return e.reduce((t,s)=>pm(s.status)>pm(t.status)?s:t)}function qA(e){const t=e.branchConvergenceSummary;if(Array.isArray(t==null?void 0:t.followUps))return t.followUps;const s=e.followUps;return Array.isArray(s)?s:(t==null?void 0:t.needsFollowUp)===!1||(t==null?void 0:t.unresolvedCount)===0?[]:null}function VA(e){var i,a,o;const t=e.sourceOfTruth,s=[],n=(i=t==null?void 0:t.fallback)==null?void 0:i.warning;return typeof n=="string"&&n.trim()&&s.push(n.trim()),(t==null?void 0:t.currentStatus)==="bootstrap_inventory_fallback"&&((a=t.directPeerTruth)==null?void 0:a.required)===!0&&((o=t.directPeerTruth)==null?void 0:o.satisfied)!==!0&&!s.some(l=>l.includes("direct mesh truth"))&&s.push("Direct mesh truth is not confirmed yet; this graph is drawn from setup inventory only."),s}function XA(e){const t=e.asyncRefineJobs;if(!Array.isArray(t))return[];const s=[];for(const n of t){if(!n||typeof n!="object")continue;const i=n,a=typeof i.jobId=="string"?i.jobId:null,o=i.status;a&&(o!=="accepted"&&o!=="running"&&o!=="completed"&&o!=="failed"||s.push({jobId:a,status:o,nodeId:typeof i.nodeId=="string"?i.nodeId:void 0,targetNodeId:typeof i.targetNodeId=="string"?i.targetNodeId:void 0,workspace:typeof i.workspace=="string"?i.workspace:void 0,branch:typeof i.branch=="string"?i.branch:void 0,into:typeof i.into=="string"?i.into:void 0,lastUpdatedAt:typeof i.lastUpdatedAt=="string"?i.lastUpdatedAt:void 0,startedAt:typeof i.startedAt=="string"?i.startedAt:void 0,completedAt:typeof i.completedAt=="string"?i.completedAt:void 0}))}return s}function hm(e){switch(e){case"running":case"accepted":return 0;case"failed":return 1;case"completed":default:return 2}}function mm(e){const t=e.lastUpdatedAt||e.completedAt||e.startedAt||"";return ab(t)??0}function YA(e){return e.length===0?null:e.reduce((t,s)=>{const n=hm(t.status),i=hm(s.status);return i!==n?i<n?s:t:mm(s)>mm(t)?s:t})}function QA(e){var s,n;const t=new Map;for(const i of e){const a=((s=i.nodeId)==null?void 0:s.trim())||((n=i.targetNodeId)==null?void 0:n.trim());if(!a)continue;const o=t.get(a)??[];o.push(i),t.set(a,o)}return t}function JA(e,t){return e.type!=="submoduleNode"&&e.branch===t&&e.ahead===0&&e.behind===0&&!e.dirty&&!e.hasConflicts&&(!e.upstreamStatus||e.upstreamStatus==="fresh")&&e.snapshotCompleteness==="complete"}function ZA(e,t){var s,n;return{status:"merged_to_main",needsConvergence:!1,reason:"clean_default_branch_aggregate",nextStep:null,branch:e,defaultBranch:e,upstream:((s=t.find(i=>i.upstream))==null?void 0:s.upstream)??null,upstreamStatus:((n=t.find(i=>i.upstreamStatus))==null?void 0:n.upstreamStatus)??null,ahead:0,behind:0,dirty:!1,hasConflicts:!1}}function eT(e,t){if(ib(e))return null;const s=e.branchConvergence;if(!s||typeof s!="object")return null;const n=s.status;if(!n||!["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"].includes(n))return null;const i=e.git,a=ob(i)||lb(i),o=!!(i!=null&&i.hasConflicts)||Iu(i),l=(i==null?void 0:i.ahead)??0,c=(i==null?void 0:i.behind)??0,d=(i==null?void 0:i.branch)??null,p=(i==null?void 0:i.upstream)??null,h=(i==null?void 0:i.upstreamStatus)??null,m=s.defaultBranch??t??null;return{status:n,needsConvergence:s.needsConvergence??n!=="merged_to_main",reason:s.reason??"provided_by_coordinator",nextStep:s.nextStep??null,branch:s.branch??d,defaultBranch:m,upstream:s.upstream??p,upstreamStatus:s.upstreamStatus??h,ahead:s.ahead??l,behind:s.behind??c,dirty:s.dirty??a,hasConflicts:s.hasConflicts??o}}function tT(e,t){const s=eT(e,t);return s?{...s,defaultBranch:s.defaultBranch??t}:null}function sT(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function rT(e){var c,d,p;const{nodeStatus:t,expectedSubmodulePaths:s,refreshedAtMs:n}=e,i=[],a=t.machineLabel||t.nodeId,o=t.git;if(!o){if(ib(t))return i.push(`${a} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:i};const h=t.health==="online"||t.machineStatus==="online"||((c=t.connection)==null?void 0:c.state)==="connected"||((d=t.connection)==null?void 0:d.state)==="self";return i.push(h?`${a} is online but no peer git snapshot is visible yet.`:`${a} has no peer git snapshot visible yet.`),{snapshotCompleteness:"missing_git",snapshotWarnings:i}}const l=new Set((o.submodules??[]).map(h=>h.path));if(s.size>0){const h=[...s].filter(m=>!l.has(m));h.length>0&&i.push(`${a} is missing submodule visibility for ${h.join(", ")} even though another peer reported it.`)}return((p=t.connection)==null?void 0:p.state)!=="self"&&n!==null&&typeof o.lastCheckedAt=="number"&&n-o.lastCheckedAt>LA&&i.push(`${a} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),i.some(h=>h.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:i}:i.some(h=>h.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:i}:{snapshotCompleteness:"complete",snapshotWarnings:i}}function cb(e){const t=iu(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??zA(t.nodes),i=ab(t.refreshedAt),a=new Set(t.nodes.flatMap(I=>{var E;return(((E=I.git)==null?void 0:E.submodules)??[]).map($=>$.path)})),o=[],l=[],c=VA(t),d=new Map,p=QA(XA(t));for(const I of t.nodes){const E=I.git,$=(E==null?void 0:E.branch)??null,M=UA(E),O=ob(E)||M==="dirty",H=KA(I,n),ae=tT(I,n),z=rT({nodeStatus:I,expectedSubmodulePaths:a,refreshedAtMs:i}),X=typeof I.clonedFromNodeId=="string"?I.clonedFromNodeId:null,te=WA(I),he=YA(p.get(I.nodeId)??[]),ke=OA(I),Q={id:I.nodeId,type:H.length>0?"orphanNode":"worktreeNode",label:I.machineLabel||I.nodeId.slice(0,8),workspace:I.workspace,branch:$,upstream:(E==null?void 0:E.upstream)??null,upstreamStatus:(E==null?void 0:E.upstreamStatus)??null,daemonId:sb(I),machineId:rb(I),machineLabel:I.machineLabel||null,locality:$A(I),connectionTransport:ke.connectionTransport,connectionState:ke.connectionState,connectionReason:ke.connectionReason,connectionReported:ke.connectionReported,connectionRttMs:ke.connectionRttMs,health:mc([I.health,M]),ahead:(E==null?void 0:E.ahead)??0,behind:(E==null?void 0:E.behind)??0,dirty:O,dirtyFiles:HA(E),hasConflicts:(E==null?void 0:E.hasConflicts)??!1,activeSessionCount:te.length,activeSessions:te.map(q=>q.sessionId),sessionDetails:te,providers:I.providers??[],isOrphan:H.length>0,orphanReasons:H,error:I.error,nextStepHint:z.snapshotWarnings[0]??H[0]??(ae==null?void 0:ae.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:X,worktreeBranch:I.worktreeBranch??null,submodulePath:null,submoduleCommit:(E==null?void 0:E.headCommit)??null,outOfSync:Iu(E),snapshotCompleteness:z.snapshotCompleteness,snapshotWarnings:z.snapshotWarnings,branchConvergence:ae,refineJobStatus:(he==null?void 0:he.status)??null,refineJobId:(he==null?void 0:he.jobId)??null,refineJobBranch:(he==null?void 0:he.branch)??null,refineJobInto:(he==null?void 0:he.into)??null,source:I};if(o.push(Q),$){const q=d.get($)??[];q.push(Q.id),d.set($,q)}for(const q of(E==null?void 0:E.submodules)??[]){const me=`${Q.id}::submodule::${q.path}`,we=q.path.split("/").filter(Boolean).pop()||q.path;o.push({id:me,type:"submoduleNode",label:we,workspace:q.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:Q.daemonId,machineId:Q.machineId,machineLabel:Q.machineLabel,locality:Q.locality,connectionTransport:Q.connectionTransport,connectionState:Q.connectionState,connectionReason:Q.connectionReason,connectionReported:Q.connectionReported,connectionRttMs:Q.connectionRttMs,health:sT(q),ahead:0,behind:0,dirty:q.dirty,dirtyFiles:q.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],error:q.error,nextStepHint:q.error||(q.outOfSync?`${q.path} is out of sync with the parent checkout`:q.dirty?`${q.path} has local changes`:`${q.path} is in sync with the parent checkout`),parentNodeId:Q.id,submodulePath:q.path,submoduleCommit:q.commit,outOfSync:q.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:Q.id,parentWorkspace:I.workspace,submodule:q}}),l.push({id:`${Q.id}--${me}`,source:Q.id,target:me,type:"submoduleLink",label:q.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const h=n?`__branch_${n}`:null;if(h&&n){const E=(d.get(n)??[]).map(X=>o.find(te=>te.id===X)).filter(Boolean),$=E.map(X=>X.branchConvergence).filter(Boolean),M=qA(t),O=E.length>0&&E.every(X=>JA(X,n)),H=(M==null?void 0:M.length)===0&&O?ZA(n,E):$.length>0?GA($):null,ae=(M==null?void 0:M.length)===0&&O?0:$.filter(X=>X.needsConvergence).length,z={id:h,type:"defaultBranchNode",label:n,workspace:t.repoIdentity,branch:n,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:"default branch",locality:"unknown",connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null,health:mc(E.map(X=>X.health)),ahead:0,behind:0,dirty:E.some(X=>X.dirty),dirtyFiles:E.reduce((X,te)=>X+te.dirtyFiles,0),hasConflicts:E.some(X=>X.hasConflicts),activeSessionCount:E.reduce((X,te)=>X+te.activeSessionCount,0),activeSessions:E.flatMap(X=>X.activeSessions),sessionDetails:E.flatMap(X=>X.sessionDetails),providers:[...new Set(E.flatMap(X=>X.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:ae>0?`${ae} workspace(s) on ${n} still need follow-up`:E.length>0?`${E.length} workspace(s) currently on ${n}`:"No workspaces currently checked out to the default branch",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:H,source:{nodeId:h,machineLabel:n,workspace:t.repoIdentity,health:mc(E.map(X=>X.health)),providers:[],activeSessions:[],activeSessionDetails:[]}};o.push(z);for(const X of o)if(!(X.id===h||X.type==="submoduleNode")){if(X.branch===n){l.push({id:`${h}--${X.id}`,source:h,target:X.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(X.branch){l.push({id:`${h}--${X.id}`,source:h,target:X.id,type:X.isOrphan?"orphanLink":"parentBranch",label:X.branch,direction:"undirected"});continue}X.isOrphan&&l.push({id:`${h}--${X.id}`,source:h,target:X.id,type:"orphanLink",label:"detached",direction:"undirected"})}}const m=new Set(o.map(I=>I.id)),g=new Set;for(const I of o){if(!I.clonedFromNodeId||I.type==="submoduleNode"||!m.has(I.clonedFromNodeId))continue;const E=`clone_${I.clonedFromNodeId}--${I.id}`;if(g.has(E))continue;g.add(E);const $=I.worktreeBranch??I.branch??void 0;l.push({id:E,source:I.clonedFromNodeId,target:I.id,type:"cloneLink",label:$?`cloned · ${$}`:"cloned",direction:"directed"})}const b=o.find(I=>I.type!=="submoduleNode"&&I.connectionState==="self");if(b)for(const I of o)I.id!==b.id&&(I.type==="submoduleNode"||I.type==="defaultBranchNode"||!I.connectionReported&&I.connectionTransport===null||I.connectionState!=="self"&&l.push({id:`coord_${b.id}--${I.id}`,source:b.id,target:I.id,type:"coordinatorLink",label:FA(I),direction:"directed"}));const f=o.filter(I=>I.type!=="defaultBranchNode"),v=f.filter(I=>I.isOrphan).length,w=f.filter(I=>I.hasConflicts).length,x=f.filter(I=>I.health==="offline").length,S=f.filter(I=>I.type==="submoduleNode"&&I.outOfSync).length,k=f.filter(I=>{var E;return I.type!=="submoduleNode"&&((E=I.branchConvergence)==null?void 0:E.needsConvergence)}).length,j=f.filter(I=>{var E;return((E=I.branchConvergence)==null?void 0:E.status)==="blocked_review"}).length,y=f.filter(I=>{var E;return((E=I.branchConvergence)==null?void 0:E.status)==="pushed_feature_branch_needs_merge"}).length,N=f.filter(I=>{var E;return((E=I.branchConvergence)==null?void 0:E.status)==="cleanup_candidate"}).length,_=f.filter(I=>{var E;return((E=I.branchConvergence)==null?void 0:E.status)==="not_mergeable"}).length,C=f.filter(I=>I.snapshotWarnings.length>0).length,D=f.filter(I=>I.snapshotCompleteness==="pending_git").length,T=f.filter(I=>I.snapshotCompleteness==="missing_git").length,A=f.filter(I=>I.snapshotCompleteness==="missing_submodule_report").length,P=f.filter(I=>I.snapshotCompleteness==="stale").length,F=f.filter(I=>I.refineJobStatus==="running"||I.refineJobStatus==="accepted").length,J=f.filter(I=>I.refineJobStatus==="failed").length,R=[D>0?`${D} node(s) are still waiting for a live peer git snapshot`:null,T>0?`${T} node(s) have no visible peer git snapshot`:null,A>0?`${A} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,P>0?`${P} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return k>0&&c.push(`${k} workspace(s) still need follow-up before the mesh is converged`),v>0&&c.push(`${v} workspace(s) need attention before safe coordination`),j>0&&c.push(`${j} workspace(s) are blocked on branch convergence or upstream sync`),y>0&&c.push(`${y} clean feature branch workspace(s) still need merge follow-up`),N>0&&c.push(`${N} worktree workspace(s) are ready for refine / cleanup`),_>0&&c.push(`${_} workspace(s) have local changes or conflicts blocking convergence`),w>0&&c.push(`${w} workspace(s) report merge conflicts`),x>0&&c.push(`${x} node(s) are currently offline`),S>0&&c.push(`${S} submodule(s) are out of sync with their parent checkout`),c.push(...R),n||c.push("Could not infer a default branch from live mesh status"),{meshId:t.meshId,meshName:t.meshName,repoIdentity:t.repoIdentity,refreshedAt:t.refreshedAt,nodes:o,edges:l,stats:{totalNodes:f.length,onlineNodes:f.filter(I=>I.health==="online").length,dirtyNodes:f.filter(I=>I.dirty).length,orphanNodes:v,errorNodes:f.filter(I=>!!I.error||I.outOfSync).length,offlineNodes:x,followUpNodes:k,blockedReviewNodes:j,mergeReadyNodes:y,cleanupCandidateNodes:N,notMergeableNodes:_,incompleteSnapshotNodes:C,pendingGitSnapshotNodes:D,missingGitSnapshotNodes:T,missingSubmoduleSnapshotNodes:A,staleGitSnapshotNodes:P,activeRefineNodes:F,failedRefineNodes:J,totalActiveSessions:f.reduce((I,E)=>I+E.activeSessionCount,0)},warnings:c,snapshotWarnings:R}}function nT(e){return!e.nodes.some(t=>t.snapshotCompleteness==="pending_git"||t.snapshotCompleteness==="missing_git"||t.snapshotCompleteness==="missing_submodule_report")}function db(e){return e.ahead<=0&&e.behind<=0?null:e.ahead>0&&e.behind>0?`ahead ${e.ahead} / behind ${e.behind}`:e.behind>0?`behind ${e.behind}`:`ahead ${e.ahead}`}function Au(e){if(e.type==="submoduleNode")return e.outOfSync||e.error?{label:"submodule drift",tone:"danger"}:e.dirty?{label:"submodule dirty",tone:"warn"}:null;const t=e.branchConvergence;if((t==null?void 0:t.status)==="not_mergeable")return{label:e.hasConflicts?"conflicts present":"dirty workspace",tone:"danger"};if((t==null?void 0:t.status)==="blocked_review"){if(t.reason==="upstream_unverified")return{label:"upstream unverified",tone:"warn"};const s=db(e);return s?{label:s,tone:"danger"}:!e.upstream&&e.branch&&e.branch!==t.defaultBranch?{label:"push branch",tone:"warn"}:{label:"blocked review",tone:"danger"}}return e.refineJobStatus==="failed"?{label:"refine failed",tone:"danger"}:e.refineJobStatus==="running"||e.refineJobStatus==="accepted"?{label:"refining…",tone:"info"}:(t==null?void 0:t.status)==="pushed_feature_branch_needs_merge"?{label:"needs merge",tone:"warn"}:(t==null?void 0:t.status)==="cleanup_candidate"?{label:"refine worktree",tone:"info"}:e.isOrphan?{label:"needs follow-up",tone:"warn"}:e.health==="offline"?{label:"offline",tone:"danger"}:null}function Tu(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function ub(e){var t;return!Tu(e)||e.type==="defaultBranchNode"?!1:!!((t=e.branchConvergence)!=null&&t.needsConvergence||e.isOrphan||e.hasConflicts||e.outOfSync||e.error||e.health==="offline"||e.health==="degraded"||e.health==="wrong_branch"||e.dirty)}function Ba(e){return[...new Set(e.filter(t=>!!t))]}function iT(e){const t=e.nodes.find(o=>o.type==="defaultBranchNode")??null,s=(t==null?void 0:t.branch)??null,n=e.nodes.filter(o=>o.type!=="defaultBranchNode"&&o.type!=="submoduleNode"&&!o.isOrphan&&!!s&&o.branch===s),i=e.nodes.filter(o=>o.type!=="submoduleNode"&&!o.isOrphan),a=e.nodes.filter(o=>o.type!=="submoduleNode");return t||n.length>0?Ba([t==null?void 0:t.id,...n.map(o=>o.id)]):i.length>0?Ba(i.map(o=>o.id)):a.length>0?Ba(a.map(o=>o.id)):Ba(e.nodes.map(o=>o.id))}function pb(e){const t=[...e.nodes].sort((n,i)=>n.id.localeCompare(i.id)).map(n=>[n.id,n.type,n.branch??"",n.parentNodeId??"",n.submodulePath??""].join(":")).join("|"),s=[...e.edges].sort((n,i)=>n.id.localeCompare(i.id)).map(n=>[n.id,n.source,n.target,n.type].join(":")).join("|");return`${e.meshId}::${t}::${s}`}function aT(e,t,s){const n=Math.max(0,Math.round(t)),i=Math.max(0,Math.round(s));return`${pb(e)}::${n}x${i}`}const oT={default:"border-white/10 bg-white/[0.04] text-slate-200",good:"border-emerald-400/20 bg-emerald-500/10 text-emerald-200",warn:"border-amber-400/20 bg-amber-500/10 text-amber-100",danger:"border-rose-400/20 bg-rose-500/10 text-rose-100",info:"border-sky-400/20 bg-sky-500/10 text-sky-100"},lT={default:"border-slate-300 bg-white/95 text-slate-700",good:"border-emerald-300 bg-emerald-50 text-emerald-700",warn:"border-amber-300 bg-amber-50 text-amber-700",danger:"border-rose-300 bg-rose-50 text-rose-700",info:"border-sky-300 bg-sky-50 text-sky-700"},cT={default:"border-white/10 bg-white/[0.04] text-slate-200 hover:bg-white/[0.08]",info:"border-sky-400/25 bg-sky-500/10 text-sky-100 hover:bg-sky-500/16",success:"border-emerald-400/25 bg-emerald-500/10 text-emerald-100 hover:bg-emerald-500/16"},dT={default:"border-slate-300 bg-white text-slate-700 hover:bg-slate-50",info:"border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100",success:"border-emerald-300 bg-emerald-50 text-emerald-700 hover:bg-emerald-100"};function qr(e){return e==="light"?{theme:e,isDark:!1,flowColorMode:"light",textPrimary:"text-slate-900",textSecondary:"text-slate-700",textMuted:"text-slate-500",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-slate-200 bg-[radial-gradient(circle_at_top,_rgba(14,165,233,0.16),_rgba(248,250,252,0.98)_42%,_rgba(255,255,255,1))]",graphStatChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-slate-700 shadow-sm",graphHintChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-[10px] text-slate-500 shadow-sm",graphControlsClass:"!bottom-4 !left-4 !shadow-md",graphBackgroundDotColor:"rgba(148, 163, 184, 0.34)",edgeLabelTextColor:"#334155",edgeLabelBackgroundColor:"rgba(255, 255, 255, 0.96)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.45)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-stretch justify-center bg-[rgba(15,23,42,0.82)] p-0 md:items-center md:p-4",dialogShellClass:"flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden bg-white md:h-auto md:max-h-[90dvh] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-slate-200 md:bg-white/98 md:shadow-[0_28px_120px_rgba(148,163,184,0.28)]",dialogHeaderClass:"sticky top-0 z-10 flex shrink-0 flex-col gap-3 border-b border-slate-200 bg-white/96 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-slate-900 md:text-xl",dialogKickerClass:"rounded-full border border-slate-300 bg-slate-50 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-600",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-500",dialogRefreshedChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1.5 text-xs text-slate-600",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-300 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",dialogBodyClass:"min-h-0 flex-1 flex flex-col overflow-y-auto bg-[linear-gradient(180deg,rgba(248,250,252,0.98),rgba(241,245,249,0.96))] px-4 py-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-slate-300 bg-white/90 px-6 text-center text-sm text-slate-500",cardClass:"rounded-2xl border border-slate-200 bg-white/95 shadow-sm",cardHeaderClass:"border-b border-slate-200 px-4 py-3",cardTitleClass:"text-sm font-semibold text-slate-900",cardSubtitleClass:"mt-1 text-xs text-slate-500",rowClass:"flex min-w-0 items-start justify-between gap-3 border-b border-slate-200/80 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"shrink-0 text-slate-500",rowValueClass:"min-w-0 flex-1 break-all text-right text-slate-800",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-slate-200 bg-white/95 p-4 shadow-md md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-slate-200 bg-white/95 p-4 text-xs text-slate-500 shadow-sm md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-900",panelCloseButtonClass:"text-xs text-slate-500 hover:text-slate-900",panelFieldRowClass:"flex min-w-0 justify-between gap-3 border-b border-slate-200/80 py-0.5 text-[11px]",panelFieldLabelClass:"shrink-0 text-slate-500",panelFieldValueClass:"min-w-0 flex-1 break-all text-right font-medium text-slate-700",infoCalloutClass:"mt-1 rounded border border-sky-300 bg-sky-50 px-2 py-1.5 text-[10px] text-sky-700",badge:t=>lT[t],actionButton:t=>dT[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",graphStatChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-slate-200",graphHintChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-[10px] text-slate-300",graphControlsClass:"!bottom-4 !left-4 !shadow-lg",graphBackgroundDotColor:"rgba(148, 163, 184, 0.22)",edgeLabelTextColor:"#cbd5e1",edgeLabelBackgroundColor:"rgba(2, 6, 23, 0.86)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.2)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-stretch justify-center bg-[#030617]/[0.92] p-0 md:items-center md:p-4",dialogShellClass:"flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden bg-slate-950 md:h-auto md:max-h-[90dvh] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-white/10 md:bg-slate-950/96 md:shadow-[0_28px_120px_rgba(2,6,23,0.46)]",dialogHeaderClass:"sticky top-0 z-10 flex shrink-0 flex-col gap-3 border-b border-white/10 bg-slate-950/92 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-white md:text-xl",dialogKickerClass:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-300",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-400",dialogRefreshedChipClass:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 bg-white/6 text-slate-300 transition hover:bg-white/10 hover:text-white",dialogBodyClass:"min-h-0 flex-1 flex flex-col overflow-y-auto bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] px-4 py-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-white/10 bg-white/[0.03] px-6 text-center text-sm text-slate-400",cardClass:"rounded-2xl border border-white/10 bg-white/[0.04]",cardHeaderClass:"border-b border-white/10 px-4 py-3",cardTitleClass:"text-sm font-semibold text-white",cardSubtitleClass:"mt-1 text-xs text-slate-400",rowClass:"flex min-w-0 items-start justify-between gap-3 border-b border-white/5 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"shrink-0 text-slate-400",rowValueClass:"min-w-0 flex-1 break-all text-right text-slate-100",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-white/10 bg-white/[0.04] p-4 shadow-lg md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-white/10 bg-white/[0.04] p-4 text-xs text-slate-400 md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-100",panelCloseButtonClass:"text-xs text-slate-400 hover:text-slate-100",panelFieldRowClass:"flex min-w-0 justify-between gap-3 border-b border-white/6 py-0.5 text-[11px]",panelFieldLabelClass:"shrink-0 text-slate-400",panelFieldValueClass:"min-w-0 flex-1 break-all text-right font-medium text-slate-200",infoCalloutClass:"mt-1 rounded bg-blue-500/10 border border-blue-500/20 px-2 py-1.5 text-[10px] text-blue-300",badge:t=>oT[t],actionButton:t=>cT[t]}}const jn={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,layerGap:220,nodeGap:82,edgeLabelBuffer:180,placeholderTopOffset:0},ea={worktreeCardWidth:188,submoduleCardWidth:188,minWorktreeCardHeight:88,minSubmoduleCardHeight:88,maxEstimatedCardHeight:178,layerGap:160,nodeGap:52,edgeLabelBuffer:120},uT={maxWidth:180};function pT(e){return e==="TB"?"DOWN":"RIGHT"}function Mu(e,t){return{"elk.algorithm":"layered","elk.direction":pT(t),"elk.edgeRouting":"ORTHOGONAL","elk.spacing.nodeNode":String(e.nodeGap),"elk.layered.spacing.nodeNodeBetweenLayers":String(e.layerGap),"elk.layered.spacing.edgeNodeBetweenLayers":String(e.edgeLabelBuffer),"elk.layered.layering.strategy":"NETWORK_SIMPLEX","elk.layered.nodePlacement.strategy":"NETWORK_SIMPLEX","elk.layered.crossingMinimization.strategy":"LAYER_SWEEP","elk.layered.considerModelOrder.strategy":"NODES_AND_EDGES","elk.layered.cycleBreaking.strategy":"GREEDY","elk.layered.mergeEdges":"false","elk.randomSeed":"1"}}const hT=Mu(jn,"LR");Mu(ea,"LR");function mT(e){const t=e.nodes.length;if(t<8)return"LR";const s=new Map;for(const i of e.edges)s.set(i.source,(s.get(i.source)??0)+1);let n=0;for(const i of s.values())i>n&&(n=i);return n>=Math.max(6,Math.floor(t/2))?"TB":"LR"}const fT=new vw;function Ai(e,t=!1){const s=t?ea:jn;return e.type==="submoduleNode"?s.submoduleCardWidth:s.worktreeCardWidth}function oo(e){var s;if(e.type==="defaultBranchNode")return e.nextStepHint||"Default branch anchor";if(e.type==="submoduleNode"){const n=[e.machineLabel?`parent ${e.machineLabel}`:null];return e.outOfSync?n.push("out of sync"):e.dirty?n.push("local changes"):n.push("synced"),n.filter(Boolean).join(" · ")}const t=[];if(e.upstream&&t.push(e.upstream),e.upstream&&e.upstreamStatus!=="fresh")t.push("upstream unverified");else{const n=db(e);n&&t.push(n)}return e.activeSessionCount>0&&t.push(`${e.activeSessionCount} session${e.activeSessionCount===1?"":"s"}`),e.dirtyFiles>0&&t.push(`${e.dirtyFiles} dirty`),e.hasConflicts&&t.push("conflicts"),t.length===0?(s=e.branchConvergence)!=null&&s.needsConvergence?"Needs follow-up":"Clean and even with upstream":t.join(" · ")}function hb(e,t=!1){const s=t?ea:jn,n=Ai(e,t),i=t?e.type==="submoduleNode"?20:22:e.type==="submoduleNode"?24:30,a=t?(e.type==="submoduleNode",2):e.type==="submoduleNode"?2:3,o=Math.ceil(gT(e)/a),l=Wa(e.label,i,2),c=Wa(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,i,2),d=Wa(oo(e),i+(t?1:4),t?2:3),p=Au(e),h=ub(e)?Tu(e):null,m=t?0:Wa(h,Math.max(24,Math.floor(n/8)),4),g=t?40+l*16+c*12+(p?22:0)+Math.max(0,o-1)*18+Math.max(18,d*16):52+l*18+c*14+(p?30:0)+o*24+Math.max(22,d*18)+(m>0?22+m*16:0),b=e.type==="submoduleNode"?s.minSubmoduleCardHeight:s.minWorktreeCardHeight;return Math.min(s.maxEstimatedCardHeight,Math.max(b,Math.ceil(g)))}function Wa(e,t,s){const n=(e||"").trim();return n?Math.max(1,Math.min(s,Math.ceil(n.length/t))):0}function gT(e){let t=1;return e.type==="submoduleNode"&&(t+=1),e.branch&&e.type!=="submoduleNode"&&(t+=1),e.submoduleCommit&&e.type==="submoduleNode"&&(t+=1),e.dirty&&(t+=1),e.outOfSync&&(t+=1),e.hasConflicts&&(t+=1),e.type!=="submoduleNode"&&e.upstream&&e.upstreamStatus!=="fresh"&&(t+=1),e.isOrphan&&(t+=1),t}function xT(e,t){return e.type==="defaultBranchNode"&&t.type!=="defaultBranchNode"?-1:t.type==="defaultBranchNode"&&e.type!=="defaultBranchNode"||e.type==="submoduleNode"&&t.type!=="submoduleNode"?1:t.type==="submoduleNode"&&e.type!=="submoduleNode"?-1:e.branch&&t.branch&&e.branch!==t.branch?e.branch.localeCompare(t.branch):e.branch&&!t.branch?-1:!e.branch&&t.branch?1:e.label.localeCompare(t.label)||e.id.localeCompare(t.id)}function bT(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function yT(e,t,s,n=!0){return{id:e.id,type:"meshNode",position:{x:t,y:s},graphNode:e,selected:!1,draggable:!1,selectable:n}}function vT(e,t,s){return{id:e.id,x:t,y:s,width:Ai(e),height:hb(e)}}function wT(e,t){return{id:`${e.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:t.repoIdentity,branch:e.branch,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:null,locality:"unknown",connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null,health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],nextStepHint:"Waiting for worktree nodes to report live mesh status.",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{nodeId:`${e.id}__placeholder`,machineLabel:"",workspace:t.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}}function mb(e){const t=[...e.nodes].sort(xT),s=t.find(i=>i.type==="defaultBranchNode")??null,n=t.some(i=>i.id!==(s==null?void 0:s.id)&&i.type!=="submoduleNode");return!s||n?t:[...t,wT(s,e)]}function ST(e,t=hT,s=!1,n="LR"){const i=mb(e),a=new Set(i.map(c=>c.id)),o=i.map(c=>({id:c.id,width:Ai(c,s),height:hb(c,s)})),l=e.edges.filter(c=>a.has(c.source)&&a.has(c.target)).sort(bT).map(c=>({id:c.id,sources:[c.source],targets:[c.target]}));return{id:`${e.meshId||"mesh"}__elk_root`,layoutOptions:{...t},children:o,edges:l}}function kT(e,t=!1){const s=[...new Set(e.map(i=>Math.round(i.x)))].sort((i,a)=>i-a),n=t?ea.layerGap:jn.layerGap;return s.length<2?n:Math.min(...s.slice(1).map((i,a)=>i-s[a]))}async function fb(e,t=!1,s="LR",n){var b,f;const a=Mu(t?ea:jn,s),o=mb(e),l=new Map(o.map(v=>[v.id,v])),c=ST(e,a,t,s);if(n&&n.size>0)for(const v of c.children??[]){const w=n.get(v.id);w&&w>0&&(v.height=w)}const d=await fT.layout(c),p=(d.children??[]).map(v=>{const w=l.get(v.id);return w?yT(w,Math.round(v.x??0),Math.round(v.y??jn.placeholderTopOffset),!v.id.endsWith("__placeholder")):null}).filter(Boolean),h=new Map(o.map((v,w)=>[v.id,w]));p.sort((v,w)=>(h.get(v.id)??0)-(h.get(w.id)??0));const m=p.map(v=>vT(v.graphNode,v.position.x,v.position.y)),g=new Map;for(const v of d.edges??[]){const w=v.sections;if(!w||w.length===0)continue;const x=w[0],S=(b=v.sources)==null?void 0:b[0],k=(f=v.targets)==null?void 0:f[0];if(!S||!k)continue;const j=[];j.push({x:Math.round(x.startPoint.x),y:Math.round(x.startPoint.y)});for(const y of x.bendPoints??[])j.push({x:Math.round(y.x),y:Math.round(y.y)});j.push({x:Math.round(x.endPoint.x),y:Math.round(x.endPoint.y)}),g.set(v.id,{id:v.id,source:S,target:k,points:j})}return{nodes:p,bounds:m,edgeRoutes:g,columnGap:kT(m,t),layoutOptions:{...a}}}function jT(e){var t,s;return[e.id,e.type,e.label,e.branch??"",e.upstream??"",e.upstreamStatus??"",e.daemonId??"",e.machineId??"",e.machineLabel??"",e.locality,e.health,e.ahead,e.behind,e.dirty?1:0,e.dirtyFiles,e.hasConflicts?1:0,e.activeSessionCount,e.sessionDetails.map(n=>[n.sessionId,n.providerType??"",n.state??"",n.chatStatus??"",n.lifecycle??"",n.role??"",n.isSelfCoordinator?1:0,n.statusNote??"",n.startedAt??"",n.createdAt??""].join("/")).join(","),e.isOrphan?1:0,e.outOfSync?1:0,e.snapshotCompleteness,((t=e.branchConvergence)==null?void 0:t.status)??"",(s=e.branchConvergence)!=null&&s.needsConvergence?1:0,e.nextStepHint??"",e.error??"",e.parentNodeId??"",e.submodulePath??"",e.submoduleCommit??""].join("|")}function gb(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function NT(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(jT),...e.edges.map(gb)].join("::")}function _T(e){return[e.meshId,e.nodes.length,e.edges.length,...e.nodes.map(t=>{var s,n;return[t.id,t.type,t.label,t.branch??"",t.machineLabel??"",t.locality,t.health,t.dirty?1:0,t.dirtyFiles,t.hasConflicts?1:0,t.activeSessionCount,t.isOrphan?1:0,t.outOfSync?1:0,t.snapshotCompleteness,((s=t.branchConvergence)==null?void 0:s.status)??"",(n=t.branchConvergence)!=null&&n.needsConvergence?1:0,t.nextStepHint??"",t.parentNodeId??"",t.submodulePath??"",t.submoduleCommit??""].join("|")}),...e.edges.map(gb)].join("::")}const CT=7,Eu=u.createContext(qr("dark")),xb=u.createContext(!1),bb=u.createContext("LR"),yb={overflowWrap:"anywhere",wordBreak:"break-word"},IT={...yb,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},AT={...yb,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function vb(e){return e.activeSessionCount>0}function TT(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function fm(e,t,s){const n=vb(e),i=TT(e);let a;t?a="border-cyan-400/70 shadow-[0_0_0_1px_rgba(34,211,238,0.35),0_24px_60px_rgba(8,145,178,0.18)]":n?a=s?"border-emerald-400/40 shadow-[0_0_0_1px_rgba(52,211,153,0.18),0_18px_48px_rgba(3,7,18,0.22)]":"border-emerald-400/60 shadow-[0_0_0_1px_rgba(52,211,153,0.2),0_18px_48px_rgba(148,163,184,0.20)]":i?a=s?"border-white/6 shadow-[0_12px_32px_rgba(3,7,18,0.16)] opacity-60":"border-slate-200/70 shadow-[0_12px_32px_rgba(148,163,184,0.14)] opacity-60":a=s?"border-white/10 shadow-[0_18px_48px_rgba(3,7,18,0.22)]":"border-slate-300/90 shadow-[0_18px_48px_rgba(148,163,184,0.20)]";const o=Au(e);if((o==null?void 0:o.tone)==="danger")return`${a} ${s?"bg-rose-500/12":"bg-rose-50/95"}`;if((o==null?void 0:o.tone)==="warn")return`${a} ${s?"bg-amber-500/10":"bg-amber-50/95"}`;if((o==null?void 0:o.tone)==="info")return`${a} ${s?"bg-violet-500/10":"bg-violet-50/95"}`;switch(e.health){case"online":return`${a} ${s?n?"bg-emerald-500/10":"bg-emerald-500/8":n?"bg-emerald-50":"bg-emerald-50/95"}`;case"dirty":return`${a} ${s?"bg-amber-500/8":"bg-amber-50/95"}`;case"degraded":return`${a} ${s?"bg-rose-500/10":"bg-rose-50/95"}`;case"wrong_branch":return`${a} ${s?"bg-violet-500/10":"bg-violet-50/95"}`;case"offline":return`${a} ${s?"bg-slate-500/10":"bg-slate-100/90"}`;default:return`${a} ${s?"bg-slate-950/78":"bg-white/96"}`}}function qt(e,t){switch(e){case"transportDirect":return t?"border-emerald-400/25 bg-emerald-500/10 text-emerald-200":"border-emerald-300 bg-emerald-50 text-emerald-700";case"transportRelay":return t?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700";case"transportDown":return t?"border-rose-400/25 bg-rose-500/10 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700";case"refineDone":return t?"border-emerald-400/25 bg-emerald-500/10 text-emerald-200":"border-emerald-300 bg-emerald-50 text-emerald-700";case"health":return t?"border-white/10 bg-slate-950/60 text-slate-200":"border-slate-300 bg-white/95 text-slate-700";case"dirty":return t?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700";case"conflict":return t?"border-rose-400/25 bg-rose-500/10 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700";case"orphan":return t?"border-fuchsia-400/25 bg-fuchsia-500/10 text-fuchsia-200":"border-fuchsia-300 bg-fuchsia-50 text-fuchsia-700";case"submodule":return t?"border-violet-400/25 bg-violet-500/10 text-violet-200":"border-violet-300 bg-violet-50 text-violet-700";case"meta":default:return t?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}}function gm(e,t){switch(e){case"danger":return t?"border-rose-400/35 bg-rose-500/14 text-rose-50":"border-rose-300 bg-rose-50 text-rose-700";case"warn":return t?"border-amber-400/35 bg-amber-500/14 text-amber-50":"border-amber-300 bg-amber-50 text-amber-700";case"info":return t?"border-violet-400/35 bg-violet-500/14 text-violet-50":"border-violet-300 bg-violet-50 text-violet-700";case"good":default:return t?"border-emerald-400/35 bg-emerald-500/12 text-emerald-50":"border-emerald-300 bg-emerald-50 text-emerald-700"}}function xm(e){switch(e){case"online":return"#34d399";case"dirty":return"#fbbf24";case"degraded":return"#fb7185";case"wrong_branch":return"#a78bfa";case"offline":return"#94a3b8";default:return"#64748b"}}function MT(e){return e.replace(/_/g," ")}function Ms(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const s=t.toLowerCase().replace(/[\s-]+/g,"_");return s.includes("approval")?"awaiting approval":s.includes("generating")||s.includes("running")||s.includes("busy")?"generating":s.includes("failed")||s.includes("stopped")||s.includes("interrupted")?s.replace(/_/g," "):s.includes("idle")||s.includes("ready")||s.includes("waiting_input")?"idle":s.replace(/_/g," ")}function ET(e){var t;return((t=e.sessionDetails)==null?void 0:t.some(s=>Ms(s)==="generating"))??!1}function fc(e,t){const s=Ms(e);return s.includes("approval")?t?"border-amber-400/30 bg-amber-500/12 text-amber-100":"border-amber-300 bg-amber-50 text-amber-700":s==="generating"?t?"border-cyan-400/30 bg-cyan-500/12 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700":s==="idle"?t?"border-emerald-400/30 bg-emerald-500/12 text-emerald-100":"border-emerald-300 bg-emerald-50 text-emerald-700":s.includes("failed")||s.includes("stopped")||s.includes("interrupted")?t?"border-rose-400/30 bg-rose-500/12 text-rose-100":"border-rose-300 bg-rose-50 text-rose-700":qt("health",t)}function RT(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function bm(e){const t=RT(e);if(t===null)return"runtime age not reported";const s=Math.max(0,Math.floor((Date.now()-t)/1e3));if(s<60)return`${s}s`;const n=Math.floor(s/60);if(n<60)return`${n}m`;const i=Math.floor(n/60);return i<48?`${i}h ${n%60}m`:`${Math.floor(i/24)}d ${i%24}h`}function gc(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function Gn(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function PT(e){if(e.sessionDetails.length===0)return null;const t=e.sessionDetails.filter(a=>Ms(a)==="generating").length,s=e.sessionDetails.filter(a=>a.isSelfCoordinator).length,n=e.sessionDetails.length-s,i=[`${e.sessionDetails.length} chat${e.sessionDetails.length===1?"":"s"}`];return t>0&&i.push(`${t} generating`),s>0&&i.push(s===1?"coordinator attached":`${s} coordinators`),n>0&&i.push(`${n} worker${n===1?"":"s"}`),t===0&&s>0&&i.push("sampled status"),i.join(" · ")}function ym(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function DT(e){return e.locality==="remote"?"meta":"health"}function LT(e){if(e.connectionTransport==="local"||e.connectionState==="self")return null;const t=nb(e);if(!t||t==="local")return null;const s=typeof e.connectionRttMs=="number"?` · ${Math.round(e.connectionRttMs)}ms`:"",n=e.connectionReason?`
|
|
74
|
+
${e.connectionReason}`:"";return t==="direct"?{label:`direct${s}`,kind:"transportDirect",title:`P2P link: direct${s}${n}`}:t==="relay"?{label:`relay${s}`,kind:"transportRelay",title:`P2P link: TURN relay (slower path)${s}${n}`}:{label:t,kind:"transportDown",title:`P2P link: ${t}${n}`}}function $T({data:e,selected:t}){const s=u.useContext(Eu),n=u.useContext(xb),i=u.useContext(bb),a=e.graphNode,o=a.type==="defaultBranchNode",l=a.type==="submoduleNode",c=ub(a),d=!o&&!l?LT(a):null,p=o?"default branch anchor":l?a.submodulePath||"submodule checkout":[a.machineLabel,ym(a.locality),d==null?void 0:d.label].filter(Boolean).join(" · ")||a.workspace,h=a.submoduleCommit?a.submoduleCommit.slice(0,7):null,m=Au(a),g=Tu(a),b=vb(a),f=a.sessionDetails,v=a.sessionDetails,w=PT(a),x=a.sessionDetails.map(k=>{const j=Ms(k),y=k.providerType||"provider unknown",N=Gn(k),_=k.startedAt||k.createdAt||null,C=k.statusNote?` · ${k.statusNote}`:"";return`Session: ${k.sessionId} · ${y} · ${j} · ${N} · ${bm(_)}${C}`});if(n)return r.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${fm(a,t,s.isDark)}`,style:{width:Ai(a,!0)},title:[a.label,a.branch?`Branch: ${a.branch}`:null,a.machineLabel?`Machine: ${a.machineLabel}`:null,a.workspace?`Workspace: ${a.workspace}`:null,m?`Status: ${m.label}`:null,oo(a),...x].filter(Boolean).join(`
|
|
75
|
+
`),children:[r.jsx(Sa,{type:"target",position:i==="TB"?Zs.Top:Zs.Left,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("div",{className:`truncate text-xs font-semibold leading-4 ${s.textPrimary}`,children:a.label}),!o&&r.jsx("div",{className:`truncate text-[10px] leading-3.5 ${s.textMuted}`,children:p})]}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[b&&r.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${s.isDark?"bg-emerald-400":"bg-emerald-500"} animate-pulse`,"aria-label":"active session"}),r.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full",style:{backgroundColor:xm(a.health)},"aria-hidden":!0})]})]}),a.health==="unknown"&&!m&&r.jsx("div",{className:`mt-1.5 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[9px] italic ${qt("health",s.isDark)}`,children:r.jsx("span",{className:"truncate",children:"Connecting..."})}),m&&r.jsx("div",{className:`mt-1.5 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[9px] font-semibold uppercase tracking-[0.14em] ${gm(m.tone,s.isDark)}`,title:m.label,children:r.jsx("span",{className:"truncate",children:m.label})}),!m&&a.branch&&!l&&a.health!=="unknown"&&r.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[10px] ${qt("meta",s.isDark)} rounded-full border px-2 py-0.5 inline-block`,title:a.branch,children:a.branch}),w&&r.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[9px] ${s.isDark?"text-cyan-100/85":"text-sky-700"}`,title:x.join(`
|
|
76
|
+
`),children:w}),v.length>0&&r.jsx("div",{className:"mt-1.5 flex max-h-28 min-w-0 flex-col gap-1 overflow-y-auto pr-1",children:v.map(k=>r.jsxs("div",{className:`min-w-0 rounded-md border px-1.5 py-1 ${s.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/80"}`,title:[`Session ID: ${k.sessionId}`,k.providerType?`Provider: ${k.providerType}`:null,`Status: ${Ms(k)}`,`Role: ${Gn(k)}`].filter(Boolean).join(`
|
|
77
|
+
`),children:[r.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-1.5",children:[r.jsx("span",{className:`min-w-0 truncate text-[9px] ${s.textMuted}`,children:k.providerType||"provider unknown"}),r.jsx("span",{className:`shrink-0 rounded-full border px-1 py-0 text-[8px] font-semibold uppercase tracking-[0.1em] ${fc(k,s.isDark)}`,children:Ms(k)})]}),r.jsxs("div",{className:`mt-0.5 flex min-w-0 items-center gap-1.5 text-[8px] ${s.textMuted}`,children:[r.jsx("span",{className:"min-w-0 truncate font-mono",children:gc(k.sessionId)}),r.jsx("span",{className:"shrink-0",children:Gn(k)})]})]},k.sessionId))}),r.jsx(Sa,{type:"source",position:i==="TB"?Zs.Bottom:Zs.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]});const S=[a.label,p,m?`Status: ${m.label}`:null,oo(a),a.branch?`Branch: ${a.branch}`:null,a.dirty?l?"Local changes":`${a.dirtyFiles} dirty`:null,a.hasConflicts?"Has conflicts":null,a.outOfSync?"Out of sync":null,!l&&a.upstream&&a.upstreamStatus!=="fresh"?"Upstream unverified":null,a.isOrphan?"Needs follow-up":null,c&&g?`Note: ${g}`:null,...x].filter(Boolean).join(`
|
|
78
|
+
`);return r.jsxs("div",{className:`rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all ${fm(a,t,s.isDark)}${ET(a)?" mesh-node-generating":""}`,style:{width:Ai(a)},title:S,children:[r.jsx(Sa,{type:"target",position:i==="TB"?Zs.Top:Zs.Left,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),r.jsxs("div",{className:"flex items-start justify-between gap-3",children:[r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("div",{className:`truncate text-sm font-semibold ${s.textPrimary}`,children:a.label}),r.jsx("div",{className:`truncate text-[11px] ${s.textMuted}`,children:p})]}),r.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 shrink-0",children:[b&&r.jsx("span",{className:`h-2 w-2 rounded-full ${s.isDark?"bg-emerald-400":"bg-emerald-500"} animate-pulse`,"aria-label":"active session"}),r.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:xm(a.health)},"aria-hidden":!0})]})]}),m?r.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${gm(m.tone,s.isDark)}`,title:m.label,children:r.jsx("span",{className:"truncate",children:m.label})}):a.branch&&!l?r.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[10px] ${qt("meta",s.isDark)}`,title:a.branch,children:r.jsx("span",{className:"truncate",children:a.branch})}):null,w&&r.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[10px] font-medium ${s.isDark?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}`,title:x.join(`
|
|
79
|
+
`),children:r.jsx("span",{className:"truncate",children:w})}),v.length>0&&r.jsx("div",{className:"mt-2 flex max-h-44 min-w-0 flex-col gap-1.5 overflow-y-auto pr-1",children:v.map(k=>{const j=Gn(k);return r.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${s.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/85"}`,title:[`Session ID: ${k.sessionId}`,k.providerType?`Provider: ${k.providerType}`:null,`Status: ${Ms(k)}`,`Role: ${j}`].filter(Boolean).join(`
|
|
80
|
+
`),children:[r.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[r.jsx("span",{className:`min-w-0 truncate text-[10px] ${s.textMuted}`,children:k.providerType||"provider unknown"}),r.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${fc(k,s.isDark)}`,children:Ms(k)})]}),r.jsxs("div",{className:`mt-0.5 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${s.textMuted}`,children:[r.jsx("span",{className:"min-w-0 truncate font-mono",children:gc(k.sessionId)}),r.jsx("span",{children:j})]})]},k.sessionId)})}),r.jsxs("div",{className:"mt-3",children:[r.jsxs("div",{className:"flex min-w-0 flex-wrap gap-1.5 text-[10px]",children:[a.health==="unknown"?r.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${qt("health",s.isDark)}`,children:"connecting..."}):r.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${qt("health",s.isDark)}`,children:MT(a.health)}),l&&r.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("submodule",s.isDark)}`,children:"submodule"}),!o&&a.health==="unknown"&&!a.locality&&r.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${qt("health",s.isDark)}`,children:"..."}),!o&&(a.health!=="unknown"||a.locality)&&r.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt(DT(a),s.isDark)}`,children:ym(a.locality)}),d&&r.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt(d.kind,s.isDark)}`,title:d.title,children:d.label}),h&&l&&r.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("meta",s.isDark)}`,children:h}),a.dirty&&r.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("dirty",s.isDark)}`,children:l?"local changes":`${a.dirtyFiles} dirty`}),a.outOfSync&&r.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("conflict",s.isDark)}`,children:"out of sync"}),a.hasConflicts&&r.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("conflict",s.isDark)}`,children:"conflicts"}),!l&&a.upstream&&a.upstreamStatus!=="fresh"&&r.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("orphan",s.isDark)}`,children:"upstream unverified"}),a.isOrphan&&r.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("orphan",s.isDark)}`,children:"needs follow-up"}),!l&&a.refineJobStatus==="completed"&&r.jsx("span",{className:`rounded-full border px-2 py-0.5 ${qt("refineDone",s.isDark)}`,title:a.refineJobBranch?`refined ${a.refineJobBranch}${a.refineJobInto?` → ${a.refineJobInto}`:""}`:"refine completed",children:"refined"})]}),r.jsx("div",{className:`mt-3 text-[11px] leading-5 ${s.textSecondary}`,style:IT,children:oo(a)}),f.length>0&&r.jsxs("div",{className:"mt-3",children:[r.jsx("div",{className:`mb-1.5 text-[9px] font-semibold uppercase tracking-[0.16em] ${s.textMuted}`,children:"Attached Chats"}),r.jsx("div",{className:"flex max-h-56 flex-col gap-1.5 overflow-y-auto pr-1",children:f.map(k=>{const j=k.startedAt||k.createdAt||null,y=Gn(k);return r.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${s.isDark?"border-white/8 bg-white/[0.035]":"border-slate-200 bg-white/80"}`,title:[`Session ID: ${k.sessionId}`,k.providerType?`Provider: ${k.providerType}`:null,`Status: ${Ms(k)}`,`Role: ${y}`,j?`Started: ${j}`:"Started: not reported",k.statusNote?`Note: ${k.statusNote}`:null].filter(Boolean).join(`
|
|
81
|
+
`),children:[r.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[r.jsx("span",{className:`min-w-0 truncate font-mono text-[10px] select-text ${s.textPrimary}`,children:gc(k.sessionId)}),r.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${fc(k,s.isDark)}`,children:Ms(k)})]}),r.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${s.textMuted}`,children:[r.jsx("span",{className:"truncate",children:k.providerType||"provider unknown"}),r.jsx("span",{children:y}),r.jsx("span",{children:bm(j)})]}),k.statusNote&&r.jsx("div",{className:`mt-1 text-[9px] leading-4 ${s.textMuted}`,children:k.statusNote})]},k.sessionId)})})]}),c&&g&&r.jsx("div",{className:`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${s.isDark?"border-cyan-400/15 bg-cyan-500/8 text-cyan-50/90":"border-sky-300 bg-sky-50 text-sky-700"}`,style:AT,children:g})]}),r.jsx(Sa,{type:"source",position:i==="TB"?Zs.Bottom:Zs.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const OT={meshNode:$T},FT=8;function BT(e){if(e.length<2)return null;if(e.length===2){const[d,p]=e;return{d:`M ${d.x},${d.y} L ${p.x},${p.y}`,labelX:(d.x+p.x)/2,labelY:(d.y+p.y)/2}}const t=FT,s=[`M ${e[0].x},${e[0].y}`];for(let d=1;d<e.length-1;d+=1){const p=e[d-1],h=e[d],m=e[d+1],g=Math.sign(h.x-p.x),b=Math.sign(h.y-p.y),f=Math.sign(m.x-h.x),v=Math.sign(m.y-h.y),w=Math.hypot(h.x-p.x,h.y-p.y),x=Math.hypot(m.x-h.x,m.y-h.y),S=Math.min(t,w/2,x/2);if(S<1||g===f&&b===v){s.push(`L ${h.x},${h.y}`);continue}const k=h.x-g*S,j=h.y-b*S,y=h.x+f*S,N=h.y+v*S;s.push(`L ${k},${j}`),s.push(`Q ${h.x},${h.y} ${y},${N}`)}const n=e[e.length-1];s.push(`L ${n.x},${n.y}`);let i=0;const a=[0];for(let d=1;d<e.length;d+=1)i+=Math.hypot(e[d].x-e[d-1].x,e[d].y-e[d-1].y),a.push(i);const o=i/2;let l=e[0].x,c=e[0].y;for(let d=1;d<e.length;d+=1)if(a[d]>=o){const p=a[d]-a[d-1],h=p===0?0:(o-a[d-1])/p;l=e[d-1].x+(e[d].x-e[d-1].x)*h,c=e[d-1].y+(e[d].y-e[d-1].y)*h;break}return{d:s.join(" "),labelX:l,labelY:c}}function WT(e){const t=e.data.routePoints;if(t&&t.length>=2){const a=BT(t);if(a)return[a.d,a.labelX,a.labelY]}const s={sourceX:e.sourceX,sourceY:e.sourceY,sourcePosition:e.sourcePosition,targetX:e.targetX,targetY:e.targetY,targetPosition:e.targetPosition},n=e.data.graphEdge;let i;return n.type==="parentBranch"?i=Rw(s):n.type==="worktreeLink"||n.type==="submoduleLink"||n.type==="cloneLink"?i=Mw(s):i=Ew(s),[i[0],i[1],i[2]]}function UT(e,t){const s="nodrag nopan rounded-md border px-2 py-1 text-[10px] font-semibold shadow-sm backdrop-blur-sm";switch(e.type){case"orphanLink":return t?`${s} border-orange-400/35 bg-orange-500/14 text-orange-100`:`${s} border-orange-300 bg-orange-50 text-orange-700`;case"submoduleLink":return t?`${s} border-violet-400/30 bg-violet-500/14 text-violet-100`:`${s} border-violet-300 bg-violet-50 text-violet-700`;case"sessionLink":return t?`${s} border-emerald-400/30 bg-emerald-500/14 text-emerald-100`:`${s} border-emerald-300 bg-emerald-50 text-emerald-700`;case"cloneLink":return t?`${s} border-teal-400/30 bg-teal-500/14 text-teal-100`:`${s} border-teal-300 bg-teal-50 text-teal-700`;case"coordinatorLink":{const n=Ru(e);return n==="direct"?t?`${s} border-emerald-400/35 bg-emerald-500/14 text-emerald-100`:`${s} border-emerald-300 bg-emerald-50 text-emerald-700`:n==="relay"?t?`${s} border-amber-400/35 bg-amber-500/14 text-amber-100`:`${s} border-amber-300 bg-amber-50 text-amber-700`:t?`${s} border-rose-400/35 bg-rose-500/14 text-rose-100`:`${s} border-rose-300 bg-rose-50 text-rose-700`}default:return t?`${s} border-sky-400/25 bg-slate-950/78 text-sky-100`:`${s} border-sky-300 bg-white/95 text-sky-700`}}function HT(e){const t=u.useContext(Eu),s=e.data.graphEdge,[n,i,a]=WT(e),o=typeof e.label=="string"?e.label:void 0;return r.jsxs(r.Fragment,{children:[r.jsx(_w,{id:e.id,path:n,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&r.jsx(Cw,{children:r.jsx("div",{className:UT(s,t.isDark),title:o,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${i}px, ${a}px)`,pointerEvents:"none",maxWidth:uT.maxWidth},children:r.jsx("span",{className:"block truncate",children:e.label})})})]})}const zT={meshEdge:HT};async function KT(e,t,s,n,i){const a=await fb(e,s,n,i);return wb(e,a,t,s)}async function GT(e,t=qr("dark"),s=!1,n="LR"){const i=await fb(e,s,n);return wb(e,i,t,s)}function wb(e,t,s,n=!1){const i=new Set(t.nodes.map(d=>d.id)),a=t.nodes.map(d=>({id:d.id,type:d.type,position:d.position,data:{graphNode:d.graphNode,compact:n},selected:d.selected,draggable:d.draggable,selectable:d.selectable})),o=e.edges.filter(d=>i.has(d.source)&&i.has(d.target)),l=XT(o),c=o.map(d=>{var p;return{id:d.id,source:d.source,target:d.target,label:l.has(d.id)?d.label:void 0,type:"meshEdge",data:{graphEdge:d,routePoints:(p=t.edgeRoutes.get(d.id))==null?void 0:p.points},animated:d.type==="orphanLink",markerEnd:d.direction==="directed"?{type:Tw.ArrowClosed,width:d.type==="submoduleLink"?16:18,height:d.type==="submoduleLink"?16:18,color:wm(d)}:void 0,style:{stroke:wm(d),strokeWidth:d.type==="orphanLink"?2.25:d.type==="submoduleLink"?1.7:d.type==="worktreeLink"?1.8:d.type==="cloneLink"?1.6:d.type==="coordinatorLink"?2.25:2,strokeDasharray:d.type==="orphanLink"?"5 4":d.type==="submoduleLink"?"4 3":d.type==="cloneLink"?"6 3":d.type==="coordinatorLink"&&Ru(d)!=="direct"?"5 4":void 0},labelStyle:{fill:s.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:s.edgeLabelBackgroundColor,fillOpacity:1,stroke:s.edgeLabelBorderColor},labelBgPadding:[6,4],labelBgBorderRadius:7}});return{nodes:a,edges:c}}const qT=3,VT=2;function vm(e){switch(e.type){case"coordinatorLink":return 6;case"orphanLink":return 5;case"parentBranch":return 4;case"submoduleLink":return 3;case"cloneLink":return 2;case"worktreeLink":return 1;case"sessionLink":return 0;default:return 0}}function XT(e){const t=new Set,s=new Map;for(const n of e){if(!n.label)continue;const i=s.get(n.source);i?i.push(n):s.set(n.source,[n])}for(const n of s.values()){if(n.length<qT){for(const a of n)t.add(a.id);continue}const i=[...n].sort((a,o)=>{const l=vm(o)-vm(a);return l!==0?l:a.id.localeCompare(o.id)});for(const a of i.slice(0,VT))t.add(a.id)}return t}function Ru(e){const t=(e.label??"").toLowerCase();return t.startsWith("direct")?"direct":t.startsWith("relay")?"relay":"down"}function wm(e){switch(e.type){case"parentBranch":return"#38bdf8";case"worktreeLink":return"#a78bfa";case"sessionLink":return"#34d399";case"orphanLink":return"#f97316";case"submoduleLink":return"#c084fc";case"cloneLink":return"#2dd4bf";case"coordinatorLink":{const t=Ru(e);return t==="direct"?"#34d399":t==="relay"?"#fbbf24":"#fb7185"}default:return"#64748b"}}function YT(e){const t=e.data.graphNode;if(t.locality==="local")return"#38bdf8";switch(t.health){case"online":return"#34d399";case"dirty":return"#fbbf24";case"degraded":case"offline":return"#fb7185";case"wrong_branch":return"#a78bfa";default:return"#94a3b8"}}function QT(e){const t=e.data.graphNode;return["mesh-minimap-node",`mesh-minimap-node--${t.type}`,`mesh-minimap-node--${t.health}`,t.isOrphan?"mesh-minimap-node--attention":null,t.dirty?"mesh-minimap-node--dirty":null,t.outOfSync?"mesh-minimap-node--out-of-sync":null].filter(Boolean).join(" ")}function JT({data:e,viewportKey:t}){const s=Iw(),n=Aw(),i=u.useRef(null),a=u.useMemo(()=>pb(e),[e]),o=u.useMemo(()=>iT(e),[e]);return u.useEffect(()=>{if(!s||e.nodes.length===0||i.current===t)return;let l=!1;const c=requestAnimationFrame(()=>{if(l)return;const d=o.length>0&&o.length<e.nodes.length;n.fitView({nodes:d?o.map(p=>({id:p})):void 0,padding:d?.24:.2,maxZoom:d?.98:.9,duration:260}),i.current=t});return()=>{l=!0,cancelAnimationFrame(c)}},[e.nodes.length,o,a,s,n,t]),null}const ZT=12;function eM(e){return e>=16?"min-h-[720px]":e>=10?"min-h-[580px]":"min-h-[460px]"}function tM({data:e,selectedNodeId:t=null,directionPref:s,onNodeClick:n,onEdgeClick:i,onNodeHoverChange:a,onEdgeHoverChange:o}){const{theme:l}=Gr(),c=u.useMemo(()=>qr(l),[l]),d=u.useMemo(()=>NT(e),[e]),p=u.useMemo(()=>_T(e),[e]),h=e.nodes.length>=CT,[m]=u.useState("LR"),g=s??m,b=u.useMemo(()=>g==="auto"?mT(e):g,[g,d,e]),f=e.nodes.length>=ZT,[v,w]=u.useState({nodes:[],edges:[]}),x=u.useRef(null),[S,k]=u.useState({width:0,height:0}),j=u.useMemo(()=>`${aT(e,S.width,S.height)}::${b}`,[d,e,S.height,S.width,b]);u.useEffect(()=>{let N=!1;return GT(e,c,h,b).then(_=>{if(N)return;w(_);const C=requestAnimationFrame(()=>{if(N)return;const D=x.current;if(!D)return;const T=new Map;for(const A of _.nodes){const P=D.querySelector(`.react-flow__node[data-id="${CSS.escape(A.id)}"]`);P&&P.offsetHeight>0&&T.set(A.id,P.offsetHeight)}T.size!==0&&KT(e,c,h,b,T).then(A=>{N||w(A)})});return()=>cancelAnimationFrame(C)}),()=>{N=!0}},[e,p,c,h,b]);const y=u.useMemo(()=>v.nodes.map(N=>({...N,selected:N.id===t})),[v.nodes,t]);return u.useEffect(()=>{const N=x.current;if(!N)return;const _=()=>{const D=Math.max(0,Math.round(N.clientWidth)),T=Math.max(0,Math.round(N.clientHeight));k(A=>A.width===D&&A.height===T?A:{width:D,height:T})};_();const C=typeof ResizeObserver=="function"?new ResizeObserver(()=>_()):null;return C==null||C.observe(N),window.addEventListener("resize",_),()=>{C==null||C.disconnect(),window.removeEventListener("resize",_)}},[]),r.jsx(Eu.Provider,{value:c,children:r.jsx(xb.Provider,{value:h,children:r.jsx(bb.Provider,{value:b,children:r.jsxs("div",{ref:x,className:`${c.graphShellClass} ${eM(e.nodes.length)}`,style:{height:"100%"},children:[r.jsx("div",{className:`pointer-events-none absolute left-1/2 top-2 z-10 -translate-x-1/2 px-3 py-1 text-[10px] ${c.graphStatChipClass}`,children:"drag or scroll to pan"}),r.jsx("div",{className:"w-full min-w-0 flex-1",style:{height:"100%"},children:r.jsxs(ww,{nodes:y,edges:v.edges,nodeTypes:OT,edgeTypes:zT,minZoom:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(N,_)=>n==null?void 0:n(_.data.graphNode),onEdgeClick:(N,_)=>{var D;const C=(D=_.data)==null?void 0:D.graphEdge;C&&(i==null||i(C))},onNodeMouseEnter:(N,_)=>a==null?void 0:a(_.data.graphNode),onNodeMouseLeave:()=>a==null?void 0:a(null),onEdgeMouseEnter:(N,_)=>{var C;return o==null?void 0:o(((C=_.data)==null?void 0:C.graphEdge)??null)},onEdgeMouseLeave:()=>o==null?void 0:o(null),className:"h-full w-full",colorMode:c.flowColorMode,proOptions:{hideAttribution:!0},children:[r.jsx(JT,{data:e,viewportKey:j}),r.jsx(Sw,{className:c.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),f&&r.jsx(kw,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:YT,nodeClassName:QT,nodeStrokeWidth:3,className:c.isDark?"overflow-hidden rounded-xl border border-white/10 bg-slate-950/85":"overflow-hidden rounded-xl border border-slate-200 bg-white/95"}),r.jsx(jw,{variant:Nw.Dots,gap:18,size:1.2,color:c.graphBackgroundDotColor})]})})]})})})})}const sM=5,rM={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function ml(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function Sb(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const s=t.toLowerCase().replace(/[\s-]+/g,"_");return s.includes("approval")?"awaiting approval":s.includes("generating")||s.includes("running")||s.includes("busy")?"generating":s.includes("idle")||s.includes("ready")||s.includes("waiting_input")?"idle":s.replace(/_/g," ")}function kb(e){return e.includes("approval")?"amber":e.includes("generating")?"sky":e.includes("idle")?"emerald":e.includes("failed")||e.includes("stopped")||e.includes("interrupted")?"rose":"muted"}function nM(e){const t=e.git;if(!t)return e.gitProbePending?"git probe pending":"no git probe";const s=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),n=[];return t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&n.push(`↑${t.ahead??0}/↓${t.behind??0}`),s>0&&n.push(`✎${s}`),t.hasConflicts&&n.push("conflicts"),n.join(" · ")||"clean"}function jb(e){switch(e){case"active":return"emerald";case"paused":return"amber";case"completed":return"sky";case"abandoned":return"rose";default:return"muted"}}function iM(e){switch(e){case"online":return"emerald";case"dirty":return"amber";case"degraded":case"offline":return"rose";case"wrong_branch":return"sky";default:return"muted"}}function Nb(e){switch(e){case"completed":return"emerald";case"failed":return"rose";case"cancelled":return"muted";case"assigned":return"sky";case"pending":return"amber";default:return"muted"}}function Sm(e){switch(e){case"assigned":return 0;case"pending":return 1;case"failed":return 2;case"completed":return 3;case"cancelled":return 4;default:return 5}}function Ns(e){if(!e)return null;const t=Date.parse(e);if(!Number.isFinite(t))return null;const s=Math.max(0,Math.floor((Date.now()-t)/1e3));if(s<60)return`${s}s ago`;const n=Math.floor(s/60);if(n<60)return`${n}m ago`;const i=Math.floor(n/60);return i<48?`${i}h ago`:`${Math.floor(i/24)}d ago`}function km(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return null;if(e<1e3)return`${Math.round(e)}ms`;const t=Math.round(e/1e3),s=t%60,n=Math.floor(t/60),i=n%60,a=Math.floor(n/60),o=[];return a>0&&o.push(`${a}h`),i>0&&o.push(`${i}m`),(s>0||o.length===0)&&o.push(`${s}s`),o.join(" ")}function Pu(e){return e.replace(/[_-]+/g," ")}function _b(e){const t=e.toLowerCase();return t.includes("fail")||t.includes("stall")||t.includes("error")?"rose":t.includes("complete")?"emerald":t.includes("dispatch")||t.includes("launch")||t.includes("assign")?"sky":t.includes("checkpoint")?"amber":"muted"}function Cb(e){if(!e)return null;const t=e.message??e.summary??e.reason??e.title;return typeof t=="string"&&t.trim()?t.trim():null}function aM({status:e}){var v,w,x,S;const{theme:t}=Gr(),s=u.useMemo(()=>qr(t),[t]),n=u.useMemo(()=>iu(e),[e]),i=((v=n.queue)==null?void 0:v.summary)??null,a=((w=n.queue)==null?void 0:w.tasks)??[],o=((x=n.ledger)==null?void 0:x.summary)??rM,l=((S=n.ledger)==null?void 0:S.entries)??[],c=n.missions??[],d=c.filter(k=>k.status==="active"||k.status==="paused"),p=c.filter(k=>k.status==="completed"||k.status==="abandoned"),h=n.asyncRefineJobs??[],[m,g]=u.useState(null),b=u.useCallback(()=>g(null),[]),f=u.useMemo(()=>{const k=[];for(const j of n.nodes){const y=j.activeSessionDetails&&j.activeSessionDetails.length>0?j.activeSessionDetails:(j.activeSessions??[]).map(N=>({sessionId:N,workspace:j.workspace,isCached:!0}));for(const N of y)k.push({node:j,session:N})}return k},[n.nodes]);return r.jsxs("div",{className:"flex flex-col gap-3 pb-2",children:[r.jsx(hM,{meshTheme:s,liveMissions:d,historyMissions:p,hasMissionField:Array.isArray(n.missions),onSelect:k=>g({kind:"mission",mission:k})}),r.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[r.jsx(mM,{meshTheme:s,ledgerSummary:o,entries:l,onSelect:k=>g({kind:"ledger",entry:k})}),r.jsx(fM,{meshTheme:s,queueSummary:i,tasks:a,onSelect:k=>g({kind:"queue",task:k})})]}),r.jsx(xM,{meshTheme:s,nodes:n.nodes}),r.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[r.jsx(bM,{meshTheme:s,entries:f,onSelect:(k,j)=>g({kind:"session",node:k,session:j})}),r.jsx(yM,{meshTheme:s,jobs:h})]}),m&&r.jsx(lM,{meshTheme:s,detail:m,onClose:b})]})}function Fr({meshTheme:e,title:t,count:s,children:n,action:i}){const a=e.isDark;return r.jsxs("div",{className:`flex min-w-0 flex-col overflow-hidden rounded-2xl border p-4 ${a?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,children:[r.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[r.jsx("span",{className:`text-[11px] font-semibold uppercase tracking-[0.14em] ${e.textSecondary}`,children:t}),s!==void 0&&r.jsx("span",{className:`tabular-nums text-[11px] ${e.textMuted}`,children:s}),i&&r.jsx("span",{className:"ml-auto",children:i})]}),n]})}function ss({meshTheme:e,label:t,tone:s}){const n=e.isDark,i=s==="rose"?n?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700":s==="sky"?n?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700":s==="amber"?n?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700":s==="emerald"?n?"border-emerald-400/25 bg-emerald-500/10 text-emerald-200":"border-emerald-300 bg-emerald-50 text-emerald-700":n?"border-white/10 bg-white/[0.04] text-slate-300":"border-slate-200 bg-slate-50 text-slate-600";return r.jsx("span",{className:`shrink-0 rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${i}`,children:t})}function Pt({meshTheme:e,label:t,value:s,tone:n}){const i=e.isDark,a=n==="rose"?i?"text-rose-300":"text-rose-600":n==="sky"?i?"text-sky-300":"text-sky-600":n==="amber"?i?"text-amber-300":"text-amber-600":n==="emerald"?i?"text-emerald-300":"text-emerald-600":n==="muted"?e.textMuted:e.textPrimary;return r.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-2 ${i?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[r.jsx("span",{className:`tabular-nums text-base font-semibold leading-none ${a}`,children:s}),r.jsx("span",{className:`mt-1 text-[9px] uppercase tracking-wide ${e.textMuted}`,children:t})]})}function ta({meshTheme:e,children:t}){return r.jsx("div",{className:`text-xs ${e.textMuted}`,children:t})}function fl({meshTheme:e,onClick:t,children:s}){const n=e.isDark,i=t?n?"hover:bg-white/[0.05]":"hover:bg-slate-100/70":"";return r.jsx("button",{type:"button",onClick:t,disabled:!t,className:`flex w-full min-w-0 items-center gap-2 overflow-hidden rounded-md px-1.5 py-1 text-left text-xs transition ${i} ${t?"cursor-pointer":"cursor-default"}`,children:s})}function gl({meshTheme:e,expanded:t,hiddenCount:s,onToggle:n}){return s<=0?null:r.jsx("button",{type:"button",onClick:n,className:`mt-1 self-start rounded-md px-1.5 py-0.5 text-[11px] font-medium ${e.textSecondary} hover:underline`,children:t?"Show fewer":`+${s} more`})}function xl(e,t=sM){const[s,n]=u.useState(!1),i=s?e:e.slice(0,t),a=Math.max(0,e.length-t),o=u.useCallback(()=>n(l=>!l),[]);return{visible:i,hiddenCount:a,expanded:s,toggle:o}}function St({meshTheme:e,label:t,value:s}){return r.jsxs("div",{className:e.rowClass,children:[r.jsx("span",{className:e.rowLabelClass,children:t}),r.jsx("span",{className:e.rowValueClass,children:s})]})}function oM(e){switch(e.kind){case"mission":return{kicker:"Mission",title:e.mission.title};case"ledger":return{kicker:"Ledger entry",title:Pu(e.entry.kind)};case"queue":return{kicker:"Queue task",title:e.task.id};case"session":return{kicker:"Session",title:ml(e.session.sessionId)}}}function lM({meshTheme:e,detail:t,onClose:s}){u.useEffect(()=>{const c=d=>{d.key==="Escape"&&s()};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[s]);const n=e.isDark,{kicker:i,title:a}=oM(t),o=n?"bg-[#030617]/[0.92]":"bg-[rgba(15,23,42,0.82)]",l=n?"border-white/10 bg-slate-950 md:bg-slate-950/98 shadow-[0_28px_120px_rgba(2,6,23,0.5)]":"border-slate-200 bg-white md:bg-white/98 shadow-[0_28px_120px_rgba(148,163,184,0.3)]";return r.jsx("div",{className:`fixed inset-0 z-[1300] flex items-stretch justify-center p-0 md:items-center md:p-4 ${o}`,role:"dialog","aria-modal":"true",onClick:s,children:r.jsxs("div",{className:`flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden border ${l} md:h-auto md:max-h-[88dvh] md:max-w-[min(640px,calc(100vw-32px))] md:rounded-2xl`,onClick:c=>c.stopPropagation(),children:[r.jsxs("div",{className:`sticky top-0 z-10 flex shrink-0 items-start justify-between gap-3 border-b px-4 py-3 ${n?"border-white/8":"border-slate-200"}`,children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:i}),r.jsx("div",{className:`mt-0.5 break-all text-sm font-semibold ${e.textPrimary}`,children:a})]}),r.jsx("button",{type:"button",onClick:s,"aria-label":"Close detail",className:n?"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white":"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",children:"✕"})]}),r.jsxs("div",{className:"min-h-0 min-w-0 flex-1 overflow-y-auto px-4 py-4",children:[t.kind==="mission"&&r.jsx(cM,{meshTheme:e,mission:t.mission}),t.kind==="ledger"&&r.jsx(dM,{meshTheme:e,entry:t.entry}),t.kind==="queue"&&r.jsx(uM,{meshTheme:e,task:t.task}),t.kind==="session"&&r.jsx(pM,{meshTheme:e,node:t.node,session:t.session})]})]})})}function cM({meshTheme:e,mission:t}){var l;const s=t.tasks,n="goal"in t&&typeof t.goal=="string"&&t.goal?t.goal:"goalPreview"in t?t.goalPreview:"",i="goalTruncated"in t?t.goalTruncated===!0:!1,a=t.stats??null,o=((l=a==null?void 0:a.incompleteTaskIds)==null?void 0:l.length)??0;return r.jsxs("div",{className:"flex flex-col gap-3",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r.jsx(ss,{meshTheme:e,label:t.status,tone:jb(t.status)}),r.jsx(ss,{meshTheme:e,label:`${s.total} tasks`,tone:"muted"})]}),n&&r.jsxs("div",{className:`max-h-64 overflow-y-auto whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:[n,i&&r.jsx("span",{className:e.textMuted,children:" … (truncated)"})]}),r.jsxs("div",{className:"grid grid-cols-3 gap-1.5 sm:grid-cols-6",children:[r.jsx(Pt,{meshTheme:e,label:"Completed",value:s.completed,tone:"emerald"}),r.jsx(Pt,{meshTheme:e,label:"Assigned",value:s.assigned,tone:s.assigned>0?"sky":void 0}),r.jsx(Pt,{meshTheme:e,label:"Pending",value:s.pending}),r.jsx(Pt,{meshTheme:e,label:"Failed",value:s.failed,tone:s.failed>0?"rose":void 0}),r.jsx(Pt,{meshTheme:e,label:"Blocked",value:s.blocked,tone:s.blocked>0?"amber":void 0}),r.jsx(Pt,{meshTheme:e,label:"Cancelled",value:s.cancelled,tone:"muted"})]}),a&&r.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[r.jsx(Pt,{meshTheme:e,label:"Wall clock",value:km(a.wallClockMs)??"—"}),r.jsx(Pt,{meshTheme:e,label:"Total runtime",value:km(a.totalDurationMs)??"—"}),r.jsx(Pt,{meshTheme:e,label:"Retries",value:a.retries,tone:a.retries>0?"amber":void 0})]}),r.jsxs("div",{className:"grid gap-1.5 text-xs",children:[r.jsx(St,{meshTheme:e,label:"Mission id",value:t.id}),r.jsx(St,{meshTheme:e,label:"Created",value:Ns(t.createdAt)??t.createdAt}),r.jsx(St,{meshTheme:e,label:"Updated",value:Ns(t.updatedAt)??t.updatedAt}),s.lastActivityAt&&r.jsx(St,{meshTheme:e,label:"Last task activity",value:Ns(s.lastActivityAt)??s.lastActivityAt}),o>0&&a&&r.jsx(St,{meshTheme:e,label:"Incomplete evidence",value:r.jsxs("details",{children:[r.jsxs("summary",{className:"cursor-pointer select-none",children:[o," task",o===1?"":"s"]}),r.jsx("div",{className:"mt-1 flex flex-col gap-0.5 break-all",children:a.incompleteTaskIds.map(c=>r.jsx("span",{className:`font-mono text-[10px] ${e.textMuted}`,children:c},c))})]})})]})]})}function dM({meshTheme:e,entry:t}){const s=Cb(t.payload);let n="";try{n=JSON.stringify(t.payload??{},null,2)}catch{n=String(t.payload)}return r.jsxs("div",{className:"flex flex-col gap-3",children:[r.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:r.jsx(ss,{meshTheme:e,label:Pu(t.kind),tone:_b(t.kind)})}),s&&r.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:s}),r.jsxs("div",{className:"grid gap-1.5 text-xs",children:[r.jsx(St,{meshTheme:e,label:"Entry id",value:t.id}),r.jsx(St,{meshTheme:e,label:"When",value:Ns(t.timestamp)??t.timestamp}),t.nodeId&&r.jsx(St,{meshTheme:e,label:"Node",value:t.nodeId}),t.sessionId&&r.jsx(St,{meshTheme:e,label:"Session",value:ml(t.sessionId)}),t.providerType&&r.jsx(St,{meshTheme:e,label:"Provider",value:t.providerType})]}),n&&n!=="{}"&&r.jsxs("div",{children:[r.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:"Payload"}),r.jsx("pre",{className:`max-h-60 max-w-full overflow-auto rounded-lg border p-2 text-[10px] leading-4 ${e.isDark?"border-white/8 bg-black/30 text-slate-300":"border-slate-200 bg-slate-50 text-slate-700"}`,children:n})]})]})}function uM({meshTheme:e,task:t}){return r.jsxs("div",{className:"flex flex-col gap-3",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r.jsx(ss,{meshTheme:e,label:t.status,tone:Nb(t.status)}),(t.requeueCount??0)>0&&r.jsx(ss,{meshTheme:e,label:`requeued ${t.requeueCount}`,tone:"amber"})]}),t.message&&r.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:t.message}),r.jsxs("div",{className:"grid gap-1.5 text-xs",children:[r.jsx(St,{meshTheme:e,label:"Task id",value:t.id}),r.jsx(St,{meshTheme:e,label:"Created",value:Ns(t.createdAt)??t.createdAt}),r.jsx(St,{meshTheme:e,label:"Updated",value:Ns(t.updatedAt)??t.updatedAt}),(t.assignedNodeId||t.targetNodeId)&&r.jsx(St,{meshTheme:e,label:"Node",value:t.assignedNodeId||t.targetNodeId}),(t.assignedSessionId||t.targetSessionId)&&r.jsx(St,{meshTheme:e,label:"Session",value:ml(t.assignedSessionId||t.targetSessionId)}),t.cancelReason&&r.jsx(St,{meshTheme:e,label:"Cancel reason",value:t.cancelReason}),t.requeueReason&&r.jsx(St,{meshTheme:e,label:"Requeue reason",value:t.requeueReason}),t.autoLaunch&&r.jsx(St,{meshTheme:e,label:"Auto launch",value:`${t.autoLaunch.status}${t.autoLaunch.reason?` · ${t.autoLaunch.reason}`:""}`})]})]})}function pM({meshTheme:e,node:t,session:s}){var i,a;const n=Sb(s);return r.jsxs("div",{className:"flex flex-col gap-3",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r.jsx(ss,{meshTheme:e,label:n,tone:kb(n)}),r.jsx(ss,{meshTheme:e,label:s.providerType||"provider unknown",tone:"muted"})]}),s.statusNote&&r.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:s.statusNote}),r.jsxs("div",{className:"grid gap-1.5 text-xs",children:[r.jsx(St,{meshTheme:e,label:"Session id",value:s.sessionId}),r.jsx(St,{meshTheme:e,label:"Node",value:t.machineLabel}),r.jsx(St,{meshTheme:e,label:"Workspace",value:s.workspace||t.workspace}),(((i=t.git)==null?void 0:i.branch)??t.worktreeBranch)&&r.jsx(St,{meshTheme:e,label:"Branch",value:((a=t.git)==null?void 0:a.branch)??t.worktreeBranch}),typeof s.role=="string"&&s.role&&r.jsx(St,{meshTheme:e,label:"Role",value:s.role}),(s.startedAt||s.createdAt)&&r.jsx(St,{meshTheme:e,label:"Started",value:Ns(s.startedAt||s.createdAt)??(s.startedAt||s.createdAt)})]})]})}function jm({meshTheme:e,mission:t,onSelect:s}){const n=t.tasks,i=Ns(n.lastActivityAt);return r.jsxs(fl,{meshTheme:e,onClick:s,children:[r.jsx(ss,{meshTheme:e,label:t.status,tone:jb(t.status)}),r.jsx("span",{className:`min-w-0 flex-1 truncate font-medium ${e.textPrimary}`,children:t.title}),r.jsxs("span",{className:`shrink-0 tabular-nums text-[11px] ${e.textMuted}`,children:["✓",n.completed,"/",n.total]}),i&&r.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:i})]})}function hM({meshTheme:e,liveMissions:t,historyMissions:s,hasMissionField:n,onSelect:i}){const[a,o]=u.useState(!1),l=e.isDark,c=xl(t);return r.jsxs(Fr,{meshTheme:e,title:"Missions",count:t.length||void 0,children:[t.length>0?r.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.visible.map(d=>r.jsx(jm,{meshTheme:e,mission:d,onSelect:()=>i(d)},d.id)),r.jsx(gl,{meshTheme:e,expanded:c.expanded,hiddenCount:c.hiddenCount,onToggle:c.toggle})]}):r.jsx(ta,{meshTheme:e,children:n?"No active missions. The coordinator creates a mission for multi-task work.":"Mission data unavailable from this daemon — update the daemon to see missions."}),s.length>0&&r.jsxs("div",{className:`mt-3 border-t pt-2 ${l?"border-white/8":"border-slate-200"}`,children:[r.jsxs("button",{type:"button",onClick:()=>o(d=>!d),className:`flex w-full items-center gap-1.5 text-[11px] font-medium ${e.textSecondary}`,children:[r.jsx("span",{className:`inline-block transition-transform ${a?"rotate-90":""}`,children:"▸"}),r.jsx("span",{children:"Completed / abandoned history"}),r.jsx("span",{className:`tabular-nums ${e.textMuted}`,children:s.length})]}),a&&r.jsx("div",{className:"mt-2 flex flex-col gap-0.5",children:s.map(d=>r.jsx(jm,{meshTheme:e,mission:d,onSelect:()=>i(d)},d.id))})]})]})}function mM({meshTheme:e,ledgerSummary:t,entries:s,onSelect:n}){const i=Ns(t.lastActivityAt),a=u.useMemo(()=>[...s].reverse(),[s]),o=xl(a);return r.jsxs(Fr,{meshTheme:e,title:"Ledger",children:[r.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[r.jsx(Pt,{meshTheme:e,label:"Dispatched",value:t.taskDispatched}),r.jsx(Pt,{meshTheme:e,label:"Completed",value:t.taskCompleted,tone:"emerald"}),r.jsx(Pt,{meshTheme:e,label:"Failed",value:t.taskFailed,tone:t.taskFailed>0?"rose":void 0}),r.jsx(Pt,{meshTheme:e,label:"Stalled",value:t.taskStalled,tone:t.taskStalled>0?"amber":void 0}),r.jsx(Pt,{meshTheme:e,label:"Sessions",value:t.sessionLaunched}),r.jsx(Pt,{meshTheme:e,label:"Checkpoints",value:t.checkpointCreated})]}),a.length>0&&r.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[r.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:"Recent activity"}),r.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.visible.map(l=>{const c=Cb(l.payload);return r.jsxs(fl,{meshTheme:e,onClick:()=>n(l),children:[r.jsx(ss,{meshTheme:e,label:Pu(l.kind),tone:_b(l.kind)}),r.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,children:c||l.nodeId||l.sessionId||"—"}),r.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:Ns(l.timestamp)??""})]},l.id)}),r.jsx(gl,{meshTheme:e,expanded:o.expanded,hiddenCount:o.hiddenCount,onToggle:o.toggle})]})]}),(t.recentFailures>0||i&&a.length===0)&&r.jsxs("div",{className:`mt-2 flex items-center justify-between text-[11px] ${e.textMuted}`,children:[t.recentFailures>0?r.jsxs("span",{className:e.isDark?"text-amber-300":"text-amber-600",children:[t.recentFailures," recent failures"]}):r.jsx("span",{}),i&&a.length===0&&r.jsx("span",{children:i})]})]})}function fM({meshTheme:e,queueSummary:t,tasks:s,onSelect:n}){const i=u.useMemo(()=>[...s].sort((o,l)=>{const c=Sm(o.status)-Sm(l.status);return c!==0?c:(l.updatedAt||"").localeCompare(o.updatedAt||"")}),[s]),a=xl(i);return t?r.jsxs(Fr,{meshTheme:e,title:"Queue",count:t.active>0?`${t.active} active`:void 0,children:[r.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[r.jsx(Pt,{meshTheme:e,label:"Pending",value:t.pending}),r.jsx(Pt,{meshTheme:e,label:"Assigned",value:t.assigned,tone:t.assigned>0?"sky":void 0}),r.jsx(Pt,{meshTheme:e,label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),r.jsx(Pt,{meshTheme:e,label:"Completed",value:t.completed,tone:"emerald"}),r.jsx(Pt,{meshTheme:e,label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0}),r.jsx(Pt,{meshTheme:e,label:"Cancelled",value:t.cancelled,tone:"muted"})]}),i.length>0&&r.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[r.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:"Recent tasks"}),r.jsxs("div",{className:"flex flex-col gap-0.5",children:[a.visible.map(o=>r.jsxs(fl,{meshTheme:e,onClick:()=>n(o),children:[r.jsx(ss,{meshTheme:e,label:o.status,tone:Nb(o.status)}),r.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,children:o.message||o.id}),r.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:Ns(o.updatedAt)??""})]},o.id)),r.jsx(gl,{meshTheme:e,expanded:a.expanded,hiddenCount:a.hiddenCount,onToggle:a.toggle})]})]})]}):r.jsx(Fr,{meshTheme:e,title:"Queue",children:r.jsx(ta,{meshTheme:e,children:"No queue activity."})})}function gM(e){return e.autoFastForwardEligible||e.suggestedAction==="auto_fast_forward"?{label:"fast-forward",tone:"sky"}:e.launchBlockedReason?{label:"blocked",tone:"rose"}:null}function xM({meshTheme:e,nodes:t}){const s=e.isDark;return r.jsx(Fr,{meshTheme:e,title:"Nodes",count:t.length,children:t.length===0?r.jsx(ta,{meshTheme:e,children:"No nodes in this mesh yet."}):r.jsx("div",{className:"flex flex-col gap-1.5",children:t.map(n=>{var l,c,d;const i=(((l=n.activeSessionDetails)==null?void 0:l.length)??0)||(((c=n.activeSessions)==null?void 0:c.length)??0),a=gM(n),o=((d=n.git)==null?void 0:d.branch)??n.worktreeBranch??null;return r.jsxs("div",{className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 overflow-hidden rounded-xl border px-3 py-2 ${s?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[r.jsx(ss,{meshTheme:e,label:n.health,tone:iM(n.health)}),r.jsx("span",{className:`min-w-0 max-w-full flex-1 truncate text-sm font-medium ${e.textPrimary}`,title:n.workspace,children:n.machineLabel}),o&&r.jsx("span",{className:`max-w-full truncate font-mono text-[11px] ${e.textSecondary}`,title:o,children:o}),r.jsx("span",{className:`max-w-full truncate font-mono text-[10px] ${e.textMuted}`,children:nM(n)}),i>0&&r.jsxs("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:[i," session",i>1?"s":""]}),a&&r.jsx(ss,{meshTheme:e,label:a.label,tone:a.tone})]},n.nodeId)})})})}function bM({meshTheme:e,entries:t,onSelect:s}){const n=xl(t);return r.jsx(Fr,{meshTheme:e,title:"Active sessions",count:t.length||void 0,children:t.length===0?r.jsx(ta,{meshTheme:e,children:"No active sessions."}):r.jsxs("div",{className:"flex flex-col gap-0.5",children:[n.visible.map(({node:i,session:a})=>{const o=Sb(a);return r.jsxs(fl,{meshTheme:e,onClick:()=>s(i,a),children:[r.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:ml(a.sessionId)}),r.jsx("span",{className:`shrink-0 ${e.textMuted}`,children:a.providerType||"?"}),r.jsx(ss,{meshTheme:e,label:o,tone:kb(o)})]},a.sessionId)}),r.jsx(gl,{meshTheme:e,expanded:n.expanded,hiddenCount:n.hiddenCount,onToggle:n.toggle})]})})}function yM({meshTheme:e,jobs:t}){const s=e.isDark,n=t.filter(i=>i.status==="failed").length;return r.jsx(Fr,{meshTheme:e,title:"Refine jobs",count:t.length||void 0,action:n>0?r.jsx(ss,{meshTheme:e,label:`${n} failed`,tone:"rose"}):void 0,children:t.length===0?r.jsx(ta,{meshTheme:e,children:"No refine jobs."}):r.jsx("div",{className:"flex flex-col gap-1",children:t.slice(0,8).map(i=>r.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[r.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:[i.branch??i.jobId.slice(0,14),i.into?` → ${i.into}`:""]}),r.jsx("span",{className:`shrink-0 text-[10px] font-semibold ${i.status==="failed"?s?"text-rose-300":"text-rose-600":i.status==="running"||i.status==="accepted"?s?"text-sky-300":"text-sky-600":s?"text-emerald-300":"text-emerald-600"}`,children:i.status})]},i.jobId))})})}const vM=[{term:"Node",summary:"A workspace participating in the mesh — a repo checkout or an isolated git worktree.",details:["Base node vs worktree clone node — a clone isolates parallel work without conflicts.","Shows health (online/offline) alongside git state (branch · ahead/behind · dirty).","Multiple nodes can share the same daemon."]},{term:"P2P connection",summary:"How the selected coordinator reaches each remote node over WebRTC.",details:["direct (green) — a direct host/STUN path; lowest latency.","relay (amber, dashed link) — TURN-relayed; works through restrictive networks but is slower.","disconnected / failed (red) — no live P2P link from the coordinator right now.","The coordinator→node link edge and the node chip both carry the transport (and RTT when measured)."]},{term:"Session",summary:"An agent CLI session running on a node.",details:["status = idle / generating / waiting_approval.","Distinguishes coordinator sessions (which dispatch and collect work) from delegated worker sessions (which do the work)."]},{term:"Task",summary:"A single unit of work handled by the queue-based pull model.",details:["States: pending → assigned → completed / failed / cancelled.","Idle nodes claim from the queue automatically; direct dispatch targets a specific session."]},{term:"Mission",summary:"A multi-task batch aimed at one goal, and the durable record of that effort.",details:["States: active / paused / completed / abandoned.","Progress is derived from the states of its member tasks."]},{term:"Refinery (refine)",summary:"The process of safely converging and merging a worktree branch into the base.",details:["Config-driven (.adhdev/refine.*) — guarded by a patch-equivalence preflight and a no-op guard.","ff-only by principle; no force-push.","If a submodule commit is unreachable from origin it must be published → classified as blocked_review."]},{term:"Completion model",summary:"Completion of delegated work is persisted to the queue (pending-events).",details:["The coordinator learns of completion via periodic polling or events.","Because it is persisted to the queue, completion signals are never lost."]},{term:"Branch convergence states",summary:"After worktree work, each branch is classified into exactly one final state.",details:["merged_to_main — merged into the base.","pushed_feature_branch_needs_merge — pushed, awaiting merge.","blocked_review — held back by review/reachability issues.","cleanup_candidate — ready to clean up.","not_mergeable — cannot be merged."]}];function wM({meshTheme:e,open:t,onToggle:s}){const n=e.isDark,i="inline-flex h-7 w-7 items-center justify-center rounded-lg border transition",a=t?n?"border-sky-400/40 bg-sky-500/15 text-sky-100":"border-sky-400 bg-sky-100 text-sky-800":n?"border-white/10 bg-white/[0.04] text-slate-400 hover:bg-white/[0.08] hover:text-slate-100":"border-slate-200 bg-white text-slate-400 hover:bg-slate-50 hover:text-slate-700";return r.jsx("button",{type:"button",onClick:s,"aria-label":"Mesh help","aria-expanded":t,title:"Mesh concept help",className:`${i} ${a}`,children:r.jsx(TS,{size:15})})}function SM({meshTheme:e,onClose:t}){const s=e.isDark;return u.useEffect(()=>{const n=i=>{i.key==="Escape"&&t()};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[t]),r.jsxs("div",{className:`shrink-0 rounded-2xl border p-4 ${s?"border-white/10 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,role:"region","aria-label":"Mesh concept help",children:[r.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:"Help"}),r.jsx("div",{className:`mt-0.5 text-sm font-semibold ${e.textPrimary}`,children:"Mesh concepts at a glance"})]}),r.jsx("button",{type:"button",onClick:t,"aria-label":"Close help",className:s?"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white":"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",children:r.jsx(Ot,{size:14})})]}),r.jsx("dl",{className:"grid gap-3 sm:grid-cols-2",children:vM.map(n=>r.jsxs("div",{className:`rounded-xl border p-3 ${s?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[r.jsx("dt",{className:`text-xs font-semibold ${e.textPrimary}`,children:n.term}),r.jsx("dd",{className:`mt-1 text-[11px] leading-5 ${e.textSecondary}`,children:n.summary}),n.details&&n.details.length>0&&r.jsx("ul",{className:`mt-1.5 flex flex-col gap-1 text-[11px] leading-5 ${e.textMuted}`,children:n.details.map((i,a)=>r.jsxs("li",{className:"flex gap-1.5",children:[r.jsx("span",{"aria-hidden":!0,className:"select-none",children:"·"}),r.jsx("span",{className:"min-w-0",children:i})]},a))})]},n.term))})]})}const kM={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0},Du=u.createContext(qr("dark"));function et({label:e,tone:t="default"}){const s=u.useContext(Du);return r.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${s.badge(t)}`,children:e})}function Ht({label:e,value:t}){const s=u.useContext(Du);return r.jsxs("div",{className:s.rowClass,children:[r.jsx("span",{className:s.rowLabelClass,children:e}),r.jsx("span",{className:s.rowValueClass,children:t})]})}function jM(e){switch(e){case"online":return"good";case"dirty":return"warn";case"degraded":case"offline":return"danger";case"wrong_branch":return"info";default:return"default"}}function xc(e){switch((e||"").toLowerCase()){case"idle":return"good";case"generating":case"running":return"info";case"waiting_approval":case"starting":case"pending":return"warn";case"failed":case"stopped":case"interrupted":return"danger";default:return"default"}}function lo(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const s=t.toLowerCase().replace(/[\s-]+/g,"_");return s.includes("approval")?"awaiting approval":s.includes("generating")||s.includes("running")||s.includes("busy")?"generating":s.includes("idle")||s.includes("ready")||s.includes("waiting_input")?"idle":s.replace(/_/g," ")}function NM(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function _M(e){return e.startedAt||e.createdAt||null}function CM(e){const t=_M(e);if(!t)return"runtime age not reported";const s=Date.parse(t);if(!Number.isFinite(s))return"runtime age not reported";const n=Math.max(0,Math.floor((Date.now()-s)/1e3));if(n<60)return`${n}s`;const i=Math.floor(n/60);if(i<60)return`${i}m`;const a=Math.floor(i/60);return a<48?`${a}h ${i%60}m`:`${Math.floor(a/24)}d ${a%24}h`}function Ib(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function IM(e){if(!e)return"default";if(e.state==="self")return"info";if(e.transport==="direct"&&e.state==="connected")return"good";if(e.transport==="relay"&&e.state==="connected")return"info";switch(e.state){case"connected":return"good";case"connecting":return"warn";case"disconnected":case"failed":case"closed":return"danger";default:return"default"}}function AM(e){return e?e.state==="self"?"mesh self":e.transport==="direct"&&e.state==="connected"?"mesh direct":e.transport==="relay"&&e.state==="connected"?"mesh relay":!e.reported&&e.source==="not_reported"?"mesh unknown / not reported":`mesh ${e.state}`:"mesh unknown"}function TM(e){var s;const t=[];for(const n of e.nodes){const i=n.activeSessionDetails&&n.activeSessionDetails.length>0?n.activeSessionDetails:(n.activeSessions??[]).map(a=>({sessionId:a,workspace:n.workspace,isCached:!0}));for(const a of i)t.push({nodeId:n.nodeId,machineLabel:n.machineLabel,workspace:n.workspace,branch:((s=n.git)==null?void 0:s.branch)??null,nodeHealth:n.health,session:a})}return t}function MM(e){return e.assignedNodeId||e.targetNodeId||null}function Nm(e){return e?e.slice(0,7):null}function EM(e,t){var a,o,l;const s=Nm((a=e==null?void 0:e.git)==null?void 0:a.headCommit),n=((l=(o=e==null?void 0:e.git)==null?void 0:o.headMessage)==null?void 0:l.trim())||"";if(s||n)return[s,n].filter(Boolean).join(" · ");const i=t[0];return i?[Nm(i.commit),i.message].filter(Boolean).join(" · "):null}function RM(e,t){const s=EM(e,t);return s||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function PM(e){const t=(e==null?void 0:e.result)??e,s=(t==null?void 0:t.log)??(e==null?void 0:e.log)??t;return Array.isArray(s==null?void 0:s.entries)?s.entries:[]}function DM(e){var s,n,i,a,o,l;const t=((s=e.selectedSessionEntry)==null?void 0:s.session.workspace)||((n=e.selectedSessionEntry)==null?void 0:n.workspace)||((a=(i=e.selectedNodeStatus)==null?void 0:i.git)==null?void 0:a.workspace)||((o=e.selectedNodeStatus)==null?void 0:o.workspace)||null;if(t&&e.selectedSessionEntry){const c=((l=e.selectedNodeStatus)==null?void 0:l.daemonId)||e.coordinatorDaemonId;return c?{daemonId:c,workspace:t}:null}if(t&&e.selectedNodeStatus){const c=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return c?{daemonId:c,workspace:t}:null}return null}function LM(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":AM(e.connection)}function $M(e){var s;const t=e.source;return t!=null&&t.kind?t.kind:((s=t==null?void 0:t.connection)==null?void 0:s.source)??"mesh_status"}function _m(e){switch(e.type){case"parentBranch":return"default branch link";case"worktreeLink":return"worktree relationship";case"sessionLink":return"session relationship";case"orphanLink":return"orphan relationship";case"submoduleLink":return"submodule relationship";case"cloneLink":return"clone relationship";default:return e.type}}function OM(e){return e.direction==="directed"?"directed":"undirected"}function FM(e,t){return t?e.nodes.find(s=>s.id===t)??null:null}function BM(e){var t,s,n,i;return[e.meshId,e.refreshedAt,e.nodes.length,((s=(t=e.queue)==null?void 0:t.summary)==null?void 0:s.active)??"",((i=(n=e.ledger)==null?void 0:n.summary)==null?void 0:i.recentFailures)??"",...e.nodes.map(a=>{var o,l,c,d,p,h,m,g,b,f,v,w,x,S,k,j,y,N,_,C,D,T;return[a.nodeId,a.daemonId??"",a.machineId??"",a.machineLabel,a.machineStatus??"",((o=a.connection)==null?void 0:o.state)??"",((l=a.connection)==null?void 0:l.transport)??"",((c=a.connection)==null?void 0:c.source)??"",a.health,a.gitProbePending?1:0,((d=a.git)==null?void 0:d.branch)??"",((p=a.git)==null?void 0:p.upstream)??"",((h=a.git)==null?void 0:h.upstreamStatus)??"",((m=a.git)==null?void 0:m.ahead)??"",((g=a.git)==null?void 0:g.behind)??"",((b=a.git)==null?void 0:b.headCommit)??"",((f=a.git)==null?void 0:f.staged)??"",((v=a.git)==null?void 0:v.modified)??"",((w=a.git)==null?void 0:w.untracked)??"",((x=a.git)==null?void 0:x.deleted)??"",((S=a.git)==null?void 0:S.renamed)??"",(k=a.git)!=null&&k.hasConflicts?1:0,((j=a.git)==null?void 0:j.lastCheckedAt)??"",((y=a.activeSessions)==null?void 0:y.join(","))??"",((N=a.activeSessionDetails)==null?void 0:N.length)??"",((_=a.activeSessionDetails)==null?void 0:_.map(A=>[A.sessionId,A.providerType??"",A.state??"",A.chatStatus??"",A.lifecycle??"",A.role??"",A.isSelfCoordinator?1:0,A.statusNote??"",A.startedAt??"",A.createdAt??""].join("/")).join(","))??"",((C=a.providers)==null?void 0:C.join(","))??"",((D=a.providerPriority)==null?void 0:D.join(","))??"",a.error??"",(((T=a.git)==null?void 0:T.submodules)??[]).map(A=>[A.path,A.commit,A.dirty?1:0,A.outOfSync?1:0,A.error??""].join("/")).join(",")].join("|")})].join("::")}function WM({canonicalStatus:e,queueSummary:t,ledgerSummary:s,isBootstrapMode:n,meshTheme:i,sessionEntries:a,inlineMode:o=!1}){var j;const l=t&&(t.active>0||t.historical>0),c=s.recentFailures>0||s.taskFailed>0,d=(j=e.queue)!=null&&j.tasks?e.queue.tasks.filter(y=>y.status==="failed"||y.status==="cancelled").slice(0,5):[],p=e.asyncRefineJobs,h=(p==null?void 0:p.filter(y=>y.status==="running"||y.status==="accepted"))??[],m=(p==null?void 0:p.filter(y=>y.status==="failed"))??[],g=e.staleDirectWorkSummary,b=g&&g.count>0;if(!l&&!c&&e.nodes.length===0&&!n&&h.length===0&&m.length===0&&!b&&a.length===0)return null;const f=i.isDark,v=`border-t ${f?"border-white/8":"border-slate-200"}`,w=`group w-full rounded-lg border text-xs ${f?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,x=`flex cursor-pointer list-none items-center gap-1.5 px-2.5 py-1.5 [&::-webkit-details-marker]:hidden ${i.textSecondary}`;function S({label:y,value:N,tone:_}){const C=_==="rose"?f?"text-rose-300":"text-rose-600":_==="sky"?f?"text-sky-300":"text-sky-600":_==="amber"?f?"text-amber-300":"text-amber-600":_==="emerald"?f?"text-emerald-300":"text-emerald-600":_==="muted"?i.textMuted:i.textPrimary;return r.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-1.5 ${f?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[r.jsx("span",{className:`tabular-nums text-sm font-semibold leading-none ${C}`,children:N}),r.jsx("span",{className:`mt-0.5 text-[9px] uppercase tracking-wide ${i.textMuted}`,children:y})]})}const k=r.jsxs("div",{className:"flex flex-col gap-3 text-xs",children:[r.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t?r.jsxs(r.Fragment,{children:[r.jsx(S,{label:"Pending",value:t.pending}),r.jsx(S,{label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),r.jsx(S,{label:"Done",value:t.completed,tone:"emerald"}),r.jsx(S,{label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0})]}):r.jsxs(r.Fragment,{children:[r.jsx(S,{label:"Done",value:s.taskCompleted,tone:"emerald"}),r.jsx(S,{label:"Failed",value:s.taskFailed,tone:s.taskFailed>0?"rose":void 0}),r.jsx(S,{label:"Sessions",value:s.sessionLaunched}),r.jsx(S,{label:"Recent↯",value:s.recentFailures,tone:s.recentFailures>0?"amber":"muted"})]})}),t&&r.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[r.jsx(S,{label:"Ledger done",value:s.taskCompleted,tone:"emerald"}),r.jsx(S,{label:"Sessions",value:s.sessionLaunched}),r.jsx(S,{label:"Recent↯",value:s.recentFailures,tone:s.recentFailures>0?"amber":"muted"})]}),s.lastActivityAt&&r.jsxs("div",{className:`flex items-center justify-between ${i.textMuted}`,children:[r.jsx("span",{children:"Last activity"}),r.jsx("span",{className:"font-mono text-[10px]",children:s.lastActivityAt.slice(5,16)})]}),e.nodes.length>0&&r.jsx("div",{className:`pt-2.5 ${v}`,children:r.jsx("div",{className:"flex flex-col gap-1",children:e.nodes.map(y=>{var A;const N=((A=y.connection)==null?void 0:A.state)??"unknown",_=N==="unknown"||N==="connecting",T=_?"bg-amber-400":N==="failed"||N==="closed"||N==="disconnected"?f?"bg-rose-400":"bg-rose-500":N==="connected"||N==="self"?f?"bg-emerald-400":"bg-emerald-500":f?"bg-slate-500":"bg-slate-400";return r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:`size-1.5 shrink-0 rounded-full ${T}`}),r.jsx("span",{className:`min-w-0 flex-1 truncate ${i.textSecondary}`,title:y.workspace,children:y.machineLabel}),r.jsx("span",{className:`shrink-0 font-mono text-[10px] ${i.textMuted}`,children:_?"…":N})]},y.nodeId)})})}),p&&p.length>0&&r.jsx("div",{className:`pt-2.5 ${v}`,children:r.jsxs("details",{className:w,children:[r.jsxs("summary",{className:x,children:[r.jsx("span",{className:"flex-1",children:"Refine jobs"}),r.jsx("span",{className:`tabular-nums ${f?"text-slate-400":"text-slate-500"}`,children:p.length}),m.length>0&&r.jsxs("span",{className:f?"text-rose-300":"text-rose-600",children:[m.length," failed"]})]}),r.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:p.slice(0,8).map(y=>r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${i.textMuted}`,children:[y.branch??y.jobId.slice(0,14),y.into?` → ${y.into}`:""]}),r.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${y.status==="failed"?f?"text-rose-300":"text-rose-600":y.status==="running"||y.status==="accepted"?f?"text-sky-300":"text-sky-600":f?"text-emerald-300":"text-emerald-600"}`,children:y.status})]},y.jobId))})]})}),d.length>0&&r.jsx("div",{className:p&&p.length>0?"":`pt-2.5 ${v}`,children:r.jsxs("details",{className:w,children:[r.jsxs("summary",{className:x,children:[r.jsx("span",{className:`flex-1 ${f?"text-rose-300":"text-rose-600"}`,children:"Failed tasks"}),r.jsx("span",{className:`tabular-nums ${f?"text-rose-400":"text-rose-500"}`,children:d.length})]}),r.jsx("div",{className:"flex flex-col gap-1 px-2.5 pb-2",children:d.map(y=>r.jsxs("div",{className:"flex flex-col gap-0.5",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:`font-mono text-[10px] ${i.textMuted}`,children:y.id.slice(0,10)}),y.message&&r.jsx("span",{className:`flex-1 truncate ${f?"text-slate-300":"text-slate-700"}`,children:y.message.slice(0,55)})]}),y.cancelReason&&r.jsx("div",{className:`truncate text-[10px] ${i.textMuted}`,children:y.cancelReason.slice(0,55)})]},y.id))})]})}),b&&r.jsxs("div",{className:`flex items-center justify-between pt-2.5 ${v}`,children:[r.jsx("span",{className:i.textMuted,children:"Stale work"}),r.jsx("span",{className:`tabular-nums ${f?"text-amber-300":"text-amber-600"}`,children:g.count})]}),a.length>0&&r.jsx("div",{className:`pt-2.5 ${v}`,children:r.jsxs("details",{className:w,children:[r.jsxs("summary",{className:x,children:[r.jsx("span",{className:"flex-1",children:"Sessions"}),r.jsx("span",{className:`tabular-nums ${f?"text-slate-400":"text-slate-500"}`,children:a.length})]}),r.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:a.map(y=>r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${i.textMuted}`,title:y.session.sessionId,children:Ib(y.session.sessionId)}),r.jsx("span",{className:`shrink-0 ${i.textMuted}`,children:y.session.providerType||"?"}),r.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${i.textMuted}`,children:lo(y.session)})]},y.session.sessionId))})]})})]});return o?k:r.jsxs("details",{className:`rounded-2xl border text-xs ${i.isDark?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[r.jsxs("summary",{className:`flex cursor-pointer list-none items-center gap-2 px-4 py-3 font-medium [&::-webkit-details-marker]:hidden ${i.textSecondary}`,children:[r.jsx("span",{className:"flex-1",children:"Mesh Health Panel"}),h.length>0&&r.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${i.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700"}`,children:[h.length," refining"]}),m.length>0&&r.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${i.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[m.length," refine failed"]}),c&&r.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${i.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[s.recentFailures," recent failures"]}),n&&r.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${i.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:"awaiting live data"})]}),k]})}function UM(e){return e.nodes.length===0?!1:e.nodes.every(t=>t.health==="unknown"&&(!t.connection||t.connection.state==="unknown"))}function Ab({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:s=null,sendDaemonCommand:n=null,bootstrapFallback:i}){var ue,ce,L,de;const{theme:a}=Gr(),o=u.useMemo(()=>qr(a),[a]),l=i??UM(e),c=u.useMemo(()=>iu(e),[e]),d=u.useMemo(()=>BM(c),[c]),p=u.useMemo(()=>cb(c),[d]),[h,m]=u.useState("overview"),[g,b]=u.useState(!1),[f,v]=u.useState(!1),[w,x]=u.useState(null),[S,k]=u.useState(null),[j,y]=u.useState(null),[N,_]=u.useState({}),[C,D]=u.useState(null),[T,A]=u.useState(null),P=u.useMemo(()=>new Map(c.nodes.map(U=>[U.nodeId,U])),[c.nodes]),F=u.useMemo(()=>new Map(p.nodes.map(U=>[U.id,U])),[p.nodes]),J=((ue=c.queue)==null?void 0:ue.summary)??null,R=((ce=c.ledger)==null?void 0:ce.summary)??kM,I=u.useMemo(()=>TM(c),[c]),E=u.useMemo(()=>{const U=new Map;for(const ie of I){const Y=lo(ie.session);U.set(Y,(U.get(Y)??0)+1)}return[...U.entries()].sort((ie,Y)=>Y[1]-ie[1])},[I]);u.useEffect(()=>{w&&(F.has(w)||(x(null),y(U=>!U||"nodeId"in U&&U.nodeId===w?null:U)))},[F,w]);const $=w?P.get(w)??null:null,M=FM(p,w),O=(j==null?void 0:j.kind)==="edge"&&S?p.edges.find(U=>U.id===S)??null:null,H=O?p.nodes.find(U=>U.id===O.source)??null:null,ae=O?p.nodes.find(U=>U.id===O.target)??null:null;u.useEffect(()=>{var U,ie,Y;if(w)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:c.meshId,selectedNodeId:w,canonicalNode:Xj($),graphNode:M?{id:M.id,branch:M.branch,upstream:M.upstream,headCommit:M.submoduleCommit,submoduleCount:((ie=(U=$==null?void 0:$.git)==null?void 0:U.submodules)==null?void 0:ie.length)??0,snapshotCompleteness:M.snapshotCompleteness,snapshotWarnings:M.snapshotWarnings,branchConvergence:((Y=M.branchConvergence)==null?void 0:Y.status)??null}:null})}catch{}},[c.meshId,M,w,$]);const z=(j==null?void 0:j.kind)==="session"?I.find(U=>U.nodeId===j.nodeId&&U.session.sessionId===j.sessionId)??null:null,X=u.useMemo(()=>I.filter(U=>U.nodeId===w),[w,I]),te=DM({coordinatorDaemonId:s,selectedNodeStatus:$,selectedSessionEntry:z}),he=(te==null?void 0:te.workspace)??null,ke=he?N[he]??null:null,Q=RM($,(ke==null?void 0:ke.entries)??[]),q=(M==null?void 0:M.daemonId)??($==null?void 0:$.daemonId)??s??null,me=!!(M&&n&&q&&M.type!=="submoduleNode"&&M.behind>0&&M.ahead===0&&M.dirtyFiles===0&&!M.dirty&&!M.hasConflicts&&M.upstreamStatus==="fresh"),we=u.useCallback(()=>{x(null),k(null),y(null),D(null)},[]);u.useEffect(()=>{D(null)},[w]);const ye=u.useCallback(async()=>{if(!M||!q||!n||!me)return;A(M.id),D(null);const U=($==null?void 0:$.workspace)??M.workspace??"";try{const ie=await n(q,"fast_forward_mesh_node",{meshId:c.meshId,nodeId:M.id,workspace:U,updateSubmodules:!0,dryRun:!0,execute:!1}),Y=(ie==null?void 0:ie.result)??ie;if(D({phase:"dry_run",code:typeof(Y==null?void 0:Y.code)=="string"?Y.code:void 0,error:typeof(Y==null?void 0:Y.operationError)=="string"?Y.operationError:null,executed:(Y==null?void 0:Y.executed)===!0}),!(Y!=null&&Y.success)||Y.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${M.label}?`))return;const Ce=await n(q,"fast_forward_mesh_node",{meshId:c.meshId,nodeId:M.id,workspace:U,updateSubmodules:!0,dryRun:!1,execute:!0}),je=(Ce==null?void 0:Ce.result)??Ce;D({phase:"execute",code:typeof(je==null?void 0:je.code)=="string"?je.code:void 0,error:typeof(je==null?void 0:je.operationError)=="string"?je.operationError:null,executed:(je==null?void 0:je.executed)===!0})}catch(ie){D({phase:"dry_run",error:ie instanceof Error?ie.message:"fast-forward failed"})}finally{A(null)}},[me,c.meshId,M,q,n]);u.useEffect(()=>{if(!M&&!O)return;const U=ie=>{ie.key==="Escape"&&we()};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[we,O,M]),u.useEffect(()=>{if(!te||!n)return;const{daemonId:U,workspace:ie}=te,Y=N[ie];if(Y!=null&&Y.loading||Y&&(Y.entries.length>0||Y.error))return;let Ae=!1;return _(Ce=>{var je;return{...Ce,[ie]:{loading:!0,error:null,entries:((je=Ce[ie])==null?void 0:je.entries)??[]}}}),n(U,"git_log",{workspace:ie,limit:5}).then(Ce=>{Ae||_(je=>({...je,[ie]:{loading:!1,error:null,entries:PM(Ce)}}))}).catch(Ce=>{Ae||_(je=>({...je,[ie]:{loading:!1,error:Ce instanceof Error?Ce.message:"git_log failed",entries:[]}}))}),()=>{Ae=!0}},[N,te,n]);const Te=[...p.warnings??[],...c.nodes.filter(U=>U.machineStatus&&U.machineStatus!=="online").map(U=>`${U.machineLabel}: ${U.machineStatus}`)],le=p.stats.incompleteSnapshotNodes>0,Se=p.stats.followUpNodes>0?`${p.stats.followUpNodes} need follow-up`:le?"mesh visibility incomplete":"mesh converged",ge=p.stats.followUpNodes>0?"danger":le?"warn":"good",[G,W]=u.useState("LR"),Z=U=>U?o.isDark?"rounded-md border border-cyan-400/40 bg-cyan-500/15 px-2 py-0.5 text-cyan-100":"rounded-md border border-sky-400 bg-sky-100 px-2 py-0.5 text-sky-800":o.isDark?"rounded-md border border-white/10 bg-white/[0.03] px-2 py-0.5 text-slate-400 hover:text-slate-200":"rounded-md border border-slate-300 bg-white/80 px-2 py-0.5 text-slate-500 hover:text-slate-800",oe=U=>U?o.isDark?"rounded-lg px-3.5 py-1.5 text-xs font-semibold text-slate-100 bg-white/[0.08] border border-white/12":"rounded-lg px-3.5 py-1.5 text-xs font-semibold text-slate-900 bg-white border border-slate-300 shadow-sm":`rounded-lg px-3.5 py-1.5 text-xs font-medium ${o.textSecondary} border border-transparent hover:bg-white/[0.04]`;return r.jsx(Du.Provider,{value:o,children:r.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[r.jsxs("div",{className:"shrink-0 flex items-center gap-2",children:[r.jsxs("div",{className:`inline-flex w-fit items-center gap-1 rounded-xl border p-1 ${o.isDark?"border-white/10 bg-slate-950/40":"border-slate-200 bg-slate-50"}`,role:"tablist","aria-label":"Mesh view",children:[r.jsx("button",{type:"button",role:"tab","aria-selected":h==="overview",className:oe(h==="overview"),onClick:()=>m("overview"),children:"Overview"}),r.jsx("button",{type:"button",role:"tab","aria-selected":h==="graph",className:oe(h==="graph"),onClick:()=>{v(!0),m("graph")},children:"Graph"})]}),r.jsx("div",{className:"ml-auto",children:r.jsx(wM,{meshTheme:o,open:g,onToggle:()=>b(U=>!U)})})]}),g&&r.jsx(SM,{meshTheme:o,onClose:()=>b(!1)}),r.jsx("div",{className:`${h==="overview"?"flex":"hidden"} min-h-0 flex-1 flex-col overflow-y-auto`,children:h==="overview"&&r.jsx(aM,{status:e})}),r.jsx("div",{className:`${h==="graph"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-4`,children:r.jsxs("div",{className:`${o.cardClass} relative flex min-h-0 flex-1 flex-col rounded-[28px]`,style:{minHeight:480},children:[r.jsxs("div",{className:`absolute inset-x-4 top-4 z-30 max-h-[42dvh] overflow-y-auto sm:static sm:mb-3 sm:overflow-visible shrink-0 flex flex-wrap items-start justify-between gap-2 px-4 pt-3 pb-2.5 border-b ${o.isDark?"border-white/8":"border-slate-200"}`,children:[r.jsxs("div",{className:`flex min-w-0 flex-1 flex-wrap gap-2 text-xs ${o.textSecondary}`,children:[r.jsx(et,{label:Se,tone:ge}),p.stats.blockedReviewNodes>0&&r.jsx(et,{label:`${p.stats.blockedReviewNodes} blocked review`,tone:"danger"}),p.stats.notMergeableNodes>0&&r.jsx(et,{label:`${p.stats.notMergeableNodes} not mergeable`,tone:"danger"}),p.stats.mergeReadyNodes>0&&r.jsx(et,{label:`${p.stats.mergeReadyNodes} need merge`,tone:"warn"}),p.stats.cleanupCandidateNodes>0&&r.jsx(et,{label:`${p.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),p.stats.offlineNodes>0&&r.jsx(et,{label:`${p.stats.offlineNodes} offline`,tone:"danger"}),p.stats.incompleteSnapshotNodes>0&&r.jsx(et,{label:`${p.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),p.stats.missingGitSnapshotNodes>0&&r.jsx(et,{label:`${p.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),p.stats.missingSubmoduleSnapshotNodes>0&&r.jsx(et,{label:`${p.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),p.stats.staleGitSnapshotNodes>0&&r.jsx(et,{label:`${p.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((J==null?void 0:J.active)??0)>0&&r.jsx(et,{label:`${(J==null?void 0:J.active)??0} active queue`,tone:"info"}),r.jsx(et,{label:`${p.stats.totalNodes} nodes`,tone:"default"}),p.stats.totalActiveSessions>0&&r.jsx(et,{label:`${p.stats.totalActiveSessions} attached chats`,tone:"info"})]}),r.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[r.jsxs("div",{className:o.isDark?"flex items-center gap-0.5 rounded-md border border-white/10 bg-slate-950/40 p-0.5 text-[10px]":"flex items-center gap-0.5 rounded-md border border-slate-300 bg-white/70 p-0.5 text-[10px]",role:"group","aria-label":"Graph layout direction",children:[r.jsx("button",{type:"button",onClick:()=>W("auto"),className:Z(G==="auto"),title:"Auto-detect direction",children:"Auto"}),r.jsx("button",{type:"button",onClick:()=>W("LR"),className:Z(G==="LR"),title:"Left to right",children:"LR"}),r.jsx("button",{type:"button",onClick:()=>W("TB"),className:Z(G==="TB"),title:"Top to bottom",children:"TB"})]}),r.jsx("div",{className:"relative",children:r.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${o.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[r.jsx("summary",{className:`cursor-pointer list-none font-medium ${o.textSecondary} [&::-webkit-details-marker]:hidden`,children:(()=>{var Y;const U=((Y=c.asyncRefineJobs)==null?void 0:Y.filter(Ae=>Ae.status==="failed").length)??0,ie=R.recentFailures;return U>0?r.jsxs("span",{className:o.isDark?"text-rose-300":"text-rose-600",children:[U," refine failed"]}):ie>0?r.jsxs("span",{className:o.isDark?"text-amber-300":"text-amber-600",children:[ie," failures"]}):"Health"})()}),r.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 max-h-[70vh] overflow-y-auto rounded-xl border p-4 shadow-xl backdrop-blur-xl ${o.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:r.jsx(WM,{canonicalStatus:c,queueSummary:J,ledgerSummary:R,isBootstrapMode:l,meshTheme:o,sessionEntries:I,inlineMode:!0})})]})}),r.jsx("div",{className:"relative",children:r.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${o.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[r.jsx("summary",{className:`cursor-pointer list-none font-medium ${o.textSecondary} [&::-webkit-details-marker]:hidden`,children:"Legend"}),r.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 rounded-xl border p-3 shadow-xl backdrop-blur-xl ${o.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:r.jsxs("div",{className:"flex flex-col gap-3",children:[r.jsxs("div",{className:"flex flex-wrap gap-2",children:[r.jsx(et,{label:`${p.stats.dirtyNodes} dirty`,tone:p.stats.dirtyNodes>0?"warn":"good"}),r.jsx(et,{label:`${p.stats.orphanNodes} orphan`,tone:p.stats.orphanNodes>0?"warn":"good"}),r.jsx(et,{label:`${R.recentFailures} recent failures`,tone:R.recentFailures>0?"danger":"good"}),E.length===0?r.jsx(et,{label:"no session metadata"}):E.slice(0,2).map(([U,ie])=>r.jsx(et,{label:`${ie} ${U}`,tone:xc(U)},U))]}),r.jsxs("div",{className:"flex flex-wrap gap-2",children:[r.jsx(et,{label:"Anchor = default branch",tone:"info"}),r.jsx(et,{label:"Peer link = same-branch worktree",tone:"default"}),r.jsx(et,{label:"Submodule link = child checkout",tone:"warn"})]}),Te.length>0&&r.jsx("div",{className:"flex flex-wrap gap-2",children:Te.map(U=>r.jsx("span",{className:o.isDark?"rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1 text-xs text-amber-100":"rounded-full border border-amber-300 bg-amber-50 px-3 py-1 text-xs text-amber-700",children:U},U))}),r.jsx("div",{className:`text-xs ${o.textMuted}`,children:"Click a node or edge to pin its drill-down details in the side panel. Click it again to close."})]})})]})})]})]}),l&&p.nodes.length>0&&r.jsxs("div",{className:`shrink-0 mx-4 mt-2 flex items-center gap-2 rounded-xl border px-3.5 py-2 text-xs ${o.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:[r.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full animate-pulse ${o.isDark?"bg-amber-400":"bg-amber-500"}`,"aria-hidden":!0}),r.jsx("span",{children:"Awaiting live data — showing setup inventory until peer mesh_status probes succeed."})]}),r.jsxs("div",{className:"relative flex flex-1 min-w-0",style:{minHeight:360},children:[r.jsx("div",{className:"flex-1 min-w-0",children:f?p.nodes.length>0?r.jsx(tM,{data:p,selectedNodeId:w,directionPref:G,onNodeClick:U=>{if((j==null?void 0:j.kind)==="node"&&w===U.id){we();return}k(null),x(U.id),y({kind:"node",nodeId:U.id})},onEdgeClick:U=>{if((j==null?void 0:j.kind)==="edge"&&S===U.id){we();return}x(null),k(U.id),y({kind:"edge",edgeId:U.id})}}):r.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:t}):r.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:"Loading graph…"})}),M&&(j==null?void 0:j.kind)==="node"&&r.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${o.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[r.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${o.textMuted}`,children:"Selected node"}),r.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("div",{className:`truncate text-sm font-semibold ${o.textPrimary}`,children:M.label}),r.jsx("div",{className:`mt-0.5 font-mono text-[11px] ${o.textMuted}`,children:M.id.slice(0,16)})]}),r.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[M.behind>0&&r.jsx("button",{type:"button",onClick:()=>{ye()},disabled:!me||T===M.id,className:o.isDark?"rounded-full border border-emerald-400/25 bg-emerald-500/10 px-2 py-0.5 text-xs font-semibold text-emerald-100 transition hover:bg-emerald-500/18 disabled:cursor-not-allowed disabled:opacity-45":"rounded-full border border-emerald-300 bg-emerald-50 px-2 py-0.5 text-xs font-semibold text-emerald-700 transition hover:bg-emerald-100 disabled:cursor-not-allowed disabled:opacity-45",children:T===M.id?"Checking":"Heal"}),r.jsx("button",{type:"button",onClick:we,"aria-label":"Close detail panel",className:o.isDark?"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]})]}),r.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[(()=>{const U=($==null?void 0:$.health)??M.health;return U==="unknown"?r.jsx(et,{label:"connecting...",tone:"default"}):r.jsx(et,{label:U,tone:jM(U)})})(),M.branch&&r.jsx(et,{label:M.branch,tone:"default"}),M.ahead>0&&r.jsx(et,{label:`ahead ${M.ahead}`,tone:"warn"}),M.behind>0&&r.jsx(et,{label:`behind ${M.behind}`,tone:"warn"}),M.dirtyFiles>0&&r.jsx(et,{label:`${M.dirtyFiles} dirty`,tone:"warn"}),($==null?void 0:$.connection)&&$.connection.state!=="unknown"&&r.jsx(et,{label:LM($),tone:IM($.connection)}),((L=$==null?void 0:$.connection)==null?void 0:L.state)==="unknown"&&r.jsx(et,{label:"mesh connecting...",tone:"warn"}),X.length>0&&r.jsx(et,{label:`${X.length} sessions`,tone:"info"})]}),r.jsxs("div",{className:"grid gap-1.5 text-xs",children:[M.machineLabel&&r.jsx(Ht,{label:"Machine",value:M.machineLabel}),M.locality&&M.locality!=="unknown"&&r.jsx(Ht,{label:"Locality",value:M.locality}),r.jsx(Ht,{label:"Workspace",value:($==null?void 0:$.workspace)??M.workspace}),Q&&r.jsx(Ht,{label:"HEAD",value:Q}),(M.dirtyFiles>0||M.ahead>0||M.behind>0)&&r.jsx(Ht,{label:"Dirty/ahead/behind",value:`${M.dirtyFiles}/${M.ahead}/${M.behind}`}),X.length>0&&r.jsx(Ht,{label:"Sessions",value:String(X.length)}),M.upstream&&r.jsx(Ht,{label:"Upstream",value:M.upstream}),(()=>{var ie;const U=((ie=$==null?void 0:$.connection)==null?void 0:ie.source)??$M(M);return U&&U!=="unknown"?r.jsx(Ht,{label:"Source",value:String(U)}):null})(),(()=>{var ie;const U=(ie=$==null?void 0:$.connection)==null?void 0:ie.transport;return U&&U!=="unknown"?r.jsx(Ht,{label:"Transport",value:U}):null})(),(()=>{const U=M.machineId??($==null?void 0:$.machineId);return U?r.jsx(Ht,{label:"Machine id",value:U}):null})(),(()=>{const U=M.daemonId??($==null?void 0:$.daemonId);return U?r.jsx(Ht,{label:"Daemon id",value:U}):null})()]}),X.length>0&&r.jsxs("div",{className:"mt-3",children:[r.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${o.textMuted}`,children:"Active Sessions"}),r.jsx("div",{className:"flex flex-col gap-1.5",children:X.map(U=>r.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${o.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:`min-w-0 truncate font-mono select-text ${o.textMuted}`,title:U.session.sessionId,children:Ib(U.session.sessionId)}),r.jsx(et,{label:lo(U.session),tone:xc(lo(U.session))})]}),r.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 ${o.textMuted}`,children:[r.jsx("span",{className:"truncate",children:U.session.providerType||"provider unknown"}),r.jsx("span",{children:NM(U.session)}),r.jsx("span",{children:CM(U.session)})]}),U.session.statusNote&&r.jsx("div",{className:`mt-1 text-[10px] leading-4 ${o.textMuted}`,children:U.session.statusNote}),r.jsxs("div",{className:`mt-0.5 truncate ${o.textMuted}`,title:U.session.workspace||U.workspace,children:[(U.session.workspace||U.workspace).slice(0,38),U.branch?` · ${U.branch}`:""]})]},U.session.sessionId))})]}),r.jsxs("div",{className:"mt-3",children:[r.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${o.textMuted}`,children:"Ledger (mesh-wide)"}),r.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[r.jsx(Ht,{label:"Completed",value:String(R.taskCompleted)}),r.jsx(Ht,{label:"Failed",value:r.jsx("span",{className:R.taskFailed>0?o.isDark?"text-rose-300":"text-rose-600":"",children:R.taskFailed})}),r.jsx(Ht,{label:"Launched",value:String(R.sessionLaunched)}),r.jsx(Ht,{label:"Recent failures",value:r.jsx("span",{className:R.recentFailures>0?o.isDark?"text-amber-300":"text-amber-600":"",children:R.recentFailures})})]})]}),(()=>{var Y,Ae;const U=((Y=c.queue)==null?void 0:Y.tasks)??((Ae=c.queue)==null?void 0:Ae.items)??null;if(!Array.isArray(U)||U.length===0)return null;const ie=U.filter(Ce=>MM(Ce)===w).slice(0,3);return ie.length===0?null:r.jsxs("div",{className:"mt-3",children:[r.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${o.textMuted}`,children:"Queue tasks"}),r.jsx("div",{className:"flex flex-col gap-1.5",children:ie.map(Ce=>r.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${o.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:`font-mono ${o.textMuted}`,children:Ce.id.slice(0,12)}),r.jsx(et,{label:Ce.status??"unknown",tone:xc(Ce.status)})]}),Ce.message&&r.jsx("div",{className:`mt-0.5 truncate ${o.textMuted}`,children:Ce.message.slice(0,48)})]},Ce.id))})]})})(),M.snapshotWarnings.length>0&&r.jsxs("div",{className:o.isDark?"mt-3 rounded-xl border border-amber-400/20 bg-amber-500/10 p-3 text-xs text-amber-100":"mt-3 rounded-xl border border-amber-300 bg-amber-50 p-3 text-xs text-amber-800",children:[r.jsx("div",{className:"font-medium",children:"Key warning"}),r.jsx("div",{className:"mt-1",children:M.snapshotWarnings[0]})]}),((de=M.branchConvergence)==null?void 0:de.nextStep)&&r.jsxs("div",{className:o.isDark?"mt-3 rounded-xl border border-sky-400/20 bg-sky-500/10 p-3 text-xs text-sky-100":"mt-3 rounded-xl border border-sky-300 bg-sky-50 p-3 text-xs text-sky-800",children:[r.jsx("div",{className:"font-medium",children:"Follow-up"}),r.jsx("div",{className:"mt-1",children:M.branchConvergence.nextStep})]}),C&&r.jsxs("div",{className:o.isDark?"mt-3 rounded-xl border border-emerald-400/20 bg-emerald-500/10 p-3 text-xs text-emerald-100":"mt-3 rounded-xl border border-emerald-300 bg-emerald-50 p-3 text-xs text-emerald-800",children:[r.jsx("div",{className:"font-medium",children:C.phase==="execute"?"Heal result":"Heal preview"}),r.jsx("div",{className:"mt-1",children:C.code??C.error??"No result code returned."})]})]}),O&&(j==null?void 0:j.kind)==="edge"&&r.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${o.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[r.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${o.textMuted}`,children:"Selected edge"}),r.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("div",{className:`truncate text-sm font-semibold ${o.textPrimary}`,children:O.label||_m(O)}),r.jsx("div",{className:`mt-0.5 break-all font-mono text-[11px] ${o.textMuted}`,children:O.id})]}),r.jsx("button",{type:"button",onClick:we,"aria-label":"Close detail panel",className:o.isDark?"shrink-0 rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"shrink-0 rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]}),r.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[r.jsx(et,{label:_m(O),tone:"default"}),r.jsx(et,{label:OM(O),tone:"info"})]}),r.jsxs("div",{className:"grid gap-1.5 text-xs",children:[r.jsx(Ht,{label:"From",value:(H==null?void 0:H.label)??O.source}),r.jsx(Ht,{label:"To",value:(ae==null?void 0:ae.label)??O.target}),r.jsx(Ht,{label:"Label",value:O.label??"none"})]})]})]})]})})]})})}function $t(e){return typeof e=="string"?e.trim():""}function fd(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Lu(...e){const t=new Set;for(const s of e){const n=$t(s);n&&t.add(n)}return[...t]}function HM(e,t){var h,m;const s=fd(e==null?void 0:e.settings),n=$t((h=e==null?void 0:e.coordinator)==null?void 0:h.meshId)||$t(s.meshCoordinatorFor),i=$t(s.meshNodeFor),a=!!n||!!i,o=n===t||i===t;if(a&&!o)return null;const l=fd(e==null?void 0:e.activeChat),c=Lu(e==null?void 0:e.id,e==null?void 0:e.sessionId,e==null?void 0:e.session_id,e==null?void 0:e.providerSessionId,e==null?void 0:e.provider_session_id,e==null?void 0:e.targetSessionId,e==null?void 0:e.target_session_id,l.sessionId,l.session_id,l.providerSessionId,l.provider_session_id),d=c[0]||"";if(!d)return null;const p=n===t?$t((m=e==null?void 0:e.coordinator)==null?void 0:m.role)||"coordinator":i===t?$t(s.meshNodeRole)||"worker":$t(e==null?void 0:e.role)||$t(s.meshNodeRole)||void 0;return{sessionId:d,aliases:c,meshId:t,nodeId:o&&$t(s.meshNodeId)||null,providerType:$t(e==null?void 0:e.providerType)||void 0,state:$t(e==null?void 0:e.status)||void 0,chatStatus:$t(l.status)||void 0,lifecycle:$t(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:$t(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:$t(e==null?void 0:e.runtimeRecoveryState)||void 0,...p?{role:p}:{},...o?{isSelfCoordinator:n===t}:{},workspace:$t(e==null?void 0:e.workspace)||null}}function Tb(e,t){var n;return t?(Array.isArray((n=e.status)==null?void 0:n.sessions)?e.status.sessions:[]).map(i=>HM(i,t)).filter(i=>i!==null):[]}function Do(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function zM(e,t){const s=new Set(Do(t));return Do(e).some(n=>s.has(n))}function KM(e,t){const s=t.filter(i=>!!i);return s.length===0?e:[...e.filter(i=>!s.some(a=>zM(i,a))),...s]}function GM(e,t){if(t.length===0)return e;const s=new Map;for(const o of t)for(const l of Do(o))s.set(l,o);let n=!1;const a=(e.nodes??[]).map((o,l)=>{const c=Array.isArray(o.activeSessionDetails)?o.activeSessionDetails:Array.isArray(o.sessions)?o.sessions:[],d=new Map;for(const m of c){const g=Lu(m==null?void 0:m.sessionId,m==null?void 0:m.session_id,m==null?void 0:m.id,m==null?void 0:m.providerSessionId,m==null?void 0:m.provider_session_id),b=g[0]||"";if(!b)continue;const f=g.map(v=>s.get(v)).find(Boolean);f&&(n=!0),d.set(b,f?{...m,sessionId:b,providerType:f.providerType||m.providerType,state:f.state||m.state,chatStatus:f.chatStatus||m.chatStatus,lifecycle:f.lifecycle||m.lifecycle,surfaceKind:f.surfaceKind||m.surfaceKind,recoveryState:f.recoveryState||m.recoveryState,role:f.role||m.role,isSelfCoordinator:f.isSelfCoordinator??m.isSelfCoordinator,workspace:f.workspace||m.workspace}:{...m,sessionId:b})}for(const m of o.activeSessions??[])d.has(m)||d.set(m,{sessionId:m,workspace:o.workspace,isCached:!0});const p=l===0;for(const m of t){if(Do(m).some(v=>d.has(v)))continue;const b=m.nodeId!=null&&m.nodeId===o.nodeId,f=m.isSelfCoordinator&&!m.nodeId&&p;!b&&!f||(n=!0,d.set(m.sessionId,{sessionId:m.sessionId,providerType:m.providerType,state:m.state,chatStatus:m.chatStatus,lifecycle:m.lifecycle,surfaceKind:m.surfaceKind,recoveryState:m.recoveryState,role:m.role,isSelfCoordinator:m.isSelfCoordinator,workspace:m.workspace||o.workspace}))}const h=[...d.values()];return h.length===0?o:{...o,activeSessionDetails:h,activeSessions:h.map(m=>m.sessionId)}});return n?{...e,nodes:a}:e}function qM(e,t){const n=Tb(e,t).map(i=>{var c;const a=(Array.isArray((c=e.status)==null?void 0:c.sessions)?e.status.sessions:[]).find(d=>$t(d==null?void 0:d.id)===i.sessionId),o=fd(a==null?void 0:a.activeInteractivePrompt),l=a!=null&&a.meshQueueStats&&typeof a.meshQueueStats=="object"?JSON.stringify(a.meshQueueStats):"";return[i.sessionId,i.providerType??"",i.state??"",i.chatStatus??"",i.lifecycle??"",i.surfaceKind??"",i.recoveryState??"",$t(o.status)||$t(o.kind)||$t(o.type),i.nodeId??"",i.isSelfCoordinator?"coordinator":"worker",l].join("|")}).filter(i=>!!i).sort();return n.length>0?n.join(`
|
|
82
|
+
`):null}function Mb({status:e,daemonId:t,extraDaemonIds:s,meshId:n,sendData:i,extraLiveSessions:a=[]}){const[o,l]=u.useState(new Map),c=u.useRef(new Map),d=u.useMemo(()=>{const g=new Set;if(t&&g.add(t),s)for(const b of s)b&&g.add(b);return[...g].sort()},[t,s]),p=d.join(",");u.useEffect(()=>{c.current=new Map,l(new Map)},[t,n]),u.useEffect(()=>{if(!n||!i||d.length===0)return;const g=d.map(b=>Os.subscribe({sendData:i},b,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${b}`,params:{includeSessions:!0}},f=>{if(f.topic!=="daemon.metadata")return;const v=qM(f,n);if(v===(c.current.get(b)??null))return;c.current.set(b,v);const w=Tb(f,n);l(x=>{const S=new Map(x);return S.set(b,w),S})}));return()=>{for(const b of g)b()}},[p,n,i]);const h=u.useMemo(()=>{const g=[];for(const b of o.values())g.push(...b);return g},[o]),m=u.useMemo(()=>KM(h,a),[a,h]);return u.useMemo(()=>e?GM(e,m):null,[m,e])}const Cm=[1500,4e3,9e3];function VM(e){var t,s,n,i,a,o;return!!(((t=e.git)==null?void 0:t.isGitRepo)===!0||(s=e.git)!=null&&s.branch||(n=e.git)!=null&&n.upstream||(i=e.git)!=null&&i.headCommit||(a=e.git)!=null&&a.workspace||(o=e.git)!=null&&o.repoRoot)}function XM(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>{var s;return VM(t)?!1:t.gitProbePending||((s=t.connection)==null?void 0:s.state)==="connecting"?!0:t.machineStatus==="online"||t.launchReady===!0})}function YM(e){return!Number.isInteger(e)||e<0?Cm[0]:Cm[e]??null}const bc=new Map;function QM(e,t){return!e||!t?null:`${e}::${t}`}function JM(e,t){var a,o,l,c;if(!t||!e.sessionId)return null;const s=((a=e.coordinator)==null?void 0:a.meshId)??(typeof((o=e.settings)==null?void 0:o.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),n=typeof((l=e.settings)==null?void 0:l.meshNodeFor)=="string"?e.settings.meshNodeFor:null;if(s!==t&&n!==t)return null;const i=typeof((c=e.settings)==null?void 0:c.meshNodeId)=="string"?e.settings.meshNodeId:null;return{sessionId:e.sessionId,aliases:Lu(e.sessionId,e.providerSessionId,e.historySessionId,e.nativeSessionId),meshId:t,nodeId:i,providerType:e.agentType,state:e.status,chatStatus:e.status,role:s===t?"coordinator":"worker",isSelfCoordinator:s===t,workspace:e.workspacePath??null}}function ZM({activeConv:e,sendDaemonCommand:t,onClose:s}){var $,M,O,H,ae,z;const n=(($=e.coordinator)==null?void 0:$.meshId)??(typeof((M=e.settings)==null?void 0:M.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),i=e.daemonId??null,a=QM(i,n),o=a?bc.get(a)??null:null,l=su(),{sendData:c}=jt(),{theme:d}=Gr(),p=u.useMemo(()=>qr(d),[d]),h=u.useMemo(()=>JM(e,n),[e.agentType,(O=e.coordinator)==null?void 0:O.meshId,e.sessionId,(H=e.settings)==null?void 0:H.meshCoordinatorFor,(ae=e.settings)==null?void 0:ae.meshNodeFor,(z=e.settings)==null?void 0:z.meshNodeId,e.status,e.workspacePath,n]),[m,g]=u.useState(o),[b,f]=u.useState(!1),[v,w]=u.useState(!1),[x,S]=u.useState(null),[k,j]=u.useState((o==null?void 0:o.refreshedAt)??null),y=u.useRef(o!==null),N=u.useRef(!1),_=u.useRef(!1),C=u.useRef(!0),D=u.useRef(0),T=u.useRef(null);u.useEffect(()=>{y.current=m!==null},[m]);const A=u.useCallback(()=>{T.current!==null&&(clearTimeout(T.current),T.current=null)},[]);u.useEffect(()=>{A(),D.current=0;const X=a?bc.get(a)??null:null;g(X),j((X==null?void 0:X.refreshedAt)??null),y.current=X!==null,_.current=!1,w(!1),S(null)},[a,A]);const P=u.useCallback(async(X=!1,te=!1)=>{if(!i||!n){S("This coordinator does not expose a live mesh id."),g(null);return}if(N.current){X&&(_.current=!0);return}te||(A(),D.current=0),N.current=!0;const he=!y.current;f(he),w(X&&y.current),S(null);try{const ke=l!=null&&l.loadMeshStatus?await l.loadMeshStatus(i,n,{refresh:X,retryProfile:te?"interactive":"settled"}):await t(i,"mesh_status",{meshId:n,refresh:X}),Q=au(ke);if(!Q){S("mesh_status returned an unexpected payload.");return}if(a&&bc.set(a,Q),g(Q),y.current=!0,j(Q.refreshedAt||new Date().toISOString()),XM(Q.nodes)){const q=YM(D.current);q!==null&&C.current&&(D.current+=1,T.current=setTimeout(()=>{C.current&&P(!0,!0)},q))}else D.current=0}catch(ke){S(ke instanceof Error?ke.message:"Failed to load live mesh status")}finally{N.current=!1,f(!1),w(!1),_.current&&C.current&&(_.current=!1,window.setTimeout(()=>{C.current&&P(!0)},0))}},[a,A,i,n,l,t]);u.useEffect(()=>(C.current=!0,D.current=0,(async()=>(await P(!1),C.current&&T.current===null&&!N.current&&P(!0,!0)))(),()=>{C.current=!1,A()}),[P,A]),u.useEffect(()=>{const X=te=>{te.key==="Escape"&&s()};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[s]);const F=(m==null?void 0:m.meshName)||n||"Repo Mesh",J=u.useMemo(()=>h?[h]:[],[h]),R=Mb({status:m,daemonId:i,meshId:n,sendData:c,extraLiveSessions:J}),I=k?new Date(k).toLocaleTimeString():null,E=u.useMemo(()=>b?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[b]);return r.jsx("div",{className:p.dialogOverlayClass,onClick:s,children:r.jsxs("div",{role:"dialog","aria-modal":"true",className:p.dialogShellClass,onClick:X=>X.stopPropagation(),children:[r.jsxs("div",{className:p.dialogHeaderClass,children:[r.jsx("div",{className:"min-w-0 flex-1",children:r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-400/20 bg-sky-500/12 text-sky-200 shadow-[0_12px_30px_rgba(14,165,233,0.18)]",children:r.jsx(qs,{size:18})}),r.jsxs("div",{className:"min-w-0",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsx("h2",{className:p.dialogTitleClass,children:F}),r.jsx("span",{className:p.dialogKickerClass,children:"Mesh observability"})]}),r.jsxs("p",{className:p.dialogSubtitleClass,children:[kt(e),e.workspaceName?` · ${e.workspaceName}`:"",m!=null&&m.repoIdentity?` · ${m.repoIdentity}`:""]})]})]})}),r.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[I&&r.jsx("span",{className:p.dialogRefreshedChipClass,children:v?"Refreshing mesh...":`Refreshed ${I}`}),!v&&m&&r.jsx("span",{className:p.dialogRefreshedChipClass,children:c&&!x?"Live daemon metadata":"Metadata subscription unavailable"}),r.jsx("button",{type:"button",onClick:()=>{P(!0)},disabled:b||v,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:b||v?"Refreshing…":"Refresh"}),r.jsx("button",{type:"button",onClick:s,className:p.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:r.jsx(Ot,{size:16})})]})]}),x&&r.jsx("div",{className:p.isDark?"shrink-0 border-b border-rose-400/20 bg-rose-500/12 px-4 py-2 text-sm text-rose-200 md:px-5":"shrink-0 border-b border-rose-300 bg-rose-50 px-4 py-2 text-sm text-rose-700 md:px-5",children:x}),r.jsx("div",{className:p.dialogBodyClass,children:R?r.jsx(Ab,{status:R,emptyMessage:E,daemonId:i,sendDaemonCommand:t}):r.jsx("div",{className:p.dialogEmptyClass,children:E})})]})})}function eE(e,t){const{sendCommand:s}=jt(),[n,i]=u.useState(null),[a,o]=u.useState(!1);u.useEffect(()=>{if(!e||!t){i(null);return}o(!0),s(e,"git_remote_url",{workspace:t}).then(c=>{const d=(c==null?void 0:c.result)??c;i(typeof(d==null?void 0:d.remoteUrl)=="string"?d.remoteUrl:null)}).catch(()=>{i(null)}).finally(()=>o(!1))},[e,t,s]);const l=tE(n);return{remoteUrl:n,githubUrl:l,loading:a}}function tE(e){if(!e)return null;const t=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(t)return`https://github.com/${t[1]}`;const s=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return s?`https://github.com/${s[1]}`:null}const Eb=5e3;function sE(e){return`git:${e}`}function rE({workspace:e,includeDiffSummary:t=!1,intervalMs:s=Eb}){return{type:"subscribe",topic:"workspace.git",key:sE(e),params:{workspace:e,includeDiffSummary:t,intervalMs:s}}}function $u(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Br(e,t){if(e instanceof Error)return e.message;if(e&&typeof e=="object"){const s=e;if(typeof s.error=="string"&&s.error.trim())return s.error;if(typeof s.message=="string"&&s.message.trim())return s.message}return t}function nE(e){const t=$u(e);return(t==null?void 0:t.success)===!1?{status:null,error:Br(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Br(t,"Git status response did not include status")}}function iE(e){const t=$u(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Br(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Br(t,"Git diff summary response did not include diffSummary")}}function yc(e){return e===void 0||typeof e=="boolean"}function aE(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&yc(t.binary)&&yc(t.truncated)&&yc(t.staged)}function oE(e){const t=$u(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Br(t,"Git file diff request failed")}:aE(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Br(t,"Git file diff response did not include a valid diff object")}}function lE({daemonId:e,workspace:t,enabled:s=!0,includeDiffSummary:n=!1,intervalMs:i=Eb}){const{sendCommand:a,sendData:o}=jt(),l=typeof t=="string"?t.trim():"",c=!!(s&&e&&l),[d,p]=u.useState(null),[h,m]=u.useState(null),[g,b]=u.useState(!1),[f,v]=u.useState(null),w=u.useCallback(async()=>{if(!(!c||!e||!l)){b(!0),v(null);try{const S=nE(await a(e,"git_status",{workspace:l}));if(S.error){p(null),m(null),v(S.error);return}if(p(S.status),!n){m(null);return}const k=iE(await a(e,"git_diff_summary",{workspace:l}));if(k.error){m(null),v(k.error);return}m(k.diffSummary)}catch(S){v(Br(S,"Git status request failed"))}finally{b(!1)}}},[c,e,n,a,l]),x=u.useMemo(()=>l?rE({workspace:l,includeDiffSummary:n,intervalMs:i}):null,[n,i,l]);return u.useEffect(()=>{if(!c||!e||!l||!x){p(null),m(null),b(!1),v(null);return}const S=o?Os.subscribe({sendData:o},e,x,k=>{var j,y;k.workspace===l&&(p(k.status),m(k.diffSummary??null),v(((j=k.status)==null?void 0:j.error)||((y=k.diffSummary)==null?void 0:y.error)||null),b(!1))},{retryIntervalMs:1e3}):null;return w(),()=>{S==null||S()}},[c,e,w,x,o,l]),{status:d,diffSummary:h,loading:g,error:f,refresh:w}}const cE={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},dE={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 Im(e){return e.split("/").pop()??e}function uE(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function pE({files:e,truncated:t,onFileClick:s,selectedPath:n,className:i=""}){return e.length===0?r.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:"No changed files."}):r.jsxs("div",{className:`flex flex-col ${i}`,children:[r.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(a=>{const o=n===a.path,l=cE[a.status]??"?",c=dE[a.status]??"text-zinc-400",d=uE(a.path),p=Im(a.path),h=a.staged?r.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return r.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:()=>s==null?void 0:s(a),children:[r.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${c}`,title:a.status,children:l}),r.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[d&&r.jsxs("span",{className:"text-text-secondary",children:[d,"/"]}),r.jsx("span",{className:"text-text-primary",children:p}),a.oldPath&&r.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",Im(a.oldPath)]}),h]}),!a.binary&&(a.insertions>0||a.deletions>0)&&r.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[a.insertions>0&&r.jsxs("span",{className:"text-emerald-500",children:["+",a.insertions]}),a.insertions>0&&a.deletions>0&&r.jsx("span",{className:"text-text-secondary",children:" "}),a.deletions>0&&r.jsxs("span",{className:"text-red-400",children:["-",a.deletions]})]}),a.binary&&r.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${a.path}-${a.staged?"S":"U"}`)})}),t&&r.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",r.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function hE(e,t){let s="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?s="bg-emerald-500/10 text-emerald-300":e.startsWith("-")&&!e.startsWith("---")?s="bg-red-500/10 text-red-300":e.startsWith("@@")?s="text-sky-400":(e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ "))&&(s="text-text-secondary"),r.jsx("div",{className:`px-3 ${s}`,children:r.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},t)}function Rb({diff:e,binary:t,truncated:s,loading:n,error:i,className:a=""}){const o=u.useRef(null);if(u.useEffect(()=>{o.current&&(o.current.scrollTop=0)},[e]),n)return r.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${a}`,children:"Loading diff…"});if(i)return r.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${a}`,children:i});if(t)return r.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${a}`,children:"Binary file — diff not available."});if(!e)return r.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${a}`,children:"No diff available."});const l=e.split(`
|
|
83
|
+
`);return r.jsxs("div",{ref:o,className:`overflow-auto ${a}`,children:[r.jsx("div",{className:"py-1",children:l.map((c,d)=>hE(c,d))}),s&&r.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary border-t border-border/30",children:["Diff truncated — run ",r.jsx("code",{className:"font-mono",children:"git diff"})," locally for full output."]})]})}function mE(e,t){const s=[`Branch: ${e||"unknown"}`];s.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const n={};for(const i of t.files)n[i.status]||(n[i.status]=[]),n[i.status].push(i.path);for(const[i,a]of Object.entries(n))s.push(`${i}: ${a.slice(0,5).join(", ")}${a.length>5?` (+${a.length-5} more)`:""}`);return s.join(`
|
|
84
|
+
`)}function Pb({daemonId:e,workspace:t,onClose:s}){const{sendCommand:n}=jt(),{status:i,diffSummary:a,loading:o,error:l,refresh:c}=lE({daemonId:e,workspace:t,includeDiffSummary:!0}),[d,p]=u.useState(null),[h,m]=u.useState(null),[g,b]=u.useState(""),[f,v]=u.useState(!1),[w,x]=u.useState(!1),[S,k]=u.useState(null),[j,y]=u.useState(null),{githubUrl:N}=eE(e,t),_=u.useCallback(async F=>{if(!((d==null?void 0:d.path)===F.path&&!d.loading)){p({path:F.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const J=await n(e,"git_diff_file",{workspace:t,path:F.path,staged:F.staged}),R=oE(J);if(R.error||!R.diff){p({path:F.path,diff:"",binary:!1,truncated:!1,loading:!1,error:R.error??"Failed to load diff"});return}p({path:F.path,diff:R.diff.diff,binary:R.diff.binary??!1,truncated:R.diff.truncated??!1,loading:!1,error:null})}catch(J){const R=J instanceof Error?J.message:"Failed to load diff";p({path:F.path,diff:"",binary:!1,truncated:!1,loading:!1,error:R})}}},[e,n,d,t]),C=u.useCallback(F=>{b(""),v(!1),k(null),y(null),m(F)},[]),D=u.useCallback(()=>{m(null),k(null),x(!1)},[]),T=u.useCallback(async()=>{var F,J,R;if(h){x(!0),k(null);try{let I;h==="checkpoint"?I=await n(e,"git_checkpoint",{workspace:t,message:g,includeUntracked:f}):h==="stash"?I=await n(e,"git_stash_push",{workspace:t,message:g,includeUntracked:f}):h==="stash_pop"?I=await n(e,"git_stash_pop",{workspace:t}):h==="checkout_files"&&d&&(I=await n(e,"git_checkout_files",{workspace:t,paths:[d.path]}));const E=(I==null?void 0:I.result)??I;if((E==null?void 0:E.success)===!1||E!=null&&E.error){k((E==null?void 0:E.error)??"Action failed"),x(!1);return}h==="checkpoint"?y(`Checkpoint created: ${((J=(F=E==null?void 0:E.checkpoint)==null?void 0:F.commit)==null?void 0:J.slice(0,7))??"done"}`):h==="stash"?y(`Stashed as ${((R=E==null?void 0:E.stash)==null?void 0:R.stashRef)??"stash@{0}"}`):h==="stash_pop"?y("Stash restored"):(y("File reverted"),p(null)),m(null),await c()}catch(I){k(I instanceof Error?I.message:"Action failed")}finally{x(!1)}}},[h,n,e,t,g,f,d,c]),A=!!(i!=null&&i.hasConflicts),P=i?i.staged+i.modified+i.untracked+i.deleted+i.renamed:null;return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:F=>{F.target===F.currentTarget&&s()},children:r.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:[r.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[r.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(i==null?void 0:i.branch)??"Git Status"}),r.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),N&&r.jsx("a",{href:`${N}/tree/${(i==null?void 0:i.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 ↗"})]}),r.jsx("button",{onClick:c,disabled:o,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),r.jsx("button",{onClick:s,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:r.jsx(Ot,{className:"h-4 w-4"})})]}),i&&r.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:[i.headCommit&&r.jsxs("span",{title:i.headMessage??void 0,children:[r.jsx("span",{className:"font-mono",children:i.headCommit.slice(0,7)}),i.headMessage&&r.jsx("span",{className:"ml-1 truncate",children:i.headMessage.slice(0,60)})]}),i.ahead>0&&r.jsxs("span",{className:"text-orange-400",children:["↑",i.ahead," ahead"]}),i.behind>0&&r.jsxs("span",{className:"text-orange-400",children:["↓",i.behind," behind"]}),i.staged>0&&r.jsxs("span",{className:"text-emerald-400",children:[i.staged," staged"]}),i.modified>0&&r.jsxs("span",{children:[i.modified," modified"]}),i.untracked>0&&r.jsxs("span",{children:[i.untracked," untracked"]}),i.deleted>0&&r.jsxs("span",{className:"text-red-400",children:[i.deleted," deleted"]}),i.stashCount>0&&r.jsxs("span",{children:[i.stashCount," stashed"]}),i.hasConflicts&&r.jsx("span",{className:"font-bold text-red-400",children:"conflicts"}),P===0&&!i.error&&r.jsx("span",{className:"text-emerald-500",children:"clean"}),a&&a.files.length>0&&r.jsxs("span",{className:"text-text-secondary",children:[a.files.length," file",a.files.length!==1?"s":"",a.totalInsertions>0&&r.jsxs("span",{className:"text-emerald-500",children:[" +",a.totalInsertions]}),a.totalDeletions>0&&r.jsxs("span",{className:"text-red-400",children:[" -",a.totalDeletions]})]})]}),l&&r.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}),r.jsxs("div",{className:"flex min-h-0 flex-1",children:[r.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[o&&!a&&r.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),a&&r.jsx(pE,{files:a.files,truncated:a.truncated,selectedPath:(d==null?void 0:d.path)??null,onFileClick:_}),!o&&!a&&!l&&r.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),r.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:d?r.jsx(Rb,{diff:d.diff,binary:d.binary,truncated:d.truncated,loading:d.loading,error:d.error,className:"h-full"}):r.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),j&&r.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:[r.jsx("span",{children:j}),r.jsx("button",{onClick:()=>y(null),className:"ml-2 text-emerald-400 hover:text-text-primary",children:"×"})]}),r.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[r.jsx("button",{onClick:()=>C("checkpoint"),disabled:A,title:A?"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"}),r.jsx("button",{onClick:()=>C("stash"),disabled:A,title:A?"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"}),r.jsx("button",{onClick:()=>C("stash_pop"),disabled:A||!(i!=null&&i.stashCount),title:A?"Resolve conflicts before restoring a stash":i!=null&&i.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"}),r.jsx("button",{onClick:()=>C("checkout_files"),disabled:!d,title:d?`Revert changes to ${d.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"}),a&&a.files.length>0&&r.jsx("button",{onClick:()=>{const F=mE((i==null?void 0:i.branch)??null,a);navigator.clipboard.writeText(F),y("Copied to clipboard"),setTimeout(()=>y(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),h&&r.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:r.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[r.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[h==="checkpoint"&&"Create checkpoint commit",h==="stash"&&"Stash changes",h==="stash_pop"&&"Restore latest stash?",h==="checkout_files"&&`Revert changes to ${(d==null?void 0:d.path)??"file"}?`]}),(h==="checkpoint"||h==="stash")&&r.jsxs(r.Fragment,{children:[r.jsx("input",{type:"text",value:g,onChange:F=>b(F.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}),r.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:f,onChange:F=>v(F.target.checked)}),"Include untracked files"]})]}),S&&r.jsx("p",{className:"text-xs text-red-400",children:S}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx("button",{onClick:D,disabled:w,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),r.jsx("button",{onClick:T,disabled:w||(h==="checkpoint"||h==="stash")&&!g.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:w?"Working…":"Confirm"})]})]})})]})})}function fE({isMobile:e,showMobileChatMode:t,visibleConversationCount:s}){const[n,i]=u.useState(!1),[a,o]=u.useState(!1),[l,c]=u.useState(!1),[d,p]=u.useState(!1),[h,m]=u.useState(!1),[g,b]=u.useState("quickstart"),[f,v]=u.useState("workspace"),w=u.useMemo(()=>!t&&!e,[t,e]),x=u.useCallback(_=>{i(_),_&&o(!1)},[]),S=u.useCallback(_=>{o(_),_&&i(!1)},[]),k=u.useCallback(()=>{b(s===0?"quickstart":"shortcuts"),v("workspace"),c(!0),i(!1),o(!1)},[s]),j=u.useCallback(()=>{c(!1)},[]),y=u.useCallback(()=>{p(!0)},[]),N=u.useCallback(()=>{p(!1)},[]);return u.useEffect(()=>{if(!w){m(!1);return}m(!0);const _=window.setTimeout(()=>{m(!1)},1e4);return()=>window.clearTimeout(_)},[w]),{inboxOpen:n,hiddenOpen:a,shortcutHelpOpen:l,newSessionOpen:d,guideNudgeVisible:h,guideTab:g,shortcutSection:f,isDesktopDashboard:w,setGuideTab:b,setShortcutSection:v,handleInboxOpenChange:x,handleHiddenOpenChange:S,handleOpenShortcutHelp:k,closeShortcutHelp:j,openNewSession:y,closeNewSession:N}}function gE(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 xE(e){return e instanceof Error?e.message:String(e||"")}function bE(e){const t=xE(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function yE({showMobileChatMode:e,isMobile:t,activeConv:s,wsStatus:n,isConnected:i,onOpenHistory:a,onOpenRemote:o,onStopCli:l,activeCliViewMode:c,onSetActiveCliViewMode:d,mobileChatConversations:p,hiddenConversations:h,ides:m,actionLogs:g,sendDaemonCommand:b,setActionLogs:f,setCliViewModeOverrides:v,isStandalone:w,initialDataLoaded:x,userName:S,requestedMobileTabKey:k,onRequestedMobileTabConsumed:j,requestedMachineId:y,onRequestedMachineConsumed:N,requestedMobileSection:_,onRequestedMobileSectionConsumed:C,containerRef:D,isSplitMode:T,numGroups:A,groupSizes:P,groupedConvs:F,clearedTabs:J,focusedGroup:R,focusGroup:I,moveTabToGroup:E,splitTabRelative:$,closeGroup:M,handleResizeStart:O,groupActiveTabIds:H,setGroupActiveTab:ae,groupTabOrders:z,setGroupTabOrder:X,toggleHiddenTab:te,visibleConversations:he,requestedDesktopTabKey:ke,onRequestedDesktopTabConsumed:Q,onDesktopActiveTabChange:q,onRequestScrollToBottom:me,onHideConversation:we,onShowHiddenConversation:ye,onShowAllHiddenConversations:Te,scrollToBottomRequest:le,machineEntries:Se,layoutProfile:ge,onBrowseMachineDirectory:G,onSaveMachineWorkspace:W,onLaunchMachineIde:Z,onLaunchMachineProvider:oe,onListMachineMeshes:ue,onLaunchMeshCoordinator:ce,onListMachineSavedSessions:L,notifications:de,notificationUnreadCount:U,liveSessionInboxState:ie,onMarkNotificationRead:Y,onMarkNotificationUnread:Ae,onDeleteNotification:Ce}){const je=Kt.useRef(null),{inboxOpen:qe,hiddenOpen:it,shortcutHelpOpen:lt,newSessionOpen:ft,guideNudgeVisible:ct,guideTab:_t,shortcutSection:Mt,isDesktopDashboard:Et,setGuideTab:De,setShortcutSection:He,handleInboxOpenChange:pt,handleHiddenOpenChange:Ze,handleOpenShortcutHelp:Lt,closeShortcutHelp:B,openNewSession:V,closeNewSession:ne}=fE({isMobile:t,showMobileChatMode:e,visibleConversationCount:he.length}),[xe,ve]=Kt.useState(null),[Ne,ee]=Kt.useState(null),se=Kt.useCallback((fe,Fe)=>{ve({daemonId:fe,workspace:Fe})},[]),be=Kt.useCallback(fe=>{ee(fe)},[]),Me=Kt.useCallback(fe=>{var Fe;Si.flushSync(()=>{ye(fe)}),(Fe=je.current)==null||Fe.restoreHiddenTabToSavedLocation(fe.tabKey)},[ye]),$e=Kt.useCallback(fe=>{var Gt;const Fe=p.find(es=>rd(es,fe))||h.find(es=>rd(es,fe));Fe&&(h.some(es=>es.tabKey===Fe.tabKey)&&Me(Fe),q(Fe.tabKey),(Gt=je.current)==null||Gt.activateConversationTab(Fe.tabKey),me(Fe.tabKey,"notification-open")),Y(fe.id),pt(!1)},[Me,h,p,q,Y,me]),Re=Kt.useCallback(()=>{var Fe;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Fe=je.current)==null||Fe.resetAllPanelsToMain(),Ze(!1))},[Ze]),Oe=Kt.useCallback(async fe=>{var Ue;if(!s)return;const Fe=(Ue=s.modalButtons)==null?void 0:Ue[fe];if(!Fe)return;const Gt=_r(s);if(!Gt)return;const es=Fe.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Qs=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(es);try{await b(Gt,"resolve_action",{button:Fe,action:Qs?"approve":"reject",buttonIndex:fe,...Nr(s)})}catch(ut){bE(ut)||console.error("[Shortcut approval] Failed:",ut)}},[s,b]),{isMac:ze,actionDefinitions:Le,actionShortcuts:Ye,shortcutListening:rt,shortcutListeningDraft:Ct,setShortcutListening:Ut,setShortcutListeningDraft:Rt,saveShortcuts:It}=uA({enabled:Et&&!lt,onTrigger:fe=>{var Fe,Gt,es,Qs,Ue,ut,Js,ma,fa,ga,xa,ba,ya,va,xr,wa;if(fe==="openShortcutHelp"){Lt();return}if(fe==="openNewSession"){V();return}if(fe==="hideCurrentTab"){s&&we(s);return}if(fe==="toggleHiddenTabs"){Ze(!it);return}if(fe==="openHistoryForActiveTab"){s&&!at(s)&&a(s);return}if(fe==="openRemoteForActiveTab"){s&&!dt(s)&&!at(s)&&o(s);return}if(fe==="splitActiveTabRight"){(Fe=je.current)==null||Fe.splitActiveTabRight();return}if(fe==="splitActiveTabDown"){(Gt=je.current)==null||Gt.splitActiveTabDown();return}if(fe==="floatActiveTab"){(es=je.current)==null||es.floatActiveTab();return}if(fe==="popoutActiveTab"){(Qs=je.current)==null||Qs.popoutActiveTab();return}if(fe==="dockActiveTab"){(Ue=je.current)==null||Ue.dockActiveTab();return}if(fe==="focusLeftPane"){(ut=je.current)==null||ut.focusLeftPane();return}if(fe==="focusRightPane"){(Js=je.current)==null||Js.focusRightPane();return}if(fe==="focusUpPane"){(ma=je.current)==null||ma.focusUpPane();return}if(fe==="focusDownPane"){(fa=je.current)==null||fa.focusDownPane();return}if(fe==="moveActiveTabToLeftPane"){(ga=je.current)==null||ga.moveActiveTabToLeftPane();return}if(fe==="moveActiveTabToRightPane"){(xa=je.current)==null||xa.moveActiveTabToRightPane();return}if(fe==="moveActiveTabToUpPane"){(ba=je.current)==null||ba.moveActiveTabToUpPane();return}if(fe==="moveActiveTabToDownPane"){(ya=je.current)==null||ya.moveActiveTabToDownPane();return}if(fe==="triggerPrimaryApprovalAction"){Oe(0);return}if(fe==="triggerSecondaryApprovalAction"){Oe(1);return}if(fe==="triggerTertiaryApprovalAction"){Oe(2);return}if(fe==="setActiveTabShortcut"){(va=je.current)==null||va.setShortcutForActiveTab();return}if(fe==="selectPreviousGroupTab"){(xr=je.current)==null||xr.activatePreviousTabInGroup();return}if(fe==="selectNextGroupTab"){(wa=je.current)==null||wa.activateNextTabInGroup();return}!s||!dt(s)||at(s)||fe==="toggleCliView"&&d(c==="chat"?"terminal":"chat")}}),Ge=Kt.useCallback(()=>{B(),Ut(null),Rt([])},[B,Ut,Rt]),gs=Kt.useMemo(()=>Mt==="all"?Le:Le.filter(fe=>gE(fe)===Mt),[Le,Mt]),pe=Kt.useCallback(()=>{const fe=Object.fromEntries(Le.map(Fe=>[Fe.id,""]));It(fe)},[Le,It]),Be=Kt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const fe=Object.fromEntries(Le.map(Fe=>[Fe.id,Fe.defaultShortcut]));It(fe)},[Le,It]);return Kt.useEffect(()=>{const fe=Fe=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Fe.metaKey&&Fe.key.toLowerCase()==="w":Fe.ctrlKey&&Fe.key.toLowerCase()==="w")&&(Fe.preventDefault(),s&&we&&we(s))};return window.addEventListener("keydown",fe),()=>window.removeEventListener("keydown",fe)},[s,we]),Kt.useEffect(()=>{if(!lt||rt)return;const fe=Fe=>{Fe.key==="Escape"&&(Fe.preventDefault(),Ge())};return window.addEventListener("keydown",fe,!0),()=>window.removeEventListener("keydown",fe,!0)},[Ge,lt,rt]),r.jsxs(r.Fragment,{children:[!e&&r.jsx(e_,{activeConv:s,wsStatus:n,isConnected:i,conversations:he,hiddenConversations:h,onOpenHistory:a,onHideConversation:we,onShowConversation:Me,onShowAllHidden:Te,onResetPanelsToMain:Re,notifications:de,notificationUnreadCount:U,onOpenNotification:$e,onMarkNotificationRead:Y,onMarkNotificationUnread:Ae,onDeleteNotification:Ce,inboxOpen:qe,onInboxOpenChange:pt,hiddenOpen:it,onHiddenOpenChange:Ze,onOpenNewSession:t?void 0:V,onOpenDashboardGuide:Lt,guideNudgeVisible:ct,actionShortcuts:Ye,onOpenRemote:()=>{!s||dt(s)||at(s)||o(s)},onStopCli:l,activeCliViewMode:c,onSetCliViewMode:d,onOpenGitDialog:se,onOpenMeshGraph:be}),e?r.jsx(ZI,{conversations:p,hiddenConversations:h,ides:m,actionLogs:g,sendDaemonCommand:b,setActionLogs:f,setCliViewModeOverrides:v,isStandalone:w,userName:S,requestedActiveTabKey:k,onRequestedActiveTabConsumed:j,requestedMachineId:y,onRequestedMachineConsumed:N,requestedMobileSection:_,onRequestedMobileSectionConsumed:C,onOpenHistory:a,onOpenRemote:o,onStopCli:l,wsStatus:n,isConnected:i,onShowAllHiddenConversations:Te,onHideConversation:we,onOpenMeshGraph:be,onOpenNewSession:V,liveSessionInboxState:ie}):t?r.jsx(oA,{containerRef:D,isSplitMode:T,numGroups:A,groupSizes:P,groupedConvs:F,clearedTabs:J,ides:m,actionLogs:g,sendDaemonCommand:b,setActionLogs:f,isStandalone:w,hasRegisteredMachines:Se.length>0,userName:S,focusedGroup:R,focusGroup:I,moveTabToGroup:E,splitTabRelative:$,closeGroup:M,handleResizeStart:O,groupActiveTabIds:H,setGroupActiveTab:ae,groupTabOrders:z,setGroupTabOrder:X,toggleHiddenTab:te,onOpenNewSession:V,allowTabShortcuts:!1,liveSessionInboxState:ie}):r.jsx(NA,{visibleConversations:he,clearedTabs:J,ides:m,actionLogs:g,sendDaemonCommand:b,setActionLogs:f,isStandalone:w,hasRegisteredMachines:Se.length>0,initialDataLoaded:x,userName:S,toggleHiddenTab:te,actionShortcuts:Ye,registerActionHandlers:fe=>{je.current=fe},onActiveTabChange:q,requestedActiveTabKey:ke,onRequestedActiveTabConsumed:Q,onRequestScrollToBottom:me,scrollToBottomRequest:le,onOpenNewSession:V,liveSessionInboxState:ie,layoutProfile:ge}),ft&&r.jsx(DA,{machines:Se,ides:m,onClose:ne,onBrowseDirectory:G,onSaveWorkspace:W,onLaunchIde:Z,onLaunchProvider:oe,onListMeshes:ue,onLaunchMeshCoordinator:ce,onListSavedSessions:L}),Ne&&r.jsx(ZM,{activeConv:Ne,sendDaemonCommand:b,onClose:()=>ee(null)}),xe&&r.jsx(Pb,{daemonId:xe.daemonId,workspace:xe.workspace,onClose:()=>ve(null)}),lt&&r.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:Ge,children:r.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:fe=>fe.stopPropagation(),children:[r.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),r.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."})]}),r.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:Ge,"aria-label":"Close dashboard guide",children:r.jsx(Ot,{size:14})})]}),r.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(fe=>r.jsx("button",{type:"button",className:`btn btn-sm ${_t===fe.id?"btn-primary":"btn-secondary"}`,onClick:()=>De(fe.id),children:fe.label},fe.id))}),_t==="overview"&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[r.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),r.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[r.jsxs("div",{children:[r.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),r.jsxs("div",{children:[r.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."]}),r.jsxs("div",{children:[r.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),r.jsxs("div",{children:[r.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),r.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[r.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),r.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[r.jsxs("div",{children:[r.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."]}),r.jsxs("div",{children:[r.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."]}),r.jsxs("div",{children:[r.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."]}),r.jsxs("div",{children:[r.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."]}),r.jsxs("div",{children:[r.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."]}),r.jsxs("div",{children:[r.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."]}),r.jsxs("div",{children:[r.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",ze?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),_t==="quickstart"&&r.jsxs("div",{className:"space-y-4",children:[r.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[r.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),r.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[r.jsxs("div",{children:[r.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."]}),r.jsxs("div",{children:[r.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),r.jsxs("div",{children:[r.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),r.jsxs("div",{children:[r.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."]})]})]}),r.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[r.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),r.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[r.jsxs("div",{children:[r.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."]}),r.jsxs("div",{children:[r.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."]}),r.jsxs("div",{children:[r.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."]})]})]})]}),_t==="shortcuts"&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[r.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(fe=>r.jsx("button",{type:"button",className:`btn btn-sm ${Mt===fe.id?"btn-primary":"btn-secondary"}`,onClick:()=>He(fe.id),children:fe.label},fe.id))}),r.jsxs("div",{className:"flex flex-wrap gap-2",children:[r.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:pe,children:"Disable all"}),r.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:Be,children:"Reset to defaults"})]})]}),r.jsx("div",{className:"space-y-2",children:gs.map(fe=>r.jsx("div",{className:`rounded-xl border px-4 py-3 ${rt===fe.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:r.jsxs("div",{className:"flex items-start justify-between gap-4",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("div",{className:"text-sm font-semibold text-text-primary",children:fe.label}),r.jsx("div",{className:"text-xs text-text-secondary mt-1",children:fe.description}),r.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",r.jsx("span",{className:"font-mono",children:fe.defaultShortcut})]})]}),r.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[r.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:rt===fe.id?Ct.length>0?`${Ct.join(" ")} ...`:"Listening...":Ye[fe.id]||"Off"}),r.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Ut(fe.id),Rt([])},children:rt===fe.id?"Listening":"Set"}),r.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Fe={...Ye};Fe[fe.id]="",It(Fe)},children:"Disable"})]})]})},fe.id))}),r.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",ze?"⌘⇧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 vc=[{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 vE({onClose:e}){const[t,s]=u.useState(0),n=vc[t],i=t===vc.length-1;return r.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:a=>{a.stopPropagation()},children:[r.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:[r.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:r.jsx(Ot,{size:20})}),r.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:vc.map((a,o)=>r.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))}),r.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),r.jsxs("div",{style:{textAlign:"center"},children:[r.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[r.jsx("span",{children:n.icon})," ",n.title]}),r.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&r.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:[r.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),i&&r.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 →"})]}),r.jsx("div",{className:"flex justify-end items-center mt-6",children:r.jsx("button",{onClick:()=>i?e():s(a=>a+1),className:"btn btn-primary",children:i?"Get Started →":"Next →"})})]}),r.jsx("style",{children:`
|
|
85
|
+
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
86
|
+
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
87
|
+
`})]})}function wE({hasExtensions:e,ideName:t,activeChatTab:s,extensionTabs:n,onSelectTab:i}){return e?r.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[r.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)] ${s==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>i("native"),children:t}),n.map(a=>{const o=s===a.tabKey,l=a.status==="waiting_approval",c=a.status==="generating";return r.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:()=>i(a.tabKey),children:[r.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":c?"var(--accent-primary)":"var(--text-muted)",boxShadow:c?"0 0 6px var(--accent-primary)":"none"}}),a.title,l&&r.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:"!"})]},a.tabKey)})]}):null}function SE({ideData:e,allIdes:t,connectionStates:s,ideName:n,preferredTabKey:i}){const[a,o]=u.useState(()=>i||"native"),l=u.useMemo(()=>rx(t),[t]),c=u.useMemo(()=>e?fu(e,{machineNames:l,connectionStates:s,defaultConnectionState:"new"}):[],[e,l,s]),d=u.useMemo(()=>c.find(f=>f.streamSource==="native"),[c]),p=u.useMemo(()=>c.filter(f=>f.streamSource==="agent-stream"),[c]),h=u.useMemo(()=>e?js(c,e.id):null,[c,e]);u.useEffect(()=>{i&&o(i)},[i]),u.useEffect(()=>{if(i||!h)return;const f=h.streamSource==="native"?"native":h.tabKey;!f||a===f||a==="native"&&o(f)},[a,h,i]),u.useEffect(()=>{var f;a!=="native"&&(p.some(v=>v.tabKey===a)||o(((f=p[0])==null?void 0:f.tabKey)||"native"))},[a,p]),u.useEffect(()=>{a==="native"&&(d||p[0]&&o(p[0].tabKey))},[a,d,p]);const m=u.useMemo(()=>a==="native"&&d?d:p.find(f=>f.tabKey===a)||h||d||p[0],[a,d,h,p]),g=u.useMemo(()=>p.map(f=>({tabKey:f.tabKey,title:qg(f)||n,status:f.status})),[p,n]),b=u.useCallback(f=>{if(f)return c.find(v=>rd(v,{sessionId:f,routeId:f,tabKey:f,providerSessionId:f}))},[c]);return{activeChatTab:a,setActiveChatTab:o,activeConv:m,conversations:c,extensionTabs:g,hasExtensions:g.length>0,resolveConversationByTarget:b}}function kE({activeConv:e,ideEntry:t,ides:s,connectionStates:n,actionLogs:i,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,userName:c,onOpenHistory:d,onConversationChange:p,onClose:h}){const[m,g]=u.useState("split"),[b,f]=u.useState(()=>dr(e)?"native":e.tabKey),v=u.useRef(null),w=u.useMemo(()=>t||s.find(I=>I.id===e.routeId),[e.routeId,t,s]),x=u.useMemo(()=>Vt((w==null?void 0:w.type)||""),[w==null?void 0:w.type]),{conversations:S,extensionTabs:k,hasExtensions:j}=SE({ideData:w,allIdes:s,connectionStates:n,ideName:x||"IDE",preferredTabKey:dr(e)?void 0:e.tabKey}),y=u.useMemo(()=>w?js(S,w.id):null,[w,S]);u.useEffect(()=>{const I=v.current,E={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(v.current=E,!(I&&I.routeId===E.routeId&&I.tabKey===E.tabKey&&I.streamSource===E.streamSource)){if(dr(e)){f("native");return}f(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),u.useEffect(()=>{if(b==="native"){if(S.some(I=>I.streamSource==="native"))return;(y==null?void 0:y.streamSource)==="agent-stream"&&f(y.tabKey);return}if(!S.some(I=>I.tabKey===b)){if((y==null?void 0:y.streamSource)==="agent-stream"){f(y.tabKey);return}f("native")}},[S,b,y]);const N=u.useMemo(()=>b==="native"?S.find(I=>I.streamSource==="native")||e:S.find(I=>I.tabKey===b)||e,[e,S,b]),_=fx(N),C=u.useMemo(()=>_.status||_.modalMessage||_.modalButtons?{...N,..._.status?{status:_.status}:{},..._.modalMessage!==void 0?{modalMessage:_.modalMessage}:{},..._.modalButtons!==void 0?{modalButtons:_.modalButtons}:{}}:N,[N,_]),D=Vi(C),T=cl({sendDaemonCommand:a,activeConv:C,setActionLogs:o,isStandalone:l}),{connScreenshot:A,screenshotUsage:P,handleRemoteAction:F}=Kx({doId:D,targetSessionId:Tg(C),connState:C.connectionState||"new",viewMode:m}),J=u.useMemo(()=>i.filter(I=>I.routeId===C.tabKey),[i,C.tabKey]);u.useEffect(()=>{p==null||p(C)},[C,p]),u.useEffect(()=>{const I=E=>{E.key==="Escape"&&h()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[h]);const R=u.useCallback(I=>{I.stopPropagation()},[]);return r.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:h,children:r.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:R,children:[r.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:[r.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[r.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:r.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:[r.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:r.jsx(_s,{size:16})}),r.jsx("span",{className:"truncate",children:ou(N)||"Remote"})]})}),r.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,children:"Close"})]}),r.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[r.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(I=>{const E=m===I;return r.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${E?"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:()=>g(I),title:I==="split"?"Split view":"Remote only",children:I==="split"?r.jsx(PS,{size:15}):r.jsx(_s,{size:15})},I)})}),r.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),r.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>d(N),title:"Chat History",children:[r.jsx(Gd,{size:14,className:"md:mr-1.5"}),r.jsx("span",{className:"hidden md:inline",children:"History"})]}),r.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:h,children:"Close"})]})]}),r.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"&&r.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:[r.jsx(wE,{hasExtensions:j,ideName:x||"IDE",activeChatTab:b,extensionTabs:k,onSelectTab:f}),r.jsx(pg,{activeConv:C,onModalButton:T.handleModalButton}),r.jsx(od,{activeConv:C,ideEntry:w,showMetaChips:!1,handleSendChat:T.handleSendChat,handleForceSendChat:T.handleForceSendChat,isSendingChat:T.isSendingChat,sendFeedbackMessage:T.sendFeedbackMessage,handleFocusAgent:T.handleFocusAgent,isFocusingAgent:T.isFocusingAgent,actionLogs:J,userName:c})]}),r.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${m==="split"?"order-1 md:order-2":""}`,children:r.jsx(lg,{addLog:()=>{},connState:C.connectionState||"new",connScreenshot:A,screenshotUsage:P,transportType:C.transport,onAction:F})})]})]})})}function jE({activeConv:e,canSaveAndStop:t=!1,onCancel:s,onStopNow:n,onSaveAndStop:i}){const a=P1(e);return r.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:[r.jsx("div",{onClick:s,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),r.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:[r.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[r.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",a,"?"]}),r.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."})]}),r.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&r.jsx("button",{onClick:i,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),r.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"}),r.jsx("button",{onClick:s,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function NE({historyModal:e,remoteDialog:t,cliStopDialog:s,connectionBanner:n,toastOverlay:i,onboarding:a,interactivePrompt:o}){var l;return r.jsxs(r.Fragment,{children:[r.jsx(X1,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&r.jsx(tx,{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&&r.jsx(kE,{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}),s.open&&s.targetConv&&(dt(s.targetConv)||at(s.targetConv))&&r.jsx(jE,{activeConv:s.targetConv,canSaveAndStop:dt(s.targetConv)&&!at(s.targetConv)&&!!((l=s.targetConv.resume)!=null&&l.supported),onCancel:s.onCancel,onStopNow:s.onStopNow,onSaveAndStop:s.onSaveAndStop}),r.jsx(sx,{toasts:i.toasts,onDismiss:i.onDismiss,onClickToast:i.onClick}),r.jsx(dg,{promptSession:(o==null?void 0:o.promptSession)??null,isSubmitting:(o==null?void 0:o.isSubmitting)??!1,error:(o==null?void 0:o.responseError)??null,onSubmit:(o==null?void 0:o.submit)??(async()=>{}),onCancel:(o==null?void 0:o.cancel)??(()=>{})}),a.open&&r.jsx(vE,{onClose:a.onClose})]})}function _E({daemons:e,targetVersion:t,required:s=!1,upgradingDaemons:n,onUpgrade:i,onDismiss:a}){return e.length===0?null:r.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:s?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:s?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[r.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:s?"var(--status-danger)":"var(--status-warning)"},children:r.jsx(il,{size:14})}),r.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[r.jsxs("span",{children:[s?"Daemon update required":"Update available",t?r.jsxs(r.Fragment,{children:[": ",r.jsxs("strong",{children:["v",t]})]}):null]}),e.map(o=>{const l=hs(o,{fallbackId:o.id}),c=n[o.id],d=o.version||o.daemonVersion||"unknown",p=o.versionUpdateRequired===!0,m=Ax(o)==="preview"?"Update to preview":p?"Update now":"Upgrade";return r.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:p?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${p?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[r.jsx("span",{className:"font-medium text-text-primary",children:l}),r.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",d]}),p&&r.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),c==="upgrading"?r.jsx("span",{className:"text-[10px] animate-pulse",style:{color:p?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):c==="done"?r.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):c==="error"?r.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>i(o.id),children:"retry"}):r.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:p?"var(--status-danger)":"var(--status-warning)",background:p?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${p?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>i(o.id),children:m})]},o.id)})]}),!s&&r.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:a,title:"Dismiss",children:r.jsx(Ot,{size:16})})]})}function CE(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function IE(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 AE(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>IE(t)).map(t=>t.id)}}function TE(){var Op,Fp,Bp,Wp;const{sendCommand:e}=jt(),t=Xi(),s=mx(),n=Ud(),i=zi(),[a,o]=Pw(),l=a.get("activeTab"),c=((Op=n.state)==null?void 0:Op.openRemoteForTabKey)||null,d=((Fp=n.state)==null?void 0:Fp.openMachineId)||null,p=((Bp=n.state)==null?void 0:Bp.mobileSection)||null,h=Hg(),m=h.ides||[],g=h.initialLoaded??!0,{updateRouteChats:b,setToasts:f}=h,[v,w]=u.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),x=h.toasts||[],S=h.wsStatus||"connected",k=h.isConnected??!0,j=h.connectionStates||{},y=h.showReconnected||!1,{layoutProfile:N,groupAssignments:_,updateGroupAssignments:C,focusedGroup:D,updateFocusedGroup:T,focusGroup:A,groupActiveTabIds:P,updateGroupActiveTabIds:F,setGroupActiveTab:J,groupTabOrders:R,updateGroupTabOrders:I,setGroupTabOrder:E,groupSizes:$,updateGroupSizes:M,isMobile:O,hasHydratedStoredLayout:H,hydrateStoredLayout:ae,focusConversationTab:z}=VC(),[X,te]=u.useState(()=>yu());u.useEffect(()=>Z_(te),[]);const he=u.useMemo(()=>CE({isMobile:O,mobileViewMode:X}),[O,X]),[ke,Q]=u.useState([]),[q,me]=u.useState({}),[we,ye]=u.useState({});qi("Dashboard",{ideCount:m.length,toastCount:x.length,focusedGroup:D,groupCount:Object.keys(_).length,actionLogCount:ke.length});const Te=u.useMemo(()=>m.filter(Je=>Je.type==="adhdev-daemon").sort(Zd),[m]),Se=!!Te[0];u.useEffect(()=>{const{metadataDaemonIds:Je,runtimeDaemonIds:xs}=AE(Te);for(const Rn of Je)t(Rn,{minFreshMs:3e4}).catch(()=>{});for(const Rn of xs)s(Rn,{minFreshMs:3e4}).catch(()=>{})},[t,s,Te]);const ge=u.useMemo(()=>vC(m,q),[m,q]),{hiddenTabs:G,autoHiddenTabs:W,autoHideTarget:Z,hideTarget:oe,toggleTarget:ue,showTarget:ce,showAllTabs:L}=uC(),{conversations:de,visibleConversations:U,visibleTabKeys:ie,resolveConversationBySessionId:Y,resolveConversationByTarget:Ae}=RC({ides:ge,connectionStates:j,clearedTabs:we,hiddenTabs:G}),Ce=u.useMemo(()=>new Map(de.map(Je=>[Je.tabKey,Je])),[de]),je=u.useMemo(()=>dC(de,G,W),[de,G,W]);u.useEffect(()=>{for(const Je of je)Z(Je)},[je,Z]),a1(U,he),u.useEffect(()=>{Object.keys(q).length!==0&&me(Je=>wC(Je,m))},[m,q]);const qe=u.useMemo(()=>Rk(m),[m]),{notifications:it,unreadCount:lt}=dI({conversations:de,liveSessionInboxState:qe}),{handleMarkDashboardNotificationRead:ft,handleMarkDashboardNotificationUnread:ct,handleDeleteDashboardNotification:_t}=uI({notifications:it,sendDaemonCommand:e}),{containerRef:Mt,normalizedGroupAssignments:Et,numGroups:De,isSplitMode:He,groupedConvs:pt,moveTabToGroup:Ze,closeGroup:Lt,handleResizeStart:B,splitTabRelative:V}=tI({groupAssignments:_,updateGroupAssignments:C,updateFocusedGroup:T,updateGroupActiveTabIds:F,updateGroupTabOrders:I,groupSizes:$,updateGroupSizes:M,isMobile:O,visibleConversations:U,visibleTabKeys:ie}),{activeConv:ne,openDesktopConversation:xe,requestScrollToBottom:ve,scrollToBottomRequest:Ne,setDesktopActiveTab:ee}=jI({isMobile:O,conversations:de,visibleConversations:U,groupActiveTabIds:P,focusedGroup:D,groupedConvs:pt,setSearchParams:o});CI({activeConv:ne,isMobile:O,liveSessionInboxState:qe,sendDaemonCommand:e});const{requestedDesktopTabKey:se,requestedMobileTabKey:be,consumeRequestedActiveTab:Me}=PC({isMobile:O,urlActiveTab:l,resolveConversationBySessionId:Y,setSearchParams:o}),{remoteDialogConv:$e,remoteDialogIdeEntry:Re,remoteDialogActiveConv:Oe,setRemoteDialogActiveConv:ze,openRemoteDialog:Le,closeRemoteDialog:Ye,cliStopDialogOpen:rt,cliStopTargetConv:Ct,requestCliStop:Ut,cancelCliStop:Rt,confirmCliStop:It}=TI({isMobile:O,location:n,navigate:i,requestedRemoteTabTarget:c,requestedDesktopTabKey:se,conversations:de,ides:m,resolveConversationByTarget:Ae,activeConv:ne,sendDaemonCommand:e}),{historyModalOpen:Ge,openHistoryModal:gs,closeHistoryModal:pe,historyTargetConv:Be,isSavedSessionHistoryTarget:fe,isHistoryCreatingChat:Fe,isHistoryRefreshingHistory:Gt,handleHistorySwitchSession:es,handleHistoryNewChat:Qs,handleHistoryRefresh:Ue,savedHistorySessions:ut,savedHistoryFilters:Js,setSavedHistoryFilters:ma,missingWorkspaceResumePath:fa,isSavedHistoryLoading:ga,resumingSavedHistorySessionId:xa,handleRefreshSavedHistory:ba,handleResumeSavedHistorySession:ya}=II({activeConv:ne,remoteDialogConv:$e,remoteDialogActiveConv:Oe,ides:m,sendDaemonCommand:e,updateRouteChats:b,setToasts:f,setClearedTabs:ye,setSearchParams:o}),va=u.useMemo(()=>U,[U]),xr=O&&X==="chat",wa=u.useMemo(()=>de.filter(Je=>pl(G,Je)),[de,G]),Dp=u.useCallback(Je=>{const xs=new URLSearchParams(a);xs.set("activeTab",Je),o(xs,{replace:!0})},[a,o]),{trackPendingLaunch:Gv}=vI({ides:m,conversations:de,onOpenSession:Dp}),{handleBrowseMachineDirectory:qv,handleSaveMachineWorkspace:Vv,handleLaunchMachineIde:Xv,handleLaunchMachineProvider:Yv,handleListMachineMeshes:Qv,handleLaunchMeshCoordinator:Jv,handleListMachineSavedSessions:Zv,setActiveCliViewMode:ew}=wI({sendDaemonCommand:e,trackPendingLaunch:Gv,onOpenSession:Dp,activeConv:ne,ides:m,setCliViewModeOverrides:me});SC({visibleConversations:U,clearedTabs:we,setClearedTabs:ye,setActionLogs:Q}),DC({ides:m,sendDaemonCommand:e,setToasts:f,resolveConversationByTarget:Ae});const tw=yx(),{isRefreshingHistory:sw,handleRefreshHistory:rw}=Ix({sendDaemonCommand:e,activeConv:ne,chats:(Wp=m.find(Je=>Je.id===(ne==null?void 0:ne.routeId)))==null?void 0:Wp.chats,updateRouteChats:b,setToasts:f,setClearedTabs:ye});YC({urlActiveTab:O&&!xr?l:null,conversations:de,resolveConversationBySessionId:Y,normalizedGroupAssignments:Et,hasHydratedStoredLayout:O&&!xr?H:!0,hydrateStoredLayout:O&&!xr?ae:()=>{},focusConversationTab:z,setSearchParams:o,historyModalOpen:Ge,activeConv:ne,isRefreshingHistory:sw,ides:m,handleRefreshHistory:rw});const nw=u.useMemo(()=>!ne||!dt(ne)||at(ne)?null:Tn(ne),[ne]),{versionMismatchDaemons:iw,hasRequiredVersionDaemons:Lp,targetVersion:aw,versionBannerDismissed:ow,setVersionBannerDismissed:lw,upgradingDaemons:cw,handleBannerUpgrade:dw}=rI({ides:m,sendDaemonCommand:e}),$p=u.useCallback(Je=>{ce(Je),xe(Je)},[xe,ce]),uw=u.useCallback(Je=>{oe(Je)},[oe]);return r.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[(!ow||Lp)&&r.jsx(_E,{daemons:iw,targetVersion:aw,required:Lp,upgradingDaemons:cw,onUpgrade:dw,onDismiss:()=>lw(!0)}),r.jsx(yE,{showMobileChatMode:xr,isMobile:O,activeConv:ne,wsStatus:S,isConnected:k,onOpenHistory:Je=>{Je&&ze(Je),gs()},onOpenRemote:Le,onStopCli:Ut,activeCliViewMode:nw,onSetActiveCliViewMode:ew,mobileChatConversations:va,ides:m,actionLogs:ke,sendDaemonCommand:e,setActionLogs:Q,setCliViewModeOverrides:me,isStandalone:Se,initialDataLoaded:g,userName:h.userName,requestedMobileTabKey:be,onRequestedMobileTabConsumed:Me,requestedMachineId:d,onRequestedMachineConsumed:()=>{i(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:p,onRequestedMobileSectionConsumed:()=>{i(n.pathname+n.search,{replace:!0,state:null})},containerRef:Mt,isSplitMode:He,numGroups:De,groupSizes:$,groupedConvs:pt,clearedTabs:we,focusedGroup:D,focusGroup:A,moveTabToGroup:Ze,splitTabRelative:V,closeGroup:Lt,handleResizeStart:B,groupActiveTabIds:P,setGroupActiveTab:J,groupTabOrders:R,setGroupTabOrder:E,toggleHiddenTab:Je=>ue(Ce.get(Je)||{tabKey:Je}),visibleConversations:U,hiddenConversations:wa,requestedDesktopTabKey:se,onRequestedDesktopTabConsumed:Me,onDesktopActiveTabChange:ee,onRequestScrollToBottom:ve,onHideConversation:uw,onShowHiddenConversation:$p,onShowAllHiddenConversations:L,scrollToBottomRequest:Ne,machineEntries:Te,layoutProfile:N,onBrowseMachineDirectory:qv,onSaveMachineWorkspace:Vv,onLaunchMachineIde:Xv,onLaunchMachineProvider:Yv,onListMachineMeshes:Qv,onLaunchMeshCoordinator:Jv,onListMachineSavedSessions:Zv,notifications:it,notificationUnreadCount:lt,liveSessionInboxState:qe,onMarkNotificationRead:ft,onMarkNotificationUnread:ct,onDeleteNotification:_t}),r.jsx("style",{children:`
|
|
88
|
+
body { overflow: hidden; overscroll-behavior: none; }
|
|
89
|
+
`}),r.jsx(NE,{historyModal:{open:Ge,targetConv:Be,ides:m,isCreatingChat:Fe,isRefreshingHistory:fe?!1:Gt,savedSessions:ut,savedHistoryFilters:Js,missingWorkspaceResumePath:fa||null,onSavedHistoryFiltersChange:ma,isSavedSessionsLoading:ga,isResumingSavedSessionId:xa,onClose:pe,onNewChat:Qs,onSwitchSession:es,onRefreshHistory:fe?ba:Ue,onResumeSavedSession:ya},remoteDialog:{conversation:$e,ideEntry:Re,ides:m,connectionStates:j,actionLogs:ke,sendDaemonCommand:e,setActionLogs:Q,isStandalone:Se,userName:h.userName,onOpenHistory:Je=>{Je&&ze(Je),gs()},onConversationChange:ze,onClose:Ye},cliStopDialog:{open:rt,targetConv:Ct,onCancel:Rt,onStopNow:async()=>{await It("hard")},onSaveAndStop:async()=>{await It("save")}},connectionBanner:{wsStatus:S,showReconnected:y,loginUrl:h.connectionLoginUrl,onReconnect:h.retryServerConnection},toastOverlay:{toasts:x,onDismiss:Je=>f(xs=>xs.filter(Rn=>Rn.id!==Je)),onClick:Je=>{if(Je.targetKey){const xs=Ae(Je.targetKey);xs&&(z(xs.tabKey,Et),$p(xs),ve(xs.tabKey,"toast-open"))}}},onboarding:{open:v,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}w(!1)}},interactivePrompt:tw})]})}function ME({machineId:e,registeredMachineId:t,sendDaemonCommand:s,onNicknameSynced:n,logsEndRef:i}){const{launchCli:a}=rl(),[o,l]=u.useState([]),[c,d]=u.useState(null),[p,h]=u.useState(null),[m,g]=u.useState(!1),[b,f]=u.useState(null),[v,w]=u.useState(!1),[x,S]=u.useState(""),k=u.useRef(null),j=u.useCallback(M=>{k.current=M},[]),y=u.useCallback((M,O,H=!1)=>{l(ae=>[...ae.slice(-100),{timestamp:Date.now(),level:M,message:O}]),setTimeout(()=>{var ae;return(ae=i.current)==null?void 0:ae.scrollIntoView({behavior:"smooth"})},100),H&&ht.showToast(O,M==="error"||M==="warn"?"warning":"success")},[i]),N=u.useCallback(M=>{const O=M instanceof Error?M.message:String(M||"");return O.includes("P2P command timeout")||O.includes("P2P not connected")||O.includes("P2P not available")},[]),_=u.useCallback(async(M,O)=>{var H;if(!e||c)return!1;d(M),y("info",`Launching ${Vt(M)}${O!=null&&O.workspace?` in ${O.workspace}`:""}...`);try{const ae={ideType:M,enableCdp:!0};(H=O==null?void 0:O.workspace)!=null&&H.trim()?ae.workspace=O.workspace.trim():O!=null&&O.useDefaultWorkspace&&(ae.useDefaultWorkspace=!0);const z=await s(e,"launch_ide",ae);return y(z!=null&&z.success?"info":"error",z!=null&&z.success?`${Vt(M)} launched`:`Failed: ${z==null?void 0:z.error}`,!0),!!(z!=null&&z.success)}catch(ae){return y("error",`Launch error: ${ae.message}`,!0),!1}finally{d(null)}},[e,c,y,s]),C=u.useCallback(async M=>{if(!e)return{success:!1};const{cliType:O,dir:H,workspaceId:ae,useDefaultWorkspace:z,useHome:X,argsStr:te,model:he,resumeSessionId:ke}=M;if(!O)return y("warn","Select a CLI or ACP provider first",!0),{success:!1};const Q=te?te.split(/\s+/).filter(Boolean):void 0,q=(H==null?void 0:H.trim())||(ae?"(saved id)":z?"(default workspace)":X?"(home)":"");y("info",`Launching ${O}${q?` in ${q}`:""}${he?` (model: ${he})`:""}...`),h(O);try{const me={cliType:O,cliArgs:Q,initialModel:he||void 0};H!=null&&H.trim()?me.dir=H.trim():ae?me.workspaceId=ae:z?me.useDefaultWorkspace=!0:X&&(me.useHome=!0),ke&&(me.resumeSessionId=ke);const we=await a(e,me),ye=(we==null?void 0:we.result)||we;return we!=null&&we.success?(y("info",`${O} launched`,!0),(ye==null?void 0:ye.launchSource)==="home"?y("info","📂 Running in home directory (explicit choice)"):(ye==null?void 0:ye.launchSource)==="defaultWorkspace"&&y("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ye==null?void 0:ye.sessionId}):(y("error",`Failed: ${(we==null?void 0:we.error)||(ye==null?void 0:ye.error)}`,!0),(we==null?void 0:we.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&f({cliType:O,argsStr:te,model:he}),{success:!1,sessionId:ye==null?void 0:ye.sessionId})}catch(me){return N(me)?(y("warn",`${O} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(y("error",`Launch error: ${me.message}`,!0),{success:!1})}finally{h(null)}},[e,y,N,s]),D=u.useCallback(async(M,O,H,ae)=>e?M?O.trim()?C({cliType:M,dir:O,argsStr:H,model:ae}):(f({cliType:M,argsStr:H,model:ae}),{success:!1}):(y("warn","Select a provider",!0),{success:!1}):{success:!1},[e,y,C]),T=u.useCallback(async(M,O,H)=>{if(e&&window.confirm(`Stop ${M}?
|
|
90
|
+
This will terminate the process.`))try{const ae=await s(e,"stop_cli",{cliType:M,dir:O,targetSessionId:H});ae!=null&&ae.success?y("info",`${M} stopped`,!0):y("error",`Stop failed: ${(ae==null?void 0:ae.error)||"Unknown error"}`,!0)}catch(ae){y("error",`Stop failed: ${ae.message}`,!0)}},[e,y,s]),A=u.useCallback(async M=>{try{await s(M.daemonId,"restart_ide",{ideType:M.type}),y("info",`${Vt(M.type)} restart initiated`,!0)}catch(O){y("error",`Restart failed: ${O.message}`,!0)}},[y,s]),P=u.useCallback(async M=>{if(window.confirm(`Stop ${Vt(M.type)}?
|
|
91
|
+
This will disconnect CDP and optionally kill the process.`))try{const O=await s(M.daemonId,"stop_ide",{ideType:M.type,killProcess:!0});O!=null&&O.success?y("info",`${Vt(M.type)} stopped`,!0):y("error",`Stop failed: ${(O==null?void 0:O.error)||"Unknown error"}`,!0)}catch(O){y("error",`Stop failed: ${O.message}`,!0)}},[y,s]),F=u.useCallback(async()=>{if(e)try{const M=await s(e,"detect_ides",{});y("info",`Found ${((M==null?void 0:M.result)||[]).length} IDE(s)`,!0)}catch(M){y("error",`Detection failed: ${M.message}`,!0)}},[e,y,s]),J=u.useCallback(async M=>{if(!e||!M.trim())return!1;g(!0);try{const O=await s(e,"workspace_add",{path:M.trim()});return O!=null&&O.success?(y("info",`Workspace added: ${M.trim()}`),!0):(y("error",(O==null?void 0:O.error)||"workspace_add failed"),!1)}catch(O){return y("error",O.message),!1}finally{g(!1)}},[e,y,s]),R=u.useCallback(async M=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){g(!0);try{const O=await s(e,"workspace_remove",{id:M});O!=null&&O.success?y("info","Workspace removed",!0):y("error",(O==null?void 0:O.error)||"workspace_remove failed",!0)}catch(O){y("error",O.message,!0)}finally{g(!1)}}},[e,y,s]),I=u.useCallback(async M=>{var O;if(e){g(!0);try{const H=await s(e,"workspace_set_default",M===null?{clear:!0}:{id:M});if(H!=null&&H.success){y("info",M?"Default workspace updated":"Default workspace cleared",!0);const ae=typeof H.defaultWorkspacePath=="string"?H.defaultWorkspacePath:"";ae&&((O=k.current)==null||O.call(k,ae))}else y("error",(H==null?void 0:H.error)||"workspace_set_default failed",!0)}catch(H){y("error",H.message,!0)}finally{g(!1)}}},[e,y,s]),E=u.useCallback(async M=>{var H;if(!e||!M.trim())return;const O=M.trim();g(!0);try{const ae=await s(e,"workspace_set_default",{path:O});ae!=null&&ae.success?(y("info","Default workspace set from history"),(H=k.current)==null||H.call(k,O)):y("error",(ae==null?void 0:ae.error)||"Could not set default (path missing on disk?)")}catch(ae){y("error",ae.message)}finally{g(!1)}},[e,y,s]),$=u.useCallback(async()=>{if(e)try{if(await s(e,"set_machine_nickname",{nickname:x}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:x})}catch(M){y("warn",`Live nickname updated, but account sync failed: ${M.message}`)}y("info",`Nickname set to "${x||"(cleared)"}"`),w(!1)}catch(M){y("error",`Failed: ${M.message}`)}},[e,x,t,y,n,s]);return{logs:o,launchingIde:c,launchingAgentType:p,workspaceBusy:m,launchPick:b,setLaunchPick:f,editingNickname:v,setEditingNickname:w,nicknameInput:x,setNicknameInput:S,addLog:y,handleLaunchIde:_,runLaunchCliCore:C,handleLaunchCli:D,handleStopCli:T,handleRestartIde:A,handleStopIde:P,handleDetectIdes:F,handleWorkspaceAdd:J,handleWorkspaceRemove:R,handleWorkspaceSetDefault:I,handleWorkspaceResumePath:E,handleSaveNickname:$,setOnDefaultWorkspaceChanged:j}}function EE({machine:e,ideSessions:t,cliSessions:s,acpSessions:n}){var c;const i=typeof e.uptime=="number"||typeof e.freeMem=="number"||typeof e.availableMem=="number"||Array.isArray(e.loadavg)&&e.loadavg.length>0,a=e.availableMem??e.freeMem??e.totalMem,o=i&&e.totalMem>0?Math.min(100,Math.max(0,Math.round((e.totalMem-a)/e.totalMem*100))):0,l=((c=e.loadavg)==null?void 0:c[0])||0;return r.jsxs("div",{children:[r.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[r.jsx(ja,{icon:r.jsx(Yf,{size:16}),label:"Uptime",value:typeof e.uptime=="number"?Fk(e.uptime):"Waiting…"}),r.jsx(ja,{icon:r.jsx(_s,{size:16}),label:"IDEs",value:`${t.length}`}),r.jsx(ja,{icon:r.jsx(Vd,{size:16}),label:"CLIs",value:`${s.length}`}),r.jsx(ja,{icon:r.jsx(LS,{size:16}),label:"ACPs",value:`${n.length}`})]}),r.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[r.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),r.jsxs("div",{className:"flex gap-6",children:[r.jsx(sh,{value:i?Math.min(Math.round(l/e.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:i?`${l.toFixed(2)} avg / ${e.cpus} cores`:"Polled from machine page"}),r.jsx(sh,{value:o,max:100,label:"Memory",color:"#3b82f6",detail:i?`${Ul(e.totalMem-a)} / ${Ul(e.totalMem)}${e.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Ul(e.totalMem)} total`})]})]})]})}function RE(e){if(!e||typeof e!="object")return null;const t=e,s=t.result&&typeof t.result=="object"?t.result:t;return!s.settings||typeof s.settings!="object"?null:{settings:s.settings,values:s.values&&typeof s.values=="object"?s.values:{}}}function PE(e,t,s){const n=[];for(const[i,a]of Object.entries(e.settings)){const o=s!=null&&s.filterSchema?s.filterSchema(a):a;if(o.length===0)continue;const l=t.find(c=>c.type===i);n.push({type:i,displayName:(l==null?void 0:l.displayName)||i,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:o,values:e.values[i]||{}})}return n}function wc(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 Am(e){if(!e||typeof e!="object")return null;if(wc(e))return e;const t=e,s=t.result;return wc(s)?s:wc(t.sourceConfig)?t.sourceConfig:null}function DE(e){const t=e.trim();return t||null}function LE({machineId:e,providers:t,sendDaemonCommand:s,onClose:n,onCreated:i}){var j;const a=t.filter(y=>y.category==="ide"),[o,l]=u.useState(((j=a[0])==null?void 0:j.type)||""),[c,d]=u.useState(""),[p,h]=u.useState(""),[m,g]=u.useState(!1),[b,f]=u.useState(""),[v,w]=u.useState(!1),x=y=>{const N=y.toLowerCase().replace(/[^a-z0-9-]/g,"");d(N),(!p||p===S(c))&&h(S(N))},S=y=>y.split("-").map(N=>N.charAt(0).toUpperCase()+N.slice(1)).join(" "),k=async()=>{if(!(!c||!p||!o)){g(!0),f("");try{const y=await s(e,"provider_clone",{type:c,name:p,category:"ide",location:"user",cloneFrom:o});y!=null&&y.success||y!=null&&y.created?(w(!0),i==null||i(c)):f((y==null?void 0:y.error)||"Failed to create provider")}catch(y){f((y==null?void 0:y.message)||"Connection failed")}g(!1)}};return r.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:r.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:y=>y.stopPropagation(),children:[r.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[r.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),r.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),r.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:v?r.jsxs("div",{className:"text-center py-6",children:[r.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),r.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),r.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[r.jsx("code",{className:"text-violet-400",children:c})," has been created at ",r.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",c,"/"]})]}),r.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",r.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",c]})," or use Auto-Fix to implement scripts."]})]}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{children:[r.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),r.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:a.map(y=>r.jsxs("button",{onClick:()=>l(y.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:o===y.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:o===y.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[r.jsx("div",{className:"text-lg",children:y.icon}),r.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:o===y.type?"#a78bfa":"var(--text-secondary)"},children:y.displayName})]},y.type))})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),r.jsx("input",{value:c,onChange:y=>x(y.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"}),r.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",r.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",c||"...","/"]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),r.jsx("input",{value:p,onChange:y=>h(y.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&&r.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})]})}),r.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:v?r.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),r.jsx("button",{onClick:k,disabled:!c||!p||m,className:"machine-btn",style:{background:c&&p?"rgba(34,197,94,0.12)":void 0,borderColor:c&&p?"rgba(34,197,94,0.3)":void 0,color:c&&p?"#86efac":void 0,opacity:!c||!p||m?.4:1},children:m?"⏳ Creating...":"✨ Create Provider"})]})})]})})}const Tm={"user-custom":"Custom",trusted:"Official","trusted-with-scripts":"Official · runs JS","external-safe":"External · spec-only","external-untrusted":"⚠ External · untrusted JS"},$E={"user-custom":"bg-violet-500/[0.10] border-violet-500/25 text-violet-300",trusted:"bg-green-500/[0.10] border-green-500/25 text-green-400","trusted-with-scripts":"bg-emerald-500/[0.10] border-emerald-500/25 text-emerald-400","external-safe":"bg-sky-500/[0.10] border-sky-500/25 text-sky-400","external-untrusted":"bg-amber-500/[0.10] border-amber-500/30 text-amber-300"};function OE({trust:e,sourceName:t,description:s}){const n=t&&(e==="external-safe"||e==="external-untrusted")?`${Tm[e]} · ${t}`:Tm[e];return r.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded border whitespace-nowrap ${$E[e]}`,title:s,children:n})}function FE(e){if(typeof e!="string")return null;try{const t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"?t.toString():null}catch{return null}}const BE={detected:"Detected",not_detected:"Not detected",enabled_unchecked:"Enabled (unchecked)",disabled:"Disabled"},Mm={detected:"bg-green-500/[0.10] border-green-500/25 text-green-400",not_detected:"bg-red-500/[0.10] border-red-500/25 text-red-400",enabled_unchecked:"bg-yellow-500/[0.10] border-yellow-500/25 text-yellow-400",disabled:"bg-white/[0.04] border-white/[0.10] text-text-muted"},WE={acp:"bg-violet-500/10 text-violet-300 border-violet-500/20",cli:"bg-blue-500/10 text-blue-300 border-blue-500/20",ide:"bg-green-500/10 text-green-300 border-green-500/20",extension:"bg-yellow-500/10 text-yellow-300 border-yellow-500/20"};function Em(e){if(!e)return"—";const t=e.ok?"OK":"Failed",s=e.message||e.path||e.command||"";return s?`${t} — ${s}`:t}function UE(e){return e==="cli"||e==="acp"}function HE({prov:e,providerInfo:t,savingKey:s,onSetSetting:n,onEnableToggle:i,onDetect:a,onResetCommand:o}){const[l,c]=u.useState(!1),d=(t==null?void 0:t.enabled)===!0||e.values.enabled===!0,p=t==null?void 0:t.machineStatus,h=d&&p==="disabled"?"enabled_unchecked":p||(d?"enabled_unchecked":"disabled"),m=UE(e.category);return r.jsxs("div",{className:"rounded-xl bg-bg-secondary border border-border-subtle",children:[r.jsxs("button",{onClick:()=>c(g=>!g),className:"w-full px-4 py-2.5 flex items-center gap-3 text-left",children:[r.jsx("span",{className:"text-base shrink-0",children:e.icon}),r.jsx("span",{className:"text-[13px] font-semibold text-text-primary truncate",children:e.displayName}),r.jsx("span",{className:`text-[9px] font-semibold px-1.5 py-px rounded border ${WE[e.category]??"border-border-subtle text-text-muted"}`,children:e.category.toUpperCase()}),(t==null?void 0:t.trust)&&r.jsx(OE,{trust:t.trust,sourceName:t.sourceName??null,description:t.trustDescription}),m&&r.jsx("span",{className:`text-[9px] font-semibold px-1.5 py-px rounded border ${Mm[h]??Mm.disabled}`,children:BE[h]??h}),r.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[m&&r.jsx("button",{onClick:g=>{g.stopPropagation(),i(e.type,!d)},disabled:s===`${e.type}.enabled`,className:`machine-btn text-[10px] px-2 py-0.5 ${d?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:d?"Disable":"Enable"}),r.jsx("span",{className:"text-text-muted text-xs",children:l?"▾":"▸"})]})]}),l&&r.jsxs("div",{className:"border-t border-border-subtle px-4 py-3 flex flex-col gap-3",children:[r.jsxs("div",{className:"grid gap-1 text-[10px] text-text-muted",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-text-secondary font-medium",children:"Type:"})," ",r.jsx("span",{className:"font-mono",children:e.type})]}),(t==null?void 0:t.providerVersion)&&r.jsxs("div",{children:[r.jsx("span",{className:"text-text-secondary font-medium",children:"Version:"})," ",t.providerVersion]}),(t==null?void 0:t.binary)&&r.jsxs("div",{children:[r.jsx("span",{className:"text-text-secondary font-medium",children:"Binary:"})," ",r.jsx("span",{className:"font-mono",children:t.binary})]}),(t==null?void 0:t.status)&&r.jsxs("div",{children:[r.jsx("span",{className:"text-text-secondary font-medium",children:"Status:"})," ",t.status]}),(t==null?void 0:t.details)&&r.jsxs("div",{children:[r.jsx("span",{className:"text-text-secondary font-medium",children:"Details:"})," ",t.details]}),(t==null?void 0:t.sourceLayer)&&r.jsxs("div",{children:[r.jsx("span",{className:"text-text-secondary font-medium",children:"Source:"})," ",t.sourceLayer,t.sourceName?` · ${t.sourceName}`:""]}),(t==null?void 0:t.trust)&&(t==null?void 0:t.trustDescription)&&r.jsxs("div",{children:[r.jsx("span",{className:"text-text-secondary font-medium",children:"Trust:"})," ",t.trustDescription]}),(()=>{const g=t==null?void 0:t.links;if(!g)return null;const b=Object.entries(g).map(([f,v])=>({k:f,href:FE(v)})).filter(f=>f.href!==null);return b.length===0?null:r.jsxs("div",{children:[r.jsx("span",{className:"text-text-secondary font-medium",children:"Links:"})," ",b.map(({k:f,href:v})=>r.jsx("a",{href:v,target:"_blank",rel:"noopener noreferrer",className:"text-violet-400 hover:underline mr-2",children:f},f))]})})()]}),m&&r.jsxs("div",{className:"grid gap-1 text-[10px] text-text-muted",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-text-secondary font-medium",children:"Detection:"})," ",Em(t==null?void 0:t.lastDetection)]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-secondary font-medium",children:"Verification:"})," ",Em(t==null?void 0:t.lastVerification)]})]}),e.schema.length>0&&r.jsx("div",{className:"flex flex-col gap-1.5",children:e.schema.map(g=>r.jsxs("div",{className:"flex items-center justify-between gap-3",children:[r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsxs("div",{className:"text-[11px] font-medium text-text-primary",children:[g.label||g.key,s===`${e.type}.${g.key}`&&r.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving…"})]}),g.description&&r.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:g.description})]}),r.jsx("div",{className:"shrink-0",children:g.type==="boolean"?r.jsx("button",{onClick:()=>void n(e.type,g.key,!(e.values[g.key]??g.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:e.values[g.key]??g.default?"#8b5cf6":"var(--border-subtle)"},children:r.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:e.values[g.key]??g.default?21:3}})}):g.type==="number"?r.jsx("input",{type:"number",value:Number(e.values[g.key]??g.default??0)||0,min:g.min,max:g.max,onChange:b=>{const f=parseInt(b.target.value)||0;g.min!==void 0&&f<g.min||g.max!==void 0&&f>g.max||n(e.type,g.key,f)},className:"machine-input w-20 text-center text-[11px]"}):g.type==="select"&&g.options?r.jsx("select",{value:String(e.values[g.key]??g.default??""),onChange:b=>void n(e.type,g.key,b.target.value),className:"machine-input text-[11px]",children:g.options.map(b=>r.jsx("option",{value:b,children:b},b))}):r.jsx("input",{type:"text",defaultValue:String(e.values[g.key]??g.default??""),onBlur:b=>void n(e.type,g.key,b.target.value),className:"machine-input w-[180px] text-[11px]"})})]},g.key))}),r.jsx("div",{className:"flex gap-1.5 flex-wrap pt-1 border-t border-border-subtle",children:m&&r.jsxs(r.Fragment,{children:[r.jsx("button",{onClick:()=>void a(e.type),disabled:!d||s===`${e.type}.detect`,className:`machine-btn text-[10px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${d?"":"opacity-40 cursor-not-allowed"}`,title:d?"Run detection for the configured executable":"Enable provider before detection",children:"Detect"}),r.jsx("button",{onClick:()=>void o(e.type),className:"machine-btn text-[10px] px-2 py-0.5",children:"Reset command"})]})})]})]})}function Ua(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function zE({machineId:e,sendDaemonCommand:t,onChange:s}){const[n,i]=u.useState([]),[a,o]=u.useState([]),[l,c]=u.useState(!1),[d,p]=u.useState(null),[h,m]=u.useState(!1),[g,b]=u.useState(""),[f,v]=u.useState("main"),[w,x]=u.useState(""),[S,k]=u.useState(!1),[j,y]=u.useState(null),[N,_]=u.useState(null),C=u.useCallback(async()=>{if(e){c(!0),p(null);try{const P=Ua(await t(e,"list_provider_sources",{}));if(!(P!=null&&P.success)){p((P==null?void 0:P.error)||"Failed to load sources");return}i(P.sources||[]),o(P.conflicts||[])}catch(P){p((P==null?void 0:P.message)||String(P))}finally{c(!1)}}},[e,t]);u.useEffect(()=>{C()},[C]);const D=async()=>{if(g.trim()){k(!0),p(null);try{const P=Ua(await t(e,"add_provider_source",{url:g.trim(),ref:f.trim()||"main",...w.trim()?{name:w.trim()}:{}}));P!=null&&P.success?(m(!1),b(""),v("main"),x(""),await C(),s==null||s()):p((P==null?void 0:P.error)||"Failed to add source")}catch(P){p((P==null?void 0:P.message)||String(P))}finally{k(!1)}}},T=async P=>{if(confirm(`Remove provider source ${P}? This deletes the cloned manifests and clears any active-source entries that pointed here.`)){y(P),p(null);try{const F=Ua(await t(e,"remove_provider_source",{name:P}));F!=null&&F.success?(await C(),s==null||s()):p((F==null?void 0:F.error)||"Failed to remove source")}catch(F){p((F==null?void 0:F.message)||String(F))}finally{y(null)}}},A=async(P,F)=>{_(`${P}:${F}`),p(null);try{const J=Ua(await t(e,"set_active_provider_source",{type:P,sourceName:F}));J!=null&&J.success?(await C(),s==null||s()):p((J==null?void 0:J.error)||"Failed to set active source")}catch(J){p((J==null?void 0:J.message)||String(J))}finally{_(null)}};return r.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[r.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-sky-400",children:"External sources"}),r.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"3rd-party git URLs you've added. Providers here may ship JavaScript the daemon will execute — activation requires a confirmation."})]}),r.jsxs("div",{className:"flex gap-1.5",children:[r.jsxs("button",{onClick:()=>void C(),disabled:l,className:"machine-btn text-[10px]",children:[l?"⏳":"↻"," Refresh"]}),r.jsx("button",{onClick:()=>m(!0),className:"machine-btn text-[10px] bg-sky-500/[0.08] border-sky-500/20 text-sky-300 hover:bg-sky-500/[0.14]",children:"+ Add source"})]})]}),d&&r.jsx("div",{className:"mb-2 text-[11px] text-red-400 bg-red-500/10 border border-red-500/20 rounded px-2 py-1",children:d}),n.length===0?r.jsx("div",{className:"text-[11px] text-text-muted italic",children:'No external sources registered. Use "+ Add source" to register a 3rd-party provider git URL.'}):r.jsx("ul",{className:"flex flex-col gap-2",children:n.map(P=>r.jsxs("li",{className:"rounded border border-border-subtle bg-bg-primary/40 px-3 py-2",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("div",{className:"font-mono text-[12px] text-text-primary",children:P.name}),r.jsxs("div",{className:"text-[10px] text-text-muted truncate",children:[P.url," ",r.jsxs("span",{className:"opacity-60",children:["@ ",P.ref]})]})]}),r.jsx("button",{type:"button",onClick:()=>void T(P.name),disabled:j===P.name,className:"machine-btn text-[10px] text-red-400 hover:bg-red-500/[0.10]",children:j===P.name?"…":"Remove"})]}),r.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:Object.entries(P.providers).map(([F,J])=>r.jsxs("span",{className:"mr-3",children:[r.jsxs("span",{className:"text-text-secondary",children:[F,":"]})," ",J.length]},F))})]},P.name))}),a.length>0&&r.jsxs("div",{className:"mt-3 rounded border border-amber-500/30 bg-amber-500/[0.06] px-3 py-2",children:[r.jsx("div",{className:"text-[11px] font-semibold text-amber-300 mb-1.5",children:"Conflicts"}),r.jsx("div",{className:"text-[10px] text-text-muted mb-2",children:"Multiple sources expose the same provider type. Pick which source's copy should be active."}),r.jsx("ul",{className:"flex flex-col gap-1.5",children:a.map(P=>r.jsxs("li",{className:"flex items-center justify-between gap-2",children:[r.jsxs("div",{className:"font-mono text-[11px]",children:[P.type," ",r.jsxs("span",{className:"text-text-muted",children:["(",P.category,")"]})]}),r.jsx("div",{className:"flex gap-1.5 flex-wrap",children:P.candidates.map(F=>r.jsxs("button",{type:"button",onClick:()=>void A(P.type,F),disabled:N===`${P.type}:${F}`,className:`text-[10px] px-2 py-0.5 rounded border ${P.active===F?"bg-amber-500/[0.18] border-amber-500/40 text-amber-200":"border-border-subtle text-text-secondary hover:bg-amber-500/[0.06]"}`,title:P.active===F?"Active":`Switch active to ${F}`,children:[P.active===F?"● ":"",F]},F))})]},P.type))})]}),h&&r.jsxs("div",{className:"mt-3 rounded border border-sky-500/30 bg-sky-500/[0.06] px-3 py-3",children:[r.jsx("div",{className:"text-[11px] font-semibold text-sky-300 mb-2",children:"Add external source"}),r.jsxs("div",{className:"grid md:grid-cols-3 gap-2",children:[r.jsxs("label",{className:"flex flex-col gap-1 text-[10px] text-text-secondary md:col-span-3",children:[r.jsx("span",{children:"Git URL"}),r.jsx("input",{type:"text",value:g,onChange:P=>b(P.target.value),placeholder:"https://github.com/vendor/extra-providers",className:"machine-input text-[11px] font-mono"})]}),r.jsxs("label",{className:"flex flex-col gap-1 text-[10px] text-text-secondary",children:[r.jsx("span",{children:"Ref (branch/tag)"}),r.jsx("input",{type:"text",value:f,onChange:P=>v(P.target.value),placeholder:"main",className:"machine-input text-[11px]"})]}),r.jsxs("label",{className:"flex flex-col gap-1 text-[10px] text-text-secondary md:col-span-2",children:[r.jsx("span",{children:"Name (optional, auto-derived from URL)"}),r.jsx("input",{type:"text",value:w,onChange:P=>x(P.target.value),placeholder:"@vendor-extra-providers",className:"machine-input text-[11px] font-mono"})]})]}),r.jsxs("div",{className:"mt-3 flex items-center justify-end gap-2",children:[r.jsx("button",{type:"button",onClick:()=>m(!1),className:"machine-btn text-[10px]",children:"Cancel"}),r.jsx("button",{type:"button",onClick:()=>void D(),disabled:S||!g.trim(),className:"machine-btn text-[10px] bg-sky-500/[0.10] border-sky-500/30 text-sky-200 hover:bg-sky-500/[0.18]",children:S?"Cloning…":"Clone + register"})]})]})]})}function KE({machineId:e,providers:t,sendDaemonCommand:s}){var I;const[n,i]=u.useState([]),[a,o]=u.useState(!1),[l,c]=u.useState(null),[d,p]=u.useState("all"),[h,m]=u.useState(!1),[g,b]=u.useState(!1),[f,v]=u.useState(!1),[w,x]=u.useState(null),[S,k]=u.useState("normal"),[j,y]=u.useState(""),[N,_]=u.useState(!1),C=u.useCallback(async()=>{if(e)try{const E=await s(e,"get_provider_source_config",{}),$=Am(E);$&&(x($),k($.sourceMode),y($.explicitProviderDir||""))}catch{}},[e,s]),D=u.useCallback(async()=>{if(e){o(!0);try{const E=await s(e,"get_provider_settings",{}),$=RE(E);if($){const M=PE($,t,{filterSchema:O=>O.filter(H=>H.key!=="enabled")});M.sort((O,H)=>O.category.localeCompare(H.category)||O.displayName.localeCompare(H.displayName)),i(M)}}catch{}o(!1)}},[e,t,s]);u.useEffect(()=>{n.length===0&&D(),w||C()},[]);const T=async(E,$,M)=>{c(`${E}.${$}`),i(O=>O.map(H=>H.type===E?{...H,values:{...H.values,[$]:M}}:H));try{const O=await s(e,"set_provider_setting",{providerType:E,key:$,value:M});O!=null&&O.success||D()}catch{D()}c(null)},A=async(E,$)=>{await T(E,"enabled",$),await D()},P=async E=>{c(`${E}.detect`);try{await s(e,"detect_provider",{providerType:E})}finally{await D(),c(null)}},F=async E=>{await T(E,"executablePath",""),await T(E,"executableArgs",""),await D()},J=async()=>{_(!0);try{const E=await s(e,"set_provider_source_config",{providerSourceMode:S,providerDir:DE(j)}),$=Am(E);$?(x($),k($.sourceMode),y($.explicitProviderDir||"")):await C(),await D()}catch{await C()}_(!1)},R=n.filter(E=>d==="all"||E.category===d);return r.jsxs("div",{className:"flex flex-col gap-3",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[r.jsxs("div",{className:"flex gap-1 items-center",children:[r.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(E=>r.jsx("button",{onClick:()=>p(E),className:`machine-btn text-[10px] px-2 py-0.5 ${d===E?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:E.toUpperCase()},E))]}),r.jsxs("div",{className:"flex gap-1.5",children:[r.jsx("button",{onClick:()=>b(E=>!E),className:`machine-btn text-[10px] ${g?"bg-sky-500/[0.10] border-sky-500/30 text-sky-300":""}`,title:"Manage 3rd-party provider sources",children:"🌐 Sources"}),r.jsx("button",{onClick:()=>m(!0),className:"machine-btn text-[10px]",title:"Create a new provider from an existing one",children:"✨ Create"}),r.jsxs("button",{onClick:D,disabled:a,className:"machine-btn text-[10px]",children:[a?"⏳":"↻"," Refresh"]}),r.jsx("button",{onClick:()=>v(E=>!E),className:"machine-btn text-[10px]",title:"Show source configuration (advanced)",children:"⚙ Advanced"})]})]}),g&&r.jsx(zE,{machineId:e,sendDaemonCommand:s,onChange:()=>{D()}}),f&&r.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[r.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),r.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Where the daemon looks for provider manifests. Affects resolution and reloads."})]}),r.jsx("button",{onClick:C,className:"machine-btn text-[10px]",children:"↻ Refresh"})]}),r.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[r.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[r.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),r.jsxs("select",{value:S,onChange:E=>k(E.target.value),className:"machine-input text-[11px]",children:[r.jsx("option",{value:"normal",children:"normal"}),r.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),r.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[r.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),r.jsx("input",{type:"text",value:j,onChange:E=>y(E.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),r.jsx("button",{onClick:()=>void J(),disabled:N,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:N?"Applying…":"Apply + Reload"})]}),r.jsxs("div",{className:"mt-3 grid gap-1 text-[10px] text-text-muted",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-text-secondary font-medium",children:"User root:"})," ",(w==null?void 0:w.userDir)||"—"]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-secondary font-medium",children:"Upstream root:"})," ",(w==null?void 0:w.upstreamDir)||"—"]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-secondary font-medium",children:"Provider roots:"})," ",((I=w==null?void 0:w.providerRoots)==null?void 0:I.join(" → "))||"—"]})]})]}),a&&n.length===0?r.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings…"}):R.length===0?r.jsx("div",{className:"px-4.5 py-8 rounded-xl border border-border-subtle bg-bg-secondary text-center",children:r.jsx("div",{className:"text-[12px] text-text-muted",children:d==="all"?'No providers installed yet. Open "Add provider" above to install one.':`No ${d.toUpperCase()} providers installed.`})}):r.jsx("div",{className:"flex flex-col gap-1.5",children:R.map(E=>r.jsx(HE,{prov:E,providerInfo:t.find($=>$.type===E.type),savingKey:l,onSetSetting:T,onEnableToggle:A,onDetect:P,onResetCommand:F},E.type))}),h&&r.jsx(LE,{machineId:e,providers:t,sendDaemonCommand:s,onClose:()=>m(!1),onCreated:()=>{m(!1),D()}})]})}const GE=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function qE({count:e,since:t,category:s}){return{count:e,since:t,...s==="all"?{}:{category:s}}}function VE(e,t){return t==="all"?e:e.filter(s=>s.category===t)}function XE(e){return e.trim().toLowerCase()}function bl(e,t){const s=XE(t);return s?e.some(n=>String(n??"").toLowerCase().includes(s)):!0}function Ou(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Nn(e,t=220){const s=Ou(e);return s?s.length>t?`${s.slice(0,t)}…`:s:""}function YE(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(s=>{const n=s;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 s=t.trim();return{kind:s?"text":"empty",entries:[],rawText:s}}return{kind:"empty",entries:[],rawText:""}}function QE(e,t){return e.filter(s=>bl([s.level,s.message],t))}function Rm(e){return`${e.timestamp}:${e.level}:${e.message}`}function JE(e,t,s=300){if(t.entries.length>0){const n=new Map;for(const o of e.entries)n.set(Rm(o),o);for(const o of t.entries)n.set(Rm(o),o);const i=Array.from(n.values()).sort((o,l)=>o.timestamp-l.timestamp).slice(-s),a=i.reduce((o,l)=>Math.max(o,Number(l.timestamp||0)),e.lastTs);return{entries:i,kind:"structured",rawText:"",lastTs:a}}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 ZE(e,t,s=120){if(t.length===0)return e;const n=new Map;for(const i of e)n.set(i.id,i);for(const i of t)n.set(i.id,i);return Array.from(n.values()).sort((i,a)=>i.ts-a.ts).slice(-s)}function e2(e,t){return e.split(`
|
|
92
|
+
`).map(s=>s.trimEnd()).filter(Boolean).filter(s=>bl([s],t))}function t2(e,t){return e.filter(s=>bl([s.level,s.category,s.stage,s.interactionId,Ou(s.payload)],t))}function s2(e,t){return e.filter(s=>bl([s.kind,s.topic,s.interactionId,Ou(s.payload)],t))}function Pm(e){return e==="warn"||e==="error"}function r2({daemonLogs:e,daemonRawLines:t,trace:s,webEvents:n}){return{all:e.length+t.length+s.length+n.length,info:e.filter(i=>i.level!=="debug").length+s.filter(i=>i.level!=="debug").length+n.length,issues:e.filter(i=>Pm(i.level)).length+s.filter(i=>Pm(i.level)).length}}function n2({daemonLogs:e,daemonRawLines:t,trace:s,webEvents:n}){const i=[];return e.length>0?i.push(["[daemon logs]",...e.map(a=>`${new Date(a.timestamp).toISOString()} ${a.level.toUpperCase()} ${a.message}`)].join(`
|
|
93
|
+
`)):t.length>0&&i.push(["[daemon logs]",...t].join(`
|
|
94
|
+
`)),s.length>0&&i.push(["[trace]",...s.map(a=>`${new Date(a.ts).toISOString()} ${a.level.toUpperCase()} ${a.category}.${a.stage} ${Nn(a.payload,500)}`.trim())].join(`
|
|
95
|
+
`)),n.length>0&&i.push(["[browser events]",...n.map(a=>`${new Date(a.ts).toISOString()} ${a.kind}${a.topic?` topic=${a.topic}`:""} ${Nn(a.payload,500)}`.trim())].join(`
|
|
96
|
+
`)),i.join(`
|
|
97
|
+
|
|
98
|
+
`)}function i2({machineId:e,sendDaemonCommand:t}){const[s,n]=u.useState([]),[i,a]=u.useState("empty"),[o,l]=u.useState(""),[c,d]=u.useState([]),[p,h]=u.useState([]),[m,g]=u.useState(null),[b,f]=u.useState(!0),[v,w]=u.useState("info"),[x,S]=u.useState("all"),[k,j]=u.useState(!0),[y,N]=u.useState(!0),[_,C]=u.useState(""),[D,T]=u.useState(""),[A,P]=u.useState(0),F=u.useRef(0),J=u.useRef(0),R=u.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),I=u.useRef([]),E=u.useCallback(()=>{const X={entries:[],kind:"empty",rawText:"",lastTs:0};R.current=X,F.current=0,n([]),l(""),a("empty"),j(!0)},[]),$=u.useCallback(()=>{I.current=[],J.current=0,d([]),N(!0)},[]),M=u.useCallback(X=>{X!==v&&(E(),w(X))},[v,E]),O=u.useCallback(X=>{S(te=>te===X?te:X)},[]),H=u.useCallback(()=>{E(),$(),h([]),g(null),C(""),T(""),gn.clear()},[E,$]),ae=u.useCallback(()=>{P(X=>X+1)},[]),z=u.useCallback(async()=>{if(!e)return;const X=F.current,te=J.current,[he,ke]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:v,since:X}),t(e,"get_debug_trace",qE({count:120,since:te,category:x}))]);if(he.status==="fulfilled"){const Q=he.value,q=(Q==null?void 0:Q.result)||Q,me=YE(q),we=JE(R.current,me,300);R.current=we,F.current=we.lastTs,j(!1),C((Q==null?void 0:Q.success)===!1?String((Q==null?void 0:Q.error)||"Could not load daemon logs"):""),a(we.kind),l(we.rawText),n(we.entries)}else j(!1),C(he.reason instanceof Error?he.reason.message:"Could not load daemon logs");if(ke.status==="fulfilled"){const Q=ke.value,q=(Q==null?void 0:Q.result)||Q;if((Q==null?void 0:Q.success)===!1)T(String((Q==null?void 0:Q.error)||"Could not load daemon trace"));else if(Array.isArray(q==null?void 0:q.trace)){const me=q.trace,we=ZE(I.current,me,120),ye=me.reduce((Te,le)=>Math.max(Te,Number(le.ts||0)),te);I.current=we,ye>te&&(J.current=ye),T(""),d(we)}else T("");N(!1)}else N(!1),T(ke.reason instanceof Error?ke.reason.message:"Could not load daemon trace");h(gn.list({limit:120})),g(Date.now())},[v,e,t,x]);return u.useEffect(()=>{$()},[$,x]),u.useEffect(()=>{if(!e||(z(),!b))return;const X=setInterval(()=>{z()},3e3);return()=>clearInterval(X)},[b,z,e,A]),{daemonLogs:s,daemonLogKind:i,daemonRawText:o,debugTrace:c,webEvents:p,lastUpdatedAt:m,autoRefresh:b,logLevel:v,traceCategory:x,daemonLoading:k,traceLoading:y,daemonFetchError:_,traceFetchError:D,setAutoRefresh:f,setLogLevel:M,setTraceCategory:O,refresh:ae,clear:H}}function a2({daemonLoading:e,traceLoading:t,daemonFetchError:s,traceFetchError:n,daemonLogKind:i,daemonLogsCount:a,daemonRawLineCount:o,traceCount:l,webEventCount:c}){return[{id:"daemon_logs",label:"Daemon logs",status:s?"error":e?"loading":a>0||o>0?"ok":"empty",detail:s||(i==="text"?`${o} raw file-fallback line(s)`:`${a} 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:c>0?"ok":"empty",detail:c>0?`${c} local browser event(s)`:"No browser events captured"}]}function Dm(e){return e==="warn"||e==="error"}function o2(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 l2(e,t){const s=e.match(/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\b/);if(s){const n=Date.parse(s[0]);if(Number.isFinite(n))return n}return Number.MAX_SAFE_INTEGER-1e5+t}function Lm(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function c2(e){const t=Nn(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function d2(e){const t=Nn(e.payload,320),s=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${s} ${t}`:`${e.kind}${s}`}function u2({daemonLogs:e,daemonRawLines:t,trace:s,webEvents:n}){const i=[];return e.forEach((a,o)=>{i.push({id:`daemon-log-${a.timestamp}-${o}`,source:"daemon_log",ts:Number(a.timestamp||0),severity:a.level,message:a.message,raw:a.message})}),n.forEach(a=>{i.push({id:`browser-event-${a.id}`,source:"browser_event",ts:Number(a.ts||0),severity:"info",message:d2(a),topic:a.topic,interactionId:a.interactionId,payload:a.payload})}),s.forEach(a=>{i.push({id:`daemon-trace-${a.id}`,source:"daemon_trace",ts:Number(a.ts||0),severity:a.level,message:c2(a),category:a.category,stage:a.stage,interactionId:a.interactionId,payload:a.payload})}),t.forEach((a,o)=>{i.push({id:`raw-file-${o}`,source:"raw_file",ts:l2(a,o),severity:o2(a),message:a,raw:a})}),i.sort((a,o)=>a.ts!==o.ts?a.ts-o.ts:Lm(a.source)-Lm(o.source))}function p2(e){return`${e.source}:${e.severity}:${e.message}`}function h2(e){const t=e.filter(n=>Dm(n.severity)).sort((n,i)=>i.ts-n.ts),s=new Map;for(const n of e){if(!Dm(n.severity))continue;const i=p2(n),a=s.get(i);a?(a.count+=1,a.firstTs=Math.min(a.firstTs,n.ts),a.lastTs=Math.max(a.lastTs,n.ts)):s.set(i,{key:i,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(s.values()).filter(n=>n.count>1).sort((n,i)=>i.count!==n.count?i.count-n.count:i.lastTs-n.lastTs).slice(0,5)}}function m2(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function $m(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",s=e.interactionId?` ix=${e.interactionId}`:"";return`${m2(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${s} ${e.message}`.trim()}function f2({events:e,summary:t,sources:s,maxTimelineEvents:n=80}){const i=[];i.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
|
|
99
|
+
`)),i.push(["[source status]",...s.map(o=>`${o.label}: ${o.status} - ${o.detail}`)].join(`
|
|
100
|
+
`)),t.latestIssue&&i.push(["[latest issue]",$m(t.latestIssue)].join(`
|
|
101
|
+
`)),t.repeatedPatterns.length>0&&i.push(["[top repeated patterns]",...t.repeatedPatterns.map(o=>`${o.count}x ${o.severity.toUpperCase()} ${o.source} ${o.message}`)].join(`
|
|
102
|
+
`));const a=e.slice(-n);return i.push(["[timeline]",...a.length>0?a.map($m):["No diagnostic events captured."]].join(`
|
|
103
|
+
`)),i.join(`
|
|
104
|
+
|
|
105
|
+
`)}function g2(e,t){return t==="issues"?e.filter(s=>s.level==="warn"||s.level==="error"):t==="info"?e.filter(s=>s.level!=="debug"):e}function x2(e,t){return t==="issues"?e.filter(s=>s.level==="warn"||s.level==="error"):t==="info"?e.filter(s=>s.level!=="debug"):e}function b2({daemonLogs:e,daemonRawText:t,daemonLogKind:s,debugTrace:n,webEvents:i,traceCategory:a,quickFilter:o,searchQuery:l,daemonLoading:c,traceLoading:d,daemonFetchError:p,traceFetchError:h}){const m=VE(n,a),g=QE(e,l),b=e2(t,l),f=t2(m,l),v=s2(i,l),w=g2(g,o),x=o==="all"?b:[],S=x2(f,o),k=o==="issues"?[]:v,j=r2({daemonLogs:g,daemonRawLines:b,trace:f,webEvents:v}),y=u2({daemonLogs:w,daemonRawLines:x,trace:S,webEvents:k}),N=h2(y),_=a2({daemonLoading:c,traceLoading:d,daemonFetchError:p,traceFetchError:h,daemonLogKind:s,daemonLogsCount:g.length,daemonRawLineCount:b.length,traceCount:f.length,webEventCount:v.length});return{filteredDaemonLogs:g,filteredDaemonRawLines:b,filteredTraceEntries:f,filteredWebEvents:v,visibleDaemonLogs:w,visibleDaemonRawLines:x,visibleTraceEntries:S,visibleWebEvents:k,quickFilterCounts:j,diagnosticEvents:y,diagnosticsSummary:N,sourceStates:_}}function y2(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Db(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function gd(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 Sc(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 Fu(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function v2({event:e}){return r.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${gd(e.severity)}`,children:[r.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[r.jsx("span",{children:Db(e.ts)}),r.jsx("span",{children:e.severity.toUpperCase()}),r.jsx("span",{children:Fu(e.source)}),e.category&&e.stage&&r.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&r.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&r.jsxs("span",{children:["ix=",e.interactionId]})]}),r.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function w2({quickFilter:e,quickFilterCounts:t,searchQuery:s,autoRefresh:n,onQuickFilterChange:i,onSearchQueryChange:a,onCopyDiagnostics:o,onCopyVisible:l,onToggleAutoRefresh:c,onRefresh:d,onClear:p}){return r.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[r.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[r.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),r.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(h=>r.jsx("button",{type:"button",onClick:()=>i(h.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===h.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:h.label},h.id))}),r.jsx("input",{value:s,onChange:h=>a(h.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"})]}),r.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[r.jsx("button",{onClick:o,className:"machine-btn",children:"Copy diagnostics"}),r.jsx("button",{onClick:l,className:"machine-btn",children:"Copy visible"}),r.jsx("button",{onClick:c,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),r.jsx("button",{onClick:d,className:"machine-btn",children:"↻ Refresh"}),r.jsx("button",{onClick:p,className:"machine-btn",children:"Clear"})]})]})}function S2({logLevel:e,traceCategory:t,onLogLevelChange:s,onTraceCategoryChange:n}){return r.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-3",children:r.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[r.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[r.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(i=>r.jsxs("button",{onClick:()=>s(i),className:`machine-btn text-[10px] px-2 py-0.5 ${e===i?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",i.toUpperCase(),"+"]},i))]}),r.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:GE.map(i=>r.jsx("button",{onClick:()=>n(i.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===i.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:i.label},i.value))})]})})}function k2({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:s,searchQuery:n,lastUpdatedAt:i,autoRefresh:a,daemonFetchError:o,traceFetchError:l}){var p,h;const c=((p=e.latestIssue)==null?void 0:p.severity)==="error"?"danger":((h=e.latestIssue)==null?void 0:h.severity)==="warn"?"warning":"good",d=o||l?"danger":a?"good":"neutral";return r.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[r.jsxs("div",{className:`rounded-xl border p-3 ${Sc(e.issueCount>0?"warning":"good")}`,children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),r.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),r.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"})]}),r.jsxs("div",{className:`rounded-xl border p-3 ${Sc(c)}`,children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[Fu(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),r.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),r.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:Db(e.latestIssue.ts)})]}):r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),r.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),r.jsxs("div",{className:`rounded-xl border p-3 ${Sc(d)}`,children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),r.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:o||l?"Needs attention":a?"Live polling every 3s":"Paused"}),r.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",y2(i)]}),r.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:s.map(m=>r.jsxs("div",{children:[m.label,": ",m.status]},m.id))})]})]})}function j2({patterns:e}){return e.length===0?null:r.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),r.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(t=>r.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[r.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[t.count,"× ",t.severity.toUpperCase()," · ",Fu(t.source)]}),r.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function N2({streams:e,sectionsOpen:t,setSectionsOpen:s,diagnosticEvents:n,visibleDaemonLogs:i,visibleDaemonRawLines:a,visibleTraceEntries:o,visibleWebEvents:l,quickFilter:c,searchQuery:d}){return r.jsxs("div",{className:"grid gap-3",children:[r.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[r.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>s(p=>({...p,timeline:!p.timeline})),children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),r.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),r.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&r.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&&r.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&r.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&r.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&r.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&r.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(p=>r.jsx(v2,{event:p},p.id))]})]}),r.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[r.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>s(p=>({...p,daemon:!p.daemon})),children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),r.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${a.length} visible raw line(s) from file fallback`:`${i.length} visible structured line(s)`})]}),r.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&r.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&&i.length===0&&a.length===0&&!e.daemonFetchError&&r.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&r.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&r.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&a.length===0&&e.daemonRawText&&r.jsx("div",{className:"p-6 text-center text-text-muted",children:c==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&i.length===0&&e.daemonLogs.length>0&&r.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&a.map((p,h)=>r.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:p},`raw-${h}`)),e.daemonLogKind!=="text"&&i.map((p,h)=>r.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${gd(p.level)}`,children:[r.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(p.timestamp).toLocaleTimeString()}),r.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:p.level==="error"?"ERR":p.level==="warn"?"WRN":p.level==="debug"?"DBG":"INF"}),r.jsx("span",{className:"break-words",children:p.message})]},`log-${h}`))]})]}),r.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[r.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>s(p=>({...p,trace:!p.trace})),children:[r.jsxs("div",{children:[r.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),r.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[o.length," visible trace event(s)"]})]}),r.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&r.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&&r.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&o.length===0&&r.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&o.length===0&&!e.traceFetchError&&r.jsx("div",{className:"p-6 text-center text-text-muted",children:d.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(p=>r.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${gd(p.level)}`,children:[r.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[r.jsx("span",{children:new Date(p.ts).toLocaleTimeString()}),r.jsx("span",{children:p.level.toUpperCase()}),r.jsxs("span",{children:[p.category,".",p.stage]}),p.interactionId&&r.jsxs("span",{children:["ix=",p.interactionId]})]}),r.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Nn(p.payload,360)||"No payload"})]},p.id))]})]}),r.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[r.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>s(p=>({...p,web:!p.web})),children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),r.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[l.length," visible browser event(s)"]})]}),r.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&r.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&&r.jsx("div",{className:"p-6 text-center text-text-muted",children:d.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),l.map(p=>r.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[r.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[r.jsx("span",{children:new Date(p.ts).toLocaleTimeString()}),r.jsx("span",{children:p.kind}),p.topic&&r.jsxs("span",{children:["topic=",p.topic]}),p.interactionId&&r.jsxs("span",{children:["ix=",p.interactionId]})]}),r.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Nn(p.payload,360)||"No payload"})]},p.id))]})]})]})}function _2({machineId:e,sendDaemonCommand:t}){const s=i2({machineId:e,sendDaemonCommand:t}),[n,i]=u.useState("info"),[a,o]=u.useState(""),[l,c]=u.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),d=u.useRef(null),p=u.useRef(!1),h=u.useMemo(()=>b2({daemonLogs:s.daemonLogs,daemonRawText:s.daemonRawText,daemonLogKind:s.daemonLogKind,debugTrace:s.debugTrace,webEvents:s.webEvents,traceCategory:s.traceCategory,quickFilter:n,searchQuery:a,daemonLoading:s.daemonLoading,traceLoading:s.traceLoading,daemonFetchError:s.daemonFetchError,traceFetchError:s.traceFetchError}),[n,a,s.daemonFetchError,s.daemonLoading,s.daemonLogKind,s.daemonLogs,s.daemonRawText,s.debugTrace,s.traceCategory,s.traceFetchError,s.traceLoading,s.webEvents]);u.useEffect(()=>{if(s.autoRefresh&&h.diagnosticEvents.length>0){const b=p.current?"smooth":"instant";setTimeout(()=>{var f;(f=d.current)==null||f.scrollIntoView({behavior:b}),p.current=!0},50)}},[h.diagnosticEvents.length,s.autoRefresh]);const m=u.useCallback(async()=>{var f;const b=n2({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!b.trim()){ht.showToast("No visible logs to copy.","info");return}try{await((f=navigator.clipboard)==null?void 0:f.writeText(b)),ht.showToast("Copied visible logs to clipboard.","success")}catch(v){ht.showToast(v instanceof Error?v.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),g=u.useCallback(async()=>{var f;const b=f2({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((f=navigator.clipboard)==null?void 0:f.writeText(b)),ht.showToast("Copied diagnostic bundle to clipboard.","success")}catch(v){ht.showToast(v instanceof Error?v.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return r.jsxs("div",{className:"space-y-4",children:[r.jsx(w2,{quickFilter:n,quickFilterCounts:h.quickFilterCounts,searchQuery:a,autoRefresh:s.autoRefresh,onQuickFilterChange:i,onSearchQueryChange:o,onCopyDiagnostics:()=>{g()},onCopyVisible:()=>{m()},onToggleAutoRefresh:()=>s.setAutoRefresh(b=>!b),onRefresh:s.refresh,onClear:s.clear}),r.jsx(S2,{logLevel:s.logLevel,traceCategory:s.traceCategory,onLogLevelChange:s.setLogLevel,onTraceCategoryChange:s.setTraceCategory}),r.jsx(k2,{diagnosticsSummary:h.diagnosticsSummary,diagnosticEventsCount:h.diagnosticEvents.length,sourceStates:h.sourceStates,searchQuery:a,lastUpdatedAt:s.lastUpdatedAt,autoRefresh:s.autoRefresh,daemonFetchError:s.daemonFetchError,traceFetchError:s.traceFetchError}),r.jsx(j2,{patterns:h.diagnosticsSummary.repeatedPatterns}),r.jsx(N2,{streams:s,sectionsOpen:l,setSectionsOpen:c,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:n,searchQuery:a}),r.jsx("div",{ref:d})]})}function C2(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 Lb(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 I2(e){var i;const t=[],s=[],n=[];for(const a of e||[]){const o=String((a==null?void 0:a.lifecycle)||"").trim(),l=Lb((a==null?void 0:a.meta)||void 0),c=((i=a==null?void 0:a.meta)==null?void 0:i.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(o)?t.push(a):(o==="stopped"||o==="failed")&&(c||l)?s.push(a):n.push(a)}return{liveRuntimes:t,recoverySnapshots:s,inactiveRecords:n}}function A2(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function kc(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 jc(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Nc(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Om(e){if(!e)return"unknown";const t=Date.now()-e,s=Math.max(0,Math.round(t/1e3));if(s<60)return`${s}s ago`;const n=Math.round(s/60);if(n<60)return`${n}m ago`;const i=Math.round(n/60);return i<48?`${i}h ago`:`${Math.round(i/24)}d ago`}function T2(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function M2(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 E2(e){var s;const t=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const i=typeof((s=n.meta)==null?void 0:s.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!i)continue;const a=`${n.providerType}::${n.workspace}::${i}`;t.set(a,(t.get(a)||0)+1)}return Array.from(t.values()).filter(n=>n>1).length}function R2({machineId:e,cliSessions:t,sendDaemonCommand:s}){const[n,i]=u.useState(""),[a,o]=u.useState(null),[l,c]=u.useState(!1),d=aC(e,{enabled:!!e,includeSessions:!0,limit:Sh,intervalMs:RN}),p=d.diagnostics,h=d.loading,m=d.applyDiagnostics,g=u.useMemo(()=>C2({diagnostics:p,loading:h,refreshing:l,error:n}),[p,h,l,n]),b=u.useMemo(()=>new Map(t.map(T=>[T.sessionId||T.id,T])),[t]),f=u.useCallback(async()=>{if(e){c(!0);try{const T=await s(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Sh}),A=jc(T);if(!(A!=null&&A.success))throw new Error((A==null?void 0:A.error)||"Could not load hosted runtime diagnostics");m(A.diagnostics||A.result||null),i("")}catch(T){const A=T instanceof Error?T.message:"Could not load hosted runtime diagnostics";i(A)}finally{c(!1)}}},[m,e,s]);u.useEffect(()=>{!e||p||h||l||f()},[p,h,e,f,l]);const v=u.useCallback(async(T,A)=>{const P=`${T}:${A.sessionId}`;if(!(T==="session_host_stop_session"&&!window.confirm(`Stop ${A.displayName}?
|
|
106
|
+
This will terminate the hosted runtime.`))){o(P);try{const F=await s(e,T,{sessionId:A.sessionId}),J=jc(F);if(!(J!=null&&J.success))throw new Error((J==null?void 0:J.error)||"Session host action failed");const R=T==="session_host_resume_session"?"resumed":T==="session_host_restart_session"?"restarted":"stopped";ht.showToast(`Session host ${R}: ${A.displayName}`,"success"),await f()}catch(F){const J=F instanceof Error?F.message:"Session host action failed";ht.showToast(J,"warning"),i(J)}finally{o(F=>F===P?null:F)}}},[e,f,s]),w=u.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
107
|
+
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 A=await s(e,"session_host_prune_duplicate_sessions",{}),P=jc(A);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const F=P.result||{},J=Array.isArray(F.prunedSessionIds)?F.prunedSessionIds.length:0,R=typeof F.duplicateGroupCount=="number"?F.duplicateGroupCount:0;ht.showToast(`Pruned ${J} duplicate runtime(s) across ${R} group(s)`,"success"),await f()}catch(A){const P=A instanceof Error?A.message:"Duplicate prune failed";ht.showToast(P,"warning"),i(P)}finally{o(A=>A==="session_host_prune_duplicate_sessions"?null:A)}}},[e,f,s]),x=u.useMemo(()=>[...(p==null?void 0:p.sessions)||[]].sort((T,A)=>(A.lastActivityAt||0)-(T.lastActivityAt||0)),[p==null?void 0:p.sessions]),S=u.useMemo(()=>p!=null&&p.liveRuntimes||p!=null&&p.recoverySnapshots||p!=null&&p.inactiveRecords?{liveRuntimes:(p==null?void 0:p.liveRuntimes)||[],recoverySnapshots:(p==null?void 0:p.recoverySnapshots)||[],inactiveRecords:(p==null?void 0:p.inactiveRecords)||[]}:I2(x),[p==null?void 0:p.inactiveRecords,p==null?void 0:p.liveRuntimes,p==null?void 0:p.recoverySnapshots,x]),k=S.liveRuntimes,j=S.recoverySnapshots,y=S.inactiveRecords,N=u.useMemo(()=>E2(k),[k]),_=u.useMemo(()=>[...(p==null?void 0:p.recentTransitions)||[]].slice(-6).reverse(),[p==null?void 0:p.recentTransitions]),C=u.useMemo(()=>[...(p==null?void 0:p.recentLogs)||[]].reverse().find(T=>T.level==="warn"||T.level==="error")||null,[p==null?void 0:p.recentLogs]),D=(T,A)=>{var O;const P=a===`session_host_resume_session:${T.sessionId}`,F=a===`session_host_restart_session:${T.sessionId}`,J=a===`session_host_stop_session:${T.sessionId}`,R=Lb(T.meta),I=b.get(T.sessionId),E=T.attachedClients.length===1?"1 client":`${T.attachedClients.length} clients`,$=A==="recovery"?"Recover":"Resume",M=A2(A);return r.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:r.jsxs("div",{className:"flex items-start justify-between gap-3",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[r.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:T.displayName||(I==null?void 0:I.cliName)||T.providerType}),r.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${M2(T.lifecycle)}`,children:T.lifecycle}),R&&r.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:R})]}),r.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[r.jsx("span",{className:"text-text-primary/90",children:T.workspaceLabel||(I==null?void 0:I.runtimeWorkspaceLabel)||T.workspace||"No workspace"}),r.jsx("span",{className:"text-text-muted",children:"·"}),r.jsx("span",{className:"font-mono text-text-primary",children:T.runtimeKey}),T.osPid?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"text-text-muted",children:"·"}),r.jsxs("span",{className:"text-text-primary/90",children:["pid ",T.osPid]})]}):null]}),r.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[r.jsx("span",{className:((O=T.writeOwner)==null?void 0:O.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:T2(T.writeOwner)}),r.jsx("span",{className:"text-text-muted",children:"·"}),r.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[r.jsx(Gf,{size:11})," ",E]}),r.jsx("span",{className:"text-text-muted",children:"·"}),r.jsxs("span",{className:"text-text-primary/85",children:["active ",Om(T.lastActivityAt)]}),r.jsx("span",{className:"text-text-muted",children:"·"}),r.jsxs("span",{className:"text-sky-200",children:["Next: ",M]})]})]}),r.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[A==="recovery"&&(T.lifecycle==="interrupted"||T.lifecycle==="failed"||T.lifecycle==="stopped")&&r.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!a,onClick:()=>{v("session_host_resume_session",T)},children:P?`${$}ing…`:$}),r.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!a,onClick:()=>{v("session_host_restart_session",T)},children:F?"Restarting…":"Restart"}),A==="live"&&(T.lifecycle==="running"||T.lifecycle==="starting"||T.lifecycle==="interrupted")&&r.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:!!a,onClick:()=>{v("session_host_stop_session",T)},children:J?"Stopping…":"Stop"})]})]})},T.sessionId)};return r.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[r.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[r.jsx(cr,{size:14})," Hosted Runtime Recovery"]}),r.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:o_()})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[N>0&&r.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{w()},disabled:a==="session_host_prune_duplicate_sessions",children:a==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${N})`}),r.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${g.toneClass}`,children:g.label}),r.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{f()},disabled:h||l,children:[r.jsx(il,{size:13}),h||l?"Refreshing…":"Refresh"]})]})]}),n&&!p&&r.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:r.jsxs("div",{className:"flex items-start gap-2",children:[r.jsx(yn,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),r.jsxs("div",{children:[r.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),r.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),p&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[r.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),r.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:p.runtimeCount})]}),r.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),r.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:j.length})]}),r.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),r.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:p.recentRequests.length})]}),r.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),r.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Om(p.hostStartedAt)}),r.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Nc(p.hostStartedAt)})]})]}),C&&r.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:[r.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[r.jsx(yn,{size:13})," Latest host warning"]}),r.jsx("div",{className:"text-text-primary leading-relaxed",children:C.message}),r.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Nc(C.timestamp),C.sessionId?` · ${C.sessionId}`:""]})]}),r.jsxs("div",{className:"mb-4 space-y-4",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[r.jsx(Vd,{size:14})," Live Hosted Runtimes"]}),r.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:kc("live")}),k.length===0?r.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."}):r.jsx("div",{className:"space-y-2",children:k.map(T=>D(T,"live"))})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[r.jsx(cr,{size:14})," Recovery Snapshots"]}),r.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:kc("recovery")}),j.length===0?r.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."}):r.jsx("div",{className:"space-y-2",children:j.map(T=>D(T,"recovery"))})]}),y.length>0&&r.jsxs("div",{children:[r.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),r.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:kc("inactive")}),r.jsx("div",{className:"space-y-2 opacity-85",children:y.map(T=>D(T,"inactive"))})]})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),_.length===0?r.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."}):r.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:_.map(T=>{var P;const A=x.find(F=>F.sessionId===T.sessionId);return r.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("div",{className:"text-text-primary font-medium",children:(A==null?void 0:A.displayName)||((P=b.get(T.sessionId))==null?void 0:P.cliName)||T.sessionId}),r.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[T.action,T.lifecycle?` · ${T.lifecycle}`:"",T.detail?` · ${T.detail}`:"",T.error?` · ${T.error}`:""]})]}),r.jsx("div",{className:`shrink-0 text-[10px] ${T.success===!1?"text-red-300":"text-text-secondary"}`,children:Nc(T.timestamp)})]},`${T.sessionId}:${T.timestamp}:${T.action}`)})})]}),r.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",r.jsx("span",{className:"font-mono text-text-primary",children:p.endpoint||"unknown"}),n?r.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function P2({machine:e,launchPick:t,actions:s}){const{runLaunchCliCore:n,setLaunchPick:i}=s;return r.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:r.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:[r.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),r.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."}),r.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?r.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(a=>r.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:()=>{i(null),n({cliType:t.cliType,workspaceId:a.id,argsStr:t.argsStr,model:t.model})},children:[r.jsx("span",{className:"font-medium text-text-primary block truncate",children:a.label||a.path}),r.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:a.path})]},a.id))}),r.jsxs("div",{className:"flex flex-wrap gap-2",children:[r.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{i(null),n({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),r.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{i(null),n({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),r.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>i(null),children:"Cancel"})]})]})})}function D2(e,t){const s=Ax(e),n=nn(e,t),i=gu(e,n),a=ui(e,n),o=s==="preview"?"Update to preview":"Update daemon";return i?{visible:!0,showButton:!0,title:a?"Daemon update required":"Version mismatch detected",description:a?"This machine is on an incompatible daemon version. Update it before starting more sessions.":s==="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.",buttonLabel:o,targetVersion:n,channel:s,required:a,tone:"warn"}:s==="preview"?{visible:!0,showButton:!1,title:n?"Preview daemon is up to date":"Preview update status unknown",description:n?"This machine is already on the current preview daemon target.":"The app is connected to preview, but the server did not report a preview target version yet.",buttonLabel:o,targetVersion:n,channel:s,required:!1,tone:n?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:o,targetVersion:n,channel:s,required:!1,tone:"info"}}function _c({icon:e,children:t}){return r.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,r.jsx("span",{children:t})]})}function Cc({children:e,className:t=""}){return r.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function L2({machineEntry:e,providers:t,recentLaunches:s,currentConversations:n,onUpgradeDaemon:i,onOpenRecent:a,onOpenConversation:o}){const l=n.slice(0,6),c=s.slice(0,4),p=D2(e,"0.9.82");return r.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&&r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx(_c,{icon:r.jsx(zr,{size:13}),children:"Current Chats"}),r.jsx(Cc,{children:r.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(h=>{const m=pd(h);return r.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(h),children:[r.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[r.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:kt(h)}),m>0&&r.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:al(m)})]}),r.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Or(h)})]},h.tabKey)})})})]}),c.length>0&&r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx(_c,{icon:r.jsx(Yf,{size:13}),children:"Recent Launches"}),r.jsx(Cc,{children:r.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(h=>{const{metaText:m,updatedLabel:g}=Wx(h);return r.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:()=>a(h),children:[r.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[r.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:h.label}),g&&r.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:g})]}),r.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:m})]},h.id)})})})]}),p.visible&&r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx(_c,{icon:r.jsx(yn,{size:13}),children:"Daemon Update"}),r.jsx(Cc,{className:p.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":p.tone==="info"?"border-sky-500/20 bg-sky-500/5":"border-amber-500/20 bg-amber-500/5",children:r.jsxs("div",{className:"flex flex-col gap-3",children:[r.jsx("div",{className:"text-sm font-semibold text-text-primary",children:p.title}),r.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[p.description,p.targetVersion&&r.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",p.targetVersion,p.channel?` (${p.channel})`:""]})]}),p.showButton?r.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:i,children:[r.jsx(il,{size:13}),r.jsx("span",{className:"text-sm font-medium",children:p.buttonLabel})]}):r.jsx("div",{className:p.tone==="good"?"text-xs font-medium text-emerald-300":"text-xs font-medium text-sky-300",children:"No preview update action is needed."})]})})]})]})}function $2({machineId:e,machine:t,ideSessions:s,cliSessions:n,acpSessions:i,actions:a,sendDaemonCommand:o}){const{workspaceBusy:l,handleWorkspaceAdd:c,handleWorkspaceRemove:d,handleWorkspaceSetDefault:p}=a,[h,m]=u.useState(!1),[g,b]=u.useState(""),[f,v]=u.useState([]),[w,x]=u.useState(!1),[S,k]=u.useState(""),j=u.useCallback(async N=>{x(!0),k("");try{const _=await ju(o,e,N);b(_.path),v(_.directories)}catch(_){k(_ instanceof Error?_.message:"Could not load folder")}finally{x(!1)}},[e,o]),y=u.useCallback(()=>{m(!0);const N=[...s.map(C=>C.workspace),...n.map(C=>C.workspace),...i.map(C=>C.workspace)],_=ku(t.platform,Su(N,t.defaultWorkspacePath,(t.workspaces||[]).map(C=>C.path)));j(_)},[i,n,s,j,t.defaultWorkspacePath,t.platform,t.workspaces]);return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"px-5 py-4 rounded-xl mb-4 bg-bg-secondary border border-border-subtle",children:[r.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[r.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[r.jsx(bn,{size:14})," Workspaces"]}),r.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:l,onClick:y,children:"+ Add workspace"})]}),(t.workspaces||[]).length===0?r.jsxs("div",{className:"text-[11px] text-text-muted py-4 text-center",children:["No saved workspaces yet. Click ",r.jsx("span",{className:"text-text-secondary",children:"+ Add workspace"})," to pick a folder."]}):r.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(N=>{const _=N.id===t.defaultWorkspaceId;return r.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${_?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[r.jsx("button",{type:"button",title:_?"Default workspace — click to unset":"Set as default workspace",disabled:l,onClick:()=>void p(_?null:N.id),className:`text-base leading-none shrink-0 transition-colors ${_?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("div",{className:"font-medium text-text-primary truncate",children:hg(N.path,N.label)}),r.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:N.path,children:N.path})]}),r.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void d(N.id),children:"Remove"})]},N.id)})})]}),h&&r.jsx(_u,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:g,directories:f,busy:w,error:S,confirmLabel:"Add workspace",onClose:()=>m(!1),onNavigate:N=>{j(N)},onConfirm:N=>{(async()=>{if(!N)return;await c(N)&&m(!1)})()}})]})}function O2({machine:e,machineId:t,ideSessions:s,cliSessions:n,acpSessions:i,actions:a,sendDaemonCommand:o}){return r.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[r.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[r.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspaces"}),r.jsx("div",{className:"text-sm text-text-secondary",children:'Save folders as workspaces on this machine. Use the dashboard "+" button to launch a session.'})]}),o&&r.jsx($2,{machineId:t,machine:e,ideSessions:s,cliSessions:n,acpSessions:i,actions:a,sendDaemonCommand:o})]})}function F2({onNicknameSynced:e}={}){var Te,le,Se,ge,G,W,Z,oe,ue,ce;const{id:t}=Dw(),s=zi(),n=Ud(),{sendCommand:i}=jt(),a=Xi(),o=mx(),l=Hg(),c=l.ides||[],d=l.initialLoaded??!0,p=c.find(L=>L.id===t&&L.type==="adhdev-daemon"),h=c.some(L=>L.type==="adhdev-daemon"),m=t?(Te=l.connectionRetryStatuses)==null?void 0:Te[t]:void 0,g=!!(m!=null&&m.blocked),[b,f]=u.useState("workspace"),[v,w]=u.useState(null);u.useCallback((L,de)=>{w({daemonId:L,workspace:de})},[]);const[,x]=u.useState("ide"),S=u.useRef(null),[k,j]=u.useState(null),y=u.useRef("__home__"),[N,_]=u.useState("__home__"),[C,D]=u.useState(!1),T=u.useRef(null);u.useEffect(()=>{!t||!p||!(!p.workspaces||!p.availableProviders||!p.detectedIdes||!p.recentLaunches)||a(t,{minFreshMs:3e4}).catch(()=>{})},[a,p,t]),u.useEffect(()=>{if(!t||!p||b!=="overview")return;const L=p.machine;(typeof(L==null?void 0:L.cpus)!="number"||typeof(L==null?void 0:L.totalMem)!="number"||typeof(L==null?void 0:L.arch)!="string"||typeof(L==null?void 0:L.release)!="string")&&o(t,{minFreshMs:3e4}).catch(()=>{})},[b,o,p,t]),iC(t&&b==="overview"?[t]:[],{enabled:b==="overview",intervalMs:AN});const A=()=>{if(h){s("/dashboard",{state:{mobileSection:"machines"}});return}s("/machines")},P=ME({machineId:t,registeredMachineId:(p==null?void 0:p.machineId)||null,sendDaemonCommand:i,onNicknameSynced:e,logsEndRef:T});u.useEffect(()=>ht.onToast(de=>{l.setToasts(ie=>{if(ie.some(Ce=>Ce.message===de.message&&de.timestamp-Ce.timestamp<3e3))return ie;const Ae={id:de.id,message:de.message,type:de.type,timestamp:de.timestamp,targetKey:de.targetKey,actions:de.actions};return[...ie.slice(-4),Ae]});const U=de.duration||5e3;setTimeout(()=>l.setToasts(ie=>ie.filter(Y=>Y.id!==de.id)),U)}),[l]);const F=(p==null?void 0:p.availableProviders)||[],J={};for(const L of F)J[L.type]=L.icon;const R=p?{id:p.id,hostname:mg(p,{fallbackId:p.id}),platform:((le=p.machine)==null?void 0:le.platform)||"unknown",arch:((Se=p.machine)==null?void 0:Se.arch)||"",cpus:((ge=p.machine)==null?void 0:ge.cpus)||0,totalMem:((G=p.machine)==null?void 0:G.totalMem)||0,freeMem:(W=p.machine)==null?void 0:W.freeMem,availableMem:(Z=p.machine)==null?void 0:Z.availableMem,loadavg:(oe=p.machine)==null?void 0:oe.loadavg,uptime:(ue=p.machine)==null?void 0:ue.uptime,release:((ce=p.machine)==null?void 0:ce.release)||"",cdpConnected:!!p.cdpConnected,machineNickname:p.machineNickname||null,p2p:p.p2p?{screenshotActive:!1,...p.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:p.detectedIdes||[],workspaces:p.workspaces||[],defaultWorkspaceId:p.defaultWorkspaceId??p.activeWorkspaceId??null,defaultWorkspacePath:p.defaultWorkspacePath??p.activeWorkspacePath??null}:null,I=c.filter(L=>L.daemonId===t&&L.type!=="adhdev-daemon").filter(L=>!Ni(L)&&!un(L)).map(L=>({id:L.id,sessionId:L.sessionId,type:L.type,version:L.version||"",instanceId:L.instanceId||"",status:L.status,workspace:L.workspace||null,terminals:L.terminals||0,aiAgents:qk(L.aiAgents||(L.agents||[]).map(de=>({id:de.name,name:de.name,status:de.status,version:de.version}))),activeChat:L.activeChat||null,chats:L.chats||[],childSessions:L.childSessions||[],cdpConnected:L.cdpConnected||!1,daemonId:t,lastMessageAt:L.lastMessageAt})),E=c.filter(L=>L.daemonId===t&&Ni(L)).map(L=>({id:L.id,sessionId:L.sessionId,type:L.type,cliName:L.cliName||L.type,status:L.status,workspace:L.workspace||"",activeChat:L.activeChat||null,providerSessionId:L.providerSessionId,mode:L.mode,runtimeKey:L.runtimeKey,runtimeDisplayName:L.runtimeDisplayName,runtimeWorkspaceLabel:L.runtimeWorkspaceLabel,runtimeWriteOwner:L.runtimeWriteOwner||null,runtimeAttachedClients:L.runtimeAttachedClients||[],daemonId:t,lastMessageAt:L.lastMessageAt})),$=c.filter(L=>L.daemonId===t&&un(L)).map(L=>({id:L.id,sessionId:L.sessionId,type:L.type,acpName:L.cliName||L.type,status:L.status,workspace:L.workspace||"",activeChat:L.activeChat||null,providerSessionId:L.providerSessionId,daemonId:t,lastMessageAt:L.lastMessageAt})),M=p?hs(p,{fallbackId:t}):"",O="workspace",H=n.state,ae=H==null?void 0:H.initialMachineTab,z=H==null?void 0:H.initialWorkspaceCategory;H==null||H.initialWorkspaceId,H==null||H.initialWorkspacePath;const X=ae==="ides"||ae==="clis"||ae==="acps"?"workspace":ae||O,te=ae==="ides"?"ide":ae==="clis"?"cli":ae==="acps"?"acp":z,he=[...I.map(L=>{var de;return{id:`ide:${L.type}:${L.workspace||""}`,label:((de=L.activeChat)==null?void 0:de.title)||L.type,kind:"ide",providerType:L.type,subtitle:L.workspace||void 0,workspace:L.workspace||void 0,lastLaunchedAt:L.lastMessageAt||0}}),...E.map(L=>{var de;return{id:`cli:${L.type}:${L.workspace||""}`,label:((de=L.activeChat)==null?void 0:de.title)||L.cliName,kind:"cli",providerType:L.type,providerSessionId:L.providerSessionId,subtitle:L.workspace||void 0,workspace:L.workspace||void 0,lastLaunchedAt:L.lastMessageAt||0}}),...$.map(L=>{var de;return{id:`acp:${L.type}:${L.workspace||""}`,label:((de=L.activeChat)==null?void 0:de.title)||L.acpName,kind:"acp",providerType:L.type,providerSessionId:L.providerSessionId,subtitle:$r(L.summaryMetadata)||L.workspace||void 0,workspace:L.workspace||void 0,lastLaunchedAt:L.lastMessageAt||0}})].sort((L,de)=>(de.lastLaunchedAt||0)-(L.lastLaunchedAt||0)),ke=((p==null?void 0:p.recentLaunches)||[]).length>0?((p==null?void 0:p.recentLaunches)||[]).map(L=>({id:L.id,label:L.title||L.providerName||L.providerType,kind:L.kind,providerType:L.providerType,providerSessionId:L.providerSessionId,subtitle:$r(L.summaryMetadata)||L.workspace||void 0,workspace:L.workspace,summaryMetadata:L.summaryMetadata,lastLaunchedAt:L.lastLaunchedAt})):he,Q=u.useMemo(()=>{var de;const L=((de=l.connectionStates)==null?void 0:de[t||""])||void 0;return c.filter(U=>U.daemonId===t&&U.type!=="adhdev-daemon").flatMap(U=>fu(U,{connectionStates:t&&L?{[t]:L}:void 0,defaultConnectionState:L})).filter(U=>!(U.transport==="pty"&&U.mode==="terminal")).sort((U,ie)=>pd(ie)-pd(U))},[c,l.connectionStates,t]),q=u.useCallback(L=>{const de=Rx(L);de&&s(Ii(de))},[s]),me=u.useCallback(()=>{S.current&&(D(!0),S.current().finally(()=>{S.current=null,D(!1),j(null)}))},[]),we=u.useCallback(L=>{if(!R)return;const{options:de,selectedKey:U}=Bx({machine:R,currentWorkspacePath:L.workspace}),ie=async()=>{x(L.kind),f("workspace")};S.current=async()=>{const Y=de.find(je=>je.key===y.current),Ae=(Y==null?void 0:Y.workspacePath)??null,Ce=(Y==null?void 0:Y.workspaceId)??null;if(L.kind==="ide"&&L.providerType){await P.handleLaunchIde(L.providerType,Ae?{workspace:Ae}:void 0);return}if((L.kind==="cli"||L.kind==="acp")&&L.providerType){await P.runLaunchCliCore({cliType:L.providerType,dir:Ce?void 0:Ae||"",workspaceId:Ce||void 0,model:L.kind==="acp"&&gg(L.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:L.providerSessionId});return}await ie()},y.current=U,_(U),j({title:L.kind==="ide"?Co("restart-ide",L.label):L.providerSessionId?Zg(L.label):Co("start-fresh",L.label),description:L.kind==="ide"?Io("restart-ide"):L.providerSessionId?ex():Io("start-fresh"),confirmLabel:L.kind==="ide"?Ao("restart-ide"):L.providerSessionId?_o(!0):Ao("start-fresh"),busyLabel:L.kind==="ide"?To("restart-ide"):L.providerSessionId?hu(!0):To("start-fresh"),workspaceOptions:de,details:[{label:"Mode",value:L.kind.toUpperCase()},...L.providerType?[{label:"Provider",value:L.providerType}]:[]]})},[P,R]);if(u.useEffect(()=>{f(X)},[O,X,t]),u.useEffect(()=>{te&&x(te)},[te,t]),!R)return d?r.jsxs("div",{className:"p-10 text-center text-text-muted",children:[r.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),r.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),r.jsx("button",{onClick:A,className:"machine-btn-back",children:"← Back"})]}):r.jsx("div",{className:"p-10 text-center text-text-muted",children:r.jsx("p",{children:"⏳ Loading machine..."})});const ye=[{id:"workspace",label:r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(_s,{size:14})," Workspace"]}),count:I.length+E.length+$.length},{id:"session-host",label:r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(cr,{size:14})," Hosted Runtimes"]})},{id:"providers",label:r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(nl,{size:14})," Providers"]})},{id:"overview",label:r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(RS,{size:14})," System"]})},{id:"logs",label:r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(AS,{size:14})," Logs"]})}];return r.jsxs("div",{className:"flex flex-col h-full",children:[r.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:[r.jsx("div",{className:"flex items-center justify-between w-full",children:r.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[r.jsx("button",{onClick:A,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:"←"}),r.jsxs("div",{className:"flex flex-col min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[P.editingNickname?r.jsxs("div",{className:"flex gap-1.5 items-center",children:[r.jsx("input",{autoFocus:!0,value:P.nicknameInput,onChange:L=>P.setNicknameInput(L.target.value),onKeyDown:L=>{L.key==="Enter"&&P.handleSaveNickname(),L.key==="Escape"&&P.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]"}),r.jsx("button",{onClick:P.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"}),r.jsx("button",{onClick:()=>P.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"})]}):r.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{P.setEditingNickname(!0),P.setNicknameInput(R.machineNickname||"")},title:"Click to set nickname",children:M}),g?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),l.retryConnection&&t&&r.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"})]}):r.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"})]}),r.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:[r.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[R.platform," · ",R.arch]}),r.jsxs("span",{children:[R.cpus," cores"]}),(p==null?void 0:p.version)&&r.jsxs("span",{children:["v",p.version]}),R.p2p.available&&r.jsxs("span",{children:["P2P ",R.p2p.state==="connected"?"connected":R.p2p.state]}),R.machineNickname&&r.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:R.hostname})]})]})]})}),r.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ye.map(L=>r.jsxs("button",{onClick:()=>f(L.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${b===L.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[L.label,L.count!==void 0&&r.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${b===L.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:L.count})]},L.id))})]}),r.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:r.jsx("div",{className:"max-w-7xl mx-auto h-full",children:r.jsxs("div",{className:"h-full",children:[b==="workspace"&&r.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[r.jsx(L2,{machineEntry:p,providers:F,recentLaunches:ke,currentConversations:Q,onUpgradeDaemon:async()=>{try{await i(t,"daemon_upgrade",Tx(p))}catch{}},onOpenRecent:we,onOpenConversation:q}),r.jsx(O2,{machine:R,machineId:t,ideSessions:I,cliSessions:E,acpSessions:$,actions:P,sendDaemonCommand:i})]}),b==="providers"&&r.jsx(KE,{machineId:t,providers:F,sendDaemonCommand:i}),b==="overview"&&r.jsx(EE,{machine:R,ideSessions:I,cliSessions:E,acpSessions:$}),b==="session-host"&&r.jsx(R2,{machineId:t,cliSessions:E,sendDaemonCommand:i}),b==="logs"&&r.jsx(_2,{machineId:t,sendDaemonCommand:i})]})})}),P.launchPick&&R&&r.jsx(P2,{machine:R,launchPick:P.launchPick,actions:P}),k&&r.jsx(Fx,{title:k.title,description:k.description,details:k.details,workspaceOptions:k.workspaceOptions,selectedWorkspaceKey:N,onWorkspaceChange:L=>{y.current=L,_(L)},confirmLabel:k.confirmLabel,busyLabel:k.busyLabel,busy:C,onConfirm:me,onCancel:()=>{S.current=null,j(null)}}),v&&r.jsx(Pb,{daemonId:v.daemonId,workspace:v.workspace,onClose:()=>w(null)}),r.jsx(sx,{toasts:l.toasts||[],onDismiss:L=>l.setToasts(de=>de.filter(U=>U.id!==L)),onClickToast:L=>{L.targetKey&&s(Ii(L.targetKey))}}),r.jsx("style",{children:`
|
|
108
|
+
@keyframes toast-in {
|
|
109
|
+
from { opacity: 0; transform: translateX(40px); }
|
|
110
|
+
to { opacity: 1; transform: translateX(0); }
|
|
111
|
+
}
|
|
112
|
+
`})]})}const B2={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},$b=u.createContext(null);function W2(){const e=u.useContext($b);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function Bu({size:e=14}){return r.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("polyline",{points:"23 4 23 10 17 10"}),r.jsx("polyline",{points:"1 20 1 14 7 14"}),r.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function U2({size:e=14}){return r.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),r.jsx("circle",{cx:"18",cy:"6",r:"3"}),r.jsx("circle",{cx:"6",cy:"18",r:"3"}),r.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function H2({size:e=14}){return r.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("polyline",{points:"3 6 5 6 21 6"}),r.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})}function Ob({size:e=14}){return r.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),r.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function Fb({status:e}){const s={online:{color:"#22c55e",label:"Online"},dirty:{color:"#f59e0b",label:"Dirty"},offline:{color:"#6b7280",label:"Offline"},degraded:{color:"#ef4444",label:"Degraded"},enabled:{color:"#22c55e",label:"Enabled"},pending:{color:"#a855f7",label:"Pending"},assigned:{color:"#3b82f6",label:"Assigned"},completed:{color:"#22c55e",label:"Completed"},failed:{color:"#ef4444",label:"Failed"},unknown:{color:"#6b7280",label:"Unknown"}}[e]||{color:"#6b7280",label:e};return r.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-md",style:{background:s.color+"15",color:s.color,border:`1px solid ${s.color}25`},children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:s.color}}),s.label]})}function z2(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function K2({meshes:e,loading:t,error:s,onDismissError:n,daemons:i,features:a,showCreate:o,onToggleCreate:l,createName:c,onCreateNameChange:d,createRepoIdentity:p,onCreateRepoIdentityChange:h,createRepoRemoteUrl:m,onCreateRepoRemoteUrlChange:g,newMeshDaemonId:b,onNewMeshDaemonIdChange:f,newMeshWorkspace:v,onNewMeshWorkspaceChange:w,createPickerWorkspaces:x,onSelectMesh:S,onCreate:k,onCancelCreate:j}){return r.jsxs(Zi,{icon:r.jsx(qs,{}),title:"Repo Meshes",subtitle:`${e.length} mesh${e.length!==1?"es":""}`,widthClassName:"max-w-5xl",actions:r.jsx("button",{className:"btn btn-primary btn-sm",onClick:l,children:"+ Create Mesh"}),children:[s&&r.jsx(or,{variant:"error",onDismiss:n,className:"mb-4",children:s}),o&&r.jsxs(wt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:[r.jsx("h3",{className:"text-base font-bold mb-4",children:"Create Repo Mesh"}),a.createDaemonPicker&&r.jsx(Wt,{label:"Create on machine",hint:"Mesh setup is stored by the selected daemon.",children:r.jsx("select",{className:"input w-full",value:b,onChange:y=>f(y.target.value),disabled:!i.length,children:i.length===0?r.jsx("option",{value:"",children:"No connected daemon"}):i.map(y=>r.jsx("option",{value:y.id,children:z2(y)},y.id))})}),a.createDaemonPicker&&r.jsx(Wt,{label:"Workspace",hint:"Choose from workspaces registered by the selected daemon.",children:r.jsx("select",{className:"input w-full",value:v,onChange:y=>w(y.target.value),disabled:!b||!x.length,children:b?x.length===0?r.jsx("option",{value:"",children:"No registered workspaces"}):x.map(y=>r.jsx("option",{value:y.path,children:y.label?`${y.label} · ${y.path}`:y.path},y.id||y.path)):r.jsx("option",{value:"",children:"Select a machine first"})})}),r.jsx(Wt,{label:"Name",children:r.jsx(di,{value:c,onChange:y=>d(y.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),r.jsx(Wt,{label:"Repo remote URL (optional)",hint:"Provide a remote URL OR a stable identity.",children:r.jsx(di,{value:m,onChange:y=>g(y.target.value),placeholder:"https://github.com/user/repo"})}),r.jsx(Wt,{label:"Repo identity (optional)",hint:"Provide a remote URL OR a stable identity.",children:r.jsx(di,{value:p,onChange:y=>h(y.target.value),placeholder:"github.com/user/repo"})}),r.jsxs("div",{className:"flex gap-2 mt-3",children:[r.jsx("button",{className:"btn btn-primary btn-sm",onClick:k,disabled:!c.trim()||!m.trim()&&!p.trim()||a.createDaemonPicker&&(!b||!v),children:"Create"}),r.jsx("button",{className:"btn btn-secondary btn-sm",onClick:j,children:"Cancel"})]})]}),t?r.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):e.length===0?r.jsx(ul,{icon:r.jsx(qs,{}),title:"No Repo Meshes",description:i.length>0?"Create a mesh to get started.":"Connect an ADHDev daemon first.",action:r.jsx("button",{className:"btn btn-primary btn-sm",disabled:!i.length,onClick:l,children:"Create First Mesh"})}):r.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(y=>{var N;return r.jsx("button",{type:"button",onClick:()=>S(y.id),className:"w-full text-left bg-bg-glass border border-border-subtle rounded-xl px-5 py-4 transition-colors hover:border-border-default hover:bg-bg-secondary/70",children:r.jsxs("div",{className:"flex justify-between items-start",children:[r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[r.jsx(qs,{size:16}),r.jsx("span",{className:"font-bold text-sm",children:y.name})]}),r.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[r.jsx("span",{className:"font-mono",children:y.repoIdentity||y.repo_identity||"No repo identity"}),(y.defaultBranch||y.default_branch)&&r.jsxs("span",{className:"inline-flex items-center gap-1",children:[r.jsx(U2,{size:11}),y.defaultBranch||y.default_branch]})]})]}),r.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[r.jsx("div",{children:new Date(y.createdAt||y.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),r.jsxs("div",{className:"text-text-muted/60",children:[((N=y.nodes)==null?void 0:N.length)??y.nodeCount??0," node(s)"]})]})]})},y.id)})})]})}var Fm=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,s)=>(typeof require<"u"?require:t)[s]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Ti=80,Mi=32;function G2(e,t){const s={},n={...e,...t||{}};for(const[i,a]of Object.entries(n))typeof a=="string"&&(s[i]=a);for(const i of Object.keys(s))(i==="INIT_CWD"||i==="npm_command"||i==="npm_execpath"||i==="npm_node_execpath"||i.startsWith("npm_")||i.startsWith("npm_config_")||i.startsWith("npm_package_")||i.startsWith("npm_lifecycle_")||i.startsWith("PNPM_")||i.startsWith("YARN_")||i.startsWith("BUN_")||i.startsWith("VSCODE_")||i.startsWith("ELECTRON_"))&&delete s[i];return delete s.CODEX_THREAD_ID,delete s.CODEX_INTERNAL_ORIGINATOR_OVERRIDE,delete s.CODEX_SANDBOX_NETWORK_DISABLED,delete s.NO_COLOR,delete s.COLOR,process.platform==="win32"&&(delete s.CLAUDECODE,delete s.CLAUDE_CODE_CHILD_SESSION,delete s.CLAUDE_CODE_ENTRYPOINT,delete s.CLAUDE_CODE_SESSION_ID,delete s.CLAUDE_CODE_EXECPATH),q2(s),s}function q2(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 V2(e){if(ot.platform()!=="win32")try{const t=Fm("fs"),s=Ee.resolve(Ee.dirname(Fm.resolve("node-pty")),".."),n=`${ot.platform()}-${ot.arch()}`,i=Ee.join(s,"prebuilds",n,"spawn-helper");if(t.existsSync(i)){const a=t.statSync(i);a.mode&73||(t.chmodSync(i,a.mode|493),e==null||e(`Fixed spawn-helper permissions: ${i}`))}}catch{}}var bt={},X2=Object.defineProperty,Y2=Object.getOwnPropertyNames,Cs=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,s)=>(typeof require<"u"?require:t)[s]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),We=(e,t)=>function(){return e&&(t=(0,e[Y2(e)[0]])(e=0)),t},Tt=(e,t)=>{for(var s in t)X2(e,s,{get:t[s],enumerable:!0})};function Bb(e){if(typeof e!="string")return bd;const t=e.trim();return Ub.includes(t)?t:bd}function xd(e){const t=Number(e==null?void 0:e.schedulingPriority);return Number.isFinite(t)?t:0}function Q2(e,t){if(!e||(t==null?void 0:t.enabled)===!1)return null;const s=t!=null&&t.byTaskMode&&Object.prototype.hasOwnProperty.call(t.byTaskMode,e)?t.byTaskMode[e]:void 0;if(typeof s=="string"){const i=s.trim().toLowerCase();return i||null}return zb[e]??null}function J2(e){const t=[...Lo],s=new Set(t),n=i=>{if(typeof i!="string")return;const a=i.trim().toLowerCase();!a||s.has(a)||(s.add(a),t.push(a))};if(e!=null&&e.byTaskMode)for(const i of Object.values(e.byTaskMode))n(i);if(Array.isArray(e==null?void 0:e.customRoles))for(const i of e.customRoles)n(i);return t}function Z2(e){return(e==null?void 0:e.autoConvergeCodeChange)===!0}function Wu(e,t){return typeof(t==null?void 0:t.delegatedWorkerAutoApprove)=="boolean"?t.delegatedWorkerAutoApprove:typeof(e==null?void 0:e.delegatedWorkerAutoApprove)=="boolean"?e.delegatedWorkerAutoApprove:!0}function eR(e,t){const s=typeof t=="string"?t.trim().toLowerCase():"";if(!s)return;const n=e==null?void 0:e.providerRoles;if(Array.isArray(n))for(const i of n){if(!i||typeof i!="object")continue;const a=typeof i.providerType=="string"?i.providerType.trim().toLowerCase():"";if(a&&a===s)return i}}function Wb(e,t){const s=eR(e,t),n=Number(s==null?void 0:s.maxParallel);if(!(!Number.isFinite(n)||n<0))return Math.floor(n)}var Ub,bd,Hb,Lo,zb,Ei,Mn=We({"src/repo-mesh-types.ts"(){Ub=["first_eligible","least_loaded","round_robin","priority_only"],bd="first_eligible",Hb="converge=refine",Lo=["investigator","coder","validator","converger"],zb={live_debug_readonly:"investigator",code_change:"coder",launch_app:"coder",validation:"validator",convergence:"converger"},Ei={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,spawnedSessionVisibility:"visible",delegatedWorkerAutoApprove:!0,sessionCleanupOnNodeRemove:"preserve",autoFastForward:{enabled:!0},maxTaskRetries:1}}}),tR={};Tt(tR,{GIT_STATUS_TIMEOUT_MS:()=>Uu,GitCommandError:()=>mt,isPathInside:()=>hi,normalizeGitOutput:()=>Wr,resolveGitRepository:()=>sa,runGit:()=>tt});async function sa(e,t={}){const s=await yd(e),n=await Gb(s,["rev-parse","--show-toplevel"],t,{mapNotGitRepo:!0}),i=Ee.resolve(n.stdout.trim());if(!i)throw new mt("not_git_repo","Git did not return a repository root",{stdout:n.stdout,stderr:n.stderr,argv:["rev-parse","--show-toplevel"],cwd:s});return{workspace:s,repoRoot:i,isGitRepo:!0}}async function tt(e,t,s={}){Kb(t);const n=typeof e=="string"?await sa(e,s):e;if(!n.repoRoot||!n.isGitRepo)throw new mt("not_git_repo","Workspace is not a Git repository",{argv:t,cwd:n.workspace});const i=s.cwd?await yd(s.cwd):await yd(n.workspace),a=await go(n.repoRoot),o=await go(i);if(!hi(a,o))throw new mt("path_outside_repo","Git cwd is outside the repository root",{argv:t,cwd:i});return Gb(i,t,s)}function Wr(e){return typeof e=="string"?e.replace(/\r\n/g,`
|
|
113
|
+
`):Buffer.isBuffer(e)?e.toString("utf8").replace(/\r\n/g,`
|
|
114
|
+
`):e==null?"":String(e).replace(/\r\n/g,`
|
|
115
|
+
`)}function hi(e,t){const s=Ee.relative(Ee.resolve(e),Ee.resolve(t));return s===""||!s.startsWith("..")&&!Ee.isAbsolute(s)}async function yd(e){if(typeof e!="string"||e.length===0||e.includes("\0"))throw new mt("invalid_args","Workspace must be a non-empty path");if(!Ee.isAbsolute(e))throw new mt("invalid_args","Workspace must be an absolute path",{cwd:e});const t=Ee.resolve(e);try{if(!(await Gw(t)).isDirectory())throw new mt("invalid_args","Workspace must be an existing directory",{cwd:t});await qw(t,zw.R_OK)}catch(s){throw s instanceof mt?s:new mt("invalid_args","Workspace must be an existing directory",{cwd:t,cause:s})}return t}function Kb(e){if(!Array.isArray(e)||e.length===0)throw new mt("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 mt("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 mt("invalid_args","Git argv contains unsafe repository override arguments",{argv:e})}async function Gb(e,t,s,n={}){Kb(t);try{const i=await qb("git",[...t],{cwd:e,encoding:"utf8",timeout:s.timeoutMs??Vb,maxBuffer:s.maxBuffer??Xb,windowsHide:!0});return{stdout:Wr(i.stdout),stderr:Wr(i.stderr)}}catch(i){throw sR(i,e,t,n)}}function sR(e,t,s,n){const i=e,a=Wr(i.stdout),o=Wr(i.stderr),l=i.code,c=i.signal,d=[o.trim(),i.message].filter(Boolean).join(`
|
|
116
|
+
`);return l==="ENOENT"?new mt("git_not_installed","Git executable was not found",{stdout:a,stderr:o,exitCode:l,signal:c,argv:s,cwd:t,cause:e}):i.killed||/timed out/i.test(i.message)?new mt("timeout","Git command timed out",{stdout:a,stderr:o,exitCode:l,signal:c,argv:s,cwd:t,cause:e}):n.mapNotGitRepo&&/not a git repository/i.test(o+`
|
|
117
|
+
`+i.message)?new mt("not_git_repo","Workspace is not a Git repository",{stdout:a,stderr:o,exitCode:l,signal:c,argv:s,cwd:t,cause:e}):new mt("git_command_failed",d||"Git command failed",{stdout:a,stderr:o,exitCode:l,signal:c,argv:s,cwd:t,cause:e})}var qb,Vb,Xb,Uu,mt,ra=We({"src/git/git-executor.ts"(){qb=In(Hd),Vb=5e3,Xb=1024*1024,Uu=process.platform==="win32"?3e4:2e4,mt=class extends Error{constructor(t,s,n={}){super(s);re(this,"reason");re(this,"stdout");re(this,"stderr");re(this,"exitCode");re(this,"signal");re(this,"argv");re(this,"cwd");n.cause!==void 0&&(this.cause=n.cause),this.name="GitCommandError",this.reason=t,this.stdout=Wr(n.stdout),this.stderr=Wr(n.stderr),this.exitCode=n.exitCode,this.signal=n.signal,this.argv=n.argv?[...n.argv]:void 0,this.cwd=n.cwd}}}});function qn(e){if(typeof e!="string")return;const t=e.trim();if(!(!t||t==="unknown"))return t}function rR(){if(Ha)return Ha;const e=qn("930909642b3f28668483159d3a8f39d0a796c61a")??"unknown",t=qn("93090964")??(e!=="unknown"?e.slice(0,7):"unknown"),s=qn("0.9.82-rc.316")??qn(typeof process<"u"?bt==null?void 0:bt.ADHDEV_PKG_VERSION:void 0)??"unknown",n=qn("2026-06-18T07:23:07.242Z");return Ha=n?{commit:e,commitShort:t,version:s,builtAt:n}:{commit:e,commitShort:t,version:s},Ha}var Ha,Hu=We({"src/build-info.ts"(){}});function nR(e){return e.reason==="timeout"||e.reason==="git_command_failed"}async function mi(e,t={}){const s=Date.now(),n=t.includeSubmodules!==!1,i=t.timeoutMs===void 0?{...t,timeoutMs:Uu}:t;try{const a=await sa(e,i),o=await iR(a,n,s,i);return vd.set(e,o),o}catch(a){const o=a instanceof mt?a:new mt("git_command_failed","Failed to read Git status",{cause:a});if(nR(o)){const l=vd.get(e);if(l)return{...l,lastCheckedAt:s,upstreamStatus:"unavailable",error:o.stderr||o.message,reason:o.reason}}return gR(e,s,o)}}async function iR(e,t,s,n){let i=await Bm(e,n),a=cR(i);n.refreshUpstream&&(a=await dR(e,i,n),a.upstreamStatus==="fresh"&&(i=await Bm(e,n)));const o=await hR(e,n),l=await mR(e,n);let c;t&&(c=await xR(e,n));const d=(c||[]).some(m=>m.dirty||m.outOfSync||!!m.error),p=i.staged+i.modified+i.untracked+i.deleted+i.renamed>0||i.conflictFiles.length>0||l>0||d,h=await lR(e,c,n);return{workspace:e.workspace,repoRoot:e.repoRoot,isGitRepo:!0,branch:i.branch,headCommit:o.commit,headMessage:o.message,upstream:i.upstream,upstreamStatus:i.upstream?a.upstreamStatus:"no_upstream",upstreamFetchedAt:a.upstreamFetchedAt,upstreamFetchError:a.upstreamFetchError,ahead:i.ahead,behind:i.behind,staged:i.staged,modified:i.modified,untracked:i.untracked,deleted:i.deleted,renamed:i.renamed,dirty:p,hasConflicts:i.conflictFiles.length>0,conflictFiles:i.conflictFiles,stashCount:l,lastCheckedAt:s,submodules:c,...h?{daemonBuildBehind:h}:{}}}function aR(e){const t=e.slice(e.lastIndexOf("/")+1);return!!(/^\.(?:verify|marker|converge|ff-verify|patch-equiv|live-verify)\b/i.test(t)||/(?:^|\/)docs\//i.test(e)||/^(?:README|CHANGELOG|LICENSE|NOTICE|AUTHORS|CONTRIBUTING|CODEOWNERS)(?:\.[A-Za-z0-9]+)?$/i.test(t))}async function oR(e,t,s){try{const i=(await tt(e,["diff","--name-only",`${t}..HEAD`],s)).stdout.split(`
|
|
118
|
+
`).map(d=>d.trim()).filter(Boolean);if(i.length===0)return{isDaemonAffecting:!0,affectedPackages:[]};const a=new Set;let o=!1;for(const d of i){const p=d.match(/(?:^|\/)packages\/([^/]+)\//);if(!p){aR(d)||(o=!0);continue}a.add(p[1])}const l=[...a].sort();return{isDaemonAffecting:!(!o&&l.every(d=>Zb.has(d)&&!Jb.has(d))),affectedPackages:l}}catch{return{isDaemonAffecting:!0,affectedPackages:[]}}}async function lR(e,t,s){const n=s.daemonBuildInfo??rR();if(!n.commit||n.commit==="unknown")return;const i=[{scope:"root",repoPath:e.repoRoot||e.workspace}];for(const a of t||[])a.repoPath&&!a.error&&i.push({scope:a.path,repoPath:a.repoPath});for(const{scope:a,repoPath:o}of i)try{await tt(o,["cat-file","-e",`${n.commit}^{commit}`],s);const c=(await tt(o,["rev-parse","HEAD"],s)).stdout.trim();if(!c||c===n.commit)continue;await tt(o,["merge-base","--is-ancestor",n.commit,"HEAD"],s);const{isDaemonAffecting:d,affectedPackages:p}=await oR(o,n.commit,s),h=a==="root"?"workspace":a,m=p.length>0?`only web packages changed (${p.join(", ")})`:"only non-runtime files changed (markers/docs)",g=d?`Live daemon was built from ${n.commitShort} which is behind ${h} HEAD ${c.slice(0,7)}. Merged code is NOT live until the daemon is rebuilt/redeployed and restarted — a local dist rebuild alone does not update a cloud daemon.`:`Live daemon was built from ${n.commitShort} which is behind ${h} HEAD ${c.slice(0,7)}, but ${m}. Daemon restart NOT required — redeploy the web app to reflect the change.`;return{buildCommit:n.commit,buildCommitShort:n.commitShort,head:c,scope:a,isDaemonAffecting:d,...p&&p.length>0?{affectedPackages:p}:{},warning:g}}catch{continue}}async function Bm(e,t){const s=await tt(e,["status","--porcelain=v2","--branch"],t);return Qb(s.stdout)}function cR(e){return{upstreamStatus:e.upstream?"unchecked":"no_upstream"}}async function dR(e,t,s){if(!t.upstream||!t.branch)return{upstreamStatus:"no_upstream"};const n=await uR(e,t.branch,s)??pR(t.upstream);if(!n)return{upstreamStatus:"stale",upstreamFetchError:`Unable to resolve remote for upstream '${t.upstream}'`};try{return await tt(e,["fetch","--quiet","--prune","--no-tags",n],s),{upstreamStatus:"fresh",upstreamFetchedAt:Date.now()}}catch(i){return{upstreamStatus:"stale",upstreamFetchError:Yb(i)}}}async function uR(e,t,s){try{return(await tt(e,["config","--get",`branch.${t}.remote`],s)).stdout.trim()||null}catch{return null}}function pR(e){const[t]=e.split("/");return(t==null?void 0:t.trim())||null}function Yb(e){return e instanceof mt?e.stderr||e.message:e instanceof Error?e.message:String(e)}function Qb(e){const t={branch:null,upstream:null,ahead:0,behind:0,staged:0,modified:0,untracked:0,deleted:0,renamed:0,conflictFiles:[]};for(const s of e.split(`
|
|
119
|
+
`))if(s){if(s.startsWith("# branch.head ")){const n=s.slice(14).trim();t.branch=n&&n!=="(detached)"?n:null;continue}if(s.startsWith("# branch.upstream ")){t.upstream=s.slice(18).trim()||null;continue}if(s.startsWith("# branch.ab ")){const n=s.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(s.startsWith("? ")){t.untracked+=1;continue}if(s.startsWith("u ")){const i=s.split(" ").slice(10).join(" ");i&&t.conflictFiles.push(i);continue}if(s.startsWith("1 ")||s.startsWith("2 ")){const n=s.split(" "),i=n[1]??"..",a=i[0]??".",o=i[1]??".";if(fR(a)&&(t.staged+=1),(o==="M"||o==="T")&&(t.modified+=1),(a==="D"||o==="D")&&(t.deleted+=1),(a==="R"||o==="R")&&(t.renamed+=1),i.includes("U")){const l=n.slice(s.startsWith("2 ")?9:8).join(" ").split(" ")[0]??"";l&&t.conflictFiles.push(l)}}}return t.conflictFiles=Array.from(new Set(t.conflictFiles)),t}async function hR(e,t){try{const n=(await tt(e,["log","-1","--pretty=%h%x00%s"],t)).stdout.trimEnd();if(!n)return{commit:null,message:null};const[i,...a]=n.split("\0");return{commit:i||null,message:a.join("\0")||null}}catch{return{commit:null,message:null}}}async function mR(e,t){try{return(await tt(e,["stash","list","--format=%gd"],t)).stdout.split(`
|
|
120
|
+
`).filter(n=>n.trim().length>0).length}catch{return 0}}function fR(e){return e!=="."&&e!=="?"&&e!=="U"}function gR(e,t,s){return{workspace:e,repoRoot:null,isGitRepo:!1,branch:null,headCommit:null,headMessage:null,upstream:null,upstreamStatus:"unavailable",ahead:0,behind:0,staged:0,modified:0,untracked:0,deleted:0,renamed:0,dirty:!1,hasConflicts:!1,conflictFiles:[],stashCount:0,lastCheckedAt:t,error:s.stderr||s.message,reason:s.reason}}async function xR(e,t){if(!e.repoRoot)return[];try{const s=await tt(e,["submodule","status"],t),n=yR(s.stdout,e.repoRoot,t.submoduleIgnorePaths);return await Promise.all(n.map(i=>bR(e,i,t))),n}catch{return[]}}async function bR(e,t,s){try{const n=await tt(e,["status","--porcelain=v2","--branch"],{...s,cwd:t.repoPath}),i=Qb(n.stdout),a=i.staged+i.modified+i.untracked+i.deleted+i.renamed>0||i.conflictFiles.length>0;t.dirty=t.dirty||a}catch(n){t.dirty=!0,t.error=Yb(n)}}function yR(e,t,s){const n=[],i=new Set(s||[]);for(const a of e.split(`
|
|
121
|
+
`)){if(!a.trim())continue;const o=a.match(/^([\-+U\s])([0-9a-f]{40})\s+(\S+)(?:\s+\(([^)]+)\))?/);if(!o)continue;const l=o[1],c=o[2],d=o[3];i.has(d)||n.push({path:d,commit:c,repoPath:t+"/"+d,dirty:l==="U",outOfSync:l==="-"||l==="+",lastCheckedAt:Date.now()})}return n}var vd,Jb,Zb,na=We({"src/git/git-status.ts"(){ra(),Hu(),vd=new Map,Jb=new Set(["daemon-core","daemon-standalone","session-host-core","session-host-daemon","terminal-mux-core","terminal-mux-control","terminal-mux-cli","ghostty-vt-node","mcp-server"]),Zb=new Set(["web-core","web-standalone","web-devconsole","terminal-render-web"])}}),vR={};Tt(vR,{getGitDiffSummary:()=>ty,getGitFileDiff:()=>wR});function ey(e){const t=e.trim();if(!t||t.startsWith("-")||t.includes("..")||!/^[A-Za-z0-9][A-Za-z0-9._/@-]*$/.test(t))throw new mt("invalid_args",`Invalid base ref: ${e}`);return t}async function ty(e,t={}){const s=Date.now();try{const n=await sa(e,t),i=n.repoRoot;if(t.baseRef){const v=`${ey(t.baseRef)}...HEAD`,[w,x]=await Promise.all([tt(n,["diff","--no-ext-diff","--name-status",v,"--"],{...t,cwd:i}),tt(n,["diff","--no-ext-diff","--numstat",v,"--"],{...t,cwd:i})]),S=wd(w.stdout+x.stdout),k=Ic(w.stdout,x.stdout,!1),j=ti(t.maxFiles,Sd),y=ti(t.maxBytes,$o),N=k.slice(0,j);return{workspace:n.workspace,repoRoot:i,isGitRepo:!0,files:N,totalInsertions:N.reduce((_,C)=>_+C.insertions,0),totalDeletions:N.reduce((_,C)=>_+C.deletions,0),truncated:k.length>N.length||S>y,lastCheckedAt:s}}const[a,o,l,c,d]=await Promise.all([tt(n,["diff","--no-ext-diff","--name-status"],{...t,cwd:i}),tt(n,["diff","--no-ext-diff","--numstat"],{...t,cwd:i}),tt(n,["diff","--cached","--no-ext-diff","--name-status"],{...t,cwd:i}),tt(n,["diff","--cached","--no-ext-diff","--numstat"],{...t,cwd:i}),tt(n,["ls-files","--others","--exclude-standard"],{...t,cwd:i})]),p=wd(a.stdout+o.stdout+l.stdout+c.stdout+d.stdout),h=[...Ic(a.stdout,o.stdout,!1),...Ic(l.stdout,c.stdout,!0),...jR(d.stdout)],m=ti(t.maxFiles,Sd),g=ti(t.maxBytes,$o),b=h.slice(0,m),f=h.length>b.length||p>g;return{workspace:n.workspace,repoRoot:i,isGitRepo:!0,files:b,totalInsertions:b.reduce((v,w)=>v+w.insertions,0),totalDeletions:b.reduce((v,w)=>v+w.deletions,0),truncated:f,lastCheckedAt:s}}catch(n){const i=n instanceof mt?n:new mt("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:s,error:i.stderr||i.message,reason:i.reason}}}async function wR(e,t,s={}){const n=Date.now(),i=await sa(e,s),a=i.repoRoot,o=await _R(a,t),l=ti(s.maxBytes,$o);if(s.baseRef){const m=`${ey(s.baseRef)}...HEAD`,g=await tt(i,["diff","--no-ext-diff",m,"--",o.relativePath],{...s,cwd:a}),b=Wm(g.stdout,l);return{workspace:i.workspace,repoRoot:a,isGitRepo:!0,path:o.relativePath,diff:b.text,truncated:b.truncated,lastCheckedAt:n}}const[c,d]=await Promise.all([tt(i,["diff","--no-ext-diff","--",o.relativePath],{...s,cwd:a}),tt(i,["diff","--cached","--no-ext-diff","--",o.relativePath],{...s,cwd:a})]);let p=[c.stdout,d.stdout].filter(m=>m.length>0).join(`
|
|
122
|
+
`);p||(await tt(i,["ls-files","--others","--exclude-standard","--",o.relativePath],{...s,cwd:a})).stdout.split(`
|
|
123
|
+
`).filter(Boolean).includes(o.relativePath)&&(p=await CR(o.absolutePath,o.relativePath,l+1));const h=Wm(p,l);return{workspace:i.workspace,repoRoot:a,isGitRepo:!0,path:o.relativePath,diff:h.text,truncated:h.truncated,lastCheckedAt:n}}function Ic(e,t,s){const n=SR(e),i=kR(t);return n.map((a,o)=>{const l=i[o];return{path:a.path,oldPath:a.oldPath,status:a.status,staged:s,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 SR(e){return e.split(`
|
|
124
|
+
`).filter(Boolean).map(t=>{const s=t.split(" "),i=(s[0]??"")[0]??"M";return i==="R"?{oldPath:s[1]??"",path:s[2]??s[1]??"",status:"renamed"}:i==="C"?{oldPath:s[1]??"",path:s[2]??s[1]??"",status:"copied"}:{path:s[1]??"",status:NR(i)}}).filter(t=>t.path.length>0)}function kR(e){return e.split(`
|
|
125
|
+
`).filter(Boolean).map(t=>{const s=t.split(" "),n=s[0]??"0",i=s[1]??"0",a=n==="-"||i==="-";return{path:s.slice(2).join(" "),insertions:a?0:Number.parseInt(n,10)||0,deletions:a?0:Number.parseInt(i,10)||0,binary:a}})}function jR(e){return e.split(`
|
|
126
|
+
`).filter(Boolean).map(t=>({path:t,status:"untracked",staged:!1,insertions:0,deletions:0}))}function NR(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"}}async function _R(e,t){if(typeof t!="string"||t.length===0||t.includes("\0"))throw new mt("invalid_args","File path must be a non-empty path");const s=await go(e).catch(()=>Ee.resolve(e)),n=Ee.isAbsolute(t)?Ee.resolve(t):Ee.resolve(e,t),i=await go(n).catch(()=>n),a=hi(s,i)?s:Ee.resolve(e);if(!hi(s,i)&&!hi(e,n))throw new mt("path_outside_repo","Selected file path is outside the repository root",{cwd:e});const o=Ee.relative(a,i).split(Ee.sep).join("/");if(!o||o.startsWith("..")||Ee.isAbsolute(o))throw new mt("path_outside_repo","Selected file path is outside the repository root",{cwd:e});return{absolutePath:n,relativePath:o}}async function CR(e,t,s){const n=await Vw(e,"utf8"),i=n.length>s?n.slice(0,s):n,a=i.length>0?i.split(`
|
|
127
|
+
`):[],o=a.filter((c,d)=>d<a.length-1||c.length>0).map(c=>`+${c}`).join(`
|
|
128
|
+
`),l=o?o.split(`
|
|
129
|
+
`).length:0;return[`diff --git a/${t} b/${t}`,"new file mode 100644","index 0000000..0000000","--- /dev/null",`+++ b/${t}`,`@@ -0,0 +1,${l} @@`,o].filter(c=>c.length>0).join(`
|
|
130
|
+
`)}function Wm(e,t){return wd(e)<=t?{text:e,truncated:!1}:{text:Buffer.from(e,"utf8").subarray(0,t).toString("utf8"),truncated:!0}}function wd(e){return Buffer.byteLength(e,"utf8")}function ti(e,t){return!Number.isFinite(e)||e==null||e<=0?t:Math.floor(e)}var Sd,$o,zu=We({"src/git/git-diff.ts"(){ra(),Sd=200,$o=2e5}}),IR={};Tt(IR,{createWorktree:()=>AR,listWorktrees:()=>MR,parseWorktreeListOutput:()=>ry,removeWorktree:()=>TR,resolveWorktreePath:()=>sy});function sy(e,t,s){const n=s.replace(/[/\\:*?"<>|]/g,"-").replace(/^\.+|\.+$/g,""),i=t.replace(/[/\\:*?"<>|]/g,"-").replace(/^\.+|\.+$/g,""),a=Ee.dirname(e);return Ee.join(a,ny,i,n)}async function AR(e){const{repoRoot:t,branch:s,baseBranch:n,meshName:i}=e,a=e.targetDir||sy(t,i,s);if(st(a))throw new Error(`Worktree target directory already exists: ${a}`);await Xw(Ee.dirname(a),{recursive:!0});const o=["worktree","add",a,"-b",s];n&&o.push(n);try{await Mr("git",o,{cwd:t,encoding:"utf8",timeout:Er,maxBuffer:hn,windowsHide:!0})}catch(l){const c=typeof l.stderr=="string"?l.stderr:"";throw/already exists/i.test(c)?st(a)?new Error(`Worktree target directory was created concurrently: ${a}`):new Error(`Branch '${s}' already exists or is checked out in another worktree`):new Error(`git worktree add failed: ${c.trim()||l.message}`)}return{success:!0,worktreePath:a,branch:s}}async function TR(e,t,s={}){if(!st(t))return await ER(e),{success:!0,removedPath:t};if(s.requireClean){const{stdout:n}=await Mr("git",["status","--porcelain"],{cwd:t,encoding:"utf8",timeout:Er,maxBuffer:hn,windowsHide:!0});if(n.trim())throw new Error(`Refusing to remove dirty worktree: ${t}`)}try{await Mr("git",["worktree","remove",t],{cwd:e,encoding:"utf8",timeout:Er,maxBuffer:hn,windowsHide:!0})}catch(n){const i=typeof n.stderr=="string"?n.stderr:"",a=typeof n.stdout=="string"?n.stdout:"",o=`${i}
|
|
131
|
+
${a}
|
|
132
|
+
${n.message||""}`;if(s.allowSubmoduleForceFallback&&iy.test(o)){process.stderr.write(`[adhdev-mesh] WARNING: git worktree remove --force fallback for submodule worktree '${t}'. Any uncommitted changes inside submodules will be lost.
|
|
133
|
+
`);try{await Mr("git",["worktree","remove","--force",t],{cwd:e,encoding:"utf8",timeout:Er,maxBuffer:hn,windowsHide:!0})}catch(l){const c=typeof l.stderr=="string"?l.stderr:"",d=typeof l.stdout=="string"?l.stdout:"";throw new Error(`git worktree remove --force fallback failed: ${c.trim()||d.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: ${i.trim()||a.trim()||n.message}`)}return{success:!0,removedPath:t}}async function MR(e){const{stdout:t}=await Mr("git",["worktree","list","--porcelain"],{cwd:e,encoding:"utf8",timeout:Er,maxBuffer:hn,windowsHide:!0});return ry(t)}function ry(e){const t=[],s=e.trim().split(/\n\n+/);for(const n of s){if(!n.trim())continue;const i=n.trim().split(`
|
|
134
|
+
`),a={path:"",head:"",branch:null,bare:!1};for(const o of i)if(o.startsWith("worktree "))a.path=o.slice(9).trim();else if(o.startsWith("HEAD "))a.head=o.slice(5).trim();else if(o.startsWith("branch ")){const l=o.slice(7).trim();a.branch=l.replace(/^refs\/heads\//,"")}else o==="bare"&&(a.bare=!0);a.path&&t.push(a)}return t}async function ER(e){try{await Mr("git",["worktree","prune"],{cwd:e,encoding:"utf8",timeout:Er,windowsHide:!0})}catch{}}var Mr,ny,Er,hn,iy,RR=We({"src/git/git-worktree.ts"(){Mr=In(Hd),ny=".adhdev-worktrees",Er=3e4,hn=4*1024*1024,iy=/working trees containing submodules cannot be moved or removed/i}}),PR={};Tt(PR,{generateMachineId:()=>ly,getConfigDir:()=>Vr,getDaemonDataDir:()=>LR,isSetupComplete:()=>FR,isStableMachineId:()=>cy,loadConfig:()=>Xs,markSetupComplete:()=>OR,resetConfig:()=>BR,resolveProviderSourceMode:()=>ay,saveConfig:()=>Ri,updateConfig:()=>uy});function ay(e,t){return e==="normal"||e==="no-upstream"?e:t===!0?"no-upstream":"normal"}function Ls(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ac(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function vr(e){return typeof e=="string"?e:null}function za(e){return typeof e=="string"&&e.trim()?e:void 0}function Um(e,t){return typeof e=="boolean"?e:t}function DR(e){if(!Ls(e))return{};const t={};for(const[s,n]of Object.entries(e)){if(!Ls(n))continue;const i={};n.enabled===!0&&(i.enabled=!0),typeof n.executable=="string"&&n.executable.trim()&&(i.executable=n.executable.trim()),Array.isArray(n.args)&&(i.args=n.args.filter(a=>typeof a=="string")),Ls(n.lastDetection)&&(i.lastDetection=n.lastDetection),Ls(n.lastVerification)&&(i.lastVerification=n.lastVerification),t[s]=i}return t}function oy(e){const t=Ls(e)?e:{};return{serverUrl:typeof t.serverUrl=="string"&&t.serverUrl.trim()?t.serverUrl:Rr.serverUrl,allowServerApiProxy:Um(t.allowServerApiProxy,Rr.allowServerApiProxy??!1),selectedIde:vr(t.selectedIde),configuredIdes:Ac(t.configuredIdes),installedExtensions:Ac(t.installedExtensions),userEmail:vr(t.userEmail),userName:vr(t.userName),setupCompleted:Um(t.setupCompleted,Rr.setupCompleted),setupDate:vr(t.setupDate),enabledIdes:Ac(t.enabledIdes),workspaces:Array.isArray(t.workspaces)?t.workspaces:[],defaultWorkspaceId:vr(t.defaultWorkspaceId)??vr(t.activeWorkspaceId),machineNickname:vr(t.machineNickname),machineId:za(t.machineId),machineSecret:t.machineSecret===null?null:za(t.machineSecret),registeredMachineId:za(t.registeredMachineId),providerSettings:Ls(t.providerSettings)?t.providerSettings:{},machineProviders:DR(t.machineProviders),ideSettings:Ls(t.ideSettings)?t.ideSettings:{},providerSourceMode:ay(t.providerSourceMode,t.disableUpstream),providerDir:za(t.providerDir),updateChannel:t.updateChannel==="preview"?"preview":"stable",terminalSizingMode:t.terminalSizingMode==="fit"?"fit":"measured"}}function ly(){return`${Ku}${Ts().replace(/-/g,"")}`}function cy(e){return typeof e=="string"&&e.startsWith(Ku)}function Tc(e){return cy(e.machineId)?{config:e,changed:!1}:{config:{...e,machineId:ly()},changed:!0}}function Vr(){const e=bt.ADHDEV_CONFIG_DIR,t=e&&e.trim()?e.trim():Dt(Jw(),".adhdev");return st(t)||Ki(t,{recursive:!0}),t}function LR(){const e=Dt(Vr(),"daemon");return st(e)||Ki(e,{recursive:!0}),e}function dy(){return Dt(Vr(),"config.json")}function $R(e){const t=Dt(Vr(),"state.json");if(st(t))return;const s=Array.isArray(e.recentActivity)?e.recentActivity:[],n=Array.isArray(e.savedProviderSessions)?e.savedProviderSessions:[],i=Ls(e.recentSessionReads)?e.recentSessionReads:{},a=Ls(e.sessionReads)?e.sessionReads:{},o=Ls(e.sessionReadMarkers)?e.sessionReadMarkers:{};if(!(s.length>0||n.length>0||Object.keys(a).length>0||Object.keys(i).length>0||Object.keys(o).length>0))return;const c=Object.fromEntries(Object.entries({...i,...a}).filter(([,h])=>typeof h=="number"&&Number.isFinite(h))),d=Object.fromEntries(Object.entries(o).filter(([,h])=>typeof h=="string"));Ss(t,JSON.stringify({recentActivity:s,savedProviderSessions:n,sessionReads:c,sessionReadMarkers:d},null,2),{encoding:"utf-8",mode:384})}function Xs(){const e=dy();if(!st(e)){const t=Tc({...Rr});try{Ri(t.config)}catch{}return t.config}try{const t=As(e,"utf-8"),s=JSON.parse(t);$R(s);const n=oy(s),i=Tc(n),a=i.config;if(i.changed||JSON.stringify(s)!==JSON.stringify(a))try{Ri(a)}catch{}return a}catch{return Tc({...Rr}).config}}function Ri(e){const t=dy(),s=Vr(),n=oy(e);st(s)||Ki(s,{recursive:!0,mode:448}),Ss(t,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384});try{Kw(t,384)}catch{}}function uy(e){const s={...Xs(),...e};return Ri(s),s}function OR(e,t){const s=Array.isArray(e)?e:[e];return uy({selectedIde:s[0],configuredIdes:s,installedExtensions:t,setupCompleted:!0,setupDate:new Date().toISOString()})}function FR(){return Xs().setupCompleted}function BR(){Ri({...Rr})}var Rr,Ku,rs=We({"src/config/config.ts"(){Rr={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"},Ku="mach_"}});function yl(e){if((e==null?void 0:e.ownerRole)==="member")throw new Error("Mesh Host daemon required to mutate mesh queue; member daemons must use the host-owned queue.")}function ia(){return{role:"host",pairing:{status:"not_configured"}}}var vl=We({"src/mesh/mesh-host-ownership.ts"(){}}),WR={};Tt(WR,{addNode:()=>tP,applyMeshHostJoinRequest:()=>ZR,configureMeshHostPairing:()=>QR,createMesh:()=>KR,createMeshHostPairingToken:()=>JR,deleteMesh:()=>qR,getMesh:()=>En,getMeshByRepo:()=>gy,listMeshes:()=>fy,markMeshHostPairingJoined:()=>eP,normalizeRepoIdentity:()=>hy,removeNode:()=>sP,tokenIdForManualPairing:()=>aa,updateMesh:()=>GR,updateNode:()=>rP});function py(){return Dt(Vr(),"meshes.json")}function ls(){const e=py();if(!st(e))return{meshes:[]};try{const t=JSON.parse(As(e,"utf-8"));return!t||!Array.isArray(t.meshes)?{meshes:[]}:t}catch{return{meshes:[]}}}function UR(e){if(!Array.isArray(e))return;const t=new Set,s=e.map(n=>typeof n=="string"?n.trim():"").filter(Boolean).filter(n=>t.has(n)?!1:(t.add(n),!0));return s.length?s:void 0}function Is(e){const t=py();Ss(t,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function hy(e){let t=e.trim();if(t.startsWith("http://")||t.startsWith("https://"))try{const n=new URL(t),i=n.pathname.replace(/^\//,"").replace(/\.git$/,"");return`${n.hostname}/${i}`}catch{}const s=t.match(/^(?:ssh:\/\/)?[\w.-]+@([\w.-]+)[:/]([\w.\-/]+?)(?:\.git)?$/);return s?`${s[1]}/${s[2]}`:t}function my(e,t){const s=zR({...Ei.autoFastForward,...e!=null&&e.autoFastForward&&typeof e.autoFastForward=="object"?e.autoFastForward:{},...t!=null&&t.autoFastForward&&typeof t.autoFastForward=="object"?t.autoFastForward:{}}),n={...Ei,...e||{},...t||{},autoFastForward:s};["block","warn","checkpoint_then_continue"].includes(n.dirtyWorkspaceBehavior)||(n.dirtyWorkspaceBehavior="warn");const i=Number(n.maxParallelTasks);n.maxParallelTasks=Number.isFinite(i)?Math.max(1,Math.min(8,Math.floor(i))):2,n.allowAutoPublishSubmoduleMainCommits=n.allowAutoPublishSubmoduleMainCommits===!0,xy.has(String(n.sessionCleanupOnNodeRemove))||(n.sessionCleanupOnNodeRemove="preserve"),by.has(String(n.spawnedSessionVisibility))||(n.spawnedSessionVisibility="visible");const a=Bb(n.schedulingStrategy);a==="first_eligible"?delete n.schedulingStrategy:n.schedulingStrategy=a,n.autoConvergeCodeChange===!0?n.autoConvergeCodeChange=!0:delete n.autoConvergeCodeChange;const o=HR(n.taskAffinity);return o?n.taskAffinity=o:delete n.taskAffinity,n}function HR(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,s={};let n=!1;if(typeof t.enabled=="boolean"&&(s.enabled=t.enabled,t.enabled===!1?n=!0:delete s.enabled),t.byTaskMode&&typeof t.byTaskMode=="object"&&!Array.isArray(t.byTaskMode)){const i={};for(const[a,o]of Object.entries(t.byTaskMode)){const l=a.trim();if(!l||typeof o!="string")continue;const c=o.trim().toLowerCase();if(i[l]=c,c&&!Lo.includes(c))try{console.warn(`[mesh] task_affinity.byTaskMode.${l}: custom role "${c}" is not a standard mesh role (${Lo.join("/")}); routing still applies`)}catch{}}Object.keys(i).length>0&&(s.byTaskMode=i,n=!0)}if(Array.isArray(t.customRoles)){const i=new Set,a=[];for(const o of t.customRoles){if(typeof o!="string")continue;const l=o.trim().toLowerCase();!l||i.has(l)||(i.add(l),a.push(l))}a.length>0&&(s.customRoles=a,n=!0)}return n?s:void 0}function zR(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},s=Number(t.maxBehind);return{enabled:t.enabled!==!1,...Number.isFinite(s)&&s>=0?{maxBehind:Math.floor(s)}:{},requireCleanSubmodules:t.requireCleanSubmodules!==!1}}function fy(){return ls().meshes}function En(e){return ls().meshes.find(t=>t.id===e)}function gy(e){return ls().meshes.find(t=>t.repoIdentity===e)}function KR(e){const t=ls();if(t.meshes.length>=20)throw new Error("Maximum 20 meshes allowed");const s=e.repoIdentity||(e.repoRemoteUrl?hy(e.repoRemoteUrl):"");if(!s)throw new Error("Either repoRemoteUrl or repoIdentity is required");const n=new Date().toISOString(),i={id:`mesh_${Ts().replace(/-/g,"")}`,name:e.name.trim().slice(0,100),repoIdentity:s,repoRemoteUrl:e.repoRemoteUrl,defaultBranch:e.defaultBranch,policy:my(void 0,e.policy),coordinator:e.coordinator||{},meshHost:e.meshHost||ia(),nodes:[],createdAt:n,updatedAt:n};return t.meshes.push(i),Is(t),i}function GR(e,t){const s=ls(),n=s.meshes.find(i=>i.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=my(n.policy,t.policy)),t.coordinator&&(n.coordinator=t.coordinator),t.meshHost&&(n.meshHost=t.meshHost),n.updatedAt=new Date().toISOString(),Is(s),n}function qR(e){const t=ls(),s=t.meshes.findIndex(n=>n.id===e);return s===-1?!1:(t.meshes.splice(s,1),Is(t),!0)}function VR(e){const t=e.trim().replace(/\/+$/,"");if(!t)throw new Error("hostAddress required");let s;try{s=new URL(t)}catch{throw new Error("hostAddress must be a valid http(s) or ws(s) URL")}if(!["http:","https:","ws:","wss:"].includes(s.protocol))throw new Error("hostAddress must use http, https, ws, or wss");return t}function aa(e){return`tok_${Rf("sha256").update(e).digest("hex").slice(0,16)}`}function XR(e){if(typeof e!="string"||!e.trim())return;const t=new Date(e);if(Number.isNaN(t.getTime()))throw new Error("expiresAt must be a valid ISO date");return t.toISOString()}function YR(e,t,s){const n=t.trim();if(!n)return{ok:!1,reason:"token required"};const i=aa(n),a=e==null?void 0:e.tokenId;return!a||(e==null?void 0:e.status)==="not_configured"||(e==null?void 0:e.status)==="revoked"?{ok:!1,reason:"host pairing token is not configured",presentedTokenId:i}:e.expiresAt&&new Date(e.expiresAt).getTime()<=new Date(s).getTime()?{ok:!1,reason:"host pairing token expired",expectedTokenId:a,presentedTokenId:i}:i!==a?{ok:!1,reason:"invalid pairing token",expectedTokenId:a,presentedTokenId:i}:{ok:!0,tokenId:i}}function QR(e,t){const s=VR(t.hostAddress),n=t.token.trim();if(!n)throw new Error("token required");const i=ls(),a=i.meshes.find(d=>d.id===e);if(!a)return;const o=t.now||new Date().toISOString(),c={...a.meshHost||ia(),role:"member",hostAddress:s,pairing:{status:"pairing",tokenId:aa(n),lastPairedAt:o}};return a.meshHost=c,a.updatedAt=o,Is(i),{mesh:a,meshHost:c,hostAddress:s}}function JR(e,t={}){const s=ls(),n=s.meshes.find(p=>p.id===e);if(!n)return;const i=t.now||new Date().toISOString(),a=(t.token||`mhj_${eS(24).toString("base64url")}`).trim();if(!a)throw new Error("token required");const o=aa(a),l=XR(t.expiresAt),c=n.meshHost||ia();if(c.role==="member")throw new Error("Mesh Host daemon required to create host pairing tokens; member daemons cannot mint host join tokens.");const d={...c,role:"host",pairing:{status:"pairing",tokenId:o,lastPairedAt:i,...l?{expiresAt:l}:{}}};return n.meshHost=d,n.updatedAt=i,Is(s),{mesh:n,meshHost:d,token:a,tokenId:o,...l?{expiresAt:l}:{}}}function ZR(e,t){var h,m,g;const s=ls(),n=s.meshes.find(b=>b.id===e);if(!n)return;const i=t.now||new Date().toISOString(),a=n.meshHost||ia();if(a.role==="member")return{accepted:!1,mesh:n,meshHost:a,reason:"Mesh Host daemon required to accept join requests"};const o={...a,role:"host"},l=YR(o.pairing,t.token,i);if(!l.ok)return n.meshHost={...o,pairing:{...o.pairing||{status:"not_configured"},status:"rejected",lastRejectedAt:i}},n.updatedAt=i,Is(s),{accepted:!1,mesh:n,meshHost:n.meshHost,tokenId:l.presentedTokenId,reason:l.reason};const c=t.memberNode.workspace.trim();if(!c)throw new Error("memberNode.workspace required");const d=(h=t.memberNode.id)==null?void 0:h.trim();let p=n.nodes.find(b=>d&&b.id===d||b.workspace===c);if(p)p.workspace=c,p.repoRoot=t.memberNode.repoRoot,p.daemonId=t.memberNode.daemonId,p.machineId=t.memberNode.machineId,p.userOverrides=t.memberNode.userOverrides||p.userOverrides||{},p.policy={...p.policy||{},...t.memberNode.policy||{}},p.role="member";else{if(n.nodes.length>=10)throw new Error("Maximum 10 nodes per mesh");p={id:d||`node_${Ts().replace(/-/g,"")}`,workspace:c,repoRoot:t.memberNode.repoRoot,daemonId:t.memberNode.daemonId,machineId:t.memberNode.machineId,userOverrides:t.memberNode.userOverrides||{},policy:t.memberNode.policy||{},role:"member"},n.nodes.push(p)}return n.meshHost={...o,pairing:{...o.pairing||{},status:"paired",tokenId:l.tokenId,joinedAt:i,lastPairedAt:((m=o.pairing)==null?void 0:m.lastPairedAt)||i,...(g=o.pairing)!=null&&g.expiresAt?{expiresAt:o.pairing.expiresAt}:{}}},n.updatedAt=i,Is(s),{accepted:!0,mesh:n,meshHost:n.meshHost,node:p,tokenId:l.tokenId}}function eP(e,t){var l,c;const s=ls(),n=s.meshes.find(d=>d.id===e);if(!n)return;const i=t.joinedAt||new Date().toISOString(),a=n.meshHost||ia(),o=t.tokenId||(t.token?aa(t.token):(l=a.pairing)==null?void 0:l.tokenId);return n.meshHost={...a,role:"member",...t.hostDaemonId?{hostDaemonId:t.hostDaemonId}:{},...t.hostNodeId?{hostNodeId:t.hostNodeId}:{},pairing:{...a.pairing||{},status:"paired",...o?{tokenId:o}:{},joinedAt:i,lastPairedAt:((c=a.pairing)==null?void 0:c.lastPairedAt)||i}},n.updatedAt=i,Is(s),{mesh:n,meshHost:n.meshHost}}function tP(e,t){const s=ls(),n=s.meshes.find(a=>a.id===e);if(!n)return;if(n.nodes.length>=10)throw new Error("Maximum 10 nodes per mesh");if(n.nodes.some(a=>a.workspace===t.workspace))throw new Error("This workspace is already in the mesh");const i={id:`node_${Ts().replace(/-/g,"")}`,workspace:t.workspace.trim(),repoRoot:t.repoRoot,daemonId:t.daemonId,machineId:t.machineId,capabilities:UR(t.capabilities),userOverrides:t.userOverrides||{},policy:t.policy||{},isLocalWorktree:t.isLocalWorktree,worktreeBranch:t.worktreeBranch,clonedFromNodeId:t.clonedFromNodeId,worktreeBootstrap:t.worktreeBootstrap,role:t.role};return n.nodes.push(i),n.updatedAt=new Date().toISOString(),Is(s),i}function sP(e,t){const s=ls(),n=s.meshes.find(a=>a.id===e);if(!n)return!1;const i=n.nodes.findIndex(a=>a.id===t);return i===-1?!1:(n.nodes.splice(i,1),n.updatedAt=new Date().toISOString(),Is(s),!0)}function rP(e,t,s){const n=ls(),i=n.meshes.find(o=>o.id===e);if(!i)return;const a=i.nodes.find(o=>o.id===t);if(a)return s.userOverrides&&(a.userOverrides={...a.userOverrides,...s.userOverrides}),s.policy&&(a.policy={...a.policy,...s.policy}),s.worktreeBootstrap&&(a.worktreeBootstrap=s.worktreeBootstrap),Object.prototype.hasOwnProperty.call(s,"systemPrompt")&&(s.systemPrompt&&s.systemPrompt.trim()?a.systemPrompt=s.systemPrompt:delete a.systemPrompt),i.updatedAt=new Date().toISOString(),Is(n),a}var xy,by,wl=We({"src/config/mesh-config.ts"(){rs(),Mn(),vl(),xy=new Set(["preserve","stop","delete_stopped","stop_and_delete"]),by=new Set(["visible","hidden"])}}),nP={};Tt(nP,{buildCoordinatorSystemPrompt:()=>iP});function iP(e){var d,p,h,m,g;const{mesh:t,userInstruction:s,coordinatorCliType:n}=e,i=(p=(d=t.coordinator)==null?void 0:d.systemPromptOverride)==null?void 0:p.trim();let a;if(i)a=Ka(i,e);else{const b=Hm(n,"md");b!==null?a=Ka(b,e):a=aP(e)}const o=[a],l=Hm(n,"append.md");l!==null&&o.push(Ka(l,e));const c=(g=((h=t.coordinator)==null?void 0:h.systemPromptAppend)??((m=t.coordinator)==null?void 0:m.systemPromptSuffix))==null?void 0:g.trim();return c&&o.push(Ka(c,e)),s&&o.push(`## Additional Context
|
|
135
|
+
${s}`),o.join(`
|
|
136
|
+
|
|
137
|
+
`)}function aP(e){var a,o;const{mesh:t,status:s,coordinatorCliType:n}=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.
|
|
138
|
+
|
|
139
|
+
Your mesh: **${t.name}**
|
|
140
|
+
Repository: \`${t.repoIdentity}\`${t.defaultBranch?`
|
|
141
|
+
Default branch: \`${t.defaultBranch}\``:""}`),(a=s==null?void 0:s.nodes)!=null&&a.length?i.push(yy(s.nodes)):t.nodes.length?i.push(vy(t)):i.push("## Nodes\nNo nodes configured yet. Ask the user to add nodes with `adhdev mesh add-node`."),(o=e.missionSection)!=null&&o.trim()&&i.push(e.missionSection.trim()),i.push(Sy({...Ei,...t.policy||{}})),i.push(Gu),i.push(qu),i.push(Vu),i.push(ky(n)),i.join(`
|
|
142
|
+
|
|
143
|
+
`)}function Hm(e,t){const s=Ee.join(ot.homedir(),".adhdev","coordinator-prompts"),n=[];e&&n.push(Ee.join(s,`${e}.${t}`)),n.push(Ee.join(s,`default.${t}`));for(const i of n)try{const a=Qe.readFileSync(i,"utf8");if(a.trim())return a}catch{}return null}function Ka(e,t){var l,c;const{mesh:s,status:n,coordinatorCliType:i}=t,a=(l=n==null?void 0:n.nodes)!=null&&l.length?yy(n.nodes):s.nodes.length?vy(s):"## Nodes\nNo nodes configured yet. Ask the user to add nodes with `adhdev mesh add-node`.",o={meshName:s.name,repo:s.repoIdentity,defaultBranch:s.defaultBranch||"",cliType:i||"",nodes:a,mission:((c=t.missionSection)==null?void 0:c.trim())||"",policy:Sy({...Ei,...s.policy||{}}),tools:Gu,workflow:Vu,rules:ky(i),toolExposurePreflight:qu};return e.replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g,(d,p)=>Object.prototype.hasOwnProperty.call(o,p)?o[p]:d)}function yy(e){var s,n;const t=["## Current Node Status","","Node labels are display context, not aliases. Use exact `nodeId` values in mesh tool calls; do not invent shorthand names such as M1/M2 unless they are explicitly configured labels.",""];for(const i of e){const a=i.health==="online"?"🟢":i.health==="dirty"?"🟡":i.health==="offline"?"⚫":"🔴",o=i.activeSessions.length>0?`sessions: ${i.activeSessions.join(", ")}`:"no active sessions",l=(s=i.git)!=null&&s.branch?`branch: \`${i.git.branch}\``:"",c=[i.daemonId?`daemon: \`${i.daemonId}\``:"",(n=i.providers)!=null&&n.length?`providers: ${i.providers.join(", ")}`:""].filter(Boolean).join(" | ");t.push(`- ${a} **${i.machineLabel}** (nodeId: \`${i.nodeId}\`)`),t.push(` workspace: \`${i.workspace}\`${c?` | ${c}`:""} | ${l} | ${o}`),i.error&&t.push(` ⚠️ ${i.error}`);const d=typeof i.systemPrompt=="string"?i.systemPrompt.trim():"";d&&t.push(` 📌 Node instruction: ${wy(d," ")}`)}return t.join(`
|
|
144
|
+
`)}function vy(e){var s,n,i,a;const t=["## Configured Nodes","","Node labels are display context, not aliases. Use exact `nodeId` values in mesh tool calls; do not invent shorthand names such as M1/M2 unless they are explicitly configured labels.",""];for(const o of e.nodes){const l=[];o.isLocalWorktree&&l.push("worktree"),(s=o.policy)!=null&&s.readOnly&&l.push("read-only");const c=l.length?` [${l.join(", ")}]`:"",d=typeof o.machineLabel=="string"?o.machineLabel:"",p=d?` label: **${d}** |`:"",h=(i=(n=o.policy)==null?void 0:n.providerPriority)!=null&&i.length?` | providers: ${o.policy.providerPriority.join(", ")}`:"",m=Array.isArray((a=o.policy)==null?void 0:a.providerRoles)?o.policy.providerRoles.map(f=>{const v=typeof(f==null?void 0:f.providerType)=="string"?f.providerType.trim():"";if(!v)return"";const w=typeof(f==null?void 0:f.role)=="string"&&f.role.trim()?`=${f.role.trim()}`:"",x=Number.isFinite(Number(f==null?void 0:f.maxParallel))?` (max ${Math.floor(Number(f.maxParallel))})`:"";return`${v}${w}${x}`}).filter(Boolean):[],g=m.length?` | roles: ${m.join(", ")}`:"";t.push(`- ${p} nodeId: \`${o.id}\` | workspace: \`${o.workspace}\`${o.daemonId?` | daemon: \`${o.daemonId}\``:""}${h}${g}${c}`);const b=typeof o.systemPrompt=="string"?o.systemPrompt.trim():"";b&&t.push(` 📌 Node instruction: ${wy(b," ")}`)}return t.push("","_Use `mesh_status` to probe live health before delegating work._"),t.join(`
|
|
145
|
+
`)}function wy(e,t){const s=e.split(`
|
|
146
|
+
`);return s.length===1?s[0]:[s[0],...s.slice(1).map(n=>t+n)].join(`
|
|
147
|
+
`)}function Sy(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.allowAutoPublishSubmoduleMainCommits&&t.push("- Refinery may auto-publish unreachable submodule gitlink commits to submodule origin/main with non-force pushes after validation and patch-equivalence pass"),e.requireApprovalForDestructiveGit&&t.push("- **Ask for user approval** before destructive git operations (force push, reset, etc.)");const s={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 s&&t.push(s),t.push(`- Maximum **${e.maxParallelTasks}** tasks running in parallel`),`## Policy
|
|
148
|
+
${t.join(`
|
|
149
|
+
`)}`}function ky(e){return`## Rules
|
|
150
|
+
|
|
151
|
+
- **Route, don't implement.** Delegate all code reading, analysis, and execution to node agents. Never read source files or run commands in the coordinator — keep context lean.
|
|
152
|
+
- **Front-load task messages.** Include everything the agent needs (files, problem, expected fix) in \`mesh_enqueue_task\` / \`mesh_send_task\`. Append a structured result request at the end: ask the worker to conclude with a JSON block containing \`status\`, \`changedFiles\`, \`gitStatus\`, \`validationResults\`, \`errors\`, \`nextAction\`. The daemon parses this automatically; you can read it from \`mesh_task_history\`.
|
|
153
|
+
- **Reuse idle sessions.** For follow-up, retry, commit/push, or cleanup on the same issue, send only the delta to the existing idle session. Start fresh only for independent work, provider mismatch, transcript contamination, or required worktree isolation.
|
|
154
|
+
- **Respect explicit provider requests.** Map: Hermes → \`hermes-cli\`, Claude/Claude Code → \`claude-cli\`, Codex → \`codex-cli\`, Gemini → \`gemini-cli\`, Antigravity → \`antigravity-cli\`. Never substitute the coordinator's own runtime.
|
|
155
|
+
- **Verify via git, not source.** Use \`mesh_git_status\` to confirm side effects. Treat agent summaries as self-reports, not verification.
|
|
156
|
+
- **Limit parallelism.** Start with 1–2 tasks; scale only on success. Never duplicate a session because \`mesh_read_chat\` shows no final message while tool/terminal activity is ongoing. This caps *concurrent* load — it does not mean serialize independent work: when a new, independent request arrives and there is headroom under \`maxParallelTasks\`, dispatch it right away rather than waiting for an in-flight task or a user nudge (read-only diagnosis especially, since it has no merge cost).
|
|
157
|
+
- **Check history first.** Call \`mesh_task_history\` at session start to avoid duplicate work and inform recovery. On failure, read task history before retrying.
|
|
158
|
+
- **Sequence shared-base-moving merges.** Parallel dispatch is encouraged, but merging one worktree can advance another in-flight worktree's base — especially the oss submodule pointer — turning a clean fast-forward into a diverged rebase (patch-equivalence correctly blocks this). Before merging an in-flight worktree while siblings are also in flight, land in an intentional order, re-clone long-running worktrees from the advanced base, or expect to manually rebase + ff-only the laggards; merging an independent fix mid-flight can strand siblings into a rebase.
|
|
159
|
+
- **Converge branches.** After worktree tasks: refine/fast-forward, or classify as \`pushed_feature_branch_needs_merge\` / \`blocked_review\` / \`cleanup_candidate\` / \`not_mergeable\`. Clean up with \`mesh_remove_node\`.
|
|
160
|
+
- **Refinery is config-driven.** \`mesh_refine_node\` must run validation from \`.adhdev/refine.{json,yaml,yml}\` or \`repo-mesh.refine.*\`. Heuristics are scaffolding only.
|
|
161
|
+
- **Submodule reachability = publish-needed.** \`submodule_reachability_failed\` → classify as \`blocked_review\`, request user approval to push to submodule main, then rerun \`mesh_refine_node\`.
|
|
162
|
+
- **Honor per-node instructions.** When a node carries a 📌 Node instruction in the nodes section, include the relevant parts of that instruction in the task message you send to that node. Don't paraphrase the instruction into your own words — quote it verbatim so the worker agent sees exactly what the user wrote.
|
|
163
|
+
- **Mission status does not update itself.** When a mission's tasks are all done or the work is abandoned, explicitly call \`mesh_mission_upsert\` to set status \`completed\` or \`abandoned\`. Never leave a finished mission in \`active\`. All-cancelled tasks with no further work → \`abandoned\`.
|
|
164
|
+
- **Never fabricate tool results.** Always call the actual tool.
|
|
165
|
+
- **Keep the user informed.** One or two sentences after each delegation round.${e?`
|
|
166
|
+
- **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 Gu,qu,Vu,oP=We({"src/mesh/coordinator-prompt.ts"(){Mn(),Gu="## 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_read_node_logs` | Fetch a remote node's daemon log tail directly over P2P (grep/since/byte-bounded, secrets redacted) — no session/PowerShell needed to debug a node's daemon |\n| `mesh_fast_forward_node` | Safely dry-run or explicitly execute an obvious clean fast-forward without launching an agent session |\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 |",qu="## 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`.",Vu='## 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. **For multi-task work, create a mission first**: call `mesh_mission_upsert` with a title and goal, then attach every enqueued task with `mission_id`. Express "B after A" ordering with `depends_on` on the queue task instead of waiting and polling — the system claims dependents automatically when their dependencies complete. When the mission\'s outcome is decided, update its status (`completed`/`abandoned`) via `mesh_mission_upsert`. If the prompt already shows an **Active Mission**, continue it from its current task state — do not re-enqueue tasks that already exist.\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. Do **not** repeatedly call `mesh_status` or `mesh_view_queue` just to wait for assigned/generating work. After dispatching a direct or queued task, send one progress update with the task/session handle, then stop. Wait for `pendingCoordinatorEvents` or another completion/approval/status signal, an explicit user status request, or a real timeout/stall signal before reading status/chat/queue again. Use at most one compact `mesh_read_chat` check after a terminal signal. Handle approvals via `mesh_approve`. **Proactively parallelize new work.** When the user reports a new bug or asks for new work, start it immediately if it is independent of in-flight tasks and there is headroom under `maxParallelTasks` — do not wait for a current task to finish or for the user to prompt you to parallelize. Read-only diagnosis (`live_debug_readonly`) has no isolation or merge cost, so dispatch it in parallel right away. The no-polling / concurrency-limit rules constrain *re-checking or duplicating already-dispatched work*; they are **not** a reason to defer starting a new, independent task.\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. For obvious clean branch catch-up (ahead 0, behind > 0, upstream fresh, no dirty/stash/submodule issues), use `mesh_fast_forward_node` dry-run first and execute only when explicitly safe/approved; this avoids consuming an agent session. Use `mesh_refine_node` for clean worktree branches when safe. Before/refine merging root commits that contain submodule gitlink changes, require each submodule commit to be reachable from the configured submodule remote main branch, not merely present on a feature ref or local checkout. If `mesh_refine_node` returns `submodule_reachability_failed` or publish-required evidence, keep the public convergence bucket as `blocked_review`; unless `allowAutoPublishSubmoduleMainCommits` is explicitly enabled and Refinery reports successful non-force publish plus post-publish verification, ask the user for explicit approval to push/publish the unreachable submodule commit(s) to submodule main, then rerun `mesh_refine_node`. Do not merge the root branch until the submodule commit(s) are reachable from submodule origin/main. 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.'}}),jy={};Tt(jy,{MAX_LEDGER_SLICE_LIMIT:()=>Sl,__clearMeshLedgerForTests:()=>wP,appendLedgerEntry:()=>ur,appendRemoteLedgerEntries:()=>bP,buildTaskCompletionEvidence:()=>Oo,buildWorkerTaskFooter:()=>uP,compactLedger:()=>Cy,getLedgerDir:()=>Bs,getLedgerSummary:()=>jP,getSessionRecoveryContext:()=>Ty,isIntentionalCleanupStopEntry:()=>Pi,meshLedgerEvents:()=>kl,normalizeMeshWorkerResult:()=>co,readLedgerEntries:()=>ms,readLedgerSlice:()=>SP,readLedgerSliceFromStore:()=>kP});function Pi(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 Bs(){const e=Dt(Vr(),My);return st(e)||Ki(e,{recursive:!0,mode:448}),e}function oa(e){const t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return Dt(Bs(),`${t}.jsonl`)}function zm(e,t){const s=e.replace(/[^a-zA-Z0-9_-]/g,"_");return Dt(Bs(),`${s}.${t}.jsonl`)}function lP(e){const t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return Dt(Bs(),`${t}.archive.jsonl`)}function Km(e,t){const s=e.replace(/[^a-zA-Z0-9_-]/g,"_");return Dt(Bs(),`${s}.archive.${t}.jsonl`)}function Ny(e){const t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return Dt(Bs(),`${t}.archived-counts.json`)}function cP(e,t){let s=1;for(;st(Km(e,s))&&(s++,!(s>5)););s>5&&(s=5);try{Lr(t,Km(e,s))}catch(n){process.stderr.write(`[adhdev-mesh] Archive rotation failed for mesh ${e}: ${(n==null?void 0:n.message)||n}
|
|
167
|
+
`)}}function _y(e){const t=Ny(e);if(!st(t))return{taskCompleted:0,taskFailed:0,taskStalled:0,recoveryAttempted:0,totalArchived:0,lastArchivedAt:""};try{return JSON.parse(As(t,"utf-8"))}catch{return{taskCompleted:0,taskFailed:0,taskStalled:0,recoveryAttempted:0,totalArchived:0,lastArchivedAt:""}}}function dP(e,t){const s=_y(e);for(const n of t)n.kind==="task_completed"?s.taskCompleted++:n.kind==="task_failed"?s.taskFailed++:n.kind==="task_stalled"?s.taskStalled++:n.kind==="recovery_attempted"&&s.recoveryAttempted++;s.totalArchived+=t.length,s.lastArchivedAt=new Date().toISOString();try{Ss(Ny(e),JSON.stringify(s),{encoding:"utf-8",mode:384})}catch{}}function uP(){return`
|
|
168
|
+
|
|
169
|
+
---
|
|
170
|
+
When your task is done, end your final response with a JSON code block in this exact format (omit fields that don't apply):
|
|
171
|
+
\`\`\`json
|
|
172
|
+
{
|
|
173
|
+
"status": "completed",
|
|
174
|
+
"changedFiles": ["src/foo.ts", "tests/foo.test.ts"],
|
|
175
|
+
"gitStatus": { "branch": "feat/your-branch", "committed": true, "pushed": false },
|
|
176
|
+
"validationResults": [{ "command": "npm test", "status": "passed" }],
|
|
177
|
+
"errors": [],
|
|
178
|
+
"nextAction": "optional guidance for the coordinator"
|
|
179
|
+
}
|
|
180
|
+
\`\`\`
|
|
181
|
+
Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`}function Cy(e){const t=oa(e);if(!st(t))return{archivedCount:0,retainedCount:0};const s=Date.now()-Py,n=ms(e),i=[],a=[];for(const l of n)Dy.has(l.kind)&&new Date(l.timestamp).getTime()<s?a.push(l):i.push(l);if(a.length===0)return{archivedCount:0,retainedCount:i.length};const o=lP(e);try{st(o)&&tl(o).size>50*1024*1024&&cP(e,o);const l=a.map(c=>JSON.stringify(c)).join(`
|
|
182
|
+
`)+`
|
|
183
|
+
`;sl(o,l,{encoding:"utf-8",mode:384}),dP(e,a)}catch(l){return process.stderr.write(`[adhdev-mesh] Ledger archive write failed for mesh ${e}: ${(l==null?void 0:l.message)||l}
|
|
184
|
+
`),{archivedCount:0,retainedCount:n.length}}try{const l=i.length?i.map(c=>JSON.stringify(c)).join(`
|
|
185
|
+
`)+`
|
|
186
|
+
`:"";Ss(t,l,{encoding:"utf-8",mode:384}),Fo(e)}catch(l){return process.stderr.write(`[adhdev-mesh] Ledger compaction rewrite failed for mesh ${e}: ${(l==null?void 0:l.message)||l}
|
|
187
|
+
`),{archivedCount:a.length,retainedCount:i.length}}try{Pe.getInstance().deleteLedgerEntries(e,a.map(l=>l.id)),Fo(e)}catch{}return{archivedCount:a.length,retainedCount:i.length}}function vt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function Gm(e){return Array.isArray(e)?e.map(t=>vt(t)).filter(Boolean):[]}function pP(e){const t=vt(e);if(!t)return;const s=t.match(/```(?:json)?\s*([\s\S]*?)```/i),n=[s==null?void 0:s[1],t].filter(Boolean);for(const i of n){const a=i.trim();if(!(!a.startsWith("{")||!a.endsWith("}")))try{const o=JSON.parse(a);if(o&&typeof o=="object"&&!Array.isArray(o)&&"status"in o&&("changedFiles"in o||"errors"in o||"gitStatus"in o||"nextAction"in o||"validationResults"in o))return o}catch{}}}function hP(e){return Array.isArray(e)?e.filter(t=>t&&typeof t=="object"&&!Array.isArray(t)).map(t=>{const s=["passed","failed","skipped","unknown"].includes(t.status)?t.status:"unknown";return{...vt(t.command)?{command:vt(t.command)}:{},status:s,...Number.isFinite(Number(t.durationMs))?{durationMs:Number(t.durationMs)}:{},...vt(t.outputPath)?{outputPath:vt(t.outputPath)}:{},...vt(t.summary)?{summary:vt(t.summary)}:{}}}):[]}function mP(e){if(!Array.isArray(e))return[];const t=new Set(["process","log","port","window","session","file","url","other"]);return e.filter(s=>s&&typeof s=="object"&&!Array.isArray(s)).map(s=>({kind:t.has(s.kind)?s.kind:"other",...vt(s.id)?{id:vt(s.id)}:{},...vt(s.label)?{label:vt(s.label)}:{},...vt(s.locator)?{locator:vt(s.locator)}:{},...Number.isFinite(Number(s.pid))?{pid:Number(s.pid)}:{},...Number.isFinite(Number(s.port))?{port:Number(s.port)}:{},...vt(s.url)?{url:vt(s.url)}:{},...vt(s.path)?{path:vt(s.path)}:{},...vt(s.sessionId)?{sessionId:vt(s.sessionId)}:{},...typeof s.keepRunning=="boolean"?{keepRunning:s.keepRunning}:{},...s.metadata&&typeof s.metadata=="object"&&!Array.isArray(s.metadata)?{metadata:s.metadata}:{}}))}function co(e,t="explicit_metadata"){const s=e&&typeof e=="object"?e:{},n=["completed","failed","blocked","partial","unknown"].includes(String(s.status))?s.status:"unknown",i=s.gitStatus&&typeof s.gitStatus=="object"&&!Array.isArray(s.gitStatus)?s.gitStatus:void 0;return{status:n,...vt(s.classification)?{classification:vt(s.classification)}:{},changedFiles:Gm(s.changedFiles),validationResults:hP(s.validationResults),...i?{gitStatus:i}:{},processArtifacts:mP(s.processArtifacts),errors:Gm(s.errors),...vt(s.nextAction)?{nextAction:vt(s.nextAction)}:{},requiresUserAction:s.requiresUserAction===!0,source:t}}function fP(e){if(e.workerResult&&typeof e.workerResult=="object")return co(e.workerResult,"explicit_metadata");const t=pP(e.finalSummary);return t?co(t,"final_summary_json"):co(void 0,"default")}function Oo(e){var n,i;const t=((n=e.providerSessionId)==null?void 0:n.trim())||void 0,s=((i=e.providerType)==null?void 0:i.trim())||void 0;return{source:"agent_status_event",event:e.event,nodeId:e.nodeId,sessionId:e.sessionId,providerType:s,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},workerResult:fP(e),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 ur(e,t){const s={id:Ts(),meshId:e,timestamp:new Date().toISOString(),...t},n=oa(e);if(st(n))try{const i=tl(n);i.size>=Ey?NP(e,n):i.size>=Ry&&Cy(e)}catch{}try{Pe.getInstance().appendLedgerEntry({id:s.id,meshId:s.meshId,timestamp:s.timestamp,kind:s.kind,nodeId:s.nodeId??null,sessionId:s.sessionId??null,providerType:s.providerType??null,payload:s.payload})}catch{mn.delete(e)}try{const i=JSON.stringify(s)+`
|
|
188
|
+
`;return sl(n,i,{encoding:"utf-8",mode:384}),Fo(e),kl.emit("append",e,s),s}catch(i){throw new Error(`Failed to append to ledger for mesh ${e}: ${i.message}`)}}function gP(e){return typeof e!="number"||!Number.isFinite(e)?Ly:Math.max(1,Math.min(Sl,Math.floor(e)))}function xP(e,t){if(!t||typeof t!="object"||Array.isArray(t))return!1;const s=t;return!(typeof s.id!="string"||!s.id.trim()||s.meshId!==e||typeof s.timestamp!="string"||Number.isNaN(new Date(s.timestamp).getTime())||typeof s.kind!="string"||!s.kind.trim()||!s.payload||typeof s.payload!="object"||Array.isArray(s.payload))}function bP(e,t){if(t.length===0)return{accepted:0,skippedDuplicate:0,rejectedInvalid:0,entries:[]};const s=oa(e),n=new Set(ms(e,{tail:1e3}).map(l=>l.id)),i=[];let a=0,o=0;for(const l of t){if(!xP(e,l)){a++;continue}if(n.has(l.id)){o++;continue}n.add(l.id),i.push(l)}if(i.length===0)return{accepted:0,skippedDuplicate:o,rejectedInvalid:a,entries:[]};try{Pe.getInstance().importLedgerEntries(i.map(l=>({id:l.id,meshId:l.meshId,timestamp:l.timestamp,kind:l.kind,nodeId:l.nodeId??null,sessionId:l.sessionId??null,providerType:l.providerType??null,payload:l.payload??{}})))}catch{}try{const l=i.map(c=>JSON.stringify(c)).join(`
|
|
189
|
+
`)+`
|
|
190
|
+
`;sl(s,l,{encoding:"utf-8",mode:384}),Fo(e);for(const c of i)kl.emit("append",e,c);return{accepted:i.length,skippedDuplicate:o,rejectedInvalid:a,entries:i}}catch(l){throw new Error(`Failed to append remote ledger entries for mesh ${e}: ${l.message}`)}}function Iy(e){const t=oa(e);if(!st(t))return[];let s;try{s=As(t,"utf-8")}catch{return[]}const n=[];for(const i of s.split(`
|
|
191
|
+
`))if(i.trim())try{const a=JSON.parse(i);a.id&&a.kind&&n.push(a)}catch{}return n}function yP(e,t){if(qm!==e&&(mn.clear(),qm=e),mn.has(t))return;mn.add(t);const s=Iy(t);if(s.length!==0)try{e.importLedgerEntries(s.map(n=>({id:n.id,meshId:n.meshId,timestamp:n.timestamp,kind:n.kind,nodeId:n.nodeId??null,sessionId:n.sessionId??null,providerType:n.providerType??null,payload:n.payload??{}})))}catch{}}function vP(e){const t=Pe.getInstance();return yP(t,e),t.readLedgerEntriesOrdered(e).map(s=>({id:s.id,meshId:s.meshId,timestamp:s.timestamp,kind:s.kind,...s.nodeId?{nodeId:s.nodeId}:{},...s.sessionId?{sessionId:s.sessionId}:{},...s.providerType?{providerType:s.providerType}:{},payload:s.payload&&typeof s.payload=="object"?s.payload:{}}))}function Xu(e){const t=Date.now(),s=Di.get(e);if(s&&t-s.cachedAt<$y)return s.entries;let n;try{n=vP(e)}catch{n=Iy(e)}return Di.set(e,{entries:n,cachedAt:t}),n}function Fo(e){Di.delete(e)}function wP(e){try{Pe.getInstance().clearLedgerForMesh(e)}catch{}Di.delete(e),mn.delete(e)}function ms(e,t){var n;let s=Xu(e);if(t!=null&&t.since){const i=new Date(t.since).getTime();isNaN(i)||(s=s.filter(a=>new Date(a.timestamp).getTime()>=i))}if((n=t==null?void 0:t.kind)!=null&&n.length){const i=new Set(t.kind);s=s.filter(a=>i.has(a.kind))}return t!=null&&t.tail&&t.tail>0&&s.length>t.tail&&(s=s.slice(-t.tail)),s}function Ay(e,t){const s=_y(e),i=Date.now()-Yu,a={meshId:e,totalEntries:t.length+s.totalArchived,taskDispatched:0,taskCompleted:s.taskCompleted,taskFailed:s.taskFailed,taskStalled:s.taskStalled,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};for(const o of t)switch(o.kind){case"task_dispatched":a.taskDispatched++;break;case"task_completed":a.taskCompleted++;break;case"task_failed":{if(Pi(o))break;a.taskFailed++,new Date(o.timestamp).getTime()>=i&&a.recentFailures++;break}case"task_stalled":{Pi(o)||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 SP(e,t){var l;const s=gP(t==null?void 0:t.limit),n=Xu(e);let i=n;if(t!=null&&t.since){const c=new Date(t.since).getTime();isNaN(c)||(i=i.filter(d=>new Date(d.timestamp).getTime()>=c))}if((l=t==null?void 0:t.kind)!=null&&l.length){const c=new Set(t.kind);i=i.filter(d=>c.has(d.kind))}const a=typeof(t==null?void 0:t.afterId)=="string"&&t.afterId.trim()?t.afterId.trim():null;if(a){const c=i.findIndex(d=>d.id===a);i=c>=0?i.slice(c+1):i}const o=i.slice(0,s);return{protocol:"adhdev.mesh.ledger.slice.v1",meshId:e,entries:o,cursor:{afterId:a,nextAfterId:o.length?o[o.length-1].id:a,limit:s,hasMore:i.length>o.length},summary:Ay(e,n),sourceOfTruth:{kind:"local_jsonl",path:oa(e),bounded:!0,maxLimit:Sl}}}function kP(e,t){var s;return Pe.getInstance().readLedgerSlice(e,{afterId:t==null?void 0:t.afterId,since:t==null?void 0:t.since,kind:(s=t==null?void 0:t.kind)!=null&&s.length?t.kind[0]:void 0,limit:t==null?void 0:t.limit})}function jP(e){return Ay(e,Xu(e))}function Ty(e,t){var g,b,f,v;const s=t.maxRetries??1,n=ms(e,{tail:500}),a=Date.now()-Yu;let o=null,l=0,c=!1;for(let w=n.length-1;w>=0;w--){const x=n[w],S=new Date(x.timestamp).getTime();if(c||(S<a?c=!0:t.nodeId&&x.nodeId!==t.nodeId||(x.kind==="task_failed"?Pi(x)||l++:(x.kind==="task_completed"||x.kind==="task_dispatched")&&(c=!0))),o===null&&x.kind==="task_dispatched"&&(t.sessionId&&x.sessionId===t.sessionId||!t.sessionId&&t.nodeId&&x.nodeId===t.nodeId)&&(o=x),o!==null&&c)break}const d=typeof((g=o==null?void 0:o.payload)==null?void 0:g.message)=="string"?o.payload.message:null;let p=0;if(o){const w=typeof((b=o.payload)==null?void 0:b.taskId)=="string"?o.payload.taskId:null;if(w)for(const x of n)x.kind==="task_dispatched"&&((f=x.payload)==null?void 0:f.taskId)===w&&p++;else if(d){const x=d.slice(0,200);for(const S of n)S.kind==="task_dispatched"&&typeof((v=S.payload)==null?void 0:v.message)=="string"&&S.payload.message.startsWith(x)&&p++}}const h=l<=s;let m;if(l===0)m="No recent failures detected. This may be a normal stop.";else if(h){const w=s-l+1;m=`Retry recommended (${l}/${s+1} attempts used, ${w} remaining). `+(d?"Re-launch the session and resend the original task.":"Re-launch the session. Original task message not found in ledger.")}else m=`Max retries exceeded (${l} consecutive failures). Consider: (1) reassigning to a different node, (2) simplifying the task, or (3) escalating to the user.`;return{lastTaskMessage:d,failedNodeId:t.nodeId||null,failedSessionId:t.sessionId||null,failedProviderType:null,consecutiveNodeFailures:l,taskAttemptCount:p,retryRecommended:h,advice:m}}function NP(e,t){let s=1;for(;st(zm(e,s))&&(s++,!(s>10)););s>10&&(s=10);try{Lr(t,zm(e,s))}catch(n){process.stderr.write(`[adhdev-mesh] Ledger rotation failed for mesh ${e}: ${(n==null?void 0:n.message)||n}. File will continue to grow.
|
|
192
|
+
`)}}var My,Ey,Ry,Py,Yu,Dy,Ly,Sl,kl,Di,$y,qm,mn,fr=We({"src/mesh/mesh-ledger.ts"(){rs(),gr(),My="mesh-ledger",Ey=10*1024*1024,Ry=2*1024*1024,Py=7*24*60*60*1e3,Yu=30*60*1e3,Dy=new Set(["task_completed","task_failed","task_stalled","recovery_attempted"]),Ly=100,Sl=500,kl=new tS,Di=new Map,$y=100,mn=new Set}}),_P={};Tt(_P,{ACTIVE_MESH_QUEUE_STATUSES:()=>Vy,HISTORICAL_MESH_QUEUE_STATUSES:()=>Xy,MESH_TASK_MODES:()=>Zu,__clearDirectDispatchesForTests:()=>WP,__clearMeshQueueForTests:()=>BP,__replaceMeshQueueForTests:()=>FP,__resetMeshRuntimeStoreForTests:()=>UP,assertNoDependencyCycle:()=>Uy,buildMeshNodeCapabilityTags:()=>la,cancelTask:()=>DP,claimNextTask:()=>zy,cleanupTerminalDirectDispatches:()=>Ju,deleteDirectDispatchesByTaskId:()=>KP,describeTaskDependencyState:()=>$P,enqueueTask:()=>Hy,getActiveDirectDispatches:()=>_l,getMeshQueueRevision:()=>RP,getMeshQueueStats:()=>OP,getQueue:()=>fs,hasPendingDependents:()=>qy,insertDirectDispatch:()=>HP,markStaleDirectDispatches:()=>zP,nodeSatisfiesRequiredTags:()=>jl,normalizeMeshCapabilityTags:()=>Ur,normalizeMeshTaskMode:()=>Oy,recordDirectDispatchTask:()=>EP,recordMeshToolCall:()=>GP,recordTaskAutoLaunch:()=>Ky,requeueTask:()=>LP,resolveConvergeRequiredTags:()=>Fy,resolveTaskAffinityRequiredTags:()=>By,updateDirectDispatchStatus:()=>Bo,updateSessionTaskStatus:()=>Gy,updateTaskStatus:()=>kd,validateMeshTaskModeRequest:()=>Qu});function CP(e){const t=/\bgit\s+([a-z][a-z0-9-]*)/gi;let s;for(;(s=t.exec(e))!==null;){const n=s[1].toLowerCase();if(Qy.has(n))return!0;if(n==="stash"){const i=e.slice(t.lastIndex).match(/^\s+([a-z][a-z0-9-]*)/i),a=i?i[1].toLowerCase():"";if(!Jy.has(a))return!0}else{if(n==="checkout")return!0;if(n==="submodule"){const i=e.slice(t.lastIndex).match(/^\s+([a-z][a-z0-9-]*)/i),a=i?i[1].toLowerCase():"";if(a==="update"||a==="add"||a==="sync"||a==="deinit")return!0}else if(n==="worktree"){const i=e.slice(t.lastIndex).match(/^\s+([a-z][a-z0-9-]*)/i),a=i?i[1].toLowerCase():"";if(a==="add"||a==="remove"||a==="move"||a==="prune")return!0}}}return!1}function Oy(e){if(typeof e!="string")return;const t=e.trim();return Zu.includes(t)?t:void 0}function Qu(e,t){const s=Oy(e);if(!s)return{valid:!0,violations:[]};if(s!=="live_debug_readonly")return{valid:!0,taskMode:s,violations:[]};const n=t||"",i=Yy.filter(a=>a.pattern.test(n)).map(a=>a.label);return CP(n)&&i.push("git_mutation"),{valid:i.length===0,taskMode:s,violations:i,allowedOperations:["process/log/window/port/session inspection","read-only filesystem listing/reading","status probes and keep-running handle reporting","diagnostic summaries without source edits, commits, checkpoints, pushes, deploys, resets, rebases, or destructive cleanups"]}}function Ur(e){if(!Array.isArray(e))return[];const t=new Set;return e.map(s=>typeof s=="string"?s.trim():"").filter(Boolean).filter(s=>t.has(s)?!1:(t.add(s),!0))}function IP(e){var s;const t=e&&typeof e=="object"&&!Array.isArray(e)?e.providerPriority:void 0;if(Array.isArray(t))return(s=t.find(n=>typeof n=="string"&&n.trim()))==null?void 0:s.trim()}function AP(e,t){const s=e&&typeof e=="object"&&!Array.isArray(e)?e.providerRoles:void 0;if(!Array.isArray(s))return[];const n=typeof t=="string"&&t.trim()?t.trim().toLowerCase():"",i=[];for(const a of s){if(!a||typeof a!="object")continue;const o=typeof a.providerType=="string"?a.providerType.trim().toLowerCase():"",l=typeof a.role=="string"?a.role.trim().toLowerCase():"";l&&(n&&o&&o!==n||i.push(`role=${l}`))}return i}function la(e,t){const s=typeof t=="string"&&t.trim()?t.trim():IP(e==null?void 0:e.policy),n=typeof(e==null?void 0:e.worktreeBranch)=="string"&&e.worktreeBranch.trim()?e.worktreeBranch.trim():null;return Ur([...Array.isArray(e==null?void 0:e.capabilities)?e.capabilities:[],`os=${process.platform}`,`arch=${process.arch}`,...s?[`provider=${s}`]:[],...(e==null?void 0:e.isLocalWorktree)===!0&&n?[`worktree=${n}`]:[],...(e==null?void 0:e.isLocalWorktree)===!0?["converge=refine"]:["converge=fast_forward"],...AP(e==null?void 0:e.policy,t)])}function jl(e,t){const s=Ur(e);if(s.length===0)return!0;const n=new Set(Ur(t));return s.every(i=>n.has(i))}function Fy(e,t,s,n){var a;if(t!=="code_change"||typeof(n==null?void 0:n.targetNodeId)=="string"&&n.targetNodeId.trim())return s;let i=!1;try{i=Z2((a=En(e))==null?void 0:a.policy)}catch{i=!1}return i?Ur([...s,Hb]):s}function TP(e,t){if(!Array.isArray(e)||e.length===0)return!1;const s=`role=${t}`;return e.some(n=>la(n).includes(s))}function By(e,t,s,n){var o;if(typeof(n==null?void 0:n.targetNodeId)=="string"&&n.targetNodeId.trim()||(n==null?void 0:n.callerSpecifiedRequiredTags)===!0)return s;let i;try{i=En(e)}catch{return s}const a=Q2(t,(o=i==null?void 0:i.policy)==null?void 0:o.taskAffinity);if(!a)return s;if(!TP(i==null?void 0:i.nodes,a)){try{console.warn(`[mesh] task_affinity: no node advertises role=${a} for taskMode=${t} in mesh ${e}; skipping injection (least_loaded fallback)`)}catch{}return s}return Ur([...s,`role=${a}`])}function Xr(e,t){return Pe.getInstance().transaction(t)}function MP(e){return Pe.getInstance().getQueueEntries(e)}function Wy(e){if(!Array.isArray(e))return[];const t=new Set;return e.map(s=>typeof s=="string"?s.trim():"").filter(Boolean).filter(s=>t.has(s)?!1:(t.add(s),!0))}function Uy(e,t,s){if(s.length===0)return;if(s.includes(t))throw new Error(`dependency_cycle_detected: task '${t}' cannot depend on itself`);const n=new Map;for(const o of MP(e))n.set(o.id,Wy(o.dependsOn));n.set(t,s);const i=[...s],a=new Set;for(;i.length>0;){const o=i.pop();if(o===t)throw new Error(`dependency_cycle_detected: task '${t}' is part of a dependency cycle via '${s.join(", ")}'`);a.has(o)||(a.add(o),i.push(...n.get(o)??[]))}}function Hy(e,t,s){yl(s);const n=Qu(s==null?void 0:s.taskMode,t);if(!n.valid)throw new Error(`live_debug_readonly_guardrail_violation: forbidden operations (${n.violations.join(", ")})`);const i=typeof(s==null?void 0:s.id)=="string"&&s.id.trim()?s.id.trim():Ts(),a=Wy(s==null?void 0:s.dependsOn);return Xr(e,()=>{if(Pe.getInstance().findQueueEntryById(e,i))throw new Error(`duplicate_task_id: task '${i}' already exists in mesh '${e}'`);Uy(e,i,a);const o=Ur(s==null?void 0:s.requiredTags),l=o.length>0;let c=Fy(e,n.taskMode,o,{targetNodeId:s==null?void 0:s.targetNodeId});c=By(e,n.taskMode,c,{targetNodeId:s==null?void 0:s.targetNodeId,callerSpecifiedRequiredTags:l});const d={id:i,meshId:e,message:t,status:"pending",taskMode:n.taskMode,targetNodeId:s==null?void 0:s.targetNodeId,targetSessionId:s==null?void 0:s.targetSessionId,requiredTags:c,...a.length>0?{dependsOn:a}:{},...typeof(s==null?void 0:s.missionId)=="string"&&s.missionId.trim()?{missionId:s.missionId.trim()}:{},createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return Pe.getInstance().insertQueueEntry(d),d})}function EP(e,t,s){const n=typeof s.missionId=="string"?s.missionId.trim():"";if(!n)return null;const i=typeof s.id=="string"?s.id.trim():"";if(!i)return null;const a=Qu(s.taskMode,t);if(!a.valid)throw new Error(`live_debug_readonly_guardrail_violation: forbidden operations (${a.violations.join(", ")})`);const o=s.dispatchedAt&&s.dispatchedAt.trim()?s.dispatchedAt:new Date().toISOString();return Xr(e,()=>{if(Pe.getInstance().findQueueEntryById(e,i))return null;const l={id:i,meshId:e,message:t,status:"assigned",...a.taskMode?{taskMode:a.taskMode}:{},missionId:n,...s.assignedNodeId?{targetNodeId:s.assignedNodeId,assignedNodeId:s.assignedNodeId}:{},...s.assignedSessionId?{targetSessionId:s.assignedSessionId,assignedSessionId:s.assignedSessionId}:{},dispatchTimestamp:o,createdAt:o,updatedAt:o};return Pe.getInstance().insertQueueEntry(l),l})}function fs(e,t){var s;return Pe.getInstance().getQueueEntries(e,(s=t==null?void 0:t.status)!=null&&s.length?t.status:void 0)}function RP(e){return Pe.getInstance().getQueueRevision(e)}function zy(e,t,s,n,i){return Pe.getInstance().claimNextQueueTask(e,t,s,n,i)}function PP(e){var t;try{return(((t=En(e))==null?void 0:t.policy)??{}).onDependencyFailure==="cancel"?"cancel":"block"}catch{return"block"}}function Nl(e,t){const s=PP(e),n=Pe.getInstance(),i=[t],a=new Set(i);for(;i.length>0;){const o=i.pop(),l=n.getQueueEntries(e,["pending"]).filter(c=>Array.isArray(c.dependsOn)&&c.dependsOn.includes(o));for(const c of l)a.has(c.id)||(a.add(c.id),s==="cancel"?(c.status="cancelled",c.cancelledAt=new Date().toISOString(),c.cancelReason=`dependency_failed:${o}`,n.updateQueueEntry(c),i.push(c.id)):(c.blockedReason=`dependency_failed:${o}`,n.updateQueueEntry(c)))}}function kd(e,t,s,n){return yl(n),Xr(e,()=>{const i=Pe.getInstance().findQueueEntryById(e,t);return i?(i.status=s,Pe.getInstance().updateQueueEntry(i),ep.has(s)&&Nl(e,t),i):null})}function Ky(e,t,s){return Xr(e,()=>{const n=Pe.getInstance().findQueueEntryById(e,t);if(!n)return null;const i=new Date().toISOString();return n.autoLaunch={...s,updatedAt:i},Pe.getInstance().updateQueueEntry(n),n})}function DP(e,t,s){return yl(s),Xr(e,()=>{const n=Pe.getInstance().findQueueEntryById(e,t);if(!n)return null;const i=new Date().toISOString();return n.status="cancelled",n.cancelledAt=i,s!=null&&s.reason&&(n.cancelReason=s.reason),Pe.getInstance().updateQueueEntry(n),Nl(e,t),n})}function LP(e,t,s){return yl(s),Xr(e,()=>{const n=Pe.getInstance().findQueueEntryById(e,t);if(!n)return null;const i=n.requeueCount||0,a=(s==null?void 0:s.maxRetries)??n.maxRetries??1;return!(s!=null&&s.force)&&i>=a?(n.status="failed",n.cancelReason=`max_retries_exceeded: requeued ${i} time(s), limit is ${a}`,n.updatedAt=new Date().toISOString(),Pe.getInstance().updateQueueEntry(n),Nl(e,t),n):(n.status="pending",delete n.blockedReason,delete n.assignedNodeId,delete n.assignedSessionId,delete n.cancelledAt,delete n.cancelReason,s!=null&&s.clearTargetNode&&delete n.targetNodeId,typeof(s==null?void 0:s.targetNodeId)=="string"&&(n.targetNodeId=s.targetNodeId),(s==null?void 0:s.clearTargetSession)!==!1&&delete n.targetSessionId,typeof(s==null?void 0:s.targetSessionId)=="string"&&(n.targetSessionId=s.targetSessionId),n.requeuedAt=new Date().toISOString(),n.requeueCount=i+1,s!=null&&s.reason&&(n.requeueReason=s.reason),Pe.getInstance().updateQueueEntry(n),n)})}function Gy(e,t,s,n){return Xr(e,()=>{const i=n!=null&&n.occurredAt?new Date(n.occurredAt).toISOString():void 0,a=Pe.getInstance().findAssignedBySession(e,t,i);return a?(a.status=s,Pe.getInstance().updateQueueEntry(a),ep.has(s)&&Nl(e,a.id),a):null})}function qy(e,t){return Pe.getInstance().getQueueEntries(e,["pending"]).some(s=>Array.isArray(s.dependsOn)&&s.dependsOn.includes(t))}function $P(e,t){const n=(Array.isArray(e.dependsOn)?e.dependsOn:[]).filter(i=>t.get(i)!=="completed");return{waitingOn:n,dependenciesSatisfied:n.length===0&&!e.blockedReason}}function OP(e){const t=Pe.getInstance().getQueueStatsByStatus(e),s={};for(const c of t)s[c.status]=c.count;const n=s.pending??0,i=s.assigned??0,a=s.completed??0,o=s.failed??0,l=s.cancelled??0;return{total:n+i+a+o+l,active:n+i,historical:a+o+l,pending:n,assigned:i,completed:a,failed:o,cancelled:l,activeCounts:{pending:n,assigned:i},historicalCounts:{completed:a,failed:o,cancelled:l},activeAssignments:Pe.getInstance().getActiveAssignmentDetails(e)}}function FP(e,t){Pe.getInstance().transaction(()=>{Pe.getInstance().replaceQueue(e,t)})}function BP(e){Pe.getInstance().deleteQueue(e)}function WP(e){Pe.getInstance().deleteDirectDispatches(e)}function UP(){Pe.resetForTests()}function HP(e,t){try{Pe.getInstance().insertDirectDispatch({...t,meshId:e})}catch(s){process.stderr.write(`[adhdev-mesh] insertDirectDispatch failed for task ${t.taskId}: ${(s==null?void 0:s.message)||s}
|
|
193
|
+
`)}}function _l(e){try{return Pe.getInstance().getActiveDirectDispatches(e)}catch{return[]}}function Bo(e,t,s){try{Pe.getInstance().updateDirectDispatchStatus(e,t,s)}catch{}}function Ju(e=7*24*60*6e4){try{Pe.getInstance().cleanupTerminalDirectDispatches(e)}catch{}}function zP(e,t=60*6e4){try{Pe.getInstance().markStaleDirectDispatches(e,t)}catch{}}function KP(e,t){try{return Pe.getInstance().deleteDirectDispatchesByTaskId(e,t)}catch{return 0}}function GP(e){try{return Pe.getInstance().recordMeshToolCall(e)}catch{return{rateLimitExceeded:!1,callsInWindow:0,advisory:null}}}var Vy,Xy,Zu,Yy,Qy,Jy,ep,Ys=We({"src/mesh/mesh-work-queue.ts"(){vl(),Mn(),gr(),wl(),Vy=["pending","assigned"],Xy=["completed","failed","cancelled"],Zu=["code_change","validation","live_debug_readonly","launch_app","convergence"],Yy=[{label:"source_edit",pattern:/\b(edit|modify|patch|apply\s+patch|write\s+(?:to\s+)?(?:file|source)|overwrite|delete\s+file|remove\s+file|create\s+file|touch\s+file)\b/i},{label:"checkpoint",pattern:/\b(checkpoint|mesh_checkpoint)\b/i},{label:"deploy_or_version_bump",pattern:/\b(deploy|wrangler\s+deploy|version[-\s]?bump|npm\s+version|release|npm\s+publish|yarn\s+publish|pnpm\s+publish)\b/i},{label:"destructive_shell",pattern:/\b(rm\s+-rf|mv\s+\S+\s+\S+|truncate\s|tee\s+\S+|sed\s+-i|shred\b)\b/i},{label:"package_install",pattern:/\b(npm\s+(?:install|i|add|link|uninstall|remove)|yarn\s+(?:add|remove|link)|pnpm\s+(?:add|remove|link)|pip\s+install|brew\s+install|apt\s+install|cargo\s+install)\b/i},{label:"container_mutation",pattern:/\b(docker\s+(?:build|run|exec|push|tag|rmi|rm|create|start|stop|kill)|kubectl\s+(?:apply|delete|patch|replace|create|scale))\b/i}],Qy=new Set(["add","commit","push","reset","rebase","clean","switch","merge","tag","restore","rm","mv","cherry-pick","revert","pull","fetch","am","apply","gc","prune"]),Jy=new Set(["list","show"]),ep=new Set(["failed","cancelled"])}});function qP(){return Ga||(Ga=(typeof Cs=="function"?Cs:Gc(import.meta.url))("better-sqlite3"),Ga)}function VP(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function XP(e){return Dt(Bs(),`${VP(e)}.queue.json`)}function YP(){const e=Bs(),t=Dt(e,"mesh-runtime.db");if(st(t))return t;const s=Dt(e,"beads.db");if(!st(s))return t;try{Lr(s,t);for(const n of["-wal","-shm"]){const i=`${s}${n}`;st(i)&&Lr(i,`${t}${n}`)}}catch{}return t}var Ga,Pe,gr=We({"src/mesh/mesh-runtime-store.ts"(){var e;fr(),Ys(),Pe=(e=class{constructor(s){re(this,"db");re(this,"dbPath");re(this,"migratedMeshIds",new Set);re(this,"fingerprintSweepCounter",0);re(this,"walWriteCounter",0);const n=Yw(s);st(n)||Ki(n,{recursive:!0}),this.dbPath=s,this.db=new(qP())(s),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),this.db.pragma("busy_timeout = 5000"),this.migrate()}static getInstance(){return this.instance||(this.instance=new e(YP())),this.instance}static resetForTests(){var s;(s=this.instance)==null||s.close(),this.instance=void 0}close(){this.db.close()}transaction(s){return this.db.transaction(s).immediate()}migrate(){this.db.exec(`
|
|
194
|
+
CREATE TABLE IF NOT EXISTS mesh_queue (
|
|
195
|
+
id TEXT PRIMARY KEY,
|
|
196
|
+
mesh_id TEXT NOT NULL,
|
|
197
|
+
status TEXT NOT NULL,
|
|
198
|
+
target_node_id TEXT,
|
|
199
|
+
target_session_id TEXT,
|
|
200
|
+
assigned_node_id TEXT,
|
|
201
|
+
assigned_session_id TEXT,
|
|
202
|
+
created_at TEXT NOT NULL,
|
|
203
|
+
updated_at TEXT NOT NULL,
|
|
204
|
+
payload TEXT NOT NULL
|
|
205
|
+
);
|
|
206
|
+
|
|
207
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_queue_mesh_status_created
|
|
208
|
+
ON mesh_queue(mesh_id, status, created_at);
|
|
209
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_queue_assignment
|
|
210
|
+
ON mesh_queue(mesh_id, assigned_node_id, assigned_session_id, status);
|
|
211
|
+
|
|
212
|
+
CREATE TABLE IF NOT EXISTS mesh_completion_fingerprints (
|
|
213
|
+
fingerprint TEXT PRIMARY KEY,
|
|
214
|
+
expires_at INTEGER NOT NULL
|
|
215
|
+
);
|
|
216
|
+
|
|
217
|
+
-- R3: idempotent coordinator inbox. When a terminal/force-inject event is
|
|
218
|
+
-- direct-injected into a LIVE local CLI coordinator (coord.onEvent('send_message')),
|
|
219
|
+
-- we record (coordinator_daemon_id, fingerprint) here. That same coordinator also
|
|
220
|
+
-- polls get_pending_mesh_events, which would re-deliver the queued copy of the very
|
|
221
|
+
-- event it just received in its PTY → user sees the completion twice. The drain for
|
|
222
|
+
-- a coordinator daemon filters out events already direct-delivered to it, giving
|
|
223
|
+
-- exactly-once-per-coordinator while keeping the queue for other consumers (idle /
|
|
224
|
+
-- MCP-only / remote) that did NOT receive the direct inject.
|
|
225
|
+
CREATE TABLE IF NOT EXISTS mesh_direct_delivered_events (
|
|
226
|
+
coordinator_daemon_id TEXT NOT NULL,
|
|
227
|
+
fingerprint TEXT NOT NULL,
|
|
228
|
+
expires_at INTEGER NOT NULL,
|
|
229
|
+
PRIMARY KEY (coordinator_daemon_id, fingerprint)
|
|
230
|
+
);
|
|
231
|
+
|
|
232
|
+
CREATE TABLE IF NOT EXISTS mesh_direct_dispatches (
|
|
233
|
+
task_id TEXT PRIMARY KEY,
|
|
234
|
+
mesh_id TEXT NOT NULL,
|
|
235
|
+
node_id TEXT,
|
|
236
|
+
session_id TEXT,
|
|
237
|
+
provider_type TEXT,
|
|
238
|
+
message TEXT NOT NULL,
|
|
239
|
+
task_mode TEXT,
|
|
240
|
+
via TEXT NOT NULL,
|
|
241
|
+
status TEXT NOT NULL DEFAULT 'dispatched',
|
|
242
|
+
dispatched_to_idle_session INTEGER NOT NULL DEFAULT 0,
|
|
243
|
+
dispatched_at TEXT NOT NULL,
|
|
244
|
+
updated_at TEXT NOT NULL
|
|
245
|
+
);
|
|
246
|
+
|
|
247
|
+
CREATE INDEX IF NOT EXISTS idx_direct_dispatches_mesh_session
|
|
248
|
+
ON mesh_direct_dispatches(mesh_id, session_id, status);
|
|
249
|
+
|
|
250
|
+
CREATE TABLE IF NOT EXISTS remote_idle_sessions (
|
|
251
|
+
node_id TEXT NOT NULL,
|
|
252
|
+
session_id TEXT NOT NULL,
|
|
253
|
+
provider_type TEXT NOT NULL,
|
|
254
|
+
expires_at INTEGER NOT NULL,
|
|
255
|
+
metadata TEXT,
|
|
256
|
+
PRIMARY KEY (node_id, session_id)
|
|
257
|
+
);
|
|
258
|
+
|
|
259
|
+
CREATE TABLE IF NOT EXISTS mesh_session_delivery (
|
|
260
|
+
id TEXT PRIMARY KEY,
|
|
261
|
+
mesh_id TEXT NOT NULL,
|
|
262
|
+
node_id TEXT,
|
|
263
|
+
session_id TEXT,
|
|
264
|
+
provider_type TEXT,
|
|
265
|
+
task_id TEXT,
|
|
266
|
+
kind TEXT NOT NULL,
|
|
267
|
+
priority INTEGER NOT NULL DEFAULT 0,
|
|
268
|
+
message TEXT NOT NULL,
|
|
269
|
+
status TEXT NOT NULL DEFAULT 'queued',
|
|
270
|
+
deliver_after TEXT,
|
|
271
|
+
expires_at TEXT,
|
|
272
|
+
attempt_count INTEGER NOT NULL DEFAULT 0,
|
|
273
|
+
source_coordinator_session_id TEXT,
|
|
274
|
+
source_coordinator_daemon_id TEXT,
|
|
275
|
+
last_error TEXT,
|
|
276
|
+
created_at TEXT NOT NULL,
|
|
277
|
+
updated_at TEXT NOT NULL
|
|
278
|
+
);
|
|
279
|
+
|
|
280
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_session_delivery_mesh_status
|
|
281
|
+
ON mesh_session_delivery(mesh_id, status, created_at);
|
|
282
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_session_delivery_session
|
|
283
|
+
ON mesh_session_delivery(mesh_id, session_id, status);
|
|
284
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_session_delivery_task
|
|
285
|
+
ON mesh_session_delivery(mesh_id, task_id);
|
|
286
|
+
|
|
287
|
+
CREATE TABLE IF NOT EXISTS mesh_completion_conflicts (
|
|
288
|
+
id TEXT PRIMARY KEY,
|
|
289
|
+
mesh_id TEXT NOT NULL,
|
|
290
|
+
fingerprint TEXT NOT NULL,
|
|
291
|
+
conflicting_task_id TEXT,
|
|
292
|
+
conflicting_session_id TEXT,
|
|
293
|
+
original_task_id TEXT,
|
|
294
|
+
original_session_id TEXT,
|
|
295
|
+
event TEXT NOT NULL,
|
|
296
|
+
created_at TEXT NOT NULL
|
|
297
|
+
);
|
|
298
|
+
|
|
299
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_completion_conflicts_mesh
|
|
300
|
+
ON mesh_completion_conflicts(mesh_id, created_at);
|
|
301
|
+
|
|
302
|
+
CREATE TABLE IF NOT EXISTS mesh_tool_call_log (
|
|
303
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
304
|
+
mesh_id TEXT NOT NULL,
|
|
305
|
+
tool TEXT NOT NULL,
|
|
306
|
+
session_id TEXT,
|
|
307
|
+
called_at INTEGER NOT NULL
|
|
308
|
+
);
|
|
309
|
+
|
|
310
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_tool_call_log_mesh_tool_time
|
|
311
|
+
ON mesh_tool_call_log(mesh_id, tool, called_at);
|
|
312
|
+
|
|
313
|
+
-- G2: Event ledger — runtime source of truth for task/session lifecycle events.
|
|
314
|
+
-- JSONL files are retained as export/import/debug/legacy artifacts only.
|
|
315
|
+
CREATE TABLE IF NOT EXISTS mesh_event_ledger (
|
|
316
|
+
id TEXT PRIMARY KEY,
|
|
317
|
+
mesh_id TEXT NOT NULL,
|
|
318
|
+
timestamp TEXT NOT NULL,
|
|
319
|
+
kind TEXT NOT NULL,
|
|
320
|
+
node_id TEXT,
|
|
321
|
+
session_id TEXT,
|
|
322
|
+
provider_type TEXT,
|
|
323
|
+
payload TEXT NOT NULL DEFAULT '{}'
|
|
324
|
+
);
|
|
325
|
+
|
|
326
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_event_ledger_mesh_time
|
|
327
|
+
ON mesh_event_ledger(mesh_id, timestamp);
|
|
328
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_event_ledger_mesh_kind
|
|
329
|
+
ON mesh_event_ledger(mesh_id, kind, timestamp);
|
|
330
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_event_ledger_session
|
|
331
|
+
ON mesh_event_ledger(mesh_id, session_id, timestamp);
|
|
332
|
+
|
|
333
|
+
-- G3: Pending coordinator event inbox — replaces <meshId>.pending-events.jsonl.
|
|
334
|
+
-- Coordinator drains this table on get_pending_mesh_events, then deletes drained rows.
|
|
335
|
+
CREATE TABLE IF NOT EXISTS mesh_pending_events (
|
|
336
|
+
id TEXT PRIMARY KEY,
|
|
337
|
+
mesh_id TEXT NOT NULL,
|
|
338
|
+
coordinator_daemon_id TEXT,
|
|
339
|
+
event TEXT NOT NULL,
|
|
340
|
+
payload TEXT NOT NULL DEFAULT '{}',
|
|
341
|
+
fingerprint TEXT,
|
|
342
|
+
queued_at INTEGER NOT NULL,
|
|
343
|
+
drained INTEGER NOT NULL DEFAULT 0,
|
|
344
|
+
drained_at INTEGER
|
|
345
|
+
);
|
|
346
|
+
|
|
347
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_pending_events_mesh_drained
|
|
348
|
+
ON mesh_pending_events(mesh_id, drained, queued_at);
|
|
349
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_mesh_pending_events_fingerprint
|
|
350
|
+
ON mesh_pending_events(mesh_id, fingerprint)
|
|
351
|
+
WHERE fingerprint IS NOT NULL;
|
|
352
|
+
|
|
353
|
+
-- M3: persistent mission records. Plans live in the system, not in the
|
|
354
|
+
-- coordinator LLM's context. Progress is derived from task statuses at
|
|
355
|
+
-- query time (mission_id on queue tasks) — never stored here.
|
|
356
|
+
CREATE TABLE IF NOT EXISTS mesh_missions (
|
|
357
|
+
id TEXT PRIMARY KEY,
|
|
358
|
+
mesh_id TEXT NOT NULL,
|
|
359
|
+
title TEXT NOT NULL,
|
|
360
|
+
goal TEXT NOT NULL DEFAULT '',
|
|
361
|
+
status TEXT NOT NULL DEFAULT 'active',
|
|
362
|
+
created_at TEXT NOT NULL,
|
|
363
|
+
updated_at TEXT NOT NULL
|
|
364
|
+
);
|
|
365
|
+
|
|
366
|
+
CREATE INDEX IF NOT EXISTS idx_mesh_missions_mesh_status
|
|
367
|
+
ON mesh_missions(mesh_id, status, updated_at);
|
|
368
|
+
|
|
369
|
+
-- Load-balancing scheduler: per-mesh round-robin rotation cursor. When
|
|
370
|
+
-- the schedulingStrategy is 'round_robin', several eligible nodes tied at
|
|
371
|
+
-- the least load are rotated by this cursor so the tie-break winner cycles
|
|
372
|
+
-- across scheduling passes instead of always favouring the same array-order
|
|
373
|
+
-- node. Persisted (not a module Map) so rotation survives daemon restarts
|
|
374
|
+
-- and stays a single source of truth across scheduling entry points.
|
|
375
|
+
CREATE TABLE IF NOT EXISTS mesh_scheduler_cursor (
|
|
376
|
+
mesh_id TEXT PRIMARY KEY,
|
|
377
|
+
cursor INTEGER NOT NULL DEFAULT 0
|
|
378
|
+
);
|
|
379
|
+
`)}hasCompletionFingerprint(s){const n=Date.now(),i=this.db.prepare("SELECT 1 FROM mesh_completion_fingerprints WHERE fingerprint = ? AND expires_at > ?").get(s,n);return++this.fingerprintSweepCounter>=100&&(this.fingerprintSweepCounter=0,this.sweepExpiredFingerprints()),i!==void 0}recordCompletionFingerprint(s,n){const i=Date.now()+n;this.db.prepare("INSERT OR REPLACE INTO mesh_completion_fingerprints (fingerprint, expires_at) VALUES (?, ?)").run(s,i),this.maybeCheckpointWal()}sweepExpiredFingerprints(){this.db.prepare("DELETE FROM mesh_completion_fingerprints WHERE expires_at <= ?").run(Date.now())}recordDirectDelivered(s,n,i){!s||!n||(this.db.prepare("INSERT OR REPLACE INTO mesh_direct_delivered_events (coordinator_daemon_id, fingerprint, expires_at) VALUES (?, ?, ?)").run(s,n,Date.now()+i),this.maybeCheckpointWal())}wasDirectDelivered(s,n){return!s||!n?!1:this.db.prepare("SELECT 1 FROM mesh_direct_delivered_events WHERE coordinator_daemon_id = ? AND fingerprint = ? AND expires_at > ?").get(s,n,Date.now())!==void 0}sweepExpiredDirectDelivered(){this.db.prepare("DELETE FROM mesh_direct_delivered_events WHERE expires_at <= ?").run(Date.now())}maybeCheckpointWal(){if(!(++this.walWriteCounter<e.WAL_CHECK_INTERVAL)){this.walWriteCounter=0;try{const s=`${this.dbPath}-wal`;if(!st(s))return;const n=tl(s).size;if(n<e.WAL_MAX_BYTES)return;process.stderr.write(`[adhdev-mesh] WAL file ${Math.round(n/1024/1024)}MB exceeds threshold; forcing checkpoint
|
|
380
|
+
`),this.db.pragma("wal_checkpoint(TRUNCATE)")}catch{}}}ensureLegacyQueueMigrated(s){if(this.migratedMeshIds.has(s)||(this.migratedMeshIds.add(s),this.db.prepare("SELECT COUNT(*) AS count FROM mesh_queue WHERE mesh_id = ?").get(s).count>0))return;const i=XP(s);if(st(i))try{const a=JSON.parse(As(i,"utf-8"));if(!Array.isArray(a))return;const o=this.db.prepare(`
|
|
381
|
+
INSERT OR REPLACE INTO mesh_queue (
|
|
382
|
+
id, mesh_id, status, target_node_id, target_session_id,
|
|
383
|
+
assigned_node_id, assigned_session_id, created_at, updated_at, payload
|
|
384
|
+
) VALUES (
|
|
385
|
+
@id, @meshId, @status, @targetNodeId, @targetSessionId,
|
|
386
|
+
@assignedNodeId, @assignedSessionId, @createdAt, @updatedAt, @payload
|
|
387
|
+
)
|
|
388
|
+
`);for(const l of a)o.run(this.toRow(l))}catch{return}}getQueueEntries(s,n){if(this.ensureLegacyQueueMigrated(s),n!=null&&n.length){const a=n.map(()=>"?").join(", ");return this.db.prepare(`SELECT payload FROM mesh_queue WHERE mesh_id = ? AND status IN (${a}) ORDER BY created_at ASC`).all(s,...n).map(l=>JSON.parse(l.payload))}return this.db.prepare("SELECT payload FROM mesh_queue WHERE mesh_id = ? ORDER BY created_at ASC").all(s).map(a=>JSON.parse(a.payload))}getQueueRevision(s){return this.ensureLegacyQueueMigrated(s),this.db.prepare("SELECT id, status, updated_at FROM mesh_queue WHERE mesh_id = ? ORDER BY id ASC").all(s).map(i=>`${i.id} ${i.status} ${i.updated_at}`).join(`
|
|
389
|
+
`)}replaceQueue(s,n){const i=this.db.prepare("DELETE FROM mesh_queue WHERE mesh_id = ?"),a=this.db.prepare(`
|
|
390
|
+
INSERT INTO mesh_queue (
|
|
391
|
+
id, mesh_id, status, target_node_id, target_session_id,
|
|
392
|
+
assigned_node_id, assigned_session_id, created_at, updated_at, payload
|
|
393
|
+
) VALUES (
|
|
394
|
+
@id, @meshId, @status, @targetNodeId, @targetSessionId,
|
|
395
|
+
@assignedNodeId, @assignedSessionId, @createdAt, @updatedAt, @payload
|
|
396
|
+
)
|
|
397
|
+
`);i.run(s);for(const o of n)a.run(this.toRow(o));this.maybeCheckpointWal()}deleteQueue(s){this.db.prepare("DELETE FROM mesh_queue WHERE mesh_id = ?").run(s),this.migratedMeshIds.delete(s)}insertQueueEntry(s){this.db.prepare(`
|
|
398
|
+
INSERT INTO mesh_queue (
|
|
399
|
+
id, mesh_id, status, target_node_id, target_session_id,
|
|
400
|
+
assigned_node_id, assigned_session_id, created_at, updated_at, payload
|
|
401
|
+
) VALUES (
|
|
402
|
+
@id, @meshId, @status, @targetNodeId, @targetSessionId,
|
|
403
|
+
@assignedNodeId, @assignedSessionId, @createdAt, @updatedAt, @payload
|
|
404
|
+
)
|
|
405
|
+
`).run(this.toRow(s)),this.maybeCheckpointWal()}updateQueueEntry(s){const n=new Date().toISOString();s.updatedAt=n,this.db.prepare(`
|
|
406
|
+
UPDATE mesh_queue SET
|
|
407
|
+
status = @status,
|
|
408
|
+
target_node_id = @targetNodeId,
|
|
409
|
+
target_session_id = @targetSessionId,
|
|
410
|
+
assigned_node_id = @assignedNodeId,
|
|
411
|
+
assigned_session_id = @assignedSessionId,
|
|
412
|
+
updated_at = @updatedAt,
|
|
413
|
+
payload = @payload
|
|
414
|
+
WHERE id = @id AND mesh_id = @meshId
|
|
415
|
+
`).run(this.toRow(s)),this.maybeCheckpointWal()}findQueueEntryById(s,n){this.ensureLegacyQueueMigrated(s);const i=this.db.prepare("SELECT payload FROM mesh_queue WHERE id = ? AND mesh_id = ?").get(n,s);return i?JSON.parse(i.payload):null}hasActiveAssignment(s,n,i){return this.ensureLegacyQueueMigrated(s),this.db.prepare(`
|
|
416
|
+
SELECT 1 FROM mesh_queue
|
|
417
|
+
WHERE mesh_id = ? AND status = 'assigned'
|
|
418
|
+
AND (assigned_session_id = ? OR assigned_node_id = ?)
|
|
419
|
+
LIMIT 1
|
|
420
|
+
`).get(s,n,i)!==void 0}hasActiveSessionAssignment(s,n){return this.db.prepare(`
|
|
421
|
+
SELECT 1 FROM mesh_queue
|
|
422
|
+
WHERE mesh_id = ? AND status = 'assigned' AND assigned_session_id = ?
|
|
423
|
+
LIMIT 1
|
|
424
|
+
`).get(s,n)!==void 0}hasActiveNodeAssignment(s,n){return this.db.prepare(`
|
|
425
|
+
SELECT 1 FROM mesh_queue
|
|
426
|
+
WHERE mesh_id = ? AND status = 'assigned' AND assigned_node_id = ?
|
|
427
|
+
LIMIT 1
|
|
428
|
+
`).get(s,n)!==void 0}nodeActiveAssignmentCount(s,n){const i=this.db.prepare(`
|
|
429
|
+
SELECT COUNT(*) as count FROM mesh_queue
|
|
430
|
+
WHERE mesh_id = ? AND status = 'assigned' AND assigned_node_id = ?
|
|
431
|
+
`).get(s,n);return(i==null?void 0:i.count)??0}getSchedulerCursor(s){const n=this.db.prepare("SELECT cursor FROM mesh_scheduler_cursor WHERE mesh_id = ?").get(s);return(n==null?void 0:n.cursor)??0}bumpSchedulerCursor(s){return this.transaction(()=>{const n=this.getSchedulerCursor(s);return this.db.prepare(`
|
|
432
|
+
INSERT INTO mesh_scheduler_cursor (mesh_id, cursor) VALUES (?, ?)
|
|
433
|
+
ON CONFLICT(mesh_id) DO UPDATE SET cursor = excluded.cursor
|
|
434
|
+
`).run(s,n+1),n})}activeProviderAssignmentCount(s,n,i){const a=this.db.prepare(`
|
|
435
|
+
SELECT payload FROM mesh_queue
|
|
436
|
+
WHERE mesh_id = ? AND status = 'assigned' AND assigned_node_id = ?
|
|
437
|
+
`).all(s,n);let o=0;for(const l of a)try{JSON.parse(l.payload).assignedProviderType===i&&(o+=1)}catch{}return o}claimNextQueueTask(s,n,i,a=[],o){return this.transaction(()=>{if(this.ensureLegacyQueueMigrated(s),this.hasActiveSessionAssignment(s,i))return null;const l=this.hasActiveNodeAssignment(s,n),c=typeof(o==null?void 0:o.providerType)=="string"?o.providerType.trim():"",d=o==null?void 0:o.providerMaxParallel;if(c&&typeof d=="number"&&Number.isFinite(d)&&d>=0&&this.activeProviderAssignmentCount(s,n,c)>=d)return null;const h=[...this.db.prepare(`
|
|
438
|
+
SELECT payload FROM mesh_queue
|
|
439
|
+
WHERE mesh_id = ? AND status = 'pending' AND target_session_id = ?
|
|
440
|
+
ORDER BY created_at ASC
|
|
441
|
+
`).all(s,i),...this.db.prepare(`
|
|
442
|
+
SELECT payload FROM mesh_queue
|
|
443
|
+
WHERE mesh_id = ? AND status = 'pending' AND target_node_id = ? AND target_session_id IS NULL
|
|
444
|
+
ORDER BY created_at ASC
|
|
445
|
+
`).all(s,n),...this.db.prepare(`
|
|
446
|
+
SELECT payload FROM mesh_queue
|
|
447
|
+
WHERE mesh_id = ? AND status = 'pending' AND target_node_id IS NULL AND target_session_id IS NULL
|
|
448
|
+
ORDER BY created_at ASC
|
|
449
|
+
`).all(s)].map(x=>JSON.parse(x.payload)),m=[...new Set(h.flatMap(x=>Array.isArray(x.dependsOn)?x.dependsOn:[]))],g=new Map;if(m.length>0){const x=m.map(()=>"?").join(", "),S=this.db.prepare(`SELECT id, status FROM mesh_queue WHERE mesh_id = ? AND id IN (${x})`).all(s,...m);for(const k of S)g.set(k.id,k.status)}const b=x=>x.blockedReason?!1:(Array.isArray(x.dependsOn)?x.dependsOn:[]).every(k=>g.get(k)==="completed"),f=x=>x.taskMode==="live_debug_readonly"?!0:!l,v=h.find(x=>jl(x.requiredTags,a)&&b(x)&&f(x));if(!v)return null;const w=new Date().toISOString();return v.status="assigned",v.assignedNodeId=n,v.assignedSessionId=i,c&&(v.assignedProviderType=c),v.dispatchTimestamp=w,v.updatedAt=w,this.db.prepare(`
|
|
450
|
+
UPDATE mesh_queue SET
|
|
451
|
+
status = 'assigned', assigned_node_id = ?, assigned_session_id = ?,
|
|
452
|
+
updated_at = ?, payload = ?
|
|
453
|
+
WHERE id = ? AND mesh_id = ?
|
|
454
|
+
`).run(n,i,w,JSON.stringify(v),v.id,s),this.maybeCheckpointWal(),v})}getQueueStatsByStatus(s){return this.ensureLegacyQueueMigrated(s),this.db.prepare("SELECT status, COUNT(*) as count FROM mesh_queue WHERE mesh_id = ? GROUP BY status").all(s)}getActiveAssignmentDetails(s){return this.ensureLegacyQueueMigrated(s),this.db.prepare(`
|
|
455
|
+
SELECT assigned_node_id, assigned_session_id, payload
|
|
456
|
+
FROM mesh_queue WHERE mesh_id = ? AND status = 'assigned'
|
|
457
|
+
`).all(s).map(i=>{let a="",o="";try{const l=JSON.parse(i.payload);a=l.id,o=l.message}catch{}return{id:a,nodeId:i.assigned_node_id??void 0,sessionId:i.assigned_session_id??void 0,message:o}})}findAssignedBySession(s,n,i){this.ensureLegacyQueueMigrated(s);const a=i?"SELECT payload FROM mesh_queue WHERE mesh_id = ? AND assigned_session_id = ? AND status = 'assigned' AND updated_at <= ? ORDER BY updated_at DESC LIMIT 1":"SELECT payload FROM mesh_queue WHERE mesh_id = ? AND assigned_session_id = ? AND status = 'assigned' ORDER BY updated_at DESC LIMIT 1",o=i?[s,n,i]:[s,n],l=this.db.prepare(a).get(...o);return l?JSON.parse(l.payload):null}toRow(s){return{id:s.id,meshId:s.meshId,status:s.status,targetNodeId:s.targetNodeId??null,targetSessionId:s.targetSessionId??null,assignedNodeId:s.assignedNodeId??null,assignedSessionId:s.assignedSessionId??null,createdAt:s.createdAt,updatedAt:s.updatedAt,payload:JSON.stringify(s)}}insertDirectDispatch(s){const n=new Date().toISOString();this.db.prepare(`
|
|
458
|
+
INSERT OR REPLACE INTO mesh_direct_dispatches
|
|
459
|
+
(task_id, mesh_id, node_id, session_id, provider_type, message, task_mode, via,
|
|
460
|
+
status, dispatched_to_idle_session, dispatched_at, updated_at)
|
|
461
|
+
VALUES
|
|
462
|
+
(@taskId, @meshId, @nodeId, @sessionId, @providerType, @message, @taskMode, @via,
|
|
463
|
+
'dispatched', @dispatchedToIdle, @dispatchedAt, @updatedAt)
|
|
464
|
+
`).run({taskId:s.taskId,meshId:s.meshId,nodeId:s.nodeId??null,sessionId:s.sessionId??null,providerType:s.providerType??null,message:s.message,taskMode:s.taskMode??null,via:s.via,dispatchedToIdle:s.dispatchedToIdleSession?1:0,dispatchedAt:s.dispatchedAt,updatedAt:n})}getActiveDirectDispatches(s){return this.db.prepare(`
|
|
465
|
+
SELECT task_id, mesh_id, node_id, session_id, provider_type, message, task_mode, via,
|
|
466
|
+
status, dispatched_to_idle_session, dispatched_at, updated_at
|
|
467
|
+
FROM mesh_direct_dispatches
|
|
468
|
+
WHERE mesh_id = ? AND status NOT IN ('completed', 'failed', 'stale')
|
|
469
|
+
ORDER BY dispatched_at ASC
|
|
470
|
+
`).all(s).map(i=>({taskId:i.task_id,meshId:i.mesh_id,nodeId:i.node_id,sessionId:i.session_id,providerType:i.provider_type,message:i.message,taskMode:i.task_mode,via:i.via,status:i.status,dispatchedToIdleSession:i.dispatched_to_idle_session===1,dispatchedAt:i.dispatched_at,updatedAt:i.updated_at}))}updateDirectDispatchStatus(s,n,i){if(!n)return;const a=new Date().toISOString();this.db.prepare(`
|
|
471
|
+
UPDATE mesh_direct_dispatches
|
|
472
|
+
SET status = @status, updated_at = @updatedAt
|
|
473
|
+
WHERE mesh_id = @meshId AND session_id = @sessionId
|
|
474
|
+
AND session_id IS NOT NULL
|
|
475
|
+
AND status NOT IN ('completed', 'failed')
|
|
476
|
+
`).run({status:i,meshId:s,sessionId:n,updatedAt:a})}cleanupTerminalDirectDispatches(s){const n=new Date(Date.now()-s).toISOString();this.db.prepare(`
|
|
477
|
+
DELETE FROM mesh_direct_dispatches
|
|
478
|
+
WHERE status IN ('completed', 'failed', 'stale') AND updated_at < ?
|
|
479
|
+
`).run(n)}deleteDirectDispatches(s){this.db.prepare("DELETE FROM mesh_direct_dispatches WHERE mesh_id = ?").run(s)}deleteDirectDispatchesByTaskId(s,n){const i=(n||[]).map(c=>typeof c=="string"?c.trim():"").filter(Boolean);if(!i.length)return 0;const a=this.db.prepare("DELETE FROM mesh_direct_dispatches WHERE mesh_id = ? AND task_id = ?");let o=0;return this.db.transaction(c=>{for(const d of c)o+=a.run(s,d).changes})(i),o}markStaleDirectDispatches(s,n){const i=new Date(Date.now()-n).toISOString(),a=new Date().toISOString();this.db.prepare(`
|
|
480
|
+
UPDATE mesh_direct_dispatches
|
|
481
|
+
SET status = 'stale', updated_at = ?
|
|
482
|
+
WHERE mesh_id = ? AND status = 'dispatched' AND dispatched_at < ?
|
|
483
|
+
`).run(a,s,i)}setRemoteIdleSession(s,n,i,a,o){this.db.prepare(`
|
|
484
|
+
INSERT OR REPLACE INTO remote_idle_sessions (node_id, session_id, provider_type, expires_at, metadata)
|
|
485
|
+
VALUES (?, ?, ?, ?, ?)
|
|
486
|
+
`).run(s,n,i,a,o?JSON.stringify(o):null)}getRemoteIdleSessions(){return this.db.prepare("SELECT node_id, session_id, provider_type, expires_at, metadata FROM remote_idle_sessions").all().map(n=>({nodeId:n.node_id,sessionId:n.session_id,providerType:n.provider_type,expiresAt:n.expires_at,metadata:n.metadata?JSON.parse(n.metadata):void 0}))}deleteRemoteIdleSession(s,n){this.db.prepare("DELETE FROM remote_idle_sessions WHERE node_id = ? AND session_id = ?").run(s,n)}pruneExpiredRemoteIdleSessions(){this.db.prepare("DELETE FROM remote_idle_sessions WHERE expires_at <= ?").run(Date.now())}insertSessionDelivery(s){this.db.prepare(`
|
|
487
|
+
INSERT OR REPLACE INTO mesh_session_delivery (
|
|
488
|
+
id, mesh_id, node_id, session_id, provider_type, task_id, kind, priority,
|
|
489
|
+
message, status, deliver_after, expires_at, attempt_count,
|
|
490
|
+
source_coordinator_session_id, source_coordinator_daemon_id,
|
|
491
|
+
last_error, created_at, updated_at
|
|
492
|
+
) VALUES (
|
|
493
|
+
@id, @meshId, @nodeId, @sessionId, @providerType, @taskId, @kind, @priority,
|
|
494
|
+
@message, @status, @deliverAfter, @expiresAt, 0,
|
|
495
|
+
@sourceCoordinatorSessionId, @sourceCoordinatorDaemonId,
|
|
496
|
+
NULL, @createdAt, @updatedAt
|
|
497
|
+
)
|
|
498
|
+
`).run({id:s.id,meshId:s.meshId,nodeId:s.nodeId??null,sessionId:s.sessionId??null,providerType:s.providerType??null,taskId:s.taskId??null,kind:s.kind,priority:s.priority??0,message:s.message,status:s.status,deliverAfter:s.deliverAfter??null,expiresAt:s.expiresAt??null,sourceCoordinatorSessionId:s.sourceCoordinatorSessionId??null,sourceCoordinatorDaemonId:s.sourceCoordinatorDaemonId??null,createdAt:s.createdAt,updatedAt:s.updatedAt}),this.maybeCheckpointWal()}updateSessionDeliveryStatus(s,n,i){const a=new Date().toISOString();i!=null&&i.incrementAttempt?this.db.prepare(`
|
|
499
|
+
UPDATE mesh_session_delivery
|
|
500
|
+
SET status = @status, last_error = @lastError, attempt_count = attempt_count + 1, updated_at = @updatedAt
|
|
501
|
+
WHERE id = @id
|
|
502
|
+
`).run({id:s,status:n,lastError:(i==null?void 0:i.lastError)??null,updatedAt:a}):this.db.prepare(`
|
|
503
|
+
UPDATE mesh_session_delivery
|
|
504
|
+
SET status = @status, last_error = @lastError, updated_at = @updatedAt
|
|
505
|
+
WHERE id = @id
|
|
506
|
+
`).run({id:s,status:n,lastError:(i==null?void 0:i.lastError)??null,updatedAt:a})}getActiveSessionDeliveries(s,n){const i=new Date().toISOString(),a=n?"SELECT * FROM mesh_session_delivery WHERE mesh_id = ? AND session_id = ? AND status NOT IN ('delivered','completed','failed','expired','cancelled') AND (expires_at IS NULL OR expires_at > ?) ORDER BY priority DESC, created_at ASC":"SELECT * FROM mesh_session_delivery WHERE mesh_id = ? AND status NOT IN ('delivered','completed','failed','expired','cancelled') AND (expires_at IS NULL OR expires_at > ?) ORDER BY priority DESC, created_at ASC";return(n?this.db.prepare(a).all(s,n,i):this.db.prepare(a).all(s,i)).map(l=>({id:l.id,meshId:l.mesh_id,nodeId:l.node_id,sessionId:l.session_id,providerType:l.provider_type,taskId:l.task_id,kind:l.kind,priority:l.priority,message:l.message,status:l.status,deliverAfter:l.deliver_after,expiresAt:l.expires_at,attemptCount:l.attempt_count,sourceCoordinatorSessionId:l.source_coordinator_session_id,sourceCoordinatorDaemonId:l.source_coordinator_daemon_id,lastError:l.last_error,createdAt:l.created_at,updatedAt:l.updated_at}))}expireStaleSessionDeliveries(s){const n=new Date().toISOString();this.db.prepare(`
|
|
507
|
+
UPDATE mesh_session_delivery
|
|
508
|
+
SET status = 'expired', updated_at = ?
|
|
509
|
+
WHERE mesh_id = ? AND expires_at IS NOT NULL AND expires_at <= ?
|
|
510
|
+
AND status NOT IN ('delivered','completed','failed','expired','cancelled')
|
|
511
|
+
`).run(n,s,n)}deleteSessionDeliveries(s){this.db.prepare("DELETE FROM mesh_session_delivery WHERE mesh_id = ?").run(s)}recordCompletionConflict(s){this.db.prepare(`
|
|
512
|
+
INSERT OR IGNORE INTO mesh_completion_conflicts
|
|
513
|
+
(id, mesh_id, fingerprint, conflicting_task_id, conflicting_session_id,
|
|
514
|
+
original_task_id, original_session_id, event, created_at)
|
|
515
|
+
VALUES (@id, @meshId, @fingerprint, @conflictingTaskId, @conflictingSessionId,
|
|
516
|
+
@originalTaskId, @originalSessionId, @event, @createdAt)
|
|
517
|
+
`).run({id:s.id,meshId:s.meshId,fingerprint:s.fingerprint,conflictingTaskId:s.conflictingTaskId??null,conflictingSessionId:s.conflictingSessionId??null,originalTaskId:s.originalTaskId??null,originalSessionId:s.originalSessionId??null,event:s.event,createdAt:s.createdAt}),this.maybeCheckpointWal()}getRecentCompletionConflicts(s,n=60*60*1e3){const i=new Date(Date.now()-n).toISOString();return this.db.prepare("SELECT * FROM mesh_completion_conflicts WHERE mesh_id = ? AND created_at >= ? ORDER BY created_at DESC LIMIT 50").all(s,i).map(o=>({id:o.id,meshId:o.mesh_id,fingerprint:o.fingerprint,conflictingTaskId:o.conflicting_task_id,conflictingSessionId:o.conflicting_session_id,originalTaskId:o.original_task_id,originalSessionId:o.original_session_id,event:o.event,createdAt:o.created_at}))}recordMeshToolCall(s){const{meshId:n,tool:i,sessionId:a=null}=s,o=s.windowMs??1e4,l=s.maxCalls??5,c=Date.now(),d=c-o;this.db.prepare("INSERT INTO mesh_tool_call_log (mesh_id, tool, session_id, called_at) VALUES (?, ?, ?, ?)").run(n,i,a,c);const p=this.db.prepare("SELECT COUNT(*) as cnt FROM mesh_tool_call_log WHERE mesh_id = ? AND tool = ? AND called_at >= ?").get(n,i,d),h=(p==null?void 0:p.cnt)??0;if(++this.walWriteCounter%200===0&&this.db.prepare("DELETE FROM mesh_tool_call_log WHERE called_at < ?").run(c-Math.max(o*10,6e4)),h>l){const m=`Rate limit: ${i} called ${h} times in the last ${o/1e3}s for mesh ${n}. Wait for pendingCoordinatorEvents or an explicit user status request before calling again.`;return{rateLimitExceeded:!0,callsInWindow:h,advisory:m}}return{rateLimitExceeded:!1,callsInWindow:h,advisory:null}}pruneToolCallLog(s){this.db.prepare("DELETE FROM mesh_tool_call_log WHERE called_at < ?").run(Date.now()-s)}appendLedgerEntry(s){this.db.prepare(`INSERT OR IGNORE INTO mesh_event_ledger
|
|
518
|
+
(id, mesh_id, timestamp, kind, node_id, session_id, provider_type, payload)
|
|
519
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(s.id,s.meshId,s.timestamp,s.kind,s.nodeId??null,s.sessionId??null,s.providerType??null,JSON.stringify(s.payload??{})),this.maybeCheckpointWal()}readLedgerEntries(s,n){const i=(n==null?void 0:n.tail)??(n==null?void 0:n.limit)??200;let a;const o=[s];return n!=null&&n.kind&&(n!=null&&n.since)?(a="SELECT * FROM mesh_event_ledger WHERE mesh_id = ? AND kind = ? AND timestamp >= ? ORDER BY timestamp DESC LIMIT ?",o.push(n.kind,n.since,i)):n!=null&&n.kind?(a="SELECT * FROM mesh_event_ledger WHERE mesh_id = ? AND kind = ? ORDER BY timestamp DESC LIMIT ?",o.push(n.kind,i)):n!=null&&n.since?(a="SELECT * FROM mesh_event_ledger WHERE mesh_id = ? AND timestamp >= ? ORDER BY timestamp DESC LIMIT ?",o.push(n.since,i)):(a="SELECT * FROM mesh_event_ledger WHERE mesh_id = ? ORDER BY timestamp DESC LIMIT ?",o.push(i)),this.db.prepare(a).all(...o).map(c=>({id:c.id,meshId:c.mesh_id,timestamp:c.timestamp,kind:c.kind,nodeId:c.node_id,sessionId:c.session_id,providerType:c.provider_type,payload:(()=>{try{return JSON.parse(c.payload)}catch{return{}}})()}))}readLedgerEntriesOrdered(s,n){const i=[s];let a="mesh_id = ?";n!=null&&n.since&&(a+=" AND timestamp >= ?",i.push(n.since));const o=Array.isArray(n==null?void 0:n.kinds)?n.kinds.filter(d=>typeof d=="string"&&d.trim()):[];o.length>0&&(a+=` AND kind IN (${o.map(()=>"?").join(", ")})`,i.push(...o));let l;return n!=null&&n.tail&&n.tail>0?(l=`SELECT * FROM (
|
|
520
|
+
SELECT rowid AS rid, * FROM mesh_event_ledger WHERE ${a}
|
|
521
|
+
ORDER BY timestamp DESC, rowid DESC LIMIT ?
|
|
522
|
+
) ORDER BY timestamp ASC, rid ASC`,i.push(Math.floor(n.tail))):l=`SELECT rowid AS rid, * FROM mesh_event_ledger WHERE ${a} ORDER BY timestamp ASC, rowid ASC`,this.db.prepare(l).all(...i).map(d=>({id:d.id,meshId:d.mesh_id,timestamp:d.timestamp,kind:d.kind,nodeId:d.node_id,sessionId:d.session_id,providerType:d.provider_type,payload:(()=>{try{return JSON.parse(d.payload)}catch{return{}}})()}))}clearLedgerForMesh(s){return this.db.prepare("DELETE FROM mesh_event_ledger WHERE mesh_id = ?").run(s).changes}deleteLedgerEntries(s,n){if(!n.length)return 0;let i=0;const a=this.db.prepare("DELETE FROM mesh_event_ledger WHERE mesh_id = ? AND id = ?");return this.db.transaction(()=>{for(const o of n)i+=a.run(s,o).changes})(),i}hasLedgerEntry(s,n){return this.db.prepare("SELECT 1 FROM mesh_event_ledger WHERE mesh_id = ? AND id = ? LIMIT 1").get(s,n)!==void 0}ledgerEntryCount(s){const n=this.db.prepare("SELECT COUNT(*) as cnt FROM mesh_event_ledger WHERE mesh_id = ?").get(s);return(n==null?void 0:n.cnt)??0}importLedgerEntries(s){let n=0;const i=this.db.prepare(`INSERT OR IGNORE INTO mesh_event_ledger
|
|
523
|
+
(id, mesh_id, timestamp, kind, node_id, session_id, provider_type, payload)
|
|
524
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);return this.db.transaction(()=>{for(const a of s)i.run(a.id,a.meshId,a.timestamp,a.kind,a.nodeId??null,a.sessionId??null,a.providerType??null,JSON.stringify(a.payload??{})).changes>0&&n++})(),n}readLedgerSlice(s,n){const o=typeof(n==null?void 0:n.limit)=="number"&&Number.isFinite(n.limit)?Math.max(1,Math.min(500,Math.floor(n.limit))):100,l=typeof(n==null?void 0:n.afterId)=="string"&&n.afterId.trim()?n.afterId.trim():null,c=[s];let d="mesh_id = ?";n!=null&&n.kind&&(d+=" AND kind = ?",c.push(n.kind)),n!=null&&n.since&&(d+=" AND timestamp >= ?",c.push(n.since)),l&&(d+=" AND (timestamp > (SELECT timestamp FROM mesh_event_ledger WHERE id = ? AND mesh_id = ?) OR (timestamp = (SELECT timestamp FROM mesh_event_ledger WHERE id = ? AND mesh_id = ?) AND id > ?))",c.push(l,s,l,s,l));const p=`SELECT * FROM mesh_event_ledger WHERE ${d} ORDER BY timestamp ASC, id ASC LIMIT ?`;c.push(o+1);const h=this.db.prepare(p).all(...c),m=h.length>o,b=(m?h.slice(0,o):h).map(f=>({id:f.id,meshId:f.mesh_id,timestamp:f.timestamp,kind:f.kind,nodeId:f.node_id,sessionId:f.session_id,providerType:f.provider_type,payload:(()=>{try{return JSON.parse(f.payload)}catch{return{}}})()}));return{protocol:"adhdev.mesh.ledger.slice.v1",meshId:s,entries:b,cursor:{afterId:l,nextAfterId:b.length?b[b.length-1].id:l,limit:o,hasMore:m},sourceOfTruth:{kind:"local_sqlite",table:"mesh_event_ledger",bounded:!0,maxLimit:500}}}insertPendingEvent(s){const n=this.db.prepare(`INSERT OR IGNORE INTO mesh_pending_events
|
|
525
|
+
(id, mesh_id, coordinator_daemon_id, event, payload, fingerprint, queued_at)
|
|
526
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`).run(s.id,s.meshId,s.coordinatorDaemonId??null,s.event,JSON.stringify(s.payload??{}),s.fingerprint??null,s.queuedAt);return this.maybeCheckpointWal(),n.changes>0}drainPendingEvents(s,n,i){return this.transaction(()=>{const a=i==null?void 0:i.onlyEvents;if(a&&a.size===0)return[];const o=a?[...a]:[],l=(Array.isArray(n)?n:n?[n]:[]).filter(g=>typeof g=="string"&&g.length>0),c=["mesh_id = ?","drained = 0"],d=[s];l.length>0&&(c.push(`(coordinator_daemon_id IS NULL OR coordinator_daemon_id IN (${l.map(()=>"?").join(",")}))`),d.push(...l)),o.length>0&&(c.push(`event IN (${o.map(()=>"?").join(",")})`),d.push(...o));const p=this.db.prepare(`SELECT id, event, payload FROM mesh_pending_events WHERE ${c.join(" AND ")} ORDER BY queued_at ASC LIMIT 100`).all(...d);if(p.length===0)return[];const h=p.map(g=>g.id),m=Date.now();return this.db.prepare(`UPDATE mesh_pending_events SET drained = 1, drained_at = ? WHERE id IN (${h.map(()=>"?").join(",")})`).run(m,...h),p.map(g=>({id:g.id,event:g.event,payload:(()=>{try{return JSON.parse(g.payload)}catch{return{}}})()}))})}peekPendingEvents(s,n){const i=(Array.isArray(n)?n:n?[n]:[]).filter(c=>typeof c=="string"&&c.length>0),a=i.length>0?`WHERE mesh_id = ? AND drained = 0 AND (coordinator_daemon_id IS NULL OR coordinator_daemon_id IN (${i.map(()=>"?").join(",")}))`:"WHERE mesh_id = ? AND drained = 0",o=i.length>0?[s,...i]:[s];return this.db.prepare(`SELECT id, event, payload FROM mesh_pending_events ${a} ORDER BY queued_at ASC LIMIT 100`).all(...o).map(c=>({id:c.id,event:c.event,payload:(()=>{try{return JSON.parse(c.payload)}catch{return{}}})()}))}hasPendingEventFingerprint(s,n){return this.db.prepare("SELECT 1 FROM mesh_pending_events WHERE mesh_id = ? AND fingerprint = ? AND drained = 0 LIMIT 1").get(s,n)!==void 0}upsertMission(s){const n=new Date().toISOString();this.db.prepare(`INSERT INTO mesh_missions (id, mesh_id, title, goal, status, created_at, updated_at)
|
|
527
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
528
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
529
|
+
title = excluded.title,
|
|
530
|
+
goal = excluded.goal,
|
|
531
|
+
status = excluded.status,
|
|
532
|
+
updated_at = excluded.updated_at`).run(s.id,s.meshId,s.title,s.goal??"",s.status??"active",n,n),this.maybeCheckpointWal()}getMission(s,n){const i=this.db.prepare("SELECT * FROM mesh_missions WHERE mesh_id = ? AND id = ?").get(s,n);return i?{id:i.id,meshId:i.mesh_id,title:i.title,goal:i.goal,status:i.status,createdAt:i.created_at,updatedAt:i.updated_at}:null}getMissions(s,n){let i;if(n!=null&&n.length){const a=n.map(()=>"?").join(", ");i=this.db.prepare(`SELECT * FROM mesh_missions WHERE mesh_id = ? AND status IN (${a}) ORDER BY updated_at DESC`).all(s,...n)}else i=this.db.prepare("SELECT * FROM mesh_missions WHERE mesh_id = ? ORDER BY updated_at DESC").all(s);return i.map(a=>({id:a.id,meshId:a.mesh_id,title:a.title,goal:a.goal,status:a.status,createdAt:a.created_at,updatedAt:a.updated_at}))}clearMissionsForMesh(s){return this.db.prepare("DELETE FROM mesh_missions WHERE mesh_id = ?").run(s).changes}clearPendingEventsForMesh(s){return this.db.prepare("DELETE FROM mesh_pending_events WHERE mesh_id = ?").run(s).changes}pendingEventCount(s){const n=this.db.prepare("SELECT COUNT(*) as cnt FROM mesh_pending_events WHERE mesh_id = ? AND drained = 0").get(s);return(n==null?void 0:n.cnt)??0}markPendingEventsDrainedById(s){const n=s.filter(a=>typeof a=="string"&&a.length>0);if(n.length===0)return 0;const i=Date.now();return this.db.prepare(`UPDATE mesh_pending_events SET drained = 1, drained_at = ? WHERE drained = 0 AND id IN (${n.map(()=>"?").join(",")})`).run(i,...n).changes}deletePendingEventsById(s){const n=s.filter(i=>typeof i=="string"&&i.length>0);return n.length===0?0:this.db.prepare(`DELETE FROM mesh_pending_events WHERE id IN (${n.map(()=>"?").join(",")})`).run(...n).changes}},re(e,"instance"),re(e,"WAL_CHECK_INTERVAL",500),re(e,"WAL_MAX_BYTES",50*1024*1024),e)}});function QP(e){var s;const t=(s=e.payload)==null?void 0:s.taskId;return typeof t=="string"&&t.trim()?t.trim():""}function Wo(e){if(!e)return null;const t=new Date(e).getTime();return Number.isFinite(t)?t:null}function JP(e,t){var d;const s=fs(e),n=new Map(s.map(p=>[p.id,p]));let i;if((d=t==null?void 0:t.taskIds)!=null&&d.length?i=[...new Set(t.taskIds)]:t!=null&&t.missionId?i=s.filter(p=>p.missionId===t.missionId).map(p=>p.id):i=s.map(p=>p.id),i.length===0)return[];const a=new Set(i),o=ms(e,{tail:(t==null?void 0:t.tail)??1e3}),l=new Map,c=new Map;for(const p of o){const h=QP(p);if(!(!h||!a.has(h)))if(p.kind==="task_dispatched"){const m=l.get(h);m?m.count+=1:l.set(h,{first:p.timestamp,count:1})}else(p.kind==="task_completed"||p.kind==="task_failed")&&c.set(h,{at:p.timestamp,kind:p.kind})}return i.map(p=>{const h=n.get(p),m=(h==null?void 0:h.status)??"unknown",g=l.get(p),b=c.get(p),f=m==="completed"||m==="failed"||m==="cancelled",v=Wo((g==null?void 0:g.first)??(h==null?void 0:h.dispatchTimestamp)),w=Wo(b==null?void 0:b.at),x={taskId:p,status:m,dispatchedAt:(g==null?void 0:g.first)??(h==null?void 0:h.dispatchTimestamp)??null,terminalAt:(b==null?void 0:b.at)??null,terminalKind:(b==null?void 0:b.kind)??null,durationMs:null,dispatchCount:(g==null?void 0:g.count)??0,requeueCount:(h==null?void 0:h.requeueCount)??0};return v!==null&&w!==null&&w>=v?x.durationMs=w-v:f&&(x.incompleteEvidence=!0),x})}function ZP(e,t){const s=JP(e,{missionId:t}),n={missionId:t,taskCount:s.length,completed:0,failed:0,totalDurationMs:0,wallClockMs:null,retries:0,incompleteTaskIds:[]};let i=null,a=null;for(const o of s){if(o.status==="completed"?n.completed+=1:o.status==="failed"&&(n.failed+=1),n.retries+=o.requeueCount,o.incompleteEvidence){n.incompleteTaskIds.push(o.taskId);continue}o.durationMs!==null&&(n.totalDurationMs+=o.durationMs);const l=Wo(o.dispatchedAt),c=Wo(o.terminalAt);l!==null&&(i===null||l<i)&&(i=l),c!==null&&(a===null||c>a)&&(a=c)}return i!==null&&a!==null&&a>=i&&(n.wallClockMs=a-i),n}var Zy=We({"src/mesh/mesh-task-stats.ts"(){fr(),Ys()}}),eD={};Tt(eD,{GOAL_PREVIEW_MAX:()=>Ho,MESH_MISSION_STATUSES:()=>Li,buildMissionPromptSection:()=>iD,getActiveMeshMissionSummaries:()=>t0,getMeshMission:()=>sD,getMeshMissions:()=>Cl,getMeshStatusMissionSummaries:()=>rD,listMeshMissionSummaries:()=>nD,summarizeMeshMission:()=>Il,summarizeMissionTasks:()=>e0,upsertMeshMission:()=>tD});function Uo(e){return Li.includes(e)?e:"active"}function tD(e,t){const s=typeof t.title=="string"?t.title.trim():"";if(!s)throw new Error("mission_title_required: a mission needs a non-empty title");if(t.status!==void 0&&!Li.includes(t.status))throw new Error(`invalid_mission_status: '${t.status}' (valid: ${Li.join(", ")})`);const n=typeof t.id=="string"&&t.id.trim()?t.id.trim():Ts(),i=Pe.getInstance(),a=i.getMission(e,n),o={id:n,meshId:e,title:s,goal:typeof t.goal=="string"?t.goal:(a==null?void 0:a.goal)??"",status:Uo(t.status??(a==null?void 0:a.status))};i.upsertMission(o);const l=i.getMission(e,n);return{...l,status:Uo(l.status)}}function Cl(e,t){return Pe.getInstance().getMissions(e,t).map(s=>({...s,status:Uo(s.status)}))}function sD(e,t){const s=Pe.getInstance().getMission(e,t);return s?{...s,status:Uo(s.status)}:null}function e0(e,t){const s=fs(e).filter(i=>i.missionId===t),n={total:s.length,pending:0,assigned:0,completed:0,failed:0,cancelled:0,blocked:0,lastActivityAt:null};for(const i of s)i.status==="pending"?n.pending+=1:i.status==="assigned"?n.assigned+=1:i.status==="completed"?n.completed+=1:i.status==="failed"?n.failed+=1:i.status==="cancelled"&&(n.cancelled+=1),i.status==="pending"&&i.blockedReason&&(n.blocked+=1),i.updatedAt&&(!n.lastActivityAt||i.updatedAt>n.lastActivityAt)&&(n.lastActivityAt=i.updatedAt);return n}function Il(e,t){return{...t,tasks:e0(e,t.id)}}function t0(e){return Cl(e,["active"]).map(t=>Il(e,t))}function s0(e){const t=typeof e.goal=="string"?e.goal:"",s=t.length>Ho,{goal:n,...i}=e;return{...i,goalPreview:s?t.slice(0,Ho):t,goalTruncated:s}}function rD(e,t){const s=Math.max(0,(t==null?void 0:t.historyLimit)??10),n=Cl(e),i=n.filter(l=>l.status==="active"||l.status==="paused"),a=n.filter(l=>l.status==="completed"||l.status==="abandoned").sort((l,c)=>(c.updatedAt||"").localeCompare(l.updatedAt||"")).slice(0,s);let o=[...i,...a].map(l=>Il(e,l));return t!=null&&t.withStats&&(o=o.map(l=>({...l,stats:ZP(e,l.id)}))),t!=null&&t.verbose?o:o.map(s0)}function nD(e,t){const s=t!=null&&t.statuses&&t.statuses.length>0?t.statuses:void 0,i=Cl(e,s).sort((a,o)=>(o.updatedAt||"").localeCompare(a.updatedAt||"")).map(a=>Il(e,a));return t!=null&&t.verbose?i:i.map(s0)}function iD(e){const t=t0(e);if(t.length===0)return"";const s=["## Active Mission"+(t.length>1?"s":"")];for(const n of t){const i=n.tasks;s.push(`- **${n.title}** (id: \`${n.id}\`)`+(n.goal?`
|
|
533
|
+
Goal: ${n.goal}`:"")+`
|
|
534
|
+
Tasks: ${i.total} total — ${i.pending} pending (${i.blocked} blocked), ${i.assigned} assigned, ${i.completed} completed, ${i.failed} failed, ${i.cancelled} cancelled`+(i.lastActivityAt?`
|
|
535
|
+
Last activity: ${i.lastActivityAt}`:""))}return s.push("Continue this mission from its current task state. Do not re-enqueue tasks that already exist — check mesh_view_queue first. Update the mission with mesh_mission_upsert when its goal changes or it reaches a terminal state (completed/abandoned)."),s.join(`
|
|
536
|
+
`)}var Li,Ho,aD=We({"src/mesh/mesh-missions.ts"(){gr(),Ys(),Zy(),Li=["active","paused","completed","abandoned"],Ho=120}});function nt(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function tr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function oD(e,t){if(e==="refine:accepted")return"accepted";if(e==="refine:completed")return"completed";if(e==="refine:failed")return"failed";if(t==="completed"||t==="failed"||t==="accepted")return t}function lD(e,t){return e==="task_completed"?"completed":e==="task_failed"?"failed":t==="accepted"?"accepted":"running"}function cD(e){return e==="accepted"?"Refine job is accepted; wait for asyncRefineJobs or pendingCoordinatorEvents to report running/completed/failed.":e==="running"?"Refine job is running; do not poll the ledger repeatedly. Watch asyncRefineJobs or pendingCoordinatorEvents for the terminal result.":e==="completed"?"Refine job completed; inspect branch convergence and cleanup evidence before reporting final merge state.":"Refine job failed; inspect result/finalBranchConvergenceState in mesh_task_history, fix the blocker, then rerun mesh_refine_node when ready."}function Vm(e,t){const s=nt(t.jobId);if(!s)return;const n=e.get(s),i=t.status||(n==null?void 0:n.status)||"running",a=Object.fromEntries(Object.entries(t).filter(([,o])=>o!==void 0));e.set(s,{...n,...a,jobId:s,status:i,instruction:cD(i)})}function dD(e){const t=new Map;for(const s of e.ledgerEntries||[]){const n=tr(s.payload);if((n==null?void 0:n.source)!=="refine_mesh_node_async_job")continue;const i=tr(n.refineJob),a=tr(n.result),o=tr(n.finalBranchConvergenceState)||tr(a==null?void 0:a.finalBranchConvergenceState),l=nt(i==null?void 0:i.jobId);if(!l)continue;const c=lD(s.kind,nt(i==null?void 0:i.status));Vm(t,{jobId:l,interactionId:nt(i==null?void 0:i.interactionId),status:c,meshId:nt(i==null?void 0:i.meshId)||e.meshId,nodeId:nt(i==null?void 0:i.nodeId)||s.nodeId,targetNodeId:nt(i==null?void 0:i.nodeId)||s.nodeId,targetDaemonId:nt(i==null?void 0:i.targetDaemonId),workspace:nt(i==null?void 0:i.workspace),branch:nt(a==null?void 0:a.branch)||nt(o==null?void 0:o.branch),into:nt(a==null?void 0:a.into)||nt(o==null?void 0:o.baseBranch),startedAt:nt(i==null?void 0:i.startedAt),completedAt:nt(i==null?void 0:i.completedAt),retryOfJobId:nt(i==null?void 0:i.retryOfJobId)||nt(n.retryOfJobId),lastLedgerKind:s.kind,lastUpdatedAt:s.timestamp})}for(const s of e.pendingEvents||[]){const n=tr(s.metadataEvent);if((n==null?void 0:n.source)!=="refine_mesh_node_async_job")continue;const i=tr(n.result),a=tr(i==null?void 0:i.finalBranchConvergenceState),o=nt(n.jobId);if(!o)continue;const l=oD(s.event,nt(n.status));Vm(t,{jobId:o,interactionId:nt(n.interactionId),...l?{status:l}:{},meshId:nt(n.meshId)||s.meshId||e.meshId,nodeId:nt(n.nodeId)||s.nodeId,targetNodeId:nt(n.nodeId)||s.nodeId,targetDaemonId:nt(n.targetDaemonId),workspace:nt(n.workspace)||s.workspace,branch:nt(i==null?void 0:i.branch)||nt(a==null?void 0:a.branch),into:nt(i==null?void 0:i.into)||nt(a==null?void 0:a.baseBranch),startedAt:nt(n.startedAt),completedAt:nt(n.completedAt),retryOfJobId:nt(n.retryOfJobId),lastEvent:s.event,lastUpdatedAt:new Date(s.queuedAt).toISOString()})}return Array.from(t.values()).sort((s,n)=>{const i=new Date(s.lastUpdatedAt||s.startedAt||"").getTime(),a=new Date(n.lastUpdatedAt||n.startedAt||"").getTime();return(Number.isFinite(a)?a:0)-(Number.isFinite(i)?i:0)})}var tp=We({"src/mesh/mesh-refine-status.ts"(){}}),uD={};Tt(uD,{deriveMeshReviewInboxItems:()=>bD});function Xt(e){return typeof e=="string"&&e.trim()?e.trim():null}function yt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Xm(e,t){if(!Array.isArray(e))return{values:[],truncated:!1};const s=e.filter(n=>typeof n=="string"&&n.trim().length>0);return{values:s.slice(0,t),truncated:s.length>t}}function pD(e){if(e.isLocalWorktree===!0)return!0;const t=yt(e.connection);return Xt(t==null?void 0:t.state)==="self"}function hD(e){const t=yt(e.branchConvergence),s=Xt(t==null?void 0:t.status);return!t||!s?null:{status:s,reason:Xt(t.reason),nextStep:Xt(t.nextStep),needsConvergence:t.needsConvergence===!0,branch:Xt(t.branch),defaultBranch:Xt(t.defaultBranch)}}function mD(e){return e.status==="pushed_feature_branch_needs_merge"?!0:e.status==="cleanup_candidate"&&e.reason==="clean_non_default_worktree_branch"}function fD(e){const t=yt(e);if(!t)return null;const s=Xm(t.changedFiles,n0);return{status:Xt(t.status)??"unknown",...Xt(t.classification)?{classification:Xt(t.classification)}:{},changedFiles:s.values,...s.truncated?{changedFilesTruncated:!0}:{},validationResults:Array.isArray(t.validationResults)?t.validationResults.map(n=>yt(n)).filter(n=>n!==null):[],errors:Xm(t.errors,20).values,requiresUserAction:t.requiresUserAction===!0}}function r0(e){return e==="task_completed"||e==="task_failed"}function gD(e,t){let s={available:!1},n=null;for(let i=t.length-1;i>=0;i--){const a=t[i];if(a.nodeId!==e||!r0(a.kind))continue;const o=yt(a.payload)??{};if(!s.available)if(o.source==="refine_mesh_node_async_job"){const l=yt(o.result),c=yt(l==null?void 0:l.validationSummary);s={available:!0,kind:a.kind,source:"refine_job",timestamp:a.timestamp,...a.sessionId?{sessionId:a.sessionId}:{},bootstrap:yt(c==null?void 0:c.bootstrap),validation:c?Object.fromEntries(Object.entries(c).filter(([d])=>d!=="bootstrap")):null,checkpoint:yt(l==null?void 0:l.checkpoint),worker:null,...yt(o.finalBranchConvergenceState)??yt(l==null?void 0:l.finalBranchConvergenceState)?{finalBranchConvergenceState:yt(o.finalBranchConvergenceState)??yt(l==null?void 0:l.finalBranchConvergenceState)}:{},...yt(o.refineJob)?{refineJob:yt(o.refineJob)}:{}}}else{const l=yt(o.evidence);s={available:!0,kind:a.kind,source:"task_completion",timestamp:a.timestamp,...Xt(o.taskId)?{taskId:Xt(o.taskId)}:{},...a.sessionId?{sessionId:a.sessionId}:{},bootstrap:null,validation:yt(l==null?void 0:l.validation),checkpoint:yt(l==null?void 0:l.checkpoint),worker:fD((l==null?void 0:l.workerResult)??o.workerResult)}}if(!n){const l=yt(o.evidence);n=yt(l==null?void 0:l.transcriptHandle)}if(s.available&&n)break}return{evidence:s,transcriptHandle:n}}function xD(e,t){for(let s=t.length-1;s>=0;s--){const n=t[s];if(n.nodeId!==e||!r0(n.kind))continue;const i=yt(n.payload)??{};if(i.source!=="refine_mesh_node_async_job")continue;const a=yt(i.result),o=yt(i.finalBranchConvergenceState)??yt(a==null?void 0:a.finalBranchConvergenceState);return Xt(o==null?void 0:o.status)==="blocked_review"||Xt(a==null?void 0:a.code)==="blocked_review"}return!1}function bD(e){const t=[],s=[],n=dD({ledgerEntries:e.ledgerEntries});for(const i of e.nodes){const a=Xt(i.nodeId)??Xt(i.id);if(!a)continue;if(!pD(i)){s.push(a);continue}const o=hD(i);if(!o||o.status==="merged_to_main")continue;let l=null;if(xD(a,e.ledgerEntries)?l="refine_blocked_review":mD(o)&&(l="merge_candidate"),!l)continue;const{evidence:c,transcriptHandle:d}=gD(a,e.ledgerEntries),p=[...n].reverse().find(h=>(h.nodeId===a||h.targetNodeId===a)&&(h.status==="accepted"||h.status==="running"))??null;t.push({nodeId:a,workspace:Xt(i.workspace),branch:o.branch??Xt(i.worktreeBranch),defaultBranch:o.defaultBranch,isLocalWorktree:i.isLocalWorktree===!0,reviewReason:l,convergence:{status:o.status,reason:o.reason,nextStep:o.nextStep,needsConvergence:o.needsConvergence},evidence:c,transcriptHandle:d,activeRefineJob:p,lastActivityAt:c.timestamp??null})}return{items:t,remoteNodesExcluded:s.length>0,excludedRemoteNodeIds:s}}var n0,yD=We({"src/mesh/mesh-review-inbox.ts"(){tp(),n0=100}}),i0,vD=We({"src/logging/async-batch-writer.ts"(){var e;i0=(e=class{static write(t,s){let n=this.buffers.get(t);n||(n=[],this.buffers.set(t,n)),n.push(s),this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flushAll()},50))}static async flushAll(){const t=Array.from(this.buffers.entries());this.buffers.clear();for(const[s,n]of t){const i=n.join(""),o=(async()=>{try{const l=this.writePromises.get(s);l&&await l,await Qe.promises.appendFile(s,i,{encoding:"utf-8",mode:384})}catch{}})();this.writePromises.set(s,o),o.finally(()=>{this.writePromises.get(s)===o&&this.writePromises.delete(s)})}}},re(e,"buffers",new Map),re(e,"writePromises",new Map),re(e,"flushTimer",null),e)}}),wD={};Tt(wD,{LOG:()=>_e,LOG_DIR_PATH:()=>m0,LOG_PATH:()=>h0,daemonLog:()=>bs,getCurrentDaemonLogPath:()=>ND,getDaemonLogDir:()=>jD,getLogBufferSize:()=>AD,getLogLevel:()=>kD,getLogPath:()=>ED,getRecentLogs:()=>ID,installGlobalInterceptor:()=>MD,setLogLevel:()=>SD});function SD(e){ca=e,bs("Logger",`Log level set to: ${e}`,"info")}function kD(){return ca}function jd(){return new Date().toISOString().slice(0,10)}function jD(){return is}function ND(e=new Date){return Ee.join(is,`daemon-${e.toISOString().slice(0,10)}.log`)}function _D(){const e=jd();e!==fi&&(fi=e,pr=Ee.join(is,`daemon-${fi}.log`),a0())}function a0(){try{const e=Qe.readdirSync(is).filter(n=>n.startsWith("daemon-")&&n.endsWith(".log")),t=new Date;t.setDate(t.getDate()-c0);const s=t.toISOString().slice(0,10);for(const n of e){const i=n.match(/daemon-(\d{4}-\d{2}-\d{2})/);if(i&&i[1]<s)try{Qe.unlinkSync(Ee.join(is,n))}catch{}}}catch{}}function CD(){try{if(Qe.statSync(pr).size>l0){const t=pr.replace(".log",".1.log");try{Qe.unlinkSync(t)}catch{}Qe.renameSync(pr,t)}}catch{}}function Sr(e){try{++d0%1e3===0&&(_D(),CD()),i0.write(pr,e+`
|
|
537
|
+
`)}catch{}}function ID(e=50,t="info"){const s=$i[t];return Bt.filter(i=>$i[i.level]>=s).slice(-e)}function AD(){return Bt.length}function TD(){return new Date().toISOString().slice(11,23)}function qa(){return new Date().toISOString()}function bs(e,t,s="info"){const n=$i[s]>=$i[ca],i=o0[s],a=`[${TD()}] [${i}] [${e}] ${t}`;n&&(Sr(a),Bt.push({ts:Date.now(),level:s,category:e,message:t}),Bt.length>Hs&&Bt.splice(0,Bt.length-Hs),sp(a))}function MD(){if(Nd)return;Nd=!0;const e=s=>s.replace(/\x1B\[[0-9;]*m/g,""),t=s=>/\[(DBG|INF|WRN|ERR)\]/.test(s);console.log=(...s)=>{sp(...s);try{const n=s.map(l=>typeof l=="string"?l:JSON.stringify(l)).join(" "),i=e(n);if(t(i))return;const a=i.startsWith("[20")?i:`[${qa()}] ${i}`;Sr(a);const o=i.match(/\[([^\]]+)\]/);Bt.push({ts:Date.now(),level:"info",category:(o==null?void 0:o[1])||"System",message:i}),Bt.length>Hs&&Bt.splice(0,Bt.length-Hs)}catch{}},console.error=(...s)=>{u0(...s);try{const n=s.map(o=>typeof o=="string"?o:JSON.stringify(o)).join(" "),i=e(n);if(t(i))return;const a=`[${qa()}] [ERROR] ${i}`;Sr(a),Bt.push({ts:Date.now(),level:"error",category:"System",message:i}),Bt.length>Hs&&Bt.splice(0,Bt.length-Hs)}catch{}},console.warn=(...s)=>{p0(...s);try{const n=s.map(o=>typeof o=="string"?o:JSON.stringify(o)).join(" "),i=e(n);if(t(i))return;const a=`[${qa()}] [WARN] ${i}`;Sr(a),Bt.push({ts:Date.now(),level:"warn",category:"System",message:i}),Bt.length>Hs&&Bt.splice(0,Bt.length-Hs)}catch{}},Sr(`
|
|
538
|
+
=== ADHDev Daemon started at ${qa()} ===`),Sr(`Log file: ${pr}`),Sr(`Log level: ${ca}`)}function ED(){return pr}var $i,o0,ca,is,l0,c0,fi,pr,d0,Hs,Bt,sp,u0,p0,_e,Nd,h0,m0,Ve=We({"src/logging/logger.ts"(){vD(),$i={debug:0,info:1,warn:2,error:3},o0={debug:"DBG",info:"INF",warn:"WRN",error:"ERR"},ca="info",is=process.platform==="win32"?Ee.join(bt.LOCALAPPDATA||bt.APPDATA||Ee.join(ot.homedir(),"AppData","Local"),"adhdev","logs"):process.platform==="darwin"?Ee.join(ot.homedir(),"Library","Logs","adhdev"):Ee.join(ot.homedir(),".local","share","adhdev","logs"),l0=5*1024*1024,c0=7;try{Qe.mkdirSync(is,{recursive:!0})}catch{}fi=jd(),pr=Ee.join(is,`daemon-${fi}.log`),a0();try{const e=Ee.join(is,"daemon.log");if(Qe.existsSync(e)){const n=Qe.statSync(e).mtime.toISOString().slice(0,10);Qe.renameSync(e,Ee.join(is,`daemon-${n}.log`))}const t=Ee.join(is,"daemon.log.old");Qe.existsSync(t)&&Qe.unlinkSync(t)}catch{}d0=0,Hs=200,Bt=[],sp=console.log.bind(console),u0=console.error.bind(console),p0=console.warn.bind(console),_e={debug:(e,t)=>bs(e,t,"debug"),info:(e,t)=>bs(e,t,"info"),warn:(e,t)=>bs(e,t,"warn"),error:(e,t)=>bs(e,t,"error"),forComponent(e){return{debug:t=>bs(e,t,"debug"),info:t=>bs(e,t,"info"),warn:t=>bs(e,t,"warn"),error:t=>bs(e,t,"error"),asLogFn:(t="info")=>s=>bs(e,s,t)}}},Nd=!1,h0=Ee.join(is,`daemon-${jd()}.log`),m0=is}}),RD={};Tt(RD,{applyMeshCoordinatorSystemPromptInjection:()=>HD,buildMeshCoordinatorRegistrationPlan:()=>GD,createHermesManualMeshCoordinatorSetup:()=>f0,execUnderPty:()=>qD,resolveMeshCoordinatorSetup:()=>LD,stripCoordinatorWrapperFile:()=>KD});function PD(e,t){var n;return((t==null?void 0:t.trim())||((n=e==null?void 0:e.type)==null?void 0:n.trim())||"")===x0}function DD(e){const t=_d({meshId:e.meshId,adhdevMcpCommand:e.adhdevMcpCommand,adhdevMcpEntryPath:e.adhdevMcpEntryPath,nodeExecutable:e.nodeExecutable,adhdevMcpTransport:e.adhdevMcpTransport,adhdevMcpPort:e.adhdevMcpPort});if(!t)return{kind:"unsupported",reason:"Could not resolve the ADHDev MCP server entrypoint and a Node runtime with WebSocket support for daemon IPC mode"};const s=Dt(OD(e.meshId,e.workspace),"config.yaml");return s.trim()?{kind:"auto_import",serverName:Oi,configPath:s,configFormat:"hermes_config_yaml",mcpServer:t}:f0(e.meshId,e.workspace)}function f0(e,t){return{kind:"manual",serverName:Oi,configFormat:"hermes_config_yaml",configPathCommand:b0,requiresRestart:!0,instructions:"Hermes CLI does not auto-import repo-local .mcp.json. Add this MCP server to Hermes config under mcp_servers, then start a fresh Hermes session.",template:g0(`mcp_servers:
|
|
539
|
+
{{serverName}}:
|
|
540
|
+
command: {{adhdevMcpCommand}}
|
|
541
|
+
args:
|
|
542
|
+
- mcp
|
|
543
|
+
- --mode
|
|
544
|
+
- ipc
|
|
545
|
+
- --repo-mesh
|
|
546
|
+
- {{meshId}}
|
|
547
|
+
enabled: true
|
|
548
|
+
`,{meshId:e,workspace:t,serverName:Oi,adhdevMcpCommand:rp})}}function LD(e){var l,c,d;const{provider:t,meshId:s,workspace:n}=e,i=t==null?void 0:t.meshCoordinator;if(!(i!=null&&i.supported))return{kind:"unsupported",reason:(i==null?void 0:i.reason)||"Provider does not declare Repo Mesh coordinator support"};if(PD(t,e.cliType))return DD(e);const a=i.mcpConfig;if(!a||a.mode==="none")return{kind:"unsupported",reason:i.reason||"Provider does not declare a usable Repo Mesh MCP configuration mode"};const o=((l=a.serverName)==null?void 0:l.trim())||Oi;if(a.mode==="auto_import"){const p=(c=a.path)==null?void 0:c.trim();if(!p)return{kind:"unsupported",reason:"Provider auto-import MCP config is missing a config path"};const h=_d({meshId:s,adhdevMcpCommand:e.adhdevMcpCommand,adhdevMcpEntryPath:e.adhdevMcpEntryPath,nodeExecutable:e.nodeExecutable,adhdevMcpTransport:e.adhdevMcpTransport,adhdevMcpPort:e.adhdevMcpPort});return h?{kind:"auto_import",serverName:o,configPath:FD(p,n),configFormat:a.format,mcpServer:h}:{kind:"unsupported",reason:"Could not resolve the ADHDev MCP server entrypoint and a Node runtime with WebSocket support for daemon IPC mode"}}if(a.mode==="manual"){const p=(d=a.instructions)==null?void 0:d.trim(),h=a.template;if(!p||!(h!=null&&h.trim()))return{kind:"unsupported",reason:"Provider manual MCP setup is missing instructions or template"};const m=_d({meshId:s,adhdevMcpCommand:e.adhdevMcpCommand,adhdevMcpEntryPath:e.adhdevMcpEntryPath,nodeExecutable:e.nodeExecutable,adhdevMcpTransport:e.adhdevMcpTransport,adhdevMcpPort:e.adhdevMcpPort});if(!m)return{kind:"unsupported",reason:"Could not resolve the ADHDev MCP server entrypoint and transport arguments"};let g=g0(h,{meshId:s,workspace:n,serverName:o,adhdevMcpCommand:m.command,adhdevMcpArgs:m.args.join(" ")});return!g.trim().includes(`
|
|
549
|
+
`)&&!g.trim().startsWith("{")?(/\{\{\s*adhdevMcpArgs\s*\}\}/.test(h)||(g=$D(g,m.args)),{kind:"cli_command",serverName:o,command:g.trim(),requiresRestart:a.requiresRestart===!0,instructions:p,mcpServer:m}):{kind:"manual",serverName:o,configFormat:a.format,configPathCommand:a.configPathCommand,requiresRestart:a.requiresRestart===!0,instructions:p,template:g}}return{kind:"unsupported",reason:`Unsupported Repo Mesh MCP configuration mode: ${String(a.mode)}`}}function g0(e,t){return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(s,n)=>t[n]||"")}function $D(e,t){return e.replace(/\bmcp\s+--mode\s+(?:ipc|local)\s+--repo-mesh\s+\S+(?:\s+--port\s+\d+)?\s*$/,t.join(" "))}function OD(e,t){const s=`${e||"mesh"}
|
|
550
|
+
${Qw(t||ot.tmpdir())}`,n=Rf("sha256").update(s).digest("hex").slice(0,16);return Dt(ot.tmpdir(),`adhdev-hermes-mesh-coordinator-${n}`)}function FD(e,t){const s=e.trim();return s==="~"?ot.homedir():s.startsWith("~/")?Dt(ot.homedir(),s.slice(2)):Mf(s)?s:Dt(t,s)}function _d(e){const t=WD(e.adhdevMcpEntryPath);if(t){const l=Ym(e.adhdevMcpTransport),c=[t,"--mode",l,"--repo-mesh",e.meshId],d=Qm(e.adhdevMcpPort);return d!==void 0&&c.push("--port",String(d)),{command:UD(e.nodeExecutable),args:c}}const s=BD(e.adhdevMcpCommand),n=Ym(e.adhdevMcpTransport),a=[...Ef(s).startsWith("adhdev-mcp")||s.includes("/vendor/mcp-server/")||s.includes("\\vendor\\mcp-server\\")?[]:["mcp"],"--mode",n,"--repo-mesh",e.meshId],o=Qm(e.adhdevMcpPort);return o!==void 0&&a.push("--port",String(o)),{command:s,args:a}}function BD(e){var t;return(e==null?void 0:e.trim())||((t=bt.ADHDEV_COORDINATOR_MCP_COMMAND)==null?void 0:t.trim())||rp}function WD(e){var s;return(e==null?void 0:e.trim())||((s=bt.ADHDEV_COORDINATOR_MCP_ENTRY_PATH)==null?void 0:s.trim())||null}function UD(e){var t;return(e==null?void 0:e.trim())||((t=bt.ADHDEV_COORDINATOR_NODE_EXECUTABLE)==null?void 0:t.trim())||process.execPath}function Ym(e){var s;return e==="local"||e==="ipc"?e:((s=bt.ADHDEV_COORDINATOR_MCP_TRANSPORT)==null?void 0:s.trim())==="local"?"local":"ipc"}function Qm(e){var n;if(typeof e=="number"&&Number.isInteger(e)&&e>0)return e;const t=(n=bt.ADHDEV_COORDINATOR_MCP_PORT)==null?void 0:n.trim();if(!t)return;const s=Number(t);return Number.isInteger(s)&&s>0?s:void 0}function HD(e,t,s){return!e||!t?{}:zD(e,t,s)}function zD(e,t,s){var n;switch(t.mode){case"cli_arg":return t.flag?(s.cliArgs.push(t.flag,e),{}):{};case"config_override":{if(!t.flag||!t.template)return{};const i=t.template.replace(/\{prompt_json\}/g,JSON.stringify(e)).replace(/\{prompt\}/g,e);return s.cliArgs.push(t.flag,i),{}}case"env_var":return t.name?(s.launchEnv[t.name]=e,{}):{};case"context_file":{if(!t.path)return{};const i=Mf(t.path)?t.path:Dt(s.workspace,t.path),a=t.wrapper&&t.wrapper.includes("{prompt}")?t.wrapper:"{prompt}",l=`> _Managed by adhdev mesh coordinator — do not hand-edit this block. Changes inside the sentinels are overwritten on next coordinator launch._
|
|
551
|
+
|
|
552
|
+
${e}`,c=a.replace(/\{prompt\}/g,l),d=a.split("{prompt}")[0].trim();try{if(st(i)){const p=As(i,"utf-8");if(d&&p.includes(d)){const h=(n=a.split("{prompt}")[1])==null?void 0:n.trim(),m=d.replace(/[.+^${}()|[\]\\]/g,"\\$&"),g=h?h.replace(/[.+^${}()|[\]\\]/g,"\\$&"):"",b=h?new RegExp(`${m}[\\s\\S]*?${g}`,"g"):new RegExp(`${m}[\\s\\S]*$`,"g");Ss(i,p.replace(b,c),"utf-8")}else Ss(i,`${p}
|
|
553
|
+
|
|
554
|
+
${c}`,"utf-8")}else Ss(i,c,"utf-8");return _e.info("MeshCoordinator",`Wrote coordinator prompt to ${i} (${s.cliType})`),{contextFilePath:i}}catch(p){return _e.warn("MeshCoordinator",`Could not write ${i}: ${(p==null?void 0:p.message)||p}`),{}}}default:return{}}}function KD(e){const t="<!-- adhdev-mesh-coordinator-prompt -->",s="<!-- /adhdev-mesh-coordinator-prompt -->";try{if(!st(e))return;const n=As(e,"utf-8"),i=n.indexOf(t);if(i<0)return;const a=n.indexOf(s,i);if(a<0)return;const o=(n.slice(0,i)+n.slice(a+s.length)).replace(/^\s*\n+/,"").replace(/\n+\s*$/,"");if(o.trim())Ss(e,o+`
|
|
555
|
+
`,"utf-8");else try{Cs("fs").unlinkSync(e)}catch{}}catch{}}function GD(e,t,s){const n=s.trim().split(/\s+/).filter(Boolean),[i,...a]=n;if(!i)return[];const o={command:i,args:a,required:!0,label:"register"};return e==="codex-cli"&&Ef(i)==="codex"&&a[0]==="mcp"&&a[1]==="add"?[{command:i,args:["mcp","remove",t],required:!1,label:"remove_existing"},o]:[o]}async function qD(e,t,s={}){let n;try{n=Cs("node-pty")}catch(o){throw new Error(`node-pty is not available: ${(o==null?void 0:o.message)||o}`)}const i={...s.env??bt,TERM:"xterm-256color"},a=typeof s.timeoutMs=="number"&&s.timeoutMs>0?s.timeoutMs:2e4;return new Promise(o=>{let l;try{l=n.spawn(e,t,{name:"xterm-256color",cols:Ti,rows:Mi,cwd:s.cwd??process.cwd(),env:i})}catch(h){o({exitCode:null,signal:null,output:String((h==null?void 0:h.message)||h),timedOut:!1});return}let c="",d=!1;const p=setTimeout(()=>{if(!d){d=!0;try{l.kill()}catch{}o({exitCode:null,signal:null,output:c,timedOut:!0})}},a);l.onData(h=>{c+=h,c.length>256*1024&&(c=c.slice(-128*1024))}),l.onExit(({exitCode:h,signal:m})=>{d||(d=!0,clearTimeout(p),o({exitCode:h,signal:m??null,output:c,timedOut:!1}))})})}var Oi,rp,x0,b0,VD=We({"src/commands/mesh-coordinator.ts"(){Ve(),Oi="adhdev-mesh",rp="adhdev",x0="hermes-cli",b0="~/.hermes/config.yaml"}});async function Jm(e){const t=typeof e.workspace=="string"?e.workspace.trim():"",s=si(e.nodeId),n=si(e.meshId),i=si(e.branch),a=si(e.trigger)||"manual",o=e.updateSubmodules===!0,l=e.dryRun===!0||e.execute!==!0,c=e.mode==="push"?"push":"merge",d=c==="push"&&e.pushSubmodules===!0,p=sL(c,o,d),h={...s?{nodeId:s}:{},...n?{meshId:n}:{},workspace:t,mode:c,dryRun:l,updateSubmodules:o,plannedSteps:p,trigger:a};if(!t)return lr(h,"invalid_workspace",["workspace_required"]);const m=await mi(t,{...zs,submoduleIgnorePaths:e.submoduleIgnorePaths,timeoutMs:e.timeoutMs??zs.timeoutMs});if(c==="push")return XD(h,e,m,{pushSubmodules:d,allowAutoPublishSubmoduleMainCommits:e.allowAutoPublishSubmoduleMainCommits===!0});const g=nL(m,i);if(g.length>0){const N=aL(m,g),_={...lr(h,N,g),current:m,finalBranchConvergenceState:as(m,v0(N))};return N==="branch_ahead"&&m.ahead>0&&m.behind===0&&rL(g)&&(_.code="ahead_needs_push",_.nextStep='Local branch is ahead of origin with nothing to merge. Re-run mesh_fast_forward_node with mode="push" (execute=true) to ff-only push the local commits to origin.'),await os(_,"blocked"),_}if(m.behind===0){const N={...h,success:!0,code:"already_up_to_date",allowed:!0,willRun:!1,executed:!1,blockingReasons:[],current:m,preStatus:m,postStatus:m,finalBranchConvergenceState:as(m,"up_to_date")};return await os(N,"noop"),N}const b=await oL(t,m.upstream||"",e.timeoutMs);if(!b.ok){const N={...lr(h,"non_fast_forward",["head_is_not_ancestor_of_upstream"]),current:m,preStatus:m,operationError:b.error,finalBranchConvergenceState:as(m,"not_mergeable")};return await os(N,"blocked"),N}if(l){const N={...h,success:!0,code:"fast_forward_available",allowed:!0,willRun:!1,executed:!1,blockingReasons:[],current:m,preStatus:m,finalBranchConvergenceState:as(m,"fast_forward_available")};return await os(N,"dry_run"),N}try{await tt(t,["merge","--ff-only",m.upstream||""],{timeoutMs:e.timeoutMs??3e4})}catch(N){const _={...lr(h,"merge_ff_only_failed",["merge_ff_only_failed"]),current:m,preStatus:m,operationError:hr(N),finalBranchConvergenceState:as(m,"not_mergeable")};return await os(_,"failed"),_}let f=await mi(t,{...zs,submoduleIgnorePaths:e.submoduleIgnorePaths,timeoutMs:e.timeoutMs??zs.timeoutMs});const v=np(f,"post");let w=!1,x;if(v.length>0)if(o)try{await tt(t,["submodule","update","--init","--recursive"],{timeoutMs:e.timeoutMs??6e4}),f=await mi(t,{...zs,submoduleIgnorePaths:e.submoduleIgnorePaths,timeoutMs:e.timeoutMs??zs.timeoutMs})}catch(N){x=hr(N)}else w=!0;const S=iL(f);x&&S.push("submodule_update_failed"),w&&S.push("submodule_update_required");const k=S.length===0||w,j=S.length===0?"fast_forward_applied":w?"fast_forward_applied_submodule_update_required":"post_verify_failed",y={...h,success:k,code:j,allowed:!0,willRun:!0,executed:!0,blockingReasons:S,current:m,preStatus:m,postStatus:f,...x?{operationError:x}:{},finalBranchConvergenceState:as(f,S.length===0?"fast_forwarded":w?"follow_up_required":"post_verify_failed")};return await os(y,k?"executed":"failed"),y}async function XD(e,t,s,n){const i=e.workspace,a=si(t.branch),o=e.dryRun,l=YD(s,a);if(l.length>0){const S=QD(s,l),k={...lr(e,S,l),current:s,preStatus:s,finalBranchConvergenceState:as(s,v0(S))};return await os(k,"blocked"),k}const c=JD(s.upstream||"");if(!c){const S={...lr(e,"upstream_unparseable",["upstream_unparseable"]),current:s,preStatus:s,finalBranchConvergenceState:as(s,"blocked")};return await os(S,"blocked"),S}const d=`HEAD:refs/heads/${c.remoteBranch}`,p={remote:c.remote,remoteBranch:c.remoteBranch,refspec:d};if(s.ahead<=0){const S={...e,success:!0,code:"nothing_to_push",allowed:!0,willRun:!1,executed:!1,blockingReasons:[],current:s,preStatus:s,postStatus:s,pushTarget:p,finalBranchConvergenceState:as(s,"up_to_date")};return await os(S,"noop"),S}const h=await ZD(i,s.upstream||"",t.timeoutMs);if(!h.ok){const S={...lr(e,"non_fast_forward_push",["head_is_not_descendant_of_upstream"]),current:s,preStatus:s,pushTarget:p,operationError:h.error,nextStep:"origin/<branch> has commits not in local HEAD; a ff-only push would lose them. Converge by rebasing onto origin first, then re-run. This operation never force-pushes.",finalBranchConvergenceState:as(s,"not_mergeable")};return await os(S,"blocked"),S}if(o){const S={...e,success:!0,code:"push_available",allowed:!0,willRun:!1,executed:!1,blockingReasons:[],current:s,preStatus:s,pushTarget:p,...n.pushSubmodules?{submodulePushes:await eL(s,n,t.timeoutMs)}:{},finalBranchConvergenceState:as(s,"push_available")};return await os(S,"dry_run"),S}try{await tt(i,["push",c.remote,d],{timeoutMs:t.timeoutMs??3e4})}catch(S){const k={...lr(e,"push_ff_only_failed",["push_ff_only_failed"]),current:s,preStatus:s,pushTarget:p,operationError:hr(S),finalBranchConvergenceState:as(s,"not_mergeable")};return await os(k,"failed"),k}let m;n.pushSubmodules&&(m=await tL(s,n,t.timeoutMs));const g=await mi(i,{...zs,submoduleIgnorePaths:t.submoduleIgnorePaths,timeoutMs:t.timeoutMs??zs.timeoutMs}),b=(m||[]).some(S=>!S.pushed&&!S.skipped),f=[];g.ahead!==0&&f.push("post_branch_ahead"),b&&f.push("submodule_push_failed");const v=f.length===0,w=v?"push_applied":b&&g.ahead===0?"push_applied_submodule_push_failed":"post_push_verify_failed",x={...e,success:v,code:w,allowed:!0,willRun:!0,executed:!0,blockingReasons:f,current:s,preStatus:s,postStatus:g,pushTarget:p,...m?{submodulePushes:m}:{},finalBranchConvergenceState:as(g,v?"pushed":"post_verify_failed")};return await os(x,v?"executed":"failed"),x}function YD(e,t){const s=[];return e.isGitRepo||s.push("not_git_repo"),e.branch||s.push("detached_head_or_unknown_branch"),t&&e.branch!==t&&s.push("branch_mismatch"),e.upstream||s.push("upstream_missing"),e.upstreamStatus!=="fresh"&&s.push("upstream_not_fresh"),e.hasConflicts&&s.push("conflicts_present"),e.staged>0&&s.push("staged_changes_present"),e.modified>0&&s.push("modified_changes_present"),e.untracked>0&&s.push("untracked_changes_present"),e.deleted>0&&s.push("deleted_changes_present"),e.renamed>0&&s.push("renamed_changes_present"),e.stashCount>0&&s.push("stash_entries_present"),e.ahead>0&&e.behind>0?s.push("branch_diverged_from_upstream"):e.behind>0&&s.push("branch_behind_upstream"),s}function QD(e,t){return t.includes("not_git_repo")?"not_git_repo":t.includes("branch_mismatch")?"branch_mismatch":t.includes("upstream_missing")?"upstream_missing":t.includes("upstream_not_fresh")?"upstream_not_fresh":t.includes("branch_diverged_from_upstream")?"branch_diverged":t.includes("branch_behind_upstream")?"non_fast_forward_push":t.some(s=>s.includes("changes")||s.includes("conflicts")||s.includes("stash"))?"dirty_worktree":"preflight_blocked"}function JD(e){const t=e.trim(),s=t.indexOf("/");return s<=0||s>=t.length-1?null:{remote:t.slice(0,s),remoteBranch:t.slice(s+1)}}async function ZD(e,t,s){if(!t)return{ok:!1,error:"missing upstream"};try{return await tt(e,["merge-base","--is-ancestor",t,"HEAD"],{timeoutMs:s??15e3}),{ok:!0}}catch(n){return{ok:!1,error:hr(n)}}}async function eL(e,t,s){return y0(e,t,!1,s)}async function tL(e,t,s){return y0(e,t,!0,s)}async function y0(e,t,s,n){const i=Array.isArray(e.submodules)?e.submodules:[],a=[];for(const o of i){const l={path:o.path,commit:o.commit,remote:"origin",remoteBranch:"main",pushed:!1,skipped:!0,code:"submodule_push_skipped"};if(!t.allowAutoPublishSubmoduleMainCommits){a.push({...l,code:"submodule_push_policy_disabled",error:"allowAutoPublishSubmoduleMainCommits is not enabled"});continue}if(o.error||o.dirty){a.push({...l,code:"submodule_not_clean",error:o.error||"submodule worktree is dirty"});continue}const c=o.repoPath;if(!c||!o.commit){a.push({...l,code:"submodule_status_incomplete"});continue}try{await tt(c,["-c","protocol.file.allow=always","fetch","origin","refs/heads/main:refs/remotes/origin/main"],{timeoutMs:n??3e4})}catch(h){a.push({...l,code:"submodule_fetch_failed",error:hr(h)});continue}let d=!1;try{await tt(c,["merge-base","--is-ancestor",o.commit,"refs/remotes/origin/main"],{timeoutMs:n??15e3}),d=!0}catch{}if(d){a.push({...l,pushed:!1,skipped:!0,code:"submodule_already_reachable"});continue}try{await tt(c,["merge-base","--is-ancestor","refs/remotes/origin/main",o.commit],{timeoutMs:n??15e3})}catch(h){a.push({...l,pushed:!1,skipped:!1,code:"submodule_non_fast_forward",error:hr(h)});continue}const p=`${o.commit}:refs/heads/main`;if(!s){a.push({...l,pushed:!1,skipped:!1,code:"submodule_push_available",refspec:p});continue}try{await tt(c,["push","origin",p],{timeoutMs:n??3e4}),await tt(c,["-c","protocol.file.allow=always","fetch","origin","refs/heads/main:refs/remotes/origin/main"],{timeoutMs:n??3e4}),await tt(c,["merge-base","--is-ancestor",o.commit,"refs/remotes/origin/main"],{timeoutMs:n??15e3}),a.push({...l,pushed:!0,skipped:!1,code:"submodule_pushed",refspec:p})}catch(h){a.push({...l,pushed:!1,skipped:!1,code:"submodule_push_failed",refspec:p,error:hr(h)})}}return a}function sL(e,t,s){const n=[{operation:"refresh_upstream",description:"Refresh the tracked upstream remote ref before trusting ahead/behind state.",safe:!0,willMutateWorktree:!1},{operation:"verify_clean_worktree",description:"Require clean staged/modified/untracked/deleted/renamed/conflict/stash/submodule state.",safe:!0,willMutateWorktree:!1}];return e==="push"?(n.push({operation:"verify_push_descendant",description:"Require HEAD to be a descendant of origin/<branch> (origin/<branch> is an ancestor of HEAD); refuse any non-fast-forward push.",safe:!0,willMutateWorktree:!1}),n.push({operation:"push_ff_only",description:"Run git push origin HEAD:<branch> as a strict ff-only push; never --force, --force-with-lease, reset, or rebase. Does not mutate the worktree.",safe:!0,willMutateWorktree:!1}),s&&n.push({operation:"push_submodules_ff_only",description:"For each submodule, if allowAutoPublishSubmoduleMainCommits is enabled and the submodule HEAD is a descendant of its origin main, ff-only push it to submodule origin main; otherwise skip.",safe:!0,willMutateWorktree:!1}),n.push({operation:"verify_post_status",description:"Re-read daemon-owned git status and report final branch convergence state.",safe:!0,willMutateWorktree:!1}),n):(n.push({operation:"verify_fast_forward",description:"Require ahead=0, behind>0, and HEAD to be an ancestor of the upstream ref.",safe:!0,willMutateWorktree:!1}),n.push({operation:"merge_ff_only",description:"Apply git merge --ff-only against the tracked upstream; no force, reset, rebase, push, or deploy.",safe:!0,willMutateWorktree:!0}),t&&n.push({operation:"submodule_update",description:"If the fast-forward changes gitlinks, run git submodule update --init --recursive and re-verify submodules.",safe:!0,willMutateWorktree:!0}),n.push({operation:"verify_post_status",description:"Re-read daemon-owned git status and report final branch convergence state.",safe:!0,willMutateWorktree:!1}),n)}function rL(e){const t=new Set(["branch_has_local_commits"]);return e.every(s=>t.has(s))}function nL(e,t){const s=[];return e.isGitRepo||s.push("not_git_repo"),e.branch||s.push("detached_head_or_unknown_branch"),t&&e.branch!==t&&s.push("branch_mismatch"),e.upstream||s.push("upstream_missing"),e.upstreamStatus!=="fresh"&&s.push("upstream_not_fresh"),e.hasConflicts&&s.push("conflicts_present"),e.staged>0&&s.push("staged_changes_present"),e.modified>0&&s.push("modified_changes_present"),e.untracked>0&&s.push("untracked_changes_present"),e.deleted>0&&s.push("deleted_changes_present"),e.renamed>0&&s.push("renamed_changes_present"),e.stashCount>0&&s.push("stash_entries_present"),s.push(...np(e,"pre")),e.ahead>0&&e.behind>0?(s.push("branch_diverged_from_upstream"),s.push("branch_has_local_commits")):e.ahead>0&&s.push("branch_has_local_commits"),s}function iL(e){const t=[];return e.isGitRepo||t.push("post_not_git_repo"),e.hasConflicts&&t.push("post_conflicts_present"),e.ahead!==0&&t.push("post_branch_ahead"),e.behind!==0&&t.push("post_branch_still_behind"),(e.staged>0||e.modified>0||e.untracked>0||e.deleted>0||e.renamed>0)&&t.push("post_working_tree_not_clean"),e.stashCount>0&&t.push("post_stash_entries_present"),t.push(...np(e,"post")),t}function np(e,t){const s=Array.isArray(e.submodules)?e.submodules:[],n=[];for(const i of s)i.error&&n.push(`${t}_submodule_status_error:${i.path}`),i.dirty&&n.push(`${t}_submodule_dirty:${i.path}`),i.outOfSync&&n.push(`${t}_submodule_out_of_sync:${i.path}`);return n}function aL(e,t){return t.includes("not_git_repo")?"not_git_repo":t.includes("branch_mismatch")?"branch_mismatch":t.includes("upstream_missing")?"upstream_missing":t.includes("upstream_not_fresh")?"upstream_not_fresh":t.some(s=>s.includes("submodule"))?"submodule_not_clean":t.includes("branch_diverged_from_upstream")?"branch_diverged":t.includes("branch_has_local_commits")||e.ahead>0?"branch_ahead":t.some(s=>s.includes("changes")||s.includes("conflicts")||s.includes("stash"))?"dirty_worktree":"preflight_blocked"}function v0(e){return e==="branch_diverged"||e==="branch_ahead"||e==="non_fast_forward"||e==="non_fast_forward_push"||e==="upstream_unparseable"?"not_mergeable":e==="dirty_worktree"||e==="submodule_not_clean"?"blocked_review":"blocked"}async function oL(e,t,s){if(!t)return{ok:!1,error:"missing upstream"};try{return await tt(e,["merge-base","--is-ancestor","HEAD",t],{timeoutMs:s??15e3}),{ok:!0}}catch(n){return{ok:!1,error:hr(n)}}}function lr(e,t,s){const n=lL(s);return{...e,success:!1,code:t,allowed:!1,willRun:!1,executed:!1,blockingReasons:n}}function lL(e){const t=new Set;for(const s of e)t.add(s);return["conflicts_present","staged_changes_present","modified_changes_present","untracked_changes_present","deleted_changes_present","renamed_changes_present"].some(s=>t.has(s))&&t.add("working_tree_not_clean"),Array.from(t)}function as(e,t){return{status:t,branch:e.branch,headCommit:e.headCommit,upstream:e.upstream,ahead:e.ahead,behind:e.behind,dirty:e.staged+e.modified+e.untracked+e.deleted+e.renamed>0||e.hasConflicts,stashCount:e.stashCount,submodules:cL(e.submodules)}}function cL(e){return(e||[]).map(t=>({path:t.path,commit:t.commit,dirty:t.dirty,outOfSync:t.outOfSync,...t.error?{error:t.error}:{}}))}function si(e){return typeof e=="string"&&e.trim()?e.trim():void 0}function hr(e){return e instanceof mt?e.stderr||e.stdout||e.message:e instanceof Error?e.message:String(e)}async function os(e,t){var s,n,i,a;if(e.meshId)try{const{appendLedgerEntry:o}=await Promise.resolve().then(()=>(fr(),jy));o(e.meshId,{kind:"direct_fast_forward",...e.nodeId?{nodeId:e.nodeId}:{},payload:{operation:"mesh_fast_forward_node",mode:e.mode,trigger:e.trigger||"manual",outcome:t,code:e.code,workspace:e.workspace,allowed:e.allowed,dryRun:e.dryRun,willRun:e.willRun,executed:e.executed,branch:((s=e.postStatus)==null?void 0:s.branch)??((n=e.current)==null?void 0:n.branch),upstream:((i=e.postStatus)==null?void 0:i.upstream)??((a=e.current)==null?void 0:a.upstream),...e.pushTarget?{pushTarget:e.pushTarget}:{},before:e.current?{headCommit:e.current.headCommit,ahead:e.current.ahead,behind:e.current.behind}:void 0,after:e.postStatus?{headCommit:e.postStatus.headCommit,ahead:e.postStatus.ahead,behind:e.postStatus.behind}:void 0,...e.submodulePushes?{submodulePushes:e.submodulePushes.map(l=>({path:l.path,commit:l.commit,pushed:l.pushed,skipped:l.skipped,code:l.code,...l.refspec?{refspec:l.refspec}:{}}))}:{},blockingReasons:e.blockingReasons}})}catch(o){e.ledgerError=o instanceof Error?o.message:String(o)}}var zs,ip=We({"src/mesh/mesh-fast-forward.ts"(){na(),ra(),zs={refreshUpstream:!0,includeSubmodules:!0,timeoutMs:15e3}}});function dL(...e){for(const t of e){if(typeof t!="string")continue;const s=t.trim();if(s)return s}}function w0(e){const t=e&&typeof e=="object"?e:{};return dL(t.id,t.nodeId,t.node_id)}function Al(e,t){if(!t)return!1;const s=t.trim();return s?w0(e)===s:!1}var da=We({"../mesh-shared/dist/index.mjs"(){}});function K(e){return typeof e=="string"&&e.trim()?e.trim():""}function Nt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Us(e,t){return K(e.targetSessionId)||K(e.sessionId)||K(e.instanceId)||K(t)}function gi(e){const t=Nt(e.metadataEvent)||e,s=Nt(t.result),n=Nt(s==null?void 0:s.refineJob);return K(t.jobId)||K(n==null?void 0:n.jobId)}function Cd(e){return Nt(e.workerResult)||Nt(e.meshWorkerResult)||Nt(e.structuredResult)}function uL(e){const t=e.completionDiagnostic&&typeof e.completionDiagnostic=="object"?e.completionDiagnostic:null,s=t?K(t.blockReason)||"present":"",n=typeof(t==null?void 0:t.finalAssistantPresent)=="boolean"?String(t.finalAssistantPresent):"",i=K(e.evidenceLevel),a=[K(e.targetSessionId)?`session_id=${K(e.targetSessionId)}`:"",K(e.providerType)?`provider=${K(e.providerType)}`:"",K(e.providerSessionId)?`provider_session_id=${K(e.providerSessionId)}`:"",s?`completion_diagnostic=${s}`:"",n?`final_assistant=${n}`:"",i&&i!=="sufficient"?`evidence_level=${i}`:""].filter(Boolean);return a.length>0?` (${a.join("; ")})`:""}function S0(e){const t=uL(e.metadataEvent);if(e.event==="agent:generating_completed"){if(e.metadataEvent.source==="long_generating_reconciliation")return`[System] ${e.nodeLabel} already has completion evidence${t}. The long-generating monitor reconciled the terminal handoff and marked the session complete; wait for the queued completion event/status refresh before doing any manual transcript check.`;const s=e.metadataEvent.reviewRecommended===!0?" Completion evidence is insufficient — verify via git status or provider_session_id before assuming the task is done. Use mesh_read_chat once if needed, but do not poll repeatedly.":" Use mesh_read_chat once to review its final progress, but do not poll repeatedly.";return`[System] ${e.nodeLabel} has completed its task and is now idle${t}. This completion came from the agent status event path;${s}`}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 s=e.recoveryContext;if(s&&s.consecutiveNodeFailures>0){const n=[`[System] ${e.nodeLabel} has stopped unexpectedly${t}.`,`
|
|
556
|
+
|
|
557
|
+
**Recovery Context:**`,`- Consecutive failures on this node: ${s.consecutiveNodeFailures}`,s.taskAttemptCount>0?`- This task has been attempted ${s.taskAttemptCount} time(s)`:"",`- Recommendation: ${s.advice}`];return s.retryRecommended&&s.lastTaskMessage?n.push(`
|
|
558
|
+
|
|
559
|
+
**Original task to retry:**`,`> ${s.lastTaskMessage.length>300?s.lastTaskMessage.slice(0,300)+"...":s.lastTaskMessage}`,"\nTo retry: call `mesh_launch_session` for this node, then `mesh_send_task` with the original task."):s.retryRecommended||n.push(`
|
|
560
|
+
Do NOT retry on this node. Consider reassigning to a different node or asking the user for guidance.`),n.filter(Boolean).join(`
|
|
561
|
+
`)}return`[System] ${e.nodeLabel} has stopped${t}. Use mesh_read_chat once if you need to inspect its last output.`}if(e.event==="monitor:long_generating")return`[System] ${e.nodeLabel} is still reported as generating after a long interval${t}. Wait for pendingCoordinatorEvents or a completion/status event; if the user explicitly asks for status, make one bounded status check and then wait again.`;if(e.event==="worktree_bootstrap_complete"){const s=K(e.metadataEvent.worktreePath),n=typeof e.metadataEvent.durationMs=="number"?e.metadataEvent.durationMs:void 0;return`[System] ${e.nodeLabel} worktree bootstrap completed${s?` at ${s}`:""}${n!==void 0?` in ${Math.round(n/1e3)}s`:""}. The worktree is ready — use \`mesh_launch_session\` to start an agent.`}if(e.event==="worktree_bootstrap_failed"){const s=K(e.metadataEvent.error);return`[System] ${e.nodeLabel} worktree bootstrap failed${s?`: ${s}`:"."}. Use \`mesh_retry_node_bootstrap\` to retry or inspect the node state.`}if(e.event==="refine:accepted"){const s=gi({metadataEvent:e.metadataEvent});return`[System] Refinery accepted async job${s?` ${s}`:""} for ${e.nodeLabel}. Completion/failure will be delivered as a terminal refine event; do not poll repeatedly.`}if(e.event==="refine:completed"){const s=gi({metadataEvent:e.metadataEvent}),n=Nt(e.metadataEvent.result),i=Nt(n==null?void 0:n.validationSummary),a=Nt(n==null?void 0:n.patchEquivalence),o=Nt(n==null?void 0:n.finalBranchConvergenceState),l=K(i==null?void 0:i.status),c=K(a==null?void 0:a.status)||((a==null?void 0:a.equivalent)===!0?"passed":""),d=K(n==null?void 0:n.into),p=K(n==null?void 0:n.branch),h=(n==null?void 0:n.merged)===!0?"merged":K(o==null?void 0:o.status),m=K(o==null?void 0:o.status),g=K(n==null?void 0:n.nextStep)||K(o==null?void 0:o.nextStep)||"Continue from the updated mesh state.",b=[s?`job_id=${s}`:"",p&&d?`${p}→${d}`:"",l?`validation=${l}`:"",c?`patch_equivalence=${c}`:"",h?`merge=${h}`:"",m?`final_convergence=${m}`:""].filter(Boolean).join("; ");return`[System] Refinery async job for ${e.nodeLabel} completed successfully${b?` (${b})`:""}.
|
|
562
|
+
Next step: ${g}`}if(e.event==="refine:failed"){const s=gi({metadataEvent:e.metadataEvent}),n=Nt(e.metadataEvent.result),i=Nt(n==null?void 0:n.validationSummary),a=Nt(n==null?void 0:n.patchEquivalence),o=Nt(n==null?void 0:n.finalBranchConvergenceState),l=K(n==null?void 0:n.code),c=K(n==null?void 0:n.error),d=K(i==null?void 0:i.status),p=K(a==null?void 0:a.status)||((a==null?void 0:a.equivalent)===!0?"passed":""),h=(n==null?void 0:n.merged)===!0?"merged":(o==null?void 0:o.merged)===!1?"not_merged":"",m=K(n==null?void 0:n.convergenceStatus)||K(o==null?void 0:o.status),g=K(n==null?void 0:n.blockedReason),b=K(n==null?void 0:n.nextStep)||K(o==null?void 0:o.nextStep),f=[s?`job_id=${s}`:"",l?`code=${l}`:"",d?`validation=${d}`:"",p?`patch_equivalence=${p}`:"",h?`merge=${h}`:"",m?`convergence=${m}`:"",g?`reason=${g}`:""].filter(Boolean).join("; ");return[`[System] Refinery async job for ${e.nodeLabel} failed${f?` (${f})`:""}${c?`: ${c}`:"."}`,b?`Next step: ${b}`:"Review the terminal refine event/ledger before retrying."].join(`
|
|
563
|
+
`)}return""}var Yr=We({"src/mesh/mesh-events-utils.ts"(){}});function ap(e){const t=Array.isArray(e)?e:e!=null?[e]:[],s=new Set,n=[];for(const i of t){if(typeof i!="string")continue;const a=i.trim();!a||s.has(a)||(s.add(a),n.push(a))}return n}function mr(e){const t=Nt(e.metadataEvent)||e,s=Nt(t.result),n=Nt(s==null?void 0:s.refineJob);return K(t.jobId)||K(n==null?void 0:n.jobId)}function pL(e){if(!Tl.has(e.event))return!1;const t=mr(e);return t?op(e.meshId).some(s=>s.event===e.event&&mr(s)===t):!1}function _n(e){var l;const t=Nt(e.metadataEvent)||{};if(e.event==="worktree_bootstrap_complete"||e.event==="worktree_bootstrap_failed")return[e.meshId,e.event,e.nodeId||""].join("::");const s=Us(t),n=K(t.providerSessionId),i=K(t.taskId)||K((l=Nt(t.payload))==null?void 0:l.taskId),a=mr(e),o=t.timestamp!==void 0&&t.timestamp!==null?String(t.timestamp):"";return[e.meshId,e.event,e.nodeId||"",s||"",n||"",i||"",a||"",o||""].join("::")}function hL(e){const t=_n(e);if(!t.trim())return!1;try{if(Pe.getInstance().hasPendingEventFingerprint(e.meshId,t))return!0}catch{}return op(e.meshId).some(s=>_n(s)===t)}function ps(e,t){const s=e.replace(/[^a-zA-Z0-9_-]/g,"_");if(t){const n=t.replace(/[^a-zA-Z0-9_-]/g,"_");return Dt(Bs(),`${s}-${n}.pending-events.jsonl`)}return Dt(Bs(),`${s}.pending-events.jsonl`)}function op(e,t){if(!e)return[];const s=ap(t),n=s[0],i=n?[ps(e,n),ps(e)]:[ps(e)],a=[];for(const o of i)if(st(o))try{const c=As(o,"utf-8").split(`
|
|
564
|
+
`).filter(Boolean).flatMap(p=>{try{return[JSON.parse(p)]}catch{return[]}}),d=n&&o===ps(e)?c.filter(p=>!p.targetCoordinatorDaemonId||s.includes(p.targetCoordinatorDaemonId)):c;a.push(...d)}catch{}return a}function mL(e,t){const s=new Set(t.filter(o=>o.event==="refine:accepted").map(o=>mr(o)).filter(Boolean));if(s.size===0)return[];const n=new Set(t.filter(o=>Tl.has(o.event)).map(o=>`${o.event}:${mr(o)}`).filter(o=>!o.endsWith(":"))),i=[],a=ms(e,{tail:200});for(let o=a.length-1;o>=0;o--){const l=a[o];if(l.kind!=="task_completed"&&l.kind!=="task_failed")continue;const c=Nt(l.payload);if((c==null?void 0:c.source)!=="refine_mesh_node_async_job")continue;const d=Nt(c.refineJob),p=K(d==null?void 0:d.jobId);if(!p||!s.has(p))continue;const h=l.kind==="task_completed"?"refine:completed":"refine:failed";if(n.has(`${h}:${p}`))continue;n.add(`${h}:${p}`);const m=Nt(c.result),g={source:"refine_mesh_node_async_job",jobId:p,interactionId:K(d==null?void 0:d.interactionId),meshId:e,nodeId:K(d==null?void 0:d.nodeId)||l.nodeId,targetDaemonId:K(d==null?void 0:d.targetDaemonId),workspace:K(d==null?void 0:d.workspace),status:h==="refine:completed"?"completed":"failed",startedAt:K(d==null?void 0:d.startedAt),completedAt:K(d==null?void 0:d.completedAt)||l.timestamp,retryOfJobId:K(d==null?void 0:d.retryOfJobId)||K(c.retryOfJobId),...m?{result:m}:{}},b=K(d==null?void 0:d.nodeId)||l.nodeId||"refine job";i.push({event:h,meshId:e,nodeLabel:b,nodeId:K(d==null?void 0:d.nodeId)||l.nodeId,workspace:K(d==null?void 0:d.workspace),metadataEvent:g,coordinatorMessage:S0({event:h,nodeLabel:b,metadataEvent:g}),queuedAt:Date.now()})}return i.reverse()}function k0(e,t){const s=mL(e,t),n=new Set([...t.filter(a=>Tl.has(a.event)),...s].map(a=>mr(a)).filter(Boolean)),i=n.size===0?t:t.filter(a=>!(a.event==="refine:accepted"&&n.has(mr(a))));return s.length===0?i:[...i,...s]}function fL(e){try{if(!st(e)||tl(e).size<=j0)return;const t=As(e,"utf-8").split(`
|
|
565
|
+
`).filter(Boolean);if(t.length<=Id)return;Ss(e,t.slice(-Id).join(`
|
|
566
|
+
`)+`
|
|
567
|
+
`,"utf-8")}catch{}}function lp(e){try{if(pL(e))return _e.info("MeshEvents",`Suppressed duplicate pending ${e.event} for refine job ${mr(e)}`),!0;if(hL(e))return _e.info("MeshEvents",`Suppressed duplicate pending ${e.event} for mesh ${e.meshId}`),!0;const t=_n(e);try{Pe.getInstance().insertPendingEvent({id:Ts(),meshId:e.meshId,coordinatorDaemonId:e.targetCoordinatorDaemonId??null,event:e.event,payload:e,fingerprint:t||null,queuedAt:e.queuedAt})}catch{}const s=ps(e.meshId,e.targetCoordinatorDaemonId);return fL(s),sl(s,JSON.stringify(e)+`
|
|
568
|
+
`,"utf-8"),!0}catch(t){return _e.warn("MeshEvents",`Failed to persist pending coordinator event: ${(t==null?void 0:t.message)||t}`),!1}}function gL(e){const t=`${e}.draining`;try{Lr(e,t)}catch{return null}try{const s=As(t,"utf-8");try{ki(t)}catch{}return s}catch{try{ki(t)}catch{}return null}}function xL(e,t){const s=`${e}.draining`;try{Lr(e,s)}catch{return[]}let n;try{n=As(s,"utf-8")}catch{try{ki(s)}catch{}return[]}const i=[],a=[];for(const o of n.split(`
|
|
569
|
+
`)){if(!o)continue;let l;try{l=JSON.parse(o)}catch{l=void 0}l&&t(l)?i.push(l):a.push(o)}try{a.length>0&&Ss(e,a.join(`
|
|
570
|
+
`)+`
|
|
571
|
+
`,"utf-8"),ki(s)}catch{try{st(s)&&!st(e)&&Lr(s,e)}catch{}return[]}return i}function cp(e,t,s){if(!e)return[];const n=ap(t),i=n[0],a=s==null?void 0:s.onlyEvents,o=h=>!a||a.has(h),l=[],c=new Set,d=h=>{const m=_n(h);if(m.trim()){if(c.has(m))return;c.add(m)}l.push(h)};try{const h=Pe.getInstance();if(h.pendingEventCount(e)>0)for(const m of h.drainPendingEvents(e,n.length>0?n:void 0,a?{onlyEvents:a}:void 0)){const g=m.payload;g&&d(g)}}catch{}const p=i?[ps(e,i),ps(e)]:[ps(e)];for(const h of p){const m=!!i&&h===ps(e),g=w=>!m||!w.targetCoordinatorDaemonId||n.includes(w.targetCoordinatorDaemonId);if(a){for(const w of xL(h,x=>g(x)&&o(x.event)))d(w);continue}const b=gL(h);if(!b)continue;const f=b.split(`
|
|
572
|
+
`).filter(Boolean).flatMap(w=>{try{return[JSON.parse(w)]}catch{return[]}}),v=m?f.filter(g):f;for(const w of v)d(w)}return l.length===0?[]:k0(e,l)}function bL(e,t){if(!e)return[];const s=ap(t),n=[],i=new Set,a=o=>{const l=_n(o);if(l.trim()){if(i.has(l))return;i.add(l)}n.push(o)};try{const o=Pe.getInstance();if(o.pendingEventCount(e)>0)for(const l of o.peekPendingEvents(e,s.length>0?s:void 0)){const c=l.payload;c&&a(c)}}catch{}for(const o of op(e,s))a(o);return k0(e,n)}function yL(e,t){if(!e)return;try{Pe.getInstance().clearPendingEventsForMesh(e)}catch{}const s=t?[ps(e,t),ps(e)]:[ps(e)];for(const n of s)if(st(n))try{ki(n)}catch{}}var Tl,j0,Id,ua=We({"src/mesh/mesh-events-pending.ts"(){Ve(),fr(),gr(),Yr(),Tl=new Set(["refine:completed","refine:failed"]),j0=100*1024,Id=50}});function Zm(e){const t=new Date().toISOString(),s=Ts(),n={id:s,meshId:e.meshId,nodeId:e.nodeId,sessionId:e.sessionId,providerType:e.providerType,taskId:e.taskId,kind:e.kind,priority:e.priority??0,message:e.message,status:e.status,deliverAfter:e.deliverAfter,expiresAt:e.expiresAt,attemptCount:0,sourceCoordinatorSessionId:e.sourceCoordinatorSessionId,sourceCoordinatorDaemonId:e.sourceCoordinatorDaemonId,createdAt:t,updatedAt:t};return Pe.getInstance().insertSessionDelivery({id:s,meshId:e.meshId,nodeId:e.nodeId,sessionId:e.sessionId,providerType:e.providerType,taskId:e.taskId,kind:e.kind,priority:e.priority??0,message:e.message,status:e.status,deliverAfter:e.deliverAfter,expiresAt:e.expiresAt,sourceCoordinatorSessionId:e.sourceCoordinatorSessionId,sourceCoordinatorDaemonId:e.sourceCoordinatorDaemonId,createdAt:t,updatedAt:t}),n}function ri(e,t,s){try{Pe.getInstance().updateSessionDeliveryStatus(e,t,s)}catch{}}function vL(e){try{Pe.getInstance().recordCompletionConflict({id:Ts(),meshId:e.meshId,fingerprint:e.fingerprint,conflictingTaskId:e.conflictingTaskId,conflictingSessionId:e.conflictingSessionId,originalTaskId:e.originalTaskId,originalSessionId:e.originalSessionId,event:e.event,createdAt:new Date().toISOString()})}catch{}}function N0(e,t,s){try{const n=Pe.getInstance().getActiveSessionDeliveries(e,t);for(const i of n)Pe.getInstance().updateSessionDeliveryStatus(i.id,s)}catch{}}var dp=We({"src/mesh/mesh-delivery-policy.ts"(){gr()}});function _0(e){if(!e.sessionId&&!e.nodeId)return null;const t=ms(e.meshId,{tail:200});for(let s=t.length-1;s>=0;s--){const n=t[s];if(!(n.kind!=="task_completed"&&n.kind!=="task_failed"&&n.kind!=="task_stalled")){if(e.sessionId&&n.sessionId===e.sessionId)return{id:n.id,kind:n.kind,payload:n.payload||{},timestamp:n.timestamp};if(!e.sessionId&&e.nodeId&&Al(n,e.nodeId))return{id:n.id,kind:n.kind,payload:n.payload||{},timestamp:n.timestamp}}}return null}function wL(e,t,s){const n=ms(e,{tail:200});let i=!1;for(const a of n){if(!i){a.id===s&&(i=!0);continue}if(a.kind==="task_dispatched"&&a.sessionId===t)return!0}return!1}function up(e,t){var n;const s=ms(e,{tail:200});for(let i=s.length-1;i>=0;i--){const a=s[i];if(a.sessionId===t){if(a.kind==="task_completed"||a.kind==="task_failed"||a.kind==="task_stalled")return!1;if(a.kind==="task_dispatched"&&((n=a.payload)==null?void 0:n.source)==="direct")return!0}}return!1}function SL(e){var s;const t=ms(e.meshId,{tail:500});for(let n=t.length-1;n>=0;n--){const i=t[n];if(!(i.kind!=="task_dispatched"||K((s=i.payload)==null?void 0:s.taskId)!==e.taskId)&&!(e.sessionId&&i.sessionId&&i.sessionId!==e.sessionId))return{id:i.id,timestamp:i.timestamp,nodeId:i.nodeId,sessionId:i.sessionId,providerType:i.providerType,payload:i.payload||{}}}return null}function kL(e){var i;const t=ms(e.meshId,{tail:500});let s=!e.dispatchEntryId&&!e.dispatchTimestamp;const n=e.dispatchTimestamp?new Date(e.dispatchTimestamp).getTime():Number.NaN;for(const a of t){if(!s){if(e.dispatchEntryId&&a.id===e.dispatchEntryId){s=!0;continue}if(!e.dispatchEntryId&&Number.isFinite(n)){const l=new Date(a.timestamp).getTime();Number.isFinite(l)&&l>=n&&(s=!0)}if(!s)continue}if(a.kind!=="task_completed"&&a.kind!=="task_failed"&&a.kind!=="task_stalled")continue;const o=K((i=a.payload)==null?void 0:i.taskId);if(o&&o===e.taskId)return!0;if(!(o&&o!==e.taskId)&&e.sessionId&&a.sessionId===e.sessionId)return!0}return!1}function jL(e){const t=K(e.finalSummary);if(!e.meshId||!e.taskId||!e.sessionId||!t)return{reconciled:!1,reason:"missing_required_completion_evidence"};const s=SL({meshId:e.meshId,taskId:e.taskId,sessionId:e.sessionId});if(kL({meshId:e.meshId,taskId:e.taskId,sessionId:e.sessionId,dispatchEntryId:s==null?void 0:s.id,dispatchTimestamp:s==null?void 0:s.timestamp}))return{reconciled:!1,alreadyTerminal:!0,reason:"terminal_ledger_entry_exists"};const n=K(e.nodeId)||(s==null?void 0:s.nodeId),i=K(e.providerType)||(s==null?void 0:s.providerType)||K(s==null?void 0:s.payload.providerType),a=e.completedAt||new Date().toISOString(),o=Oo({event:"agent:generating_completed",nodeId:n||"unknown",sessionId:e.sessionId,providerType:i,providerSessionId:K(e.providerSessionId),finalSummary:t,completedAt:a}),l=o.workerResult,c=s!=null&&s.timestamp?new Date(s.timestamp).getTime():Number.NaN,d=e.transcriptMessageAt?new Date(e.transcriptMessageAt).getTime():Number.NaN,p=Number.isFinite(c)&&Number.isFinite(d)&&d>=c;if(l.source!=="final_summary_json"&&!p)return{reconciled:!1,reason:"transcript_not_proven_after_dispatch"};const m=l.status==="failed"||l.status!=="completed"&&l.errors.length>0?"task_failed":"task_completed",g=ur(e.meshId,{kind:m,nodeId:n||void 0,sessionId:e.sessionId,providerType:i||void 0,payload:{event:"agent:generating_completed",source:e.source||"direct_task_transcript_reconciliation",taskId:e.taskId,providerSessionId:K(e.providerSessionId),finalSummary:t,workerResult:l,completionDiagnostic:{reason:"direct_task_transcript_reconciliation",dispatchEntryId:s==null?void 0:s.id,dispatchTimestamp:s==null?void 0:s.timestamp,transcriptMessageAt:K(e.transcriptMessageAt),transcriptFinalAssistantPresent:!0},evidence:o}});return Bo(e.meshId,e.sessionId,m==="task_completed"?"completed":"failed"),N0(e.meshId,e.sessionId,m==="task_completed"?"completed":"failed"),setImmediate(()=>Ju()),lp({event:m==="task_completed"?"agent:generating_completed":"agent:stopped",meshId:e.meshId,nodeLabel:n?`Node '${n}'`:"Remote agent",nodeId:n||void 0,metadataEvent:{targetSessionId:e.sessionId,providerType:i||void 0,providerSessionId:K(e.providerSessionId),finalSummary:t,taskId:e.taskId,workerResult:l,completionDiagnostic:{reason:"direct_task_transcript_reconciliation",terminalLedgerKind:m,terminalLedgerId:g.id}},coordinatorMessage:void 0,queuedAt:Date.now(),...K(e.targetCoordinatorDaemonId)?{targetCoordinatorDaemonId:K(e.targetCoordinatorDaemonId)}:{}}),{reconciled:!0,kind:m,workerResult:l,ledgerEntryId:g.id}}function NL(e){const t=Us(e.metadataEvent,e.sourceInstanceId),s=K(e.nodeId)||K(e.metadataEvent.meshNodeId),n=K(e.metadataEvent.providerType),i=K(e.metadataEvent.providerSessionId),a=Cd(e.metadataEvent),o=Nt(e.metadataEvent.completionDiagnostic),l=K(e.metadataEvent.finalSummary),c=K(e.metadataEvent.status).toLowerCase();if(!!(l||a||(o==null?void 0:o.finalAssistantPresent)===!0||c==="idle"||c==="ready"||c==="completed"))return{...e.metadataEvent,targetSessionId:t,providerType:n,providerSessionId:i,finalSummary:l,source:"long_generating_reconciliation",reconciledFromEvent:"monitor:long_generating",timestamp:e.metadataEvent.timestamp??Date.now(),completionDiagnostic:{...o||{},reconciliationReason:"provider_completion_evidence"}};const p=_0({meshId:e.meshId,sessionId:t||void 0,nodeId:s||void 0});return p?{...e.metadataEvent,source:"long_generating_terminal_ledger_suppression",terminalLedgerKind:p.kind,terminalLedgerAt:p.timestamp}:null}var pp=We({"src/mesh/mesh-events-stale.ts"(){fr(),Ys(),dp(),ua(),Yr(),da()}});function C0(e){return/^[a-zA-Z0-9_./:@%+=,-]+$/.test(e)?e:`"${e.replace(/(["\\$`])/g,"\\$1")}"`}function _L(e){const t=e.trim();return t.startsWith("~")?Ee.join(ot.homedir(),t.slice(1)):t}function CL(e){const t=e.trim();return Ee.isAbsolute(t)||t.includes("/")||t.includes("\\")||t.startsWith("~")}function I0(e){const t=e.trim();if(!t)return null;if(CL(t)){const s=_L(t),n=Ee.isAbsolute(s)?s:Ee.resolve(s);return st(n)?n:null}return null}function A0(e,t=5e3){return new Promise(s=>{el(e,{encoding:"utf-8",timeout:t,...process.platform==="win32"?{windowsHide:!0}:{}},(i,a)=>{i||!(a!=null&&a.trim())?s(null):s(a.trim())}).on("error",()=>s(null))})}async function IL(e,t){const n=ot.platform()==="win32"?"where":"which",i=(t==null?void 0:t.includeVersion)!==!1,a=e?e.getCliDetectionList():[];return await Promise.all(a.map(async l=>{try{const c=I0(l.command),d=c||await A0(`${n} ${C0(l.command)}`);if(!d)return{...l,installed:!1};const p=c||d.split(`
|
|
573
|
+
`)[0];return{...l,installed:!0,version:void 0,path:p}}catch{return{...l,installed:!1}}}))}async function AL(e,t,s){const n=t?t.resolveAlias(e):e;if(t){const o=t.getCliDetectionList().find(l=>l.id===n);if(o){const c=ot.platform()==="win32"?"where":"which";try{const d=I0(o.command),p=d||await A0(`${c} ${C0(o.command)}`);if(!p)return null;const h=d||p.split(`
|
|
574
|
+
`)[0];let m;return s==null||s.includeVersion,{...o,installed:!0,version:m,path:h}}catch{return null}}}return(await IL(t,s)).find(a=>a.id===n&&a.installed)||null}var pa=We({"src/detection/cli-detector.ts"(){}});function TL(e){return e!=null&&e.settings&&typeof e.settings=="object"?e.settings:{}}function ML(e,t,s){var j,y;const n=K(t);let i="",a="",o="";const l=N=>({isDelegate:!1,meshId:"",nodeId:o,nodeLabel:"",coordinatorDaemonId:a,workspace:i,sessionId:n,rejectionReason:N}),c=e.instanceManager.getInstance(t);if(!c||c.category!=="cli")return l("not_cli");const d=c.getState();if(i=K(d.workspace),!i)return l("no_workspace");const p=TL(d);a=K(p.meshCoordinatorDaemonId),o=K(p.meshNodeId);const h=K(p.meshCoordinatorFor);let m="";if(h){let N=!1;try{N=_l(h).some(_=>_.sessionId===t)||up(h,t)}catch{}if(!N)return l("coordinator_not_dispatch_target");m=h}const g=K(p.meshNodeFor)||m;if(!!!(g||p.launchedByCoordinator||a||K(p.meshCoordinatorNodeId)))return l("no_worker_envelope");const f=g?s.getMeshById(g):s.getMeshByWorkspace(i),v=g||K(f==null?void 0:f.id);if(!v)return l("mesh_unresolved");const x=(o?(j=f==null?void 0:f.nodes)==null?void 0:j.find(N=>Al(N,o)):void 0)||((y=f==null?void 0:f.nodes)==null?void 0:y.find(N=>N.workspace===i)),S=o||K(x==null?void 0:x.id),k=S?`Node '${S}'`:`Agent at ${i}`;return{isDelegate:!0,meshId:v,nodeId:S,nodeLabel:k,coordinatorDaemonId:a,workspace:i,sessionId:n}}function T0(e){return!e.isDelegate&&e.rejectionReason==="mesh_unresolved"}function EL(e,t){if(!T0(e))return!1;const s=`${e.sessionId}::${t}::${e.workspace}`,n=Date.now(),i=an.get(s);if(i!==void 0&&n-i<Ad)return!1;if(an.set(s,n),an.size>256)for(const[a,o]of an)n-o>=Ad&&an.delete(a);try{return ur(M0,{kind:"delivery_unroutable",sessionId:e.sessionId||void 0,payload:{event:t,reason:e.rejectionReason,workspace:e.workspace||void 0,coordinatorDaemonId:e.coordinatorDaemonId||void 0,detail:"Worker envelope was present but no mesh could be resolved; the event could not be routed to a coordinator."}}),_e.warn("MeshEvents",`delivery_unroutable: ${t} from session ${e.sessionId||"(unknown)"} at ${e.workspace||"(no workspace)"} — envelope present but mesh unresolved`),!0}catch(a){return _e.warn("MeshEvents",`Failed to record delivery_unroutable diagnostic: ${(a==null?void 0:a.message)||a}`),!1}}var M0,Ad,an,E0=We({"src/mesh/mesh-routing.ts"(){Ys(),pp(),fr(),Ve(),Yr(),da(),M0="__unroutable__",Ad=60*1e3,an=new Map}});function Ml(){try{return Pe.getInstance()}catch{return}}function RL(e,t,s){const n=K(e),i=K(t);if(!n||!i)return!1;const a=Ml();if(!a)return!1;const o=Date.now(),l={event:i,meshId:zo,nodeLabel:K(s.nodeId)||K(s.workspace)||"unresolved-delegate",nodeId:K(s.nodeId)||void 0,workspace:K(s.workspace)||void 0,metadataEvent:s},c=`${n}::${_n(l)}`;try{return a.insertPendingEvent({id:Ts(),meshId:zo,coordinatorDaemonId:n,event:i,payload:{forwardPayload:s,coordinatorDaemonId:n,queuedAt:o},fingerprint:c,queuedAt:o})&&_e.info("MeshEvents",`Durably queued unresolved-delegate ${i} for coordinator ${n} (outbox)`),!0}catch(d){return _e.warn("MeshEvents",`Failed to persist unresolved-delegate forward to outbox: ${(d==null?void 0:d.message)||d}`),!1}}function hp(){const e=Ml();if(!e)return[];let t;try{t=e.peekPendingEvents(zo)}catch{return[]}const s=[];for(const n of t){const i=n.payload&&typeof n.payload=="object"?n.payload:{},a=K(i.coordinatorDaemonId),o=i.forwardPayload&&typeof i.forwardPayload=="object"?i.forwardPayload:void 0;if(!a||!o)continue;const l=typeof i.queuedAt=="number"?i.queuedAt:0;s.push({id:n.id,coordinatorDaemonId:a,payload:o,queuedAt:l})}return s}function R0(e){const t=Ml();if(t)try{t.markPendingEventsDrainedById([e])}catch{}}function PL(e=Date.now()){const s=hp().filter(i=>i.queuedAt>0&&e-i.queuedAt>=Td).map(i=>i.id);if(s.length===0)return 0;const n=Ml();if(!n)return 0;try{const i=n.deletePendingEventsById(s);return i>0&&_e.warn("MeshEvents",`Expired ${i} unresolved-delegate forward(s) after ${Math.round(Td/6e4)}m of failed retries — coordinator unreachable, completion dropped`),i}catch{return 0}}var zo,Td,P0=We({"src/mesh/mesh-unresolved-forward-outbox.ts"(){Ve(),gr(),ua(),Yr(),zo="__unresolved_forward_outbox__",Td=30*60*1e3}});function DL(e){const t=new Set,s=K(e.statusInstanceId);s&&t.add(s);const n=K(Xs().machineId);return n&&t.add(n),[...t]}function D0(e){const t=Date.now(),s=Go.get(e);if(s&&t-s.cachedAt<G0)return s.mesh;const n=gy(e);return Go.set(e,{mesh:n,cachedAt:t}),n}function LL(){qo.clear()}function $L(){Go.clear()}function OL(){try{Pe.getInstance().pruneExpiredRemoteIdleSessions()}catch{}}function El(e,t){var n;const s=En(t);return s||((n=e.router)==null?void 0:n.getCachedInlineMesh(t))}function FL(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 BL(e,t,s){if(!t&&!s)return!1;const n=Date.now()-V0,i=ms(e,{tail:200});for(let a=i.length-1;a>=0;a--){const o=i[a],l=new Date(o.timestamp).getTime();if(!Number.isNaN(l)&&l<n)break;if(Pi(o)&&(t&&o.sessionId===t||!t&&s&&Al(o,s)))return!0}return!1}function WL(e){return e.event!=="agent:stopped"&&e.event!=="monitor:long_generating"?!1:FL(e.metadataEvent)?!0:BL(e.meshId,e.sessionId,e.nodeId)}function mp(e){try{return Pe.getInstance().hasCompletionFingerprint(e)}catch{return!1}}function fp(e){try{const t=Pe.getInstance();t.recordCompletionFingerprint(e,X0),t.sweepExpiredFingerprints()}catch{}}function UL(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()){const t=Number(e);if(Number.isFinite(t))return t;const s=Date.parse(e);if(Number.isFinite(s))return s}return null}function HL(e){const t=Number.isFinite(e.timestamp)?String(e.timestamp):K(e.finalSummary).slice(0,200);return[e.meshId,e.event,e.sessionId,e.providerType||"",e.providerSessionId||"",t,e.coordinatorDaemonId||""].join("::")}function ef(e){const t=HL(e);return t?mp(t)?(e.taskId&&vL({meshId:e.meshId,fingerprint:t,conflictingTaskId:e.taskId,conflictingSessionId:e.sessionId,event:e.event}),!0):(fp(t),!1):!1}function zL(e){const t=Array.isArray(e.modalButtons)?e.modalButtons.map(i=>String(i).trim()).filter(Boolean):[],s=Number.isFinite(e.timestamp)?String(e.timestamp):JSON.stringify({message:e.modalMessage||"",buttons:t});if(!s||s==='{"message":"","buttons":[]}')return!1;const n=[e.meshId,"agent:waiting_approval",e.sessionId,e.providerType||"",s].join("::");return mp(n)?!0:(fp(n),!1)}function KL(e,t,s){const n=gi({metadataEvent:s}),i=n&&new Set(["refine:completed","refine:failed"]).has(t)?`${e}::${t}::${n}`:"";return i?mp(i)?!0:(fp(i),!1):!1}function ha(e,t,s,n,i){const a=El(e,t),o=a==null?void 0:a.nodes.find(h=>xi(h)===s),l=la(o,i),c=Wb(o==null?void 0:o.policy,i),d=zy(t,s,n,l,{providerType:i,...c!==void 0?{providerMaxParallel:c}:{}});if(!d)return!1;if(_e.info("MeshQueue",`Node ${s} (${n}) pulled task ${d.id}`),o!=null&&o.daemonId&&e.dispatchMeshCommand&&!e.cliManager.adapters.has(n)){const m=Zm({meshId:t,nodeId:s,sessionId:n,providerType:i,taskId:d.id,kind:"task",message:d.message,status:"delivering"}),g=K(Xs().machineId)||void 0;return e.dispatchMeshCommand(o.daemonId,"agent_command",{targetSessionId:n,cliType:i,action:"send_chat",message:d.message,meshContext:{meshId:t,nodeId:s,taskId:d.id,...g?{coordinatorDaemonId:g}:{}}}).then(()=>{ri(m.id,"delivered")}).catch(b=>{_e.error("MeshQueue",`Failed to dispatch task via P2P to remote node ${s}: ${b==null?void 0:b.message}`),ri(m.id,"failed",{lastError:b==null?void 0:b.message,incrementAttempt:!0}),kd(t,d.id,"pending");try{ur(t,{kind:"dispatch_failed",nodeId:s,sessionId:n,payload:{taskId:d.id,deliveryId:m.id,error:b==null?void 0:b.message,retryable:!0}})}catch{}}),!0}try{const h=e.instanceManager.getInstance(n);if(h&&typeof h.updateSettings=="function"){const m=K(Xs().machineId);h.updateSettings({meshNodeFor:t,meshNodeId:s,launchedByCoordinator:!0,autoApprove:Wu(a==null?void 0:a.policy,o==null?void 0:o.policy),...m?{meshCoordinatorDaemonId:m}:{}})}}catch{}const p=Zm({meshId:t,nodeId:s,sessionId:n,providerType:i,taskId:d.id,kind:"task",message:d.message,status:"delivering"});return e.cliManager.handleCliCommand("agent_command",{targetSessionId:n,cliType:i,action:"send_chat",message:d.message}).then(()=>{ri(p.id,"delivered")}).catch(h=>{_e.error("MeshQueue",`Failed to dispatch task locally to node ${s}: ${h==null?void 0:h.message}`),ri(p.id,"failed",{lastError:h==null?void 0:h.message,incrementAttempt:!0}),kd(t,d.id,"failed")}),!0}function tf(){const e=Date.now();for(const[t,s]of nr)e>=s&&nr.delete(t)}function L0(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e.providerPriority:void 0;if(!Array.isArray(t))return[];const s=new Set;return t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean).filter(n=>s.has(n)?!1:(s.add(n),!0))}function gp(e){return["stopped","failed","terminated","exited","closed"].includes(e)}function $0(e){var s;const t=K(e==null?void 0:e.status).toLowerCase();return gp(t)?!1:t==="idle"||((s=e==null?void 0:e.activeChat)==null?void 0:s.status)==="waiting_input"}function GL(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 qL(e){var n;const t=(n=e==null?void 0:e.policy)!=null&&n.autoFastForward&&typeof e.policy.autoFastForward=="object"&&!Array.isArray(e.policy.autoFastForward)?e.policy.autoFastForward:{},s=Number(t.maxBehind);return{enabled:t.enabled!==!1,...Number.isFinite(s)&&s>=0?{maxBehind:Math.floor(s)}:{},requireCleanSubmodules:t.requireCleanSubmodules!==!1}}function VL(e){var i;const t=K(e==null?void 0:e.status).toLowerCase(),s=K((i=e==null?void 0:e.activeChat)==null?void 0:i.status).toLowerCase(),n=new Set(["generating","streaming","long_generating","working","starting","waiting_approval"]);return n.has(t)||n.has(s)}function XL(e,t,s,n){return O0(t,s)?!0:e.instanceManager.getByCategory("cli").some(i=>{const a=i.getState(),o=a.settings||{};if(K(o.meshNodeFor)!==t||(K(o.meshNodeId)||K(o.nodeId))!==s)return!1;const c=K(a.instanceId);return n&&c===n&&$0(a)?!1:VL(a)})}function YL(e){if(!e||e.status==="disabled"||e.status==="removed")return!1;const t=K(e.health).toLowerCase();return t?t==="online"||t==="unknown":!0}function QL(e){const t=K(e==null?void 0:e.daemonId),s=K(e==null?void 0:e.machineId),n=Xs(),i=K(n.machineId)||K(n.registeredMachineId),a=i?`daemon_${i}`:"",o=i?`standalone_${i}`:"",l=!t||t===a||t===o,c=!s||i&&s===i;return(e==null?void 0:e.isLocalWorktree)===!0||t||s?l&&c?null:"remote_auto_launch_unsupported":null}function JL(e){return fs(e,{status:["assigned"]}).filter(t=>t.taskMode!=="live_debug_readonly").length}function ZL(e){return fs(e,{status:["assigned"]}).filter(t=>t.taskMode==="live_debug_readonly").length}function O0(e,t){return fs(e,{status:["assigned"]}).some(s=>s.assignedNodeId===t)}function Ko(e,t){return Pe.getInstance().nodeActiveAssignmentCount(e,t)}function F0(e){var t;return Bb((t=e==null?void 0:e.policy)==null?void 0:t.schedulingStrategy)}function B0(e,t,s,n){if(t==="first_eligible"||s.length<=1)return s;const i=l=>{var c;return xd((c=l.node)==null?void 0:c.policy)};let a=0;t==="round_robin"&&(a=((n!=null&&n.bumpCursor?Pe.getInstance().bumpSchedulerCursor(e):Pe.getInstance().getSchedulerCursor(e))%s.length+s.length)%s.length);const o=l=>(l-a+s.length)%s.length;return[...s].sort((l,c)=>{const d=i(c)-i(l);if(d!==0)return d;if(t==="least_loaded"||t==="round_robin"){const p=Ko(e,l.nodeId)-Ko(e,c.nodeId);if(p!==0)return p}return o(l.index)-o(c.index)})}function e5(e,t,s){return fs(e,{status:["assigned"]}).filter(n=>n.assignedNodeId===t&&n.assignedProviderType===s).length}function t5(e,t){if(fs(e,{status:["assigned"]}).some(s=>s.assignedSessionId===t))return!0;try{if(_l(e).some(s=>s.sessionId===t)||up(e,t))return!0}catch{}return!1}function s5(e,t,s){return e.instanceManager.getByCategory("cli").filter(n=>{const i=n.getState(),a=i.settings||{};if(K(a.meshNodeFor)!==t||(K(a.meshNodeId)||K(a.nodeId))!==s)return!1;const l=K(i.status).toLowerCase();return!gp(l)}).length}function r5(e,t){try{ur(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(s){_e.warn("MeshQueue",`Failed to record auto-launch ledger event: ${(s==null?void 0:s.message)||s}`)}}function zt(e,t,s){Ky(e,t,{status:s.status,reason:s.reason||s.error,nodeId:s.nodeId,providerType:s.providerType,sessionId:s.sessionId}),r5(e,{phase:s.status,taskId:t,nodeId:s.nodeId,providerType:s.providerType,sessionId:s.sessionId,reason:s.reason,error:s.error})}async function n5(e,t,s,n){var l;const i=L0(s==null?void 0:s.policy);if(!i.length)return{reason:"missing_provider_priority"};const a=e.providerLoader;if(!a)return{reason:"provider_loader_unavailable"};const o=[];for(const c of i){const d=typeof a.resolveAlias=="function"?a.resolveAlias(c):c;if(n!=null&&n.length&&!jl(n,la(s,d))){o.push(`${c}: required_tags_mismatch`);continue}if(typeof a.isMachineProviderEnabled=="function"&&!a.isMachineProviderEnabled(d)){o.push(`${c}: disabled`);continue}let p;try{p=await AL(d,a,{includeVersion:!1})}catch(h){o.push(`${c}: detect failed: ${(h==null?void 0:h.message)||h}`);continue}if(typeof a.setCliDetectionResults=="function"&&a.setCliDetectionResults([{id:d,installed:!!p,path:p==null?void 0:p.path}],!1),(l=e.onStatusChange)==null||l.call(e),p)return{providerType:d};o.push(`${c}: not detected`)}return{reason:`provider_priority_unusable: ${o.join("; ")||t}`}}function xi(e){return w0(e)??""}async function i5(e,t,s){var l,c,d;const i=fs(t).filter(p=>p.status==="pending");if(!i.length)return!1;const a=Math.max(1,Math.floor(Number((l=s==null?void 0:s.policy)==null?void 0:l.maxParallelTasks)||2)),o=Math.max(2,a*2);for(const p of i){if(p.taskMode==="live_debug_readonly"){if(ZL(t)>=o){zt(t,p.id,{status:"skipped",reason:"max_readonly_parallel_tasks_reached"});continue}}else if(JL(t)>=a){zt(t,p.id,{status:"skipped",reason:"max_parallel_tasks_reached"});continue}if(p.targetSessionId){zt(t,p.id,{status:"skipped",reason:"target_session_constraint"});continue}const m=Array.isArray(s==null?void 0:s.nodes)?s.nodes.filter(f=>{var v;if(p.targetNodeId&&xi(f)!==p.targetNodeId)return!1;if((v=p.requiredTags)!=null&&v.length){const w=L0(f==null?void 0:f.policy);return(w.length?w:[void 0]).some(S=>jl(p.requiredTags,la(f,S)))}return!0}):[];if(!m.length){zt(t,p.id,{status:"skipped",reason:"no_node_satisfies_required_tags",nodeId:p.targetNodeId});continue}const g=F0(s),b=g==="first_eligible"?m:B0(t,g,m.map((f,v)=>({nodeId:xi(f),node:f,index:v})).filter(f=>f.nodeId),{bumpCursor:!0}).map(f=>f.node);for(const f of b){const v=xi(f);if(!v)continue;const w=`${t}:${v}`,x=Date.now(),S=nr.get(w)||0;if(S>0&&x>=S&&nr.delete(w),uo.has(w)){zt(t,p.id,{status:"skipped",reason:"auto_launch_in_progress",nodeId:v});continue}if(x<S){zt(t,p.id,{status:"skipped",reason:"auto_launch_cooldown",nodeId:v});continue}if(GL(f)){zt(t,p.id,{status:"skipped",reason:"dirty_workspace",nodeId:v});continue}if(!YL(f)){zt(t,p.id,{status:"skipped",reason:"node_not_launch_ready",nodeId:v});continue}const k=QL(f);if(k){zt(t,p.id,{status:"skipped",reason:k,nodeId:v});continue}if(p.taskMode!=="live_debug_readonly"&&O0(t,v)){zt(t,p.id,{status:"skipped",reason:"node_has_active_assignment",nodeId:v});continue}const j=Number((c=f==null?void 0:f.policy)==null?void 0:c.maxConcurrentSessions);if(Number.isFinite(j)&&j>=0&&s5(e,t,v)>=j){zt(t,p.id,{status:"skipped",reason:"max_concurrent_sessions_reached",nodeId:v});continue}uo.add(w);try{const y=await n5(e,v,f,p.requiredTags);if(!y.providerType){zt(t,p.id,{status:"skipped",reason:y.reason||"provider_unusable",nodeId:v});continue}const N=Wb(f==null?void 0:f.policy,y.providerType);if(N!==void 0&&e5(t,v,y.providerType)>=N){zt(t,p.id,{status:"skipped",reason:"max_provider_parallel_reached",nodeId:v,providerType:y.providerType});continue}zt(t,p.id,{status:"started",nodeId:v,providerType:y.providerType});const _=await e.cliManager.handleCliCommand("launch_cli",{cliType:y.providerType,dir:f.workspace,settings:{role:"worker",meshNodeFor:t,meshNodeId:v,spawnedSessionVisibility:((d=s==null?void 0:s.policy)==null?void 0:d.spawnedSessionVisibility)||"hidden",autoApprove:Wu(s==null?void 0:s.policy,f==null?void 0:f.policy),launchedByCoordinator:!0,autoLaunchedForQueueTaskId:p.id}});if(!(_!=null&&_.success)){const D=(_==null?void 0:_.error)||"launch_cli_failed";return zt(t,p.id,{status:"failed",reason:D,nodeId:v,providerType:y.providerType}),nr.set(w,Date.now()+po),tf(),!1}const C=K(_.sessionId)||K(_.id)||K(_.runtimeSessionId);return C?(zt(t,p.id,{status:"completed",nodeId:v,providerType:y.providerType,sessionId:C}),ha(e,t,v,C,y.providerType),!0):(zt(t,p.id,{status:"failed",reason:"launch_missing_session_id",nodeId:v,providerType:y.providerType}),nr.set(w,Date.now()+po),tf(),!1)}catch(y){return zt(t,p.id,{status:"failed",error:(y==null?void 0:y.message)||String(y),nodeId:v}),nr.set(w,Date.now()+po),!1}finally{uo.delete(w)}}}return!1}function sf(e,t){return fs(e,{status:[t]}).length}function a5(e){return new Map(fs(e).map(t=>[t.id,t.status]))}async function W0(e,t){const s=El(e,t),n=sf(t,"pending"),i=sf(t,"assigned"),a=a5(t),o=[];let l=0,c=0,d=!1;if(!s)return{success:!0,meshId:t,pendingBefore:n,assignedBefore:i,pendingAfter:n,assignedAfter:i,claimed:!1,newlyAssignedTasks:[],localIdleSessionsChecked:l,remoteIdleSessionsChecked:c,skippedSessions:[{reason:"mesh_not_found"}],autoLaunchStarted:d,noIdleMeshSessionAvailable:!0};const p=F0(s),h=[],m=e.instanceManager.getByCategory("cli");for(const k of m){const j=k.getState(),y=j.settings||{};if(K(y.meshNodeFor)!==t)continue;const _=K(y.meshNodeId)||K(y.nodeId);if(!_)continue;if(!$0(j)){const T=K(j.status).toLowerCase();o.push({nodeId:_,sessionId:K(j.instanceId),reason:gp(T)?"terminal_session":"session_not_idle",status:T||void 0});continue}const C=j.instanceId,D=j.type||K(y.providerType);D?(l+=1,h.push({nodeId:_,sessionId:C,providerType:D,origin:"local",node:s.nodes.find(T=>xi(T)===_)})):o.push({nodeId:_,sessionId:C,reason:"provider_type_missing"})}let g=[];try{g=Pe.getInstance().getRemoteIdleSessions()}catch{}const b=[];for(const k of g){const j=s.nodes.find(y=>y.id===k.nodeId);j&&(c+=1,b.push({nodeId:k.nodeId,sessionId:k.sessionId,providerType:k.providerType,origin:"remote",node:j}))}const f=k=>{if(ha(e,t,k.nodeId,k.sessionId,k.providerType)&&k.origin==="remote")try{Pe.getInstance().deleteRemoteIdleSession(k.nodeId,k.sessionId)}catch{}};if(p==="first_eligible"){for(const k of h)f(k);for(const k of b)f(k)}else{const k=[...h,...b],j=new Map;k.forEach((D,T)=>{j.has(D.nodeId)||j.set(D.nodeId,T)});const y=[...new Set(k.map(D=>D.nodeId))].map((D,T)=>{var A;return{nodeId:D,node:(A=k.find(P=>P.nodeId===D))==null?void 0:A.node,index:T}}),N=B0(t,p,y,{bumpCursor:!0}),_=new Map(N.map((D,T)=>[D.nodeId,T])),C=[...k];for(;C.length>0;)C.sort((D,T)=>{var F,J;const A=xd((F=D.node)==null?void 0:F.policy),P=xd((J=T.node)==null?void 0:J.policy);if(A!==P)return P-A;if(p==="least_loaded"||p==="round_robin"){const R=Ko(t,D.nodeId)-Ko(t,T.nodeId);if(R!==0)return R}return(_.get(D.nodeId)??0)-(_.get(T.nodeId)??0)}),f(C.shift())}d=await i5(e,t,s);const v=fs(t),w=v.filter(k=>k.status==="pending").length,x=v.filter(k=>k.status==="assigned").length,S=v.filter(k=>k.status==="assigned"&&a.get(k.id)!=="assigned").map(k=>({id:k.id,nodeId:k.assignedNodeId,sessionId:k.assignedSessionId}));return{success:!0,meshId:t,pendingBefore:n,assignedBefore:i,pendingAfter:w,assignedAfter:x,claimed:S.length>0,newlyAssignedTasks:S,localIdleSessionsChecked:l,remoteIdleSessionsChecked:c,skippedSessions:o,autoLaunchStarted:d,...w>0&&S.length===0&&l===0&&c===0&&!d?{noIdleMeshSessionAvailable:!0}:{}}}async function U0(e,t){var p,h,m,g;const s=El(e,t.meshId),n=(p=s==null?void 0:s.nodes)==null?void 0:p.find(b=>Al(b,t.nodeId)),i=K(n==null?void 0:n.workspace);if(!i||!st(i))return;const a=qL(s);if(!a.enabled||XL(e,t.meshId,t.nodeId,t.sessionId))return;const o=`${t.meshId}:${t.nodeId}`,l=Date.now(),c=qo.get(o)||0;if(l-c<q0)return;qo.set(o,l);const d=Array.isArray((h=n==null?void 0:n.policy)==null?void 0:h.submoduleIgnorePaths)?n.policy.submoduleIgnorePaths.filter(b=>typeof b=="string"):void 0;try{const b=await Jm({meshId:t.meshId,nodeId:t.nodeId,workspace:i,execute:!1,dryRun:!0,updateSubmodules:!1,submoduleIgnorePaths:d,trigger:"idle_auto"});if(!b||b.code!=="fast_forward_available"||b.allowed!==!0)return;const f=Number((m=b.current)==null?void 0:m.behind);if(a.maxBehind!==void 0&&Number.isFinite(f)&&f>a.maxBehind||a.requireCleanSubmodules&&(Array.isArray((g=b.current)==null?void 0:g.submodules)?b.current.submodules:[]).some(w=>(w==null?void 0:w.dirty)||(w==null?void 0:w.outOfSync)||(w==null?void 0:w.error)))return;await Jm({meshId:t.meshId,nodeId:t.nodeId,workspace:i,execute:!0,dryRun:!1,updateSubmodules:!1,submoduleIgnorePaths:d,trigger:"idle_auto"})}catch(b){_e.warn("MeshFastForward",`Idle auto fast-forward check failed for ${t.nodeId}: ${(b==null?void 0:b.message)||b}`)}}function o5(e,t){setImmediate(()=>{U0(e,t).finally(()=>{try{ha(e,t.meshId,t.nodeId,t.sessionId,t.providerType)}catch(s){_e.warn("MeshQueue",`Failed to assign idle queue task after maintenance for ${t.nodeId}: ${(s==null?void 0:s.message)||s}`)}})})}function xp(e){return typeof e=="string"&&Y0.has(e)}function H0(e){return typeof e=="string"&&yp.has(e)}function bp(e,t){var b,f,v,w;const s=Us(t.metadataEvent,t.sourceInstanceId),n=K(t.nodeId)||K(t.metadataEvent.meshNodeId),i=t.sourceInstanceId?e.instanceManager.getInstance(t.sourceInstanceId):void 0,a=K((f=(b=i==null?void 0:i.getState())==null?void 0:b.settings)==null?void 0:f.meshCoordinatorDaemonId);if(e.onMeshCoordinatorEventForwarded)try{e.onMeshCoordinatorEventForwarded({event:t.event,meshId:t.meshId,nodeId:n||void 0,...t.metadataEvent})}catch{}if(WL({event:t.event,meshId:t.meshId,metadataEvent:t.metadataEvent,sessionId:s||void 0,nodeId:n||void 0})){if(s&&n)try{Pe.getInstance().deleteRemoteIdleSession(n,s)}catch{}return _e.info("MeshEvents",`Suppressed ${t.event} for intentionally cleanup-stopped session ${s||"(unknown session)"}`),{success:!0,forwarded:0,suppressed:!0,intentionalCleanupStop:!0}}if(t.event==="monitor:long_generating"){const x=NL({meshId:t.meshId,nodeId:t.nodeId,nodeLabel:t.nodeLabel,metadataEvent:t.metadataEvent,sourceInstanceId:t.sourceInstanceId});if((x==null?void 0:x.source)==="long_generating_reconciliation")return _e.info("MeshEvents",`Reconciled long-generating monitor to completion for session ${s||"(unknown session)"}`),bp(e,{...t,event:"agent:generating_completed",metadataEvent:x});if((x==null?void 0:x.source)==="long_generating_terminal_ledger_suppression")return _e.info("MeshEvents",`Suppressed long-generating monitor because terminal ledger evidence already exists for session ${s||"(unknown session)"}`),{success:!0,forwarded:0,suppressed:!0,terminalLedgerEvidence:!0,terminalLedgerKind:x.terminalLedgerKind}}if(KL(t.meshId,t.event,t.metadataEvent))return _e.info("MeshEvents",`Suppressed duplicate ${t.event} for refine job ${gi({metadataEvent:t.metadataEvent})}`),{success:!0,forwarded:0,suppressed:!0,duplicateRefineTerminalEvent:!0};const l=UL(t.metadataEvent.timestamp);if(t.event==="agent:waiting_approval"&&s&&zL({meshId:t.meshId,sessionId:s,providerType:K(t.metadataEvent.providerType)||void 0,timestamp:l,modalMessage:K(t.metadataEvent.modalMessage)||void 0,modalButtons:t.metadataEvent.modalButtons}))return _e.info("MeshEvents",`Suppressed duplicate approval event for mesh ${t.meshId} session ${s}`),{success:!0,forwarded:0,suppressed:!0,duplicateApproval:!0};if(t.event==="agent:generating_completed"&&s){const x=_0({meshId:t.meshId,sessionId:s,nodeId:n||void 0});if((x==null?void 0:x.kind)==="task_completed"&&!t5(t.meshId,s)&&!wL(t.meshId,s,x.id)){const j=K(x.payload.providerSessionId),y=K(x.payload.finalSummary),N=K(t.metadataEvent.providerSessionId),_=K(t.metadataEvent.finalSummary);if(j&&j===N||y&&y===_||t.metadataEvent.source==="long_generating_reconciliation")return _e.info("MeshEvents",`Suppressed duplicate completion with existing terminal ledger evidence for mesh ${t.meshId} session ${s}`),{success:!0,forwarded:0,suppressed:!0,duplicateCompletion:!0,terminalLedgerEvidence:!0}}if(ef({meshId:t.meshId,event:t.event,sessionId:s,providerType:K(t.metadataEvent.providerType)||void 0,providerSessionId:K(t.metadataEvent.providerSessionId)||void 0,timestamp:l,finalSummary:K(t.metadataEvent.finalSummary)||void 0,coordinatorDaemonId:a||void 0,taskId:K(t.metadataEvent.taskId)||void 0}))return _e.info("MeshEvents",`Suppressed duplicate completion for mesh ${t.meshId} session ${s}`),{success:!0,forwarded:0,suppressed:!0,duplicateCompletion:!0}}if(t.event==="agent:stopped"&&s&&ef({meshId:t.meshId,event:t.event,sessionId:s,providerType:K(t.metadataEvent.providerType)||void 0,providerSessionId:K(t.metadataEvent.providerSessionId)||void 0,timestamp:l,finalSummary:K(t.metadataEvent.finalSummary)||void 0,coordinatorDaemonId:a||void 0,taskId:K(t.metadataEvent.taskId)||void 0}))return _e.info("MeshEvents",`Suppressed duplicate stopped event for mesh ${t.meshId} session ${s}`),{success:!0,forwarded:0,suppressed:!0,duplicateStopped:!0};function c(x,S,k){const j=Gy(t.meshId,x,S,{occurredAt:k!=null?new Date(k).toISOString():void 0});return Bo(t.meshId,x,S),N0(t.meshId,x,S),setImmediate(()=>Ju()),j?{id:j.id}:null}let d=null;if(t.event==="agent:generating_completed"){const x=Us(t.metadataEvent,t.sourceInstanceId),S=K(t.nodeId)||K(t.metadataEvent.meshNodeId),k=K(t.metadataEvent.providerType);if(x){d=c(x,"completed",l),S&&k&&o5(e,{meshId:t.meshId,nodeId:S,sessionId:x,providerType:k});const j=d==null?void 0:d.id;j&&qy(t.meshId,j)&&setImmediate(()=>{W0(e,t.meshId).catch(y=>{_e.warn("MeshQueue",`Dependent wake after task ${j} failed: ${(y==null?void 0:y.message)||y}`)})})}}else if(t.event==="agent:ready"){const x=Us(t.metadataEvent,t.sourceInstanceId),S=K(t.nodeId)||K(t.metadataEvent.meshNodeId),k=K(t.metadataEvent.providerType),j=K(t.metadataEvent.providerSessionId)||void 0,y=K(t.metadataEvent.finalSummary)||void 0,N=Cd(t.metadataEvent);if(x&&(!!y||!!N)&&(d=c(x,"completed"),d))try{ur(t.meshId,{kind:"task_completed",nodeId:S||void 0,sessionId:x,providerType:k||void 0,payload:{event:t.event,nodeLabel:t.nodeLabel,taskId:d.id,completedViaReady:!0,providerSessionId:j,finalSummary:y,workerResult:N,evidence:Oo({event:"agent:ready",nodeId:S,sessionId:x,providerType:k||void 0,providerSessionId:j,finalSummary:y,workerResult:N})}})}catch(C){_e.warn("MeshLedger",`Failed to record task_completed from ready: ${(C==null?void 0:C.message)||C}`)}if(x&&S&&k){OL();try{Pe.getInstance().setRemoteIdleSession(S,x,k,Date.now()+K0)}catch{}setImmediate(()=>{U0(e,{meshId:t.meshId,nodeId:S,sessionId:x,providerType:k}).finally(()=>{try{ha(e,t.meshId,S,x,k)&&Pe.getInstance().deleteRemoteIdleSession(S,x)}catch(C){_e.warn("MeshQueue",`Failed to assign idle queue task after maintenance for ${S}: ${(C==null?void 0:C.message)||C}`)}})})}}else if(t.event==="agent:generating_started"){const x=Us(t.metadataEvent,t.sourceInstanceId),S=K(t.nodeId)||K(t.metadataEvent.meshNodeId);if(x&&S)try{Pe.getInstance().deleteRemoteIdleSession(S,x)}catch{}if(x){Bo(t.meshId,x,"acked");const k=(()=>{try{return Pe.getInstance().getActiveSessionDeliveries(t.meshId,x)}catch{return[]}})();for(const j of k)ri(j.id,"acked")}}else if(t.event==="agent:stopped"){const x=Us(t.metadataEvent,t.sourceInstanceId),S=K(t.nodeId)||K(t.metadataEvent.meshNodeId);if(x&&S)try{Pe.getInstance().deleteRemoteIdleSession(S,x)}catch{}x&&(d=c(x,"failed"))}const p=Q0[t.event];if(p)try{const x=K(t.nodeId)||K(t.metadataEvent.meshNodeId)||void 0,S=Us(t.metadataEvent,t.sourceInstanceId)||void 0,k=K(t.metadataEvent.providerType)||void 0,j=K(t.metadataEvent.providerSessionId)||void 0,y=K(t.metadataEvent.finalSummary)||void 0,N=Cd(t.metadataEvent),_=p==="task_completed"&&x&&S?Oo({event:"agent:generating_completed",nodeId:x,sessionId:S,providerType:k,providerSessionId:j,finalSummary:y,workerResult:N}):void 0;ur(t.meshId,{kind:p,nodeId:x,sessionId:S,providerType:k,payload:{event:t.event,nodeLabel:t.nodeLabel,taskId:(d==null?void 0:d.id)||void 0,providerSessionId:j,finalSummary:y,workerResult:N,completionDiagnostic:t.metadataEvent.completionDiagnostic&&typeof t.metadataEvent.completionDiagnostic=="object"?t.metadataEvent.completionDiagnostic:void 0,evidence:_,..._?_.workerResult.source==="default"?{evidenceLevel:"insufficient",reviewRecommended:!0}:{evidenceLevel:"sufficient"}:{}}})}catch(x){_e.warn("MeshLedger",`Failed to record ${p}: ${(x==null?void 0:x.message)||x}`)}let h=null;if(t.event==="agent:stopped")try{const x=En(t.meshId),S=((v=x==null?void 0:x.policy)==null?void 0:v.maxTaskRetries)??1;if(h=Ty(t.meshId,{sessionId:Us(t.metadataEvent,t.sourceInstanceId)||void 0,nodeId:K(t.nodeId)||K(t.metadataEvent.meshNodeId)||void 0,maxRetries:S}),h.failedProviderType=K(t.metadataEvent.providerType)||null,h.retryRecommended&&h.consecutiveNodeFailures>0&&(ur(t.meshId,{kind:"recovery_attempted",nodeId:h.failedNodeId||void 0,sessionId:h.failedSessionId||void 0,providerType:h.failedProviderType||void 0,payload:{consecutiveFailures:h.consecutiveNodeFailures,taskAttemptCount:h.taskAttemptCount,retryRecommended:h.retryRecommended,advice:h.advice}}),h.lastTaskMessage&&h.failedNodeId&&h.failedProviderType)){const k=h.failedNodeId;try{const j=Hy(t.meshId,h.lastTaskMessage,{targetNodeId:k});_e.info("MeshRecovery",`Auto-requeued failed task: ${j.id} for node ${k}`);const y=x==null?void 0:x.nodes.find(N=>N.id===k);y&&e.cliManager.handleCliCommand("launch_cli",{cliType:h.failedProviderType,dir:y.workspace,settings:{role:"worker",meshNodeFor:t.meshId,meshNodeId:y.id,spawnedSessionVisibility:((w=x==null?void 0:x.policy)==null?void 0:w.spawnedSessionVisibility)||"hidden",autoApprove:Wu(x==null?void 0:x.policy,y==null?void 0:y.policy),launchedByCoordinator:!0}}).catch(N=>_e.error("MeshRecovery",`Failed to auto-relaunch session for ${y.id}: ${N==null?void 0:N.message}`))}catch(j){_e.warn("MeshRecovery",`Failed to execute auto-recovery: ${j==null?void 0:j.message}`)}}_e.info("MeshRecovery",`Recovery context for ${t.nodeLabel}: ${h.advice}`)}catch(x){_e.warn("MeshRecovery",`Failed to build recovery context: ${(x==null?void 0:x.message)||x}`)}const m=S0({event:t.event,nodeLabel:t.nodeLabel,metadataEvent:t.metadataEvent,recoveryContext:h});if(!m)return{success:!1,error:"unsupported mesh event"};const g={event:t.event,meshId:t.meshId,nodeLabel:t.nodeLabel,nodeId:t.nodeId||void 0,workspace:K(t.metadataEvent.workspace),metadataEvent:{...t.metadataEvent,...h?{recoveryContext:h}:{}},coordinatorMessage:m,queuedAt:Date.now(),...a?{targetCoordinatorDaemonId:a}:{}};return lp(g)&&_e.info("MeshEvents",`Queued ${t.event} for coordinator (mesh ${t.meshId}${a?`, coordinator daemon ${a}`:""})`),{success:!0,forwarded:0}}function z0(e,t){var d;const s=K(t.event);if(!xp(s))return{success:!1,error:"unsupported mesh event"};const n=K(t.nodeId),i=K(t.workspace),a=K(t.meshId)||(i?K((d=D0(i))==null?void 0:d.id):"");if(!a)return{success:!1,error:"meshId required"};const o=n?`Node '${n}'`:i?`Agent at ${i}`:"Remote agent",l=K(t.modalMessage),c=Array.isArray(t.modalButtons)?t.modalButtons.filter(p=>typeof p=="string"&&p.trim().length>0):null;return bp(e,{meshId:a,nodeId:n,nodeLabel:o,event:s,metadataEvent:{targetSessionId:K(t.targetSessionId)||K(t.sessionId)||K(t.instanceId),providerType:K(t.providerType),providerSessionId:K(t.providerSessionId),finalSummary:K(t.finalSummary)||K(t.summary),jobId:K(t.jobId),interactionId:K(t.interactionId),status:K(t.status),targetDaemonId:K(t.targetDaemonId),startedAt:K(t.startedAt),completedAt:K(t.completedAt),retryOfJobId:K(t.retryOfJobId),...l?{modalMessage:l}:{},...c&&c.length>0?{modalButtons:c}:{},...t.result&&typeof t.result=="object"&&!Array.isArray(t.result)?{result:t.result}:{},...t.completionDiagnostic&&typeof t.completionDiagnostic=="object"&&!Array.isArray(t.completionDiagnostic)?{completionDiagnostic:t.completionDiagnostic}:{},...t.workerResult&&typeof t.workerResult=="object"&&!Array.isArray(t.workerResult)?{workerResult:t.workerResult}:{},...t.meshWorkerResult&&typeof t.meshWorkerResult=="object"&&!Array.isArray(t.meshWorkerResult)?{meshWorkerResult:t.meshWorkerResult}:{},...t.structuredResult&&typeof t.structuredResult=="object"&&!Array.isArray(t.structuredResult)?{structuredResult:t.structuredResult}:{},...t.timestamp!==void 0?{timestamp:t.timestamp}:{},intentional:t.intentional===!0,intentionalStop:t.intentionalStop===!0,operatorCleanup:t.operatorCleanup===!0,reason:K(t.reason),stopReason:K(t.stopReason),cleanupReason:K(t.cleanupReason),source:K(t.source)}})}function l5(e,t,s){const n=K(t.coordinatorDaemonId);if(!n||!e.dispatchMeshCommand)return!1;const i=K(s.event);if(!i)return!1;const a={...s,event:i,nodeId:K(t.nodeId)||K(s.meshNodeId)||void 0,workspace:K(t.workspace)||K(s.workspace)||void 0},o=RL(n,i,a);return Promise.resolve(e.dispatchMeshCommand(n,"mesh_forward_event",a)).then(l=>{if(l&&l.success===!1){_e.warn("MeshEvents",`Immediate forward of ${i} to coordinator ${n} rejected (${K(l.error)||"no reason"}) — left queued for retry`);return}o&&c5(n,i,a)}).catch(l=>{_e.warn("MeshEvents",`Immediate forward of ${i} to coordinator ${n} failed: ${(l==null?void 0:l.message)||l} — left queued for retry`)}),_e.info("MeshEvents",`Durably forwarded ${i} for unresolved-mesh worker at ${t.workspace||"(no workspace)"} to coordinator daemon ${n}`),!0}function c5(e,t,s){const n=hp().find(i=>i.coordinatorDaemonId===e&&K(i.payload.event)===t&&K(i.payload.targetSessionId||i.payload.sessionId||i.payload.instanceId)===K(s.targetSessionId||s.sessionId||s.instanceId)&&K(i.payload.workspace)===K(s.workspace));n&&R0(n.id)}function d5(e){e.instanceManager.onEvent(t=>{if(t.event==="agent:ready"||t.event==="agent:generating_completed"){const i=K(t.instanceId);if(i){const a=e.instanceManager.getInstance(i);if(a&&a.category==="cli"){const o=a.getState(),l=o.settings&&typeof o.settings=="object"?o.settings:{},c=K(l.meshCoordinatorFor);if(c){if(K(o.status).toLowerCase()==="idle")try{const h=DL(e),m=cp(c,h.length>0?h:void 0);if(m.length>0){_e.info("MeshEvents",`Auto-flushing ${m.length} pending coordinator event(s) for mesh ${c} on coordinator idle`);for(const g of m){if(!g.coordinatorMessage)continue;const b=H0(g.event);a.onEvent("send_message",{input:{text:g.coordinatorMessage,textFallback:g.coordinatorMessage},...b?{force:!0}:{}})}}}catch(h){_e.warn("MeshEvents",`Failed to auto-flush pending coordinator events: ${(h==null?void 0:h.message)||h}`)}let p=!1;try{p=_l(c).some(h=>h.sessionId===i)||up(c,i)}catch{}if(!p)return}}}}if(!xp(t.event))return;const s=K(t.instanceId);if(!s)return;const n=ML(e,s,{getMeshById:i=>El(e,i),getMeshByWorkspace:i=>D0(i)});if(!n.isDelegate){if(T0(n)&&l5(e,n,t))return;EL(n,t.event);return}bp(e,{meshId:n.meshId,sourceInstanceId:s,nodeId:n.nodeId,nodeLabel:n.nodeLabel,event:t.event,metadataEvent:t})})}var K0,Go,G0,q0,qo,V0,X0,uo,nr,po,Y0,Q0,yp,J0=We({"src/mesh/mesh-events-coordinator.ts"(){rs(),wl(),pa(),Ve(),fr(),Ys(),ip(),dp(),gr(),ua(),E0(),P0(),Mn(),da(),pp(),Yr(),K0=5*60*1e3,Go=new Map,G0=5e3,q0=30*60*1e3,qo=new Map,V0=30*60*1e3,X0=10*60*1e3,uo=new Set,nr=new Map,po=5e3,Y0=new Set(["agent:generating_started","agent:generating_completed","agent:waiting_approval","agent:stopped","agent:ready","monitor:long_generating","refine:accepted","refine:completed","refine:failed","worktree_bootstrap_complete","worktree_bootstrap_failed"]),Q0={"agent:generating_completed":"task_completed","agent:waiting_approval":"task_approval_needed","agent:stopped":"task_failed","monitor:long_generating":"task_stalled"},yp=new Set(["agent:generating_completed","agent:stopped","agent:waiting_approval","refine:completed","refine:failed","worktree_bootstrap_complete","worktree_bootstrap_failed"])}});function u5(){const e=K(bt.MESH_RECONCILE_INTERVAL_MS);if(e){const t=Number.parseInt(e,10);if(Number.isFinite(t)&&t>=1e3&&t<=6e4)return t}return ev}function p5(e){const t=new Set,s=K(e.statusInstanceId);s&&t.add(s);const n=K(Xs().machineId);return n&&t.add(n),[...t]}function h5(e,t){const s=e.meshHost;if(!s)return!0;if(s.role&&s.role!=="host")return!1;const n=K(s.hostDaemonId);return n?t.includes(n):!0}function m5(e,t){var i;const s=new Set(t);for(const a of e.nodes){const o=K(a.daemonId),l=K(a.machineId);(o&&t.includes(o)||l&&t.includes(l))&&(o&&s.add(o),l&&s.add(l))}const n=K((i=e.meshHost)==null?void 0:i.hostDaemonId);return n&&s.has(n)&&s.add(n),[...s]}function f5(e){const t=[];for(const s of e.instanceManager.getByCategory("cli")){const n=s.getState(),i=n.settings&&typeof n.settings=="object"?n.settings:{},a=K(i.meshCoordinatorFor);if(!a)continue;const o=K(n.status).toLowerCase();t.push({meshId:a,instance:s,idle:o==="idle"})}return t}function g5(e,t){if(!e||!t.coordinatorMessage)return;const s=H0(t.event);e.onEvent("send_message",{input:{text:t.coordinatorMessage,textFallback:t.coordinatorMessage},...s?{force:!0}:{}})}async function Z0(e){const t=K(Xs().machineId)||void 0,s=p5(e),n=e.dispatchMeshCommand,i=(()=>{try{return Pe.getInstance()}catch{return}})();if(n)try{await x5(e)}catch(l){_e.warn("MeshReconcile",`Unresolved-delegate forward retry failed: ${(l==null?void 0:l.message)||l}`)}if(n)for(const l of fy()){const c=m5(l,s);if(h5(l,c))try{await b5(e,l,t,c)}catch(d){_e.warn("MeshReconcile",`Remote node pull failed for mesh ${l.id}: ${(d==null?void 0:d.message)||d}`)}}const a=f5(e);if(a.length===0)return;const o=new Map;for(const l of a){const c=o.get(l.meshId);c?c.push(l):o.set(l.meshId,[l])}for(const[l,c]of o){const d=c.filter(f=>f.idle),p=c.filter(f=>!f.idle),h=d.length>0?d:p,m=d.length===0;if(i)try{if(i.pendingEventCount(l)===0)continue}catch{}let g=[];try{g=cp(l,s.length>0?s:t,m?{onlyEvents:yp}:void 0)}catch(f){_e.warn("MeshReconcile",`Drain failed for mesh ${l}: ${(f==null?void 0:f.message)||f}`);continue}if(g.length===0)continue;const b=m?"force-drain → generating":"inject → idle";_e.info("MeshReconcile",`Reconcile ${b}: ${g.length} pending event(s) → ${h.length} coordinator(s) for mesh ${l}`);for(const f of g)for(const v of h)g5(v.instance,f)}}async function x5(e){const t=e.dispatchMeshCommand;if(!t)return;PL();const s=hp();if(s.length!==0)for(const n of s){let i;try{i=await t(n.coordinatorDaemonId,"mesh_forward_event",n.payload)}catch(a){_e.warn("MeshReconcile",`Retry forward to coordinator ${n.coordinatorDaemonId} failed: ${(a==null?void 0:a.message)||a} — left queued`);continue}if(i&&i.success===!1){_e.warn("MeshReconcile",`Retry forward to coordinator ${n.coordinatorDaemonId} rejected (${K(i.error)||"no reason"}) — left queued`);continue}R0(n.id),_e.info("MeshReconcile",`Retried+delivered unresolved-delegate ${K(n.payload.event)} to coordinator ${n.coordinatorDaemonId}`)}}async function b5(e,t,s,n){const i=e.dispatchMeshCommand;if(!i)return;const a=t.id,o=n.length>0?n.map(l=>({meshId:a,coordinatorDaemonId:l})):[{meshId:a}];for(const l of t.nodes){const c=K(l.daemonId);if(c&&!(s&&c===s)&&!n.includes(c))for(const d of o){let p;try{p=await i(c,"get_pending_mesh_events",d)}catch{break}const h=y5(p).filter(m=>K(m==null?void 0:m.meshId)===a);for(const m of h){const g=v5(m);if(!(!g.event||!g.meshId))try{z0(e,g)}catch{}}}}}function y5(e){if(Array.isArray(e))return e;if(e&&typeof e=="object"){const t=e.events;if(Array.isArray(t))return t}return[]}function v5(e){const t=e!=null&&e.metadataEvent&&typeof e.metadataEvent=="object"?e.metadataEvent:{};return{event:K(e==null?void 0:e.event),meshId:K(e==null?void 0:e.meshId),nodeId:K(e==null?void 0:e.nodeId)||K(t.meshNodeId),workspace:K(e==null?void 0:e.workspace)||K(t.workspace),...t}}function w5(e){const t=u5();let s=!1;const n=setInterval(()=>{s||(s=!0,Z0(e).catch(i=>_e.warn("MeshReconcile",`Reconcile tick error: ${(i==null?void 0:i.message)||i}`)).finally(()=>{s=!1}))},t);return typeof n.unref=="function"&&n.unref(),_e.info("MeshReconcile",`Mesh reconcile loop started (interval ${t}ms)`),{stop(){clearInterval(n),_e.info("MeshReconcile","Mesh reconcile loop stopped")}}}var ev,tv=We({"src/mesh/mesh-reconcile-loop.ts"(){rs(),wl(),Ve(),ua(),gr(),J0(),P0(),Yr(),ev=4e3}}),S5={};Tt(S5,{__resetIdleAutoFastForwardForTests:()=>LL,__resetMeshWorkspaceCacheForTests:()=>$L,clearPendingMeshCoordinatorEvents:()=>yL,drainPendingMeshCoordinatorEvents:()=>cp,getPendingMeshCoordinatorEvents:()=>bL,handleMeshForwardEvent:()=>z0,isMeshCoordinatorEvent:()=>xp,queuePendingMeshCoordinatorEvent:()=>lp,reconcileDirectDispatchCompletionFromTranscript:()=>jL,runMeshReconcileTick:()=>Z0,setupMeshEventForwarding:()=>d5,setupMeshReconcileLoop:()=>w5,triggerMeshQueue:()=>W0,tryAssignQueueTask:()=>ha});var vp=We({"src/mesh/mesh-events.ts"(){ua(),pp(),tv(),J0()}});function sv(){return{...Md,traceCategories:[...Md.traceCategories]}}var rf,nf,Md,wp=We({"src/logging/debug-config.ts"(){rf=200,nf={logLevel:"info",collectDebugTrace:!1,traceContent:!1,traceBufferSize:rf,traceCategories:[]},Md={...nf}}}),k5={};Tt(k5,{classifyTrust:()=>N5,describeTrust:()=>C5,inspectManifestShape:()=>j5,requiresConfirmation:()=>_5});function j5(e){const t=!!e.tui&&typeof e.tui=="object"&&Object.keys(e.tui).length>0,s=!!e.overrides&&typeof e.overrides=="object"&&!Array.isArray(e.overrides)&&Object.keys(e.overrides).length>0,a=(Array.isArray(e.compatibility)?e.compatibility:[]).some(o=>typeof(o==null?void 0:o.scriptDir)=="string")||typeof e.defaultScriptDir=="string";return{hasTui:t,hasOverrides:s,hasScriptDir:a}}function N5(e,t){const s=!t.hasTui&&!t.hasOverrides&&!t.hasScriptDir;switch(e){case"user":return"user-custom";case"upstream":return s?"trusted":"trusted-with-scripts";case"external":return s?"external-safe":"external-untrusted"}}function _5(e){return e==="external-untrusted"}function C5(e){switch(e){case"user-custom":return"Hand-authored in ~/.adhdev/providers/. Runs your own code.";case"trusted":return"Official, declarative-only manifest from the ADHDev registry.";case"trusted-with-scripts":return"Official manifest from the ADHDev registry. Ships JavaScript hooks executed by the daemon.";case"external-safe":return"Manifest from a 3rd-party git source you added. Declarative-only — the daemon never runs JS from this source.";case"external-untrusted":return"Manifest from a 3rd-party git source you added. Ships JavaScript that the daemon will execute. Treat as untrusted code — review the source before enabling."}}var rv,I5=We({"src/providers/sdk/v1/schemas/cli/provider.schema.json"(){rv={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"adhdev:cli/provider@1",title:"CLI provider.json — v1",description:"Schema for CLI provider manifests. Validates the contract documented in docs/provider-contract/cli/v1.md. All 4 production CLI providers (codex, claude, hermes, antigravity) pass this schema without modification.",type:"object",required:["type","name","category","binary","spawn"],additionalProperties:!1,properties:{$schema:{type:"string",description:"Schema URL. Hint for editor tooling; not consumed by the daemon."},links:{type:"object",additionalProperties:{type:"string"},description:"Documentation URLs. Surfaced in marketplace UI."},install:{type:"object",additionalProperties:{type:"string"},description:"Install instructions by channel (npm/pip/manual/brew). UI-only."},source:{type:"object",description:"GitHub source descriptor. Daemon uses this to fetch script files on install.",additionalProperties:!1,properties:{type:{const:"github"},repo:{type:"string",pattern:"^[\\w.-]+/[\\w.-]+$"},ref:{type:"string"},subdir:{type:"string"}},required:["type","repo","ref"]},type:{type:"string",pattern:"^[a-z][a-z0-9-]*$",description:"Stable identifier. Lowercase kebab-case."},name:{type:"string",minLength:1,description:"Short canonical name."},displayName:{type:"string",description:"Optional UI label. Defaults to name."},category:{const:"cli",description:'Must be "cli" for this schema.'},icon:{type:"string",maxLength:4,description:"Single emoji or short glyph."},aliases:{type:"array",items:{type:"string"},description:"Alternative identifiers accepted at launch."},engines:{type:"object",additionalProperties:!1,properties:{adhdev:{type:"string",description:"SemVer range against the ADHDev contract version. Required for marketplace-published providers."}},description:"Optional today; required by marketplace publish flow once registry is live."},providerVersion:{type:"string",description:"Provider package SemVer."},contractVersion:{type:["number","string"],description:"Legacy contract version. Reserved."},status:{enum:["Stable","Beta","Experimental","Deprecated"]},details:{type:"string",description:"Short blurb shown in marketplace."},disableUpstream:{type:"boolean",description:"When true, daemon does not auto-sync this provider from registry. claude-cli uses this for explicit-version pinning."},binary:{type:"string",minLength:1,description:"Binary basename used for which-style detection."},versionCommand:{type:"string",description:'Command the daemon runs to probe installed version. Example: "my-cli --version".'},spawn:{type:"object",required:["command"],additionalProperties:!1,properties:{command:{type:"string",minLength:1},args:{type:"array",items:{type:"string"},default:[]},shell:{type:"boolean",default:!1},env:{type:"object",additionalProperties:{type:"string"},default:{}}}},sendDelayMs:{type:"number",minimum:0,description:"Delay between pasting prompt text and pressing Enter."},scriptCallBudgetMs:{type:"integer",minimum:1,maximum:5e3,default:50,description:"Per-invocation wall-clock budget (ms) for provider scripts (detectStatus, parseSession, parseApproval). Default 50. Scripts that exceed the budget are flagged in the runner's invocation trace and surfaced via the debug bundle so operators can identify a hanging settle loop. The budget is NOT a hard kill — Node CJS cannot interrupt synchronous code without a worker thread."},sendKey:{type:"string",default:"\r",description:"Character sent to submit a prompt. Default carriage return."},submitStrategy:{enum:["wait_for_echo","immediate"],default:"immediate"},requirePromptEchoBeforeSubmit:{type:"boolean",default:!1,description:"When true, daemon waits for the typed prompt to be visible in the PTY screen before sending sendKey."},allowInputDuringGeneration:{type:"boolean",default:!1,description:"When true, daemon permits sending a new prompt mid-generation."},requiresFinalAssistantBeforeIdle:{type:"boolean",default:!1,description:"When true, daemon defers generating→idle until parseSession includes a final standard assistant message."},augmentStaleSnapshot:{type:"boolean",description:"Reserved for future use."},transcriptAuthority:{enum:["provider","daemon"],description:"When 'provider', daemon treats parsed output as canonical and suppresses fallback parsing."},transcriptContext:{enum:["full","tail"],description:"When 'full', provider-owned parser receives the entire accumulated transcript context."},patterns:{type:"object",additionalProperties:!1,description:"Optional regex hints for the legacy fallback detector. Modern providers express these via primitives.",properties:{prompt:{$ref:"#/$defs/patternList"},generating:{$ref:"#/$defs/patternList"},approval:{$ref:"#/$defs/patternList"},ready:{$ref:"#/$defs/patternList"},dialog:{$ref:"#/$defs/patternList"}}},approvalKeys:{type:"object",patternProperties:{"^[0-9]+$":{type:"string"}},additionalProperties:!1,description:"Map of button index → key sequence to send."},approvalPositiveHints:{type:"array",items:{type:"string"},description:'Lowercase substrings considered "positive" (accept). Auto-approve picks the matching button.'},timeouts:{type:"object",additionalProperties:!1,properties:{ptyFlush:{type:"number",minimum:0},dialogAccept:{type:"number",minimum:0},approvalCooldown:{type:"number",minimum:0},generatingIdle:{type:"number",minimum:0},idleFinish:{type:"number",minimum:0},idleFinishConfirm:{type:"number",minimum:0},statusActivityHold:{type:"number",minimum:0},maxResponse:{type:"number",minimum:0},shutdownGrace:{type:"number",minimum:0},outputSettle:{type:"number",minimum:0}}},resume:{type:"object",additionalProperties:!1,required:["supported"],properties:{supported:{type:"boolean"},stopStrategy:{enum:["command","ctrl_c","signal"]},stopCommand:{type:"string"},shutdownGraceMs:{type:"number",minimum:0},sessionIdFormat:{enum:["uuid","free","string"]},newSessionArgs:{type:"array",items:{type:"string"}},resumeSessionArgs:{type:"array",items:{type:"string"}},resumeArgs:{type:"array",items:{type:"string"}}}},compatibility:{type:"array",minItems:1,items:{type:"object",required:["ideVersion"],additionalProperties:!1,properties:{ideVersion:{type:"string",description:"SemVer range."},scriptDir:{type:"string",pattern:"^scripts/[^/]+$"},spec:{type:"string",pattern:"^specs/[^/]+\\.json$",description:"Path to declarative spec.json driving SpecCliAdapter for this version range."}}},description:"Maps installed agent versions to script subdirectories and/or declarative specs."},defaultScriptDir:{type:"string",pattern:"^scripts/[^/]+$",description:"Fallback when no compatibility[] entry matches."},capabilities:{type:"object",additionalProperties:!1,properties:{input:{type:"object",additionalProperties:!0,properties:{multipart:{type:"boolean"},mediaTypes:{type:"array",items:{type:"string"}},strategies:{type:"array"}}},output:{type:"object",additionalProperties:!0,properties:{richContent:{type:"boolean"},mediaTypes:{type:"array",items:{type:"string"}}}},controls:{type:"object",additionalProperties:!0,properties:{typedResults:{type:"boolean"}}}}},meshCoordinator:{type:"object",additionalProperties:!1,required:["supported"],properties:{supported:{type:"boolean"},mcpConfig:{type:"object",additionalProperties:!1,properties:{mode:{enum:["manual","auto_import"]},format:{type:"string"},path:{type:"string"},configPathCommand:{type:"string"},serverName:{type:"string"},requiresRestart:{type:"boolean"},instructions:{type:"string"},template:{type:"string"}}},systemPromptInjection:{description:"How the coordinator system prompt reaches the launched CLI. Replaces hard-coded router branches per CLI type; users may override the prompt body or the injection mechanism here.",oneOf:[{type:"object",additionalProperties:!1,required:["mode","flag"],properties:{mode:{const:"cli_arg"},flag:{type:"string"}}},{type:"object",additionalProperties:!1,required:["mode","flag","template"],properties:{mode:{const:"config_override"},flag:{type:"string"},template:{type:"string"}}},{type:"object",additionalProperties:!1,required:["mode","path"],properties:{mode:{const:"context_file"},path:{type:"string"},wrapper:{type:"string"}}},{type:"object",additionalProperties:!1,required:["mode","name"],properties:{mode:{const:"env_var"},name:{type:"string"}}}]},delegatedWorkerIsolation:{description:"Provider-declared launch isolation for coordinator-spawned worker sessions. Keeps worker-only sessions from inheriting coordinator MCP/tools/config.",type:"object",additionalProperties:!1,properties:{env:{type:"object",additionalProperties:!1,properties:{unset:{type:"array",items:{type:"string",minLength:1}}}},args:{type:"array",items:{oneOf:[{type:"object",additionalProperties:!1,required:["mode","flag"],properties:{mode:{const:"empty_mcp_config"},flag:{type:"string",minLength:1},strictFlag:{type:"string",minLength:1}}},{type:"object",additionalProperties:!1,required:["mode","flag","key","value"],properties:{mode:{const:"config_override"},flag:{type:"string",minLength:1},key:{type:"string",minLength:1},value:{type:"string",minLength:1},dedupeKey:{type:"string",minLength:1}}}]}}}}}},nativeHistory:{type:"object",description:"Native transcript adapter declaration. v1 canonical field name. Daemon reads/lists provider-native history files via the named scripts (or the built-in adapter identified by $schema).",additionalProperties:!0,properties:{$schema:{type:"string"},format:{type:"string"},watchPath:{type:"string"},mode:{enum:["native-source","materialized-mirror","disabled","daemon-mirror"]},contractVersion:{type:"string"},scripts:{type:"object",additionalProperties:!1,properties:{readSession:{type:"string"},listSessions:{type:"string"}}}}},canonicalHistory:{type:"object",description:"Deprecated v0 alias for `nativeHistory`. The loader copies this block into `nativeHistory` at load time. New manifests should use `nativeHistory` directly.",additionalProperties:!0,properties:{format:{type:"string"},watchPath:{type:"string"},mode:{enum:["native-source","materialized-mirror","disabled","daemon-mirror"]},contractVersion:{type:"string"},scripts:{type:"object",additionalProperties:!1,properties:{readSession:{type:"string"},listSessions:{type:"string"}}}}},settings:{type:"object",additionalProperties:{$ref:"#/$defs/settingDef"}},controls:{type:"array",items:{$ref:"#/$defs/controlDef"}},tui:{type:"object",description:"Declarative TUI parsing primitives. When present, daemon's builder synthesises detectStatus / parseApproval / parseSession from these blocks. Each block is identified by its $schema.",additionalProperties:!0},overrides:{type:"object",description:"Optional JS override pointers. Presence promotes the provider tier to `extended`. Each value identifies the handler being overridden and the relative path to the JS file implementing it.",additionalProperties:{oneOf:[{type:"string",description:"Relative path to the override JS file."},{type:"object",required:["path"],additionalProperties:!1,properties:{$schema:{type:"string"},path:{type:"string"},reason:{type:"string"}}}]}}},$defs:{patternList:{type:"array",items:{type:"object",required:["source"],additionalProperties:!1,properties:{source:{type:"string",description:"Regex source."},flags:{type:"string",pattern:"^[gimsuy]*$"}}}},settingDef:{type:"object",required:["type"],additionalProperties:!1,properties:{type:{enum:["boolean","number","string","select"]},default:{},public:{type:"boolean"},label:{type:"string"},description:{type:"string"},options:{type:"array"},min:{type:"number"},max:{type:"number"}},allOf:[{if:{properties:{type:{const:"select"}}},then:{required:["options"]}}]},controlDef:{type:"object",required:["id","type","label"],additionalProperties:!1,properties:{id:{type:"string"},type:{enum:["select","action","toggle"]},label:{type:"string"},icon:{type:"string"},placement:{type:"string"},order:{type:"number"},dynamic:{type:"boolean"},hidden:{type:"boolean",description:"When true, dashboard does not render the control directly. Used for commands triggered by other UI (slash menu, etc.)."},options:{type:"array"},listScript:{type:"string"},setScript:{type:"string"},invokeScript:{type:"string"},readFrom:{type:"string"},resultDisplay:{type:"string"},defaultValue:{},confirmTitle:{type:"string"},confirmMessage:{type:"string"},confirmLabel:{type:"string"}}}}}}}),A5={};Tt(A5,{formatManifestValidationIssues:()=>P5,validateCliProviderManifest:()=>R5});function T5(){return on||(on=new $w({strict:!1,allErrors:!0,allowUnionTypes:!0}),Ow(on),on)}function M5(){return ni||(ni=T5().compile(rv),ni)}function E5(e){const t=e.instancePath||"",s=e.params;let n=e.message||"validation failed",i;return e.keyword==="additionalProperties"?n=`unexpected property "${s.additionalProperty}"`:e.keyword==="required"?n=`missing required property "${s.missingProperty}"`:e.keyword==="enum"?(i=s.allowedValues,n=`must be one of ${JSON.stringify(i)}`):e.keyword==="const"?(i=s.allowedValue,n=`must equal ${JSON.stringify(i)}`):e.keyword==="type"&&(n=`must be ${s.type}`),{path:t,keyword:e.keyword,message:n,...i!==void 0?{allowed:i}:{}}}function R5(e){const t=M5();return t(e)?{ok:!0,issues:[]}:{ok:!1,issues:(t.errors||[]).map(E5)}}function P5(e){return e.map(t=>` - ${t.path||"<root>"}: ${t.message} (${t.keyword})`).join(`
|
|
575
|
+
`)}var on,ni,D5=We({"src/providers/sdk/v1/validators/manifest.ts"(){I5(),on=null,ni=null}}),L5={};Tt(L5,{activeFilePath:()=>Xo,deriveSourceName:()=>W5,externalRoot:()=>nv,inventoryExternalSources:()=>ov,loadExternalSources:()=>$5,loadProvidersActive:()=>av,resolveActiveSource:()=>U5,saveExternalSources:()=>O5,saveProvidersActive:()=>F5,sourcesFilePath:()=>Vo,sourcesProviding:()=>lv});function Rl(){return Ee.join(ot.homedir(),".adhdev")}function nv(){return Ee.join(Rl(),"external")}function Vo(){return Ee.join(Rl(),cv)}function Xo(){return Ee.join(Rl(),dv)}function iv(){const e=Rl();Qe.existsSync(e)||Qe.mkdirSync(e,{recursive:!0})}function $5(){const e=Vo();if(!Qe.existsSync(e))return{schema:1,sources:[]};try{const t=JSON.parse(Qe.readFileSync(e,"utf-8"));return!t||typeof t!="object"?{schema:1,sources:[]}:{schema:1,sources:Array.isArray(t.sources)?t.sources.filter(B5):[]}}catch{return{schema:1,sources:[]}}}function O5(e){iv();const t=Vo()+".tmp";Qe.writeFileSync(t,JSON.stringify(e,null,2)+`
|
|
576
|
+
`,"utf-8"),Qe.renameSync(t,Vo())}function av(){const e=Xo();if(!Qe.existsSync(e))return{schema:1,active:{}};try{const t=JSON.parse(Qe.readFileSync(e,"utf-8"));return!t||typeof t!="object"?{schema:1,active:{}}:{schema:1,active:t.active&&typeof t.active=="object"?t.active:{}}}catch{return{schema:1,active:{}}}}function F5(e){iv();const t=Xo()+".tmp";Qe.writeFileSync(t,JSON.stringify(e,null,2)+`
|
|
577
|
+
`,"utf-8"),Qe.renameSync(t,Xo())}function B5(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.name=="string"&&t.name.length>0&&typeof t.url=="string"&&t.url.length>0&&typeof t.ref=="string"&&t.ref.length>0&&typeof t.addedAt=="string"}function W5(e){const t=e.match(/[/:]([^/:]+)\/([^/]+?)(?:\.git)?$/);if(!t)return"@source";const s=t[1].toLowerCase().replace(/[^a-z0-9_-]/g,"-"),n=t[2].toLowerCase().replace(/[^a-z0-9_-]/g,"-");return`@${s}-${n}`}function ov(){const e=nv();if(!Qe.existsSync(e))return[];const t=[];let s;try{s=Qe.readdirSync(e,{withFileTypes:!0})}catch{return[]}for(const n of s){if(!n.isDirectory())continue;const i=n.name,a=Ee.join(e,i),o={};let l;try{l=Qe.readdirSync(a,{withFileTypes:!0})}catch{continue}for(const c of l){if(!c.isDirectory())continue;const d=c.name,p=Ee.join(a,d);let h;try{h=Qe.readdirSync(p,{withFileTypes:!0})}catch{continue}const m=[];for(const g of h){if(!g.isDirectory())continue;const b=Ee.join(p,g.name),f=Qe.existsSync(Ee.join(b,"provider.v1.json")),v=Qe.existsSync(Ee.join(b,"provider.json"));(f||v)&&m.push(g.name)}m.length>0&&(o[d]=m)}t.push({sourceName:i,providers:o})}return t}function lv(e,t){return ov().filter(n=>(n.providers[e]||[]).includes(t)).map(n=>n.sourceName)}function U5(e,t,s){const n=lv(e,t);if(n.length===0)return{source:null,ambiguous:!1,candidates:n};if(n.length===1)return{source:n[0],ambiguous:!1,candidates:n};const i=(s??av()).active[t];return i&&n.includes(i)?{source:i,ambiguous:!1,candidates:n}:{source:n[0],ambiguous:!0,candidates:n}}var cv,dv,H5=We({"src/providers/external-sources.ts"(){cv="providers-sources.json",dv="providers-active.json"}});function z5(e,t){if(!(e instanceof Error))return!1;const s=e.message||"";return("code"in e?e.code:void 0)==="MODULE_NOT_FOUND"&&s.includes(t)}function K5(e,t){var n;const s=(n=e==null?void 0:e.default)!=null&&n.createTerminal?e.default:e!=null&&e.createTerminal?e:null;if(!s)throw new Error(`Ghostty VT binding "${t}" does not export createTerminal()`);return s}function G5(){var t;const e=(t=bt.ADHDEV_GHOSTTY_VT_BINDING)==null?void 0:t.trim();return e?[e]:uv}function q5(){if(Zr!==void 0){if(!Zr&&ln)throw ln;return Zr}const e=[];for(const t of G5())try{const s=Cs(t);return Zr=K5(s,t),ln=null,Zr}catch(s){if(z5(s,t)){e.push(`${t}: module not found`);continue}const n=s instanceof Error?s.message:String(s);e.push(`${t}: ${n}`)}throw Zr=null,ln=new Error(`ghostty-vt binding unavailable (${e.join("; ")||"no candidates tried"})`),ln}var uv,Zr,ln,pv,V5=We({"src/cli-adapters/terminal-backends/ghostty-vt-backend.ts"(){uv=["@adhdev/ghostty-vt-node"],ln=null,pv=class Ed{constructor(t){re(this,"kind","ghostty-vt");re(this,"terminal");re(this,"rows");re(this,"disposed",!1);const s=q5();this.rows=Math.max(1,t.rows|0),this.terminal=s.createTerminal({cols:Math.max(1,t.cols|0),rows:this.rows,scrollback:Math.max(0,t.scrollback|0)})}resize(t,s){this.rows=Math.max(1,t|0),this.terminal.resize(Math.max(1,s|0),this.rows)}write(t){!t||this.disposed||this.terminal.write(t)}formatLines(){const t=this.terminal.formatPlainText({trim:!1})||"";return t?t.split(`
|
|
578
|
+
`).map(s=>s.replace(/\s+$/,"")):[]}static trimBlankEnds(t){let s=0,n=t.length;for(;s<n&&!t[s];)s+=1;for(;n>s&&!t[n-1];)n-=1;return t.slice(s,n).join(`
|
|
579
|
+
`)}getText(){if(this.disposed)return"";const t=this.formatLines();if(t.length===0)return"";const s=t.length>this.rows?t.slice(-this.rows):t;return Ed.trimBlankEnds(s)}getTextWithScrollback(){if(this.disposed)return"";const t=this.formatLines();return t.length===0?"":Ed.trimBlankEnds(t)}getCursorPosition(){return this.disposed?{col:0,row:0}:this.terminal.getCursorPosition()}dispose(){this.disposed||(this.disposed=!0,this.terminal.dispose())}}}}),af,hv,Sp=We({"src/cli-adapters/terminal-screen.ts"(){V5(),af=2e3,hv=class{constructor(e=Mi,t=Ti){re(this,"backendKind","ghostty-vt");re(this,"rows");re(this,"cols");re(this,"terminal");this.rows=Math.max(1,e|0),this.cols=Math.max(1,t|0),this.terminal=this.createBackend()}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()}getTextWithScrollback(){return this.terminal.getTextWithScrollback()}getCursorPosition(){return this.terminal.getCursorPosition()}dispose(){this.terminal.dispose()}createBackend(){return new pv({cols:this.cols,rows:this.rows,scrollback:af})}}}}),mv=We({"src/cli-adapters/spawn-env.ts"(){}});function X5(e){if(process.platform!=="win32")return e;const t=(e||"").trim();if(!t)return e;if(Ee.isAbsolute(t)&&st(t))return t;try{const s=Hw("where",[t],{encoding:"utf8",windowsHide:!0}).trim();if(s){const n=s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean);return n.find(a=>fv.has(Ee.extname(a).toLowerCase()))||n[0]||e}}catch{}return e}var fv,gv=We({"src/cli-adapters/resolve-executable.ts"(){fv=new Set([".exe",".com"])}}),Y5={};Tt(Y5,{NodePtyTransportFactory:()=>kp});function Q5(){if(Vn!==void 0)return Vn;try{Vn=Cs("node-pty"),V2()}catch{Vn=null}return Vn}var Vn,of,kp,xv=We({"src/cli-adapters/pty-transport.ts"(){mv(),gv(),of=class{constructor(e){re(this,"ready",Promise.resolve());re(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)}},kp=class{spawn(e,t,s){const n=Q5();if(!n)throw new Error("node-pty is not installed");let i=s.cwd;if(i)try{Cs("fs").statSync(i).isDirectory()||(i=ot.homedir())}catch{i=ot.homedir()}const a=n.spawn(X5(e),t,{name:"xterm-256color",cols:s.cols,rows:s.rows,cwd:i,env:s.env});return new of(a)}}}});function J5(e){return e.replace(/\x1B\][^\x07]*(?:\x07|\x1B\\)/g,"").replace(/\x1B[P^_X][\s\S]*?(?:\x07|\x1B\\)/g,"").replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"")}function Z5(e,t=1){const s=Number(String(e||"").split(";")[0]||t);return Math.max(1,Number.isFinite(s)?s:t)}function e$(e){return/[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/.test(e)}function t$(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 s$(e){return String(e||"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g,"").replace(/\r+/g,`
|
|
580
|
+
`).replace(/[ \t]+\n/g,`
|
|
581
|
+
`).replace(/\n{4,}/g,`
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
`)}function bi(e){const t=new jp;return s$(J5(t.append(e)))}function r$(e){return e?Object.entries(e).filter(([,t])=>typeof t=="function").map(([t])=>t):[]}function n$(e){return String(e||"").replace(/\u0007/g,"").replace(/\r\n/g,`
|
|
585
|
+
`).replace(/\r/g,`
|
|
586
|
+
`).split(`
|
|
587
|
+
`).map(t=>t.replace(/\s+$/,""))}function i$(e){const t=String(e||"").trim();return t?/^[❯›>]\s*(?:$|\S.*)$/.test(t):!1}function ts(e){const t=String(e||"").replace(/\r\n/g,`
|
|
588
|
+
`).replace(/\r/g,`
|
|
589
|
+
`),n=n$(t).map((c,d,p)=>{const h=String(c||"").trim();return{index:d,fromTop:d,fromBottom:p.length-d-1,text:c,trimmed:h,isEmpty:h.length===0}}),i=n.filter(c=>!c.isEmpty),a=i[0]??null,o=i[i.length-1]??null;let l=-1;for(let c=n.length-1;c>=0;c-=1)if(i$(n[c].text)){l=c;break}return{text:t,lineCount:n.length,lines:n,nonEmptyLines:i,firstNonEmptyLineIndex:(a==null?void 0:a.index)??-1,lastNonEmptyLineIndex:(o==null?void 0:o.index)??-1,firstNonEmptyLine:a,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 a$(e){const t=String(e||"").trim();if(!t)return t;const s=t.startsWith("~")?Ee.join(ot.homedir(),t.slice(1)):t;if(Ee.isAbsolute(s)||s.includes("/")||s.includes("\\"))return Ee.isAbsolute(s)?s:Ee.resolve(s);const n=ot.platform()==="win32",i=(bt.PATH||"").split(Ee.delimiter),a=[];if(n){bt.APPDATA&&a.push(Ee.join(bt.APPDATA,"npm"));try{a.push(Ee.dirname(process.execPath))}catch{}}else{a.push(Ee.join(ot.homedir(),".npm-global","bin")),a.push("/usr/local/bin","/opt/homebrew/bin");try{a.push(Ee.dirname(process.execPath))}catch{}}const o=[...i,...a],l=n?[".exe",".cmd",".bat",""]:[""];for(const c of o)if(c)for(const d of l){const p=Ee.join(c,t+d);try{const h=Cs("fs");if(h.existsSync(p)){const m=h.statSync(p);if(m.isFile()&&(n||m.mode&73))return p}}catch{}}return n?`${t}.cmd`:t}function lf(e){if(!Ee.isAbsolute(e))return!1;try{const t=Cs("fs"),s=t.realpathSync(e),n=Buffer.alloc(8),i=t.openSync(s,"r");t.readSync(i,n,0,8,0),t.closeSync(i);let a=0;return n[0]===239&&n[1]===187&&n[2]===191&&(a=3),n[a]===35&&n[a+1]===33}catch{return!1}}function o$(e){if(!Ee.isAbsolute(e))return!1;try{const t=Cs("fs"),s=t.realpathSync(e),n=Buffer.alloc(8),i=t.openSync(s,"r");t.readSync(i,n,0,8,0),t.closeSync(i);let a=0;n[0]===239&&n[1]===187&&n[2]===191&&(a=3);const o=n.subarray(a);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),c=o.readUInt32BE(0);return[4277009102,4277009103,3405691582,3199925962].some(p=>p===l||p===c)}catch{return!1}}function bv(e){return/^[a-zA-Z0-9@%_+=:,./-]+$/.test(e)?e:ot.platform()==="win32"?`"${e.replace(/"/g,'""')}"`:`'${e.replace(/'/g,"'\\''")}'`}function l$(e,t=80){const s=String(e||"").replace(/\r/g,"");return s?s.split(`
|
|
590
|
+
`).reduce((n,i)=>n+Math.max(1,Math.ceil(Math.max(1,i.length)/t)),0):1}function c$(e){const t=String(e||"").replace(/\r/g,"").split(`
|
|
591
|
+
`).map(n=>n.trim()).filter(Boolean);return(t[t.length-1]||t[0]||"").slice(-120)}function Cn(e){return String(e||"").replace(/\s+/g," ").trim()}function Pr(e){return String(e||"").replace(/\s+/g,"").trim()}function Rd(e,t){const s=Cn(t);if(!s)return!1;const n=Cn(e);if(n.includes(s))return!0;const i=Pr(e),a=Pr(t);if(a&&i.includes(a))return!0;const o=s.split(/[^A-Za-z0-9_.:/-]+/).map(d=>d.trim()).filter(d=>d.length>=4);if(o.length===0)return!1;const l=Math.min(o.length,3);return o.filter(d=>n.includes(d)||i.includes(Pr(d))).length>=l}function Mc(e){return bi(String(e||"")).replace(/\s+/g," ").trim()}function d$(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 u$(e){return Array.isArray(e)?e.map(d$).filter(t=>t!=null):[]}function p$(e){const t=e&&typeof e=="object"?e.patterns:void 0;return{patterns:{approval:u$(t&&typeof t=="object"?t.approval:void 0)}}}var jp,yv,Hr=We({"src/cli-adapters/provider-cli-shared.ts"(){mv(),jp=class{constructor(){re(this,"lines",[[]]);re(this,"row",0);re(this,"col",0);re(this,"savedCursor",null);re(this,"pendingEscape","")}append(e){const t=this.pendingEscape+String(e||"");this.pendingEscape="";for(let s=0;s<t.length;s+=1){let n=t[s];if(n==="\x1B"){const a=this.consumeEscape(t.slice(s));if(a===0){this.pendingEscape=t.slice(s);break}s+=a-1;continue}const i=t.codePointAt(s);i&&i>65535&&(n=String.fromCodePoint(i),s+=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(`
|
|
592
|
+
`)}ensureRow(e=this.row){for(;this.lines.length<=e;)this.lines.push([])}writeControlOrChar(e){if(e==="\r"){this.col=0;return}if(e===`
|
|
593
|
+
`){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(e$(e)&&this.col>0){t[this.col-1]=`${t[this.col-1]||""}${e}`;return}for(;t.length<this.col;)t.push(" ");const s=t$(e);t[this.col]=e,s&&(t[this.col+1]=""),this.col+=s?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 s=e.indexOf("\x07",2),n=e.indexOf("\x1B\\",2);return s>=0&&(n<0||s<n)?s+1:n>=0?n+2:0}if(t==="["){const s=e.match(/^\x1B\[([0-?]*)([ -/]*)([@-~])/);return s?(this.applyCsi(s[1]||"",s[3]),s[0].length):e.length<32?0:1}if(/[P^_X]/.test(t)){const s=e.indexOf("\x07",2),n=e.indexOf("\x1B\\",2);return s>=0&&(n<0||s<n)?s+1:n>=0?n+2:0}return 2}applyCsi(e,t){const s=Z5(e);if(this.ensureRow(),t==="A")this.row=Math.max(0,this.row-s);else if(t==="B")this.row+=s;else if(t==="C"){const n=this.lines[this.row];for(let i=this.col;i<this.col+s;i+=1)n[i]===void 0&&(n[i]=" ");this.col+=s}else if(t==="D")this.col=Math.max(0,this.col-s);else if(t==="G")this.col=Math.max(0,s-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 a=0;a<this.row;a+=1)this.lines[a]=[];const i=this.lines[this.row];for(let a=0;a<=Math.min(this.col,i.length-1);a+=1)i[a]=" "}}else if(t==="K"){const n=Number(e||0)||0,i=this.lines[this.row];if(n===2)this.lines[this.row]=[];else if(n===1)for(let a=0;a<=Math.min(this.col,i.length-1);a+=1)i[a]=" ";else this.lines[this.row]=i.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()}},yv=G2}});function cf(e,t){try{return new RegExp(e,t??"")}catch(s){throw new Error(`Invalid visible-region anchor regex /${e}/${t??""}: ${s.message}`)}}function df(e,t){const s=[],n=new RegExp(e.source,e.flags.replace("g","")+"g");let i;for(;(i=n.exec(t))!==null;)s.push(i),i[0].length===0&&(n.lastIndex+=1);return s}function uf(e,t){if(!t)return t;switch(e.scope){case"screen":case"buffer":return t;case"tail":{const s=e.tailChars??4e3;return t.length<=s?t:t.slice(-s)}case"between-anchors":{const s=e.anchors;if(!(s!=null&&s.top)&&!(s!=null&&s.bottom))return t;const n=(e.selectAnchor??"first")==="last";let i=0;if(s.top){const o=cf(s.top.pattern,s.top.flags),l=df(o,t);if(l.length===0)return t;const c=n?l[l.length-1]:l[0];i=c.index+c[0].length}let a=t.length;if(s.bottom){const o=cf(s.bottom.pattern,s.bottom.flags),l=i,c=t.slice(l),d=df(o,c);if(d.length===0)return t;const p=n?d[d.length-1]:d[0];a=l+p.index}return i>=a?t:t.slice(i,a)}default:return t}}var Np=We({"src/providers/sdk/v1/builders/cli/visible-region.ts"(){}});function Fi(e,t){try{return new RegExp(e,t??"")}catch(s){throw new Error(`Invalid regex /${e}/${t??""}: ${s.message}`)}}function h$(e,t){if(!e)return"";const s=e.split(`
|
|
594
|
+
`);return s.length<=t?e:s.slice(-t).join(`
|
|
595
|
+
`)}function pf(e,t,s){const n=s&&s>0?s:8;switch(t){case"whole-screen":return e.screenText??"";case"recent-buffer":return e.tail??"";case"last-n-lines":case"live-frame-tail":case void 0:default:return h$(e.screenText??"",n)}}function m$(e){return e.patterns.map(t=>Fi(t.regex,t.flags??"i"))}function f$(e){const t=Fi(e.regex,e.flags??"m"),s=(e.withFooter??[]).map(n=>{if(n.kind==="regex"){const a=Fi(n.pattern,n.flags??"i");return{test:o=>a.test(o)}}const i=n.pattern.toLowerCase();return{test:a=>a.toLowerCase().includes(i)}});return{prompt:t,footers:s}}function g$(e,t){const s=t.screenText??"";if(Fi(e.questionPattern,e.questionFlags??"i").test(s))return!0;for(const i of e.questionVariants??[])if(Fi(i.regex,i.flags??"i").test(s))return!0;return!1}function x$(e,t,s,n){switch(e){case"spinner":{if(!t.spinner||!n.spinner)return null;const i=pf(s,t.spinner.scope,t.spinner.scopeWindowLines);return n.spinner.some(a=>a.test(i))?"generating":null}case"modal":return t.modal&&g$(t.modal,s)?"waiting_approval":null;case"settled-prompt":{if(!t.settledPrompt||!n.settled)return null;const i=pf(s,t.settledPrompt.scope,t.settledPrompt.scopeWindowLines);return n.settled.prompt.test(i)&&(n.settled.footers.length===0||n.settled.footers.every(a=>a.test(i)))?"idle":null}case"cue-ordering":case"error-detection":case"approval-stitching":return null;default:return null}}function vv(e){var a;const t=e.spinner?m$(e.spinner):null,s=e.settledPrompt?f$(e.settledPrompt):null,n={spinner:t,settled:s},i=(a=e.dispatchOrder)!=null&&a.order&&e.dispatchOrder.order.length>0?e.dispatchOrder.order:wv;return function(l){const c=e.visibleRegion?{...l,screenText:uf(e.visibleRegion,l.screenText??""),tail:uf(e.visibleRegion,l.tail)}:l;for(const d of i){const p=x$(d,e,c,n);if(p!==null)return p}return null}}var wv,_p=We({"src/providers/sdk/v1/builders/cli/detect-status.ts"(){Np(),wv=["spinner","modal","settled-prompt"]}});function Bi(e,t){try{return new RegExp(e,t)}catch(s){throw new Error(`Invalid regex /${e}/${t??""}: ${s.message}`)}}function b$(e,t){const s=Bi(e.questionPattern,e.questionFlags??"i");for(let n=t.length-1;n>=0;n-=1)if(s.test(t[n]))return{index:n,matchedSource:"primary"};for(const n of e.questionVariants??[]){const i=Bi(n.regex,n.flags??"i");for(let a=t.length-1;a>=0;a-=1)if(i.test(t[a]))return{index:a,matchedSource:n.label??"variant"}}return null}function y$(e,t,s){const n=e.scope??"between-last-two-separators";if(n==="whole-screen")return{start:0,end:t.length};if(n==="window-around-question"){const o=e.scopeWindowLines??16;return{start:Math.max(0,s-2),end:Math.min(t.length,s+o)}}let i=-1,a=-1;for(let o=t.length-1;o>=0;o-=1)if(kv.test(t[o].trim())){if(i<0)i=o;else if(a<0){a=o;break}}return i>=0&&a>=0?{start:a,end:i+1}:{start:Math.max(0,s-4),end:Math.min(t.length,s+16)}}function v$(e,t,s,n){const i=Bi(e.buttonPattern,e.buttonFlags??"m"),a=[],o=Number.isInteger(e.buttonLabelGroup)&&(e.buttonLabelGroup??0)>0?e.buttonLabelGroup:1;let l=s;for(;l<n;){const c=t[l],d=i.exec(c),p=(d==null?void 0:d[o])??(o===1&&d&&d.length>2?d[d.length-1]:void 0);if(d&&p){let h=p.trim();if(e.continuationLines){let m=l+1;for(;m<n;){const g=t[m];if(!g.trim()||i.test(g)||!/^\s+/.test(g))break;h+=" "+g.trim(),m+=1}l=m}else l+=1;a.push(h)}else l+=1}return a}function w$(e,t,s,n,i){const a=[];if(e.contextHeader){const o=Bi(e.contextHeader.regex,(e.contextHeader.flags??"i")+"m"),l=t.slice(n,i).join(`
|
|
596
|
+
`),c=o.exec(l);c&&a.push(c[1]?c[1].trim():c[0].trim())}return a.push(t[s].trim()),a.filter(Boolean).join(" — ")}function S$(e,t,s,n){if(!e.inlineButtonPattern)return[];const i=e.inlineButtonFlags??"gi",a=i.includes("g")?i:i+"g",o=Bi(e.inlineButtonPattern,a),l=[];for(let c=s;c<n;c+=1){let d;for(o.lastIndex=0;(d=o.exec(t[c]))!==null;){const p=(d[1]??d[0]).trim();p&&!l.includes(p)&&l.push(p),d.index===o.lastIndex&&(o.lastIndex+=1)}}return l}function Sv(e,t){const s=e.minButtons??2;return function(i){const a=i.screenText??i.buffer??"";if(!a)return null;const l=a.split(`
|
|
597
|
+
`),c=b$(e,l);if(!c)return null;const{start:d,end:p}=y$(e,l,c.index);if(c.index<d||c.index>=p)return null;let h=v$(e,l,c.index+1,p);return h.length<s&&e.inlineButtonPattern&&(h=S$(e,l,c.index,p)),h.length<s?null:{message:w$(e,l,c.index,d,p),buttons:h}}}var kv,Cp=We({"src/providers/sdk/v1/builders/cli/parse-approval.ts"(){Np(),kv=/^(?:─|━|═|━){10,}\s*$/}});function jv(e){return String(e||"").replace(/\x1b\[(\d*)C/g,(t,s)=>" ".repeat(Math.max(1,Number(s)||1))).replace(/\x1b\[\d*D/g,"").replace(Nv,"").replace(_v,"").replace(/\x1b[P^_X][\s\S]*?(?:\x07|\x1b\\)/g,"").replace(/\x1b(?:[@-Z\\-_])/g,"")}function k$(e){return jv(e).replace(//g,"").split(/\r?\n/).map(t=>t.replace(/\s+$/,""))}function hf(e,t){var s;return e?String(t==="screen"?e.screenText||((s=e.screen)==null?void 0:s.text)||"":t==="tail"?e.tail||e.recentBuffer||e.buffer||"":e.buffer||e.rawBuffer||e.screenText||""):""}function j$(e){return Zw.createHash("sha1").update(String(e||"")).digest("hex").slice(0,12)}function N$(e,t){const s=Array.isArray(e)?e:[];let n=-1;return s.map((i,a)=>{const o=(i==null?void 0:i.role)||"assistant",l=(i==null?void 0:i.kind)||"standard",c=typeof(i==null?void 0:i.content)=="string"?i.content:"";(o==="user"||n<0)&&(n+=1);const d=[o,l,"",a,c].join(`
|
|
598
|
+
`),p=`v2-pty:${o}:${l}:${a}:${j$(d)}`,h=`bubble:${p}`,m=`turn:${n}`,g=t==="generating"&&o==="assistant"&&a===s.length-1;return{...i,providerUnitKey:p,bubbleId:h,sequence:a,_turnKey:m,bubbleState:g?"streaming":"final"}})}function _$(e){var g,b,f;if(!e.transcriptPty)throw new Error("buildParseSessionFromTui: spec.transcriptPty is required");const t=new RegExp(e.transcriptPty.assistantPrefix.regex,e.transcriptPty.assistantPrefix.flags||""),s=e.transcriptPty.userPrefix?new RegExp(e.transcriptPty.userPrefix.regex,e.transcriptPty.userPrefix.flags||""):null,n=e.transcriptPty.toolPrefix?new RegExp(e.transcriptPty.toolPrefix.regex,e.transcriptPty.toolPrefix.flags||""):null,i=((g=e.transcriptPty.toolPrefix)==null?void 0:g.skip)??!1,a=(e.transcriptPty.chromePatterns||[]).map(v=>new RegExp(v.regex,v.flags||"")),o=((b=e.transcriptPty.continuationLine)==null?void 0:b.indented)??!1,l=e.transcriptPty.stripLeadingChrome??!0,c=e.transcriptPty.scope??"buffer",d=e.spinner||e.settledPrompt||e.modal||e.dispatchOrder?vv({spinner:e.spinner,settledPrompt:e.settledPrompt,modal:e.modal,dispatchOrder:e.dispatchOrder}):()=>null,p=e.modal?Sv(e.modal):()=>null,h=e.sessionIdExtraction?new RegExp(e.sessionIdExtraction.regex,e.sessionIdExtraction.flags??"i"):null,m=((f=e.sessionIdExtraction)==null?void 0:f.scope)??"tail";return function(w){var C;const x=d(w)??"idle",S=p(w),k=hf(w,c),j=k$(k),y=[];let N=!l;for(const D of j){const T=D;if(T.trim()==="")continue;let A=!1;for(const E of a)if(E.test(T)){A=!0;break}if(A)continue;const P=s?T.match(s):null,F=n?T.match(n):null,J=T.match(t);if(P){N=!0;const E=(P[1]??P[0]).trim();E&&y.push({role:"user",kind:"standard",content:E});continue}if(F){if(N=!0,i)continue;const E=(F[1]??F[0]).trim();E&&y.push({role:"assistant",kind:"tool",content:E});continue}if(J){N=!0;const E=(J[1]??J[0]).trim();E&&y.push({role:"assistant",kind:"standard",content:E});continue}if(!N||o&&!/^\s/.test(T))continue;const R=y[y.length-1];if(!R)continue;const I=T.replace(/^\s+/,"");I&&(R.content=R.content?`${R.content}
|
|
599
|
+
${I}`:I)}const _={status:x,messages:y,activeModal:S,modal:S,parsedStatus:x};if(h){const T=jv(hf(w,m)).match(h),A=(C=T==null?void 0:T[1])==null?void 0:C.trim();A&&(_.providerSessionId=A)}return _}}var Nv,_v,Cv=We({"src/providers/sdk/v1/builders/cli/parse-session.ts"(){_p(),Cp(),Nv=/\x1b\[[0-?]*[ -/]*[@-~]/g,_v=/\x1b\][^\x07\x1b\n]*(?:\x07|\x1b\\|(?=\n|$))/g}});function mf(e){const t=typeof(e==null?void 0:e.screenText)=="string"?e.screenText:"",s=typeof(e==null?void 0:e.rawBuffer)=="string"?e.rawBuffer:"",n=typeof(e==null?void 0:e.tail)=="string"?e.tail:"";return{screenTextLen:t.length,rawBufferLen:s.length,tailLen:n.length,isWaitingForResponse:typeof(e==null?void 0:e.isWaitingForResponse)=="boolean"?e.isWaitingForResponse:void 0,screenTextHead:t?t.slice(0,200):void 0}}function C$(e){try{const t=JSON.stringify(e);return t&&t.length>400?`${t.slice(0,400)}…[truncated ${t.length-400}]`:t??"undefined"}catch(t){return`<unserializable: ${(t==null?void 0:t.message)||t}>`}}var Ec,Rc,ff,Iv,I$=We({"src/cli-adapters/cli-script-runner.ts"(){Ve(),Hr(),_p(),Cp(),Cv(),Ec=64,Rc=50,ff=3e4,Iv=class{constructor(e){re(this,"scripts",{});re(this,"scriptState",null);re(this,"_parseErrorMessage",null);re(this,"cliType");re(this,"sdk",{});re(this,"invocationTrace",[]);re(this,"scriptCallBudgetMs",Rc);re(this,"lastBudgetWarnAt",new Map);this.cliType=e}getInvocationTrace(){return this.invocationTrace.slice()}clearInvocationTrace(){this.invocationTrace=[]}setScriptCallBudget(e){if(typeof e!="number"||!Number.isFinite(e)){this.scriptCallBudgetMs=Rc;return}const t=Math.max(1,Math.min(5e3,Math.floor(e)));this.scriptCallBudgetMs=t}getScriptCallBudgetMs(){return this.scriptCallBudgetMs}recordTrace(e){this.invocationTrace.push(e),this.invocationTrace.length>Ec&&this.invocationTrace.splice(0,this.invocationTrace.length-Ec)}setScripts(e,t){this.sdk=this.buildSdk(t);const s=t,n={...e};if(typeof n.detectStatus!="function"&&this.sdk.declarativeDetectStatus&&(n.detectStatus=this.sdk.declarativeDetectStatus),typeof n.parseApproval!="function"&&this.sdk.declarativeParseApproval&&(n.parseApproval=this.sdk.declarativeParseApproval),typeof n.parseSession!="function"&&(s!=null&&s.transcriptPty))try{const i=_$({spinner:s.spinner,settledPrompt:s.settledPrompt,modal:s.modal,dispatchOrder:s.dispatchOrder,transcriptPty:s.transcriptPty});n.parseSession=a=>{const o=i(a);return{...o,messages:N$(o.messages,o.status??"idle")}}}catch(i){_e.warn("CLI",`[${this.cliType}] buildParseSessionFromTui failed: ${(i==null?void 0:i.message)||i}`)}this.scripts=n,this._parseErrorMessage=null,this.scriptState=typeof n.createState=="function"?n.createState()??null:null}buildSdk(e){const t=e;if(!t)return{};const s={};if(t.spinner||t.settledPrompt||t.modal||t.dispatchOrder)try{s.declarativeDetectStatus=vv({spinner:t.spinner,settledPrompt:t.settledPrompt,modal:t.modal,dispatchOrder:t.dispatchOrder})}catch(n){_e.warn("CLI",`[${this.cliType}] buildDetectStatusFromTui failed: ${(n==null?void 0:n.message)||n}`)}if(t.modal)try{s.declarativeParseApproval=Sv(t.modal)}catch(n){_e.warn("CLI",`[${this.cliType}] buildParseApprovalFromTui failed: ${(n==null?void 0:n.message)||n}`)}return s}resetSessionState(){this.scriptState=null,this.invocationTrace=[],this.lastBudgetWarnAt.clear()}get cliScripts(){return this.scripts}hasDetectStatus(){return typeof this.scripts.detectStatus=="function"}hasParseSession(){return typeof this.scripts.parseSession=="function"}getScriptNames(){return r$(this.scripts)}get parseErrorMessage(){return this._parseErrorMessage}clearParseError(){this._parseErrorMessage=null}detectStatus(e){if(!this.scripts.detectStatus)return null;try{return this.invoke("detectStatus",this.scripts.detectStatus,e)}catch(t){return _e.warn("CLI",`[${this.cliType}] detectStatus error: ${(t==null?void 0:t.message)||t}`),null}}parseApproval(e){if(!this.scripts.parseApproval)return null;try{return this.invoke("parseApproval",this.scripts.parseApproval,e)}catch(t){return _e.warn("CLI",`[${this.cliType}] parseApproval error: ${(t==null?void 0:t.message)||t}`),null}}parseSession(e){if(!this.scripts.parseSession)return this._parseErrorMessage=`${this.cliType} parseSession unavailable`,null;try{const t=this.invoke("parseSession",this.scripts.parseSession,e);return this._parseErrorMessage=null,t&&typeof t=="object"?t:null}catch(t){return this._parseErrorMessage=(t==null?void 0:t.message)||String(t),_e.warn("CLI",`[${this.cliType}] parseSession error: ${this._parseErrorMessage}`),null}}invokeByName(e,t){const s=this.scripts[e];if(typeof s!="function")throw new Error(`CLI script '${e}' not available`);return this.invoke(e,s,t)}invoke(e,t,s){const n=t.length,i=Date.now(),a=typeof process<"u"&&typeof process.hrtime=="function"?process.hrtime.bigint():null;let o;try{n>=3?o=t(this.scriptState,s,this.sdk):n===2?o=t(this.scriptState,s):o=t(s);const l=a?Number((process.hrtime.bigint()-a)/1000n):0,c=this.checkBudget(e,l);return this.recordTrace({at:i,scriptName:e,arity:n,inputSummary:mf(s),ok:!0,elapsedUs:l,resultSummary:C$(o),...c?{timedOut:!0}:{}}),o}catch(l){const c=a?Number((process.hrtime.bigint()-a)/1000n):0,d=this.checkBudget(e,c);throw this.recordTrace({at:i,scriptName:e,arity:n,inputSummary:mf(s),ok:!1,elapsedUs:c,error:l!=null&&l.message?String(l.message).slice(0,400):String(l).slice(0,400),...d?{timedOut:!0}:{}}),l}}checkBudget(e,t){const s=this.scriptCallBudgetMs*1e3;if(t<=s)return!1;const n=Date.now(),i=this.lastBudgetWarnAt.get(e)??0;return n-i>=ff&&(this.lastBudgetWarnAt.set(e,n),_e.warn("CLI",`[${this.cliType}] script ${e} took ${t}us, budget ${s}us`)),!0}}}});function gf(e,t){return e?!Number.isFinite(t)||t<=0?e:t>=e.length?"":e.slice(t):""}function Pd(e,t){return Array.isArray(e)?e:[]}function Dd(e){const{accumulatedBuffer:t,accumulatedRawBuffer:s,recentOutputBuffer:n,terminalScreenText:i,workingDir:a,providerSessionId:o,historySessionId:l,baseMessages:c,partialResponse:d,isWaitingForResponse:p,scope:h,runtimeSettings:m,spawnAt:g}=e,b=h?gf(t,h.bufferStart):t,f=h?gf(s,h.rawBufferStart):s,v=i,w=b.slice(-1e3)||n;return{buffer:b,rawBuffer:f,recentBuffer:w,screenText:v,workspace:a,workingDir:a,providerSessionId:o,historySessionId:l,screen:ts(v),bufferScreen:ts(b),recentScreen:ts(w),messages:[...c],partialResponse:d,isWaitingForResponse:p,promptText:(h==null?void 0:h.prompt)||"",settings:{...m},...typeof g=="number"&&g>0?{spawnAt:g}:{}}}function sr(e,t=800){const s=bi(String(e||""));return s.length<=t?s:`…${s.slice(-t)}`}var Av=We({"src/cli-adapters/provider-cli-parse.ts"(){Hr()}}),Va,xf,bf,Pc,yf,Dc,Tv,A$=We({"src/cli-adapters/cli-state-engine.ts"(){Ve(),Av(),Hr(),Va=3e3,xf=2,bf=300,Pc=250,yf=6e4,Dc=2e3,Tv=class{constructor(e,t,s,n,i){re(this,"currentStatus","starting");re(this,"isWaitingForResponse",!1);re(this,"currentTurnScope",null);re(this,"activeModal",null);re(this,"lastApprovalResolvedAt",0);re(this,"lastResolvedModalMessage","");re(this,"approvalEntrySeq",0);re(this,"lastResolvedEntrySeq",-1);re(this,"modalLostAt",0);re(this,"approvalExitTimeout",null);re(this,"responseEpoch",0);re(this,"submitPendingUntil",0);re(this,"responseSettleIgnoreUntil",0);re(this,"submitRetryUsed",!1);re(this,"submitRetryPromptSnippet","");re(this,"finishRetryCount",0);re(this,"providerErrorMessage",null);re(this,"providerErrorReason",null);re(this,"settleTimer",null);re(this,"idleTimeout",null);re(this,"finishRetryTimer",null);re(this,"providerErrorRetryTimer",null);re(this,"providerErrorRetryKey","");re(this,"pendingScriptStatus",null);re(this,"pendingScriptStatusSince",0);re(this,"pendingScriptStatusTimer",null);re(this,"idleFinishCandidate",null);re(this,"pendingIdleFinishTimer",null);re(this,"pendingIdleFinishAt",0);re(this,"statusHistory",[]);re(this,"traceEntries",[]);re(this,"traceSeq",0);re(this,"traceSessionId","");this.provider=e,this.runner=t,this.transport=s,this.callbacks=n,this.timeouts=i}setStatus(e,t){const s=this.currentStatus;s!==e&&(this.currentStatus=e,this.statusHistory.push({status:e,at:Date.now(),trigger:t}),this.statusHistory.length>50&&this.statusHistory.shift(),this.recordTrace("status",{previousStatus:s,trigger:t||null}),_e.info("CLI",`[${this.provider.type}] status: ${s} → ${e}${t?` (${t})`:""}`))}scheduleSettle(){this.settleTimer&&clearTimeout(this.settleTimer);const e=this.responseEpoch,t=Math.max(this.timeouts.outputSettle,this.submitPendingUntil>Date.now()?this.submitPendingUntil-Date.now()+this.timeouts.outputSettle:0);this.settleTimer=setTimeout(()=>{this.settleTimer=null,e===this.responseEpoch&&this.evaluateSettled(this.transport.getSnapshot())},t)}onTurnStarted(e){this.isWaitingForResponse=!0,this.finishRetryCount=0,this.clearIdleFinishCandidate("send_message"),this.currentTurnScope=e,this.responseEpoch+=1}onPtyExit(){this.clearAllTimers(),this.setStatus("stopped","pty_exit")}onSpawnReady(){this.setStatus("starting","pty_ready"),this.traceEntries=[],this.traceSeq=0,this.traceSessionId=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,this.recordTrace("session_start",{providerType:this.provider.type})}resolveModal(e){const t=this.transport.getSnapshot(),s=typeof this.transport.runParseApproval=="function"?d=>this.transport.runParseApproval(d.recentOutputBuffer.slice(-500)):d=>this.runParseApproval(d);let n=this.activeModal??s(t);if(!n&&this.runner.hasParseSession())try{const d=this.runParseSession(t),p=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"&&p&&(n=p,this.activeModal=p,this.approvalEntrySeq++,this.currentStatus!=="waiting_approval"&&(this.setStatus("waiting_approval","resolve_modal_parse"),this.callbacks.onStatusChange()))}catch{}if(!this.transport.isAlive())return;const i=Array.isArray(n==null?void 0:n.buttons)&&n.buttons.some(d=>typeof d=="string"&&d.trim());if(!n||!i)return;const a=typeof(n==null?void 0:n.message)=="string"?n.message.trim():"",o=!!this.lastApprovalResolvedAt&&Date.now()-this.lastApprovalResolvedAt<this.timeouts.approvalCooldown,l=this.approvalEntrySeq===this.lastResolvedEntrySeq;if(o&&l&&a===this.lastResolvedModalMessage)return;this.clearIdleFinishCandidate("resolve_modal"),this.recordTrace("resolve_modal",{buttonIndex:e,activeModal:n,approvalEntrySeq:this.approvalEntrySeq}),this.activeModal=null,this.lastApprovalResolvedAt=Date.now(),this.lastResolvedModalMessage=a,this.lastResolvedEntrySeq=this.approvalEntrySeq,this.responseSettleIgnoreUntil=Date.now()+this.timeouts.outputSettle+400,this.approvalExitTimeout&&(clearTimeout(this.approvalExitTimeout),this.approvalExitTimeout=null),this.setStatus("generating","approval_resolved"),this.callbacks.onStatusChange();const c=this.transport.getApprovalKeyForIndex(e);if(c!==void 0)this.transport.writeRaw(c);else{const d="\x1B[B",p=Array.isArray(n==null?void 0:n.buttons)?n.buttons.length:0,h=p>0?Math.min(Math.max(0,e),p-1):Math.max(0,e);this.transport.writeRaw(d.repeat(h)+"\r")}}isApprovalRecentlyResolved(){return!!(this.lastApprovalResolvedAt&&Date.now()-this.lastApprovalResolvedAt<this.timeouts.approvalCooldown)}clearStaleIdleResponseGuard(e,t){const s=this.activeModal??(typeof this.transport.runParseApproval=="function"?this.transport.runParseApproval(t.recentOutputBuffer.slice(-500)):this.runParseApproval(t)),n=(typeof this.transport.runDetectStatus=="function"?this.transport.runDetectStatus(t.recentOutputBuffer):this.runDetectStatus(t))==="idle";return!this.isWaitingForResponse||this.currentStatus!=="idle"||!n||s?!1:(this.clearAllTimers(),this.clearIdleFinishCandidate(e),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:e}),this.callbacks.onTurnCompleted(),!0)}clearParsedIdleResponseGuard(e,t,s){const n=typeof(t==null?void 0:t.status)=="string"?t.status.trim():"",i=(t==null?void 0:t.activeModal)??(t==null?void 0:t.modal)??null,a=this.activeModal??(typeof this.transport.runParseApproval=="function"?this.transport.runParseApproval(s.recentOutputBuffer.slice(-500)):this.runParseApproval(s));return!this.isWaitingForResponse||n!=="idle"||i||a||!this.parsedStatusHasFinalAssistantMessage(t)?!1:(this.clearAllTimers(),this.clearIdleFinishCandidate(e),this.isWaitingForResponse=!1,this.responseSettleIgnoreUntil=0,this.submitRetryUsed=!1,this.submitRetryPromptSnippet="",this.finishRetryCount=0,this.currentTurnScope=null,this.activeModal=null,this.setStatus("idle",e),this.recordTrace("parsed_idle_response_cleared",{reason:e,parsedStatus:n,parsedMessageCount:Array.isArray(t==null?void 0:t.messages)?t.messages.length:0}),this.callbacks.onTurnCompleted(),!0)}clearAllTimers(){this.settleTimer&&(clearTimeout(this.settleTimer),this.settleTimer=null),this.idleTimeout&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.approvalExitTimeout&&(clearTimeout(this.approvalExitTimeout),this.approvalExitTimeout=null),this.finishRetryTimer&&(clearTimeout(this.finishRetryTimer),this.finishRetryTimer=null),this.pendingScriptStatusTimer&&(clearTimeout(this.pendingScriptStatusTimer),this.pendingScriptStatusTimer=null),this.providerErrorRetryTimer&&(clearTimeout(this.providerErrorRetryTimer),this.providerErrorRetryTimer=null),this.pendingIdleFinishTimer&&(clearTimeout(this.pendingIdleFinishTimer),this.pendingIdleFinishTimer=null,this.pendingIdleFinishAt=0),this.providerErrorRetryKey=""}resetActiveTurnState(){this.clearAllTimers(),this.isWaitingForResponse=!1,this.responseSettleIgnoreUntil=0,this.submitRetryUsed=!1,this.submitRetryPromptSnippet="",this.finishRetryCount=0,this.currentTurnScope=null,this.activeModal=null,this.pendingScriptStatus=null,this.pendingScriptStatusSince=0}clearIdleFinishCandidate(e){this.idleFinishCandidate&&(this.recordTrace("idle_candidate_reset",{reason:e,candidate:this.idleFinishCandidate}),this.idleFinishCandidate=null)}hasActionableApproval(e){return!!(e??this.activeModal)}getTraceEntries(){return this.traceEntries}getStatusHistory(){return this.statusHistory}getTraceSessionId(){return this.traceSessionId}recordExternalTrace(e,t={}){this.recordTrace(e,t)}runDetectStatus(e){const t=e.recentOutputBuffer.slice(-500);return this.runner.detectStatus({tail:t,screenText:e.screenText,rawBuffer:e.accumulatedRawBuffer,isWaitingForResponse:e.isWaitingForResponse,screen:ts(e.screenText),tailScreen:ts(t)})}runParseApproval(e){const t=e.recentOutputBuffer.slice(-500),s=e.screenText||e.accumulatedBuffer;return this.runner.parseApproval({buffer:s,screenText:e.screenText,rawBuffer:e.accumulatedRawBuffer,tail:t,screen:ts(e.screenText),bufferScreen:ts(s),tailScreen:ts(t)})}runParseSession(e){if(typeof this.transport.runParseSession=="function"){const i=this.transport.runParseSession();return i&&typeof i=="object"&&this.callbacks.onApplyParsedSession(i),i}const t=e.recentOutputBuffer.slice(-500),s=Dd({accumulatedBuffer:e.accumulatedBuffer,accumulatedRawBuffer:e.accumulatedRawBuffer,recentOutputBuffer:e.recentOutputBuffer,terminalScreenText:e.parseScreenText,workingDir:e.workingDir,providerSessionId:e.providerSessionId||void 0,historySessionId:e.providerSessionId||void 0,baseMessages:[],partialResponse:e.responseBuffer,isWaitingForResponse:e.isWaitingForResponse,scope:e.currentTurnScope,runtimeSettings:e.runtimeSettings}),n=this.runner.parseSession({...s,tail:t,tailScreen:ts(t)});return n&&typeof n=="object"&&this.callbacks.onApplyParsedSession(n),n}evaluateSettled(e){var b,f,v;const t=Date.now();if(this.submitPendingUntil>t||this.responseSettleIgnoreUntil>t){const w=Math.max(this.submitPendingUntil-t,this.responseSettleIgnoreUntil-t)+50;this.settleTimer&&clearTimeout(this.settleTimer),this.settleTimer=setTimeout(()=>{this.settleTimer=null,this.evaluateSettled(this.transport.getSnapshot())},w);return}if(!this.isWaitingForResponse&&!this.currentTurnScope&&!this.activeModal&&!this.runner.parseErrorMessage){e.recentOutputBuffer;const w=this.runParseApproval(e),x=this.runner.hasDetectStatus()?this.runDetectStatus(e):null;if(!w&&x==="idle"&&this.currentStatus==="idle")return}const s=this.runParseSession(e);if(!s)return;const{status:n,messages:i}=s,a=s.activeModal??s.modal??null,o=s.parsedStatus??null,l=Pd(i,{lastOutputAt:e.lastOutputAt});if(this.maybeCommitVisibleIdleTranscript(s,l,e))return;const c=[...l].reverse().find(w=>w.role==="assistant");if(this.currentTurnScope&&!c&&!this.submitRetryUsed&&this.transport.isAlive()&&!this.hasActionableApproval()&&Rd(e.screenText,Cn(this.submitRetryPromptSnippet||((b=this.currentTurnScope)==null?void 0:b.prompt)||""))&&!this.hasMeaningfulResponseBuffer(e,Cn(this.submitRetryPromptSnippet||((f=this.currentTurnScope)==null?void 0:f.prompt)||""))){this.submitRetryUsed=!0,this.responseSettleIgnoreUntil=Date.now()+this.timeouts.outputSettle+400,_e.info("CLI",`[${this.provider.type}] Retrying submit key from settled parser (no assistant yet)`),this.transport.writeRaw("\r"),this.settleTimer&&clearTimeout(this.settleTimer),this.settleTimer=setTimeout(()=>{this.settleTimer=null,this.evaluateSettled(this.transport.getSnapshot())},this.timeouts.outputSettle+150);return}if(!n)return;const d=this.currentStatus,p={now:t,modal:a,status:n,parsedMessages:l,lastParsedAssistant:c,parsedStatus:o||null,prevStatus:d};if(!this.applyPendingScriptStatusDebounce(p))return;const h=this.hasRecentInteractiveActivity(e,t);_e.debug("CLI",`[${this.provider.type}] settled diagnostics prompt=${JSON.stringify(((v=this.currentTurnScope)==null?void 0:v.prompt)||"").slice(0,140)} status=${String(n||"")} parsedStatus=${String(o||"")} parsedMsgCount=${l.length} lastParsedAssistant=${JSON.stringify(((c==null?void 0:c.content)||"").slice(0,120)).slice(0,160)} responseBuffer=${JSON.stringify((e.responseBuffer||"").slice(0,160)).slice(0,220)} recentActivity=${h}`);const m=(()=>{var k;if(o!=="idle")return!1;const w=Array.isArray(l)?l:[];let x=-1;for(let j=w.length-1;j>=0;j--)if(((k=w[j])==null?void 0:k.role)==="user"){x=j;break}return(x>=0?w.slice(x+1):w).some(j=>{var N;return!j||j.role!=="assistant"||typeof j.content!="string"||!j.content.trim()?!1:(typeof j.kind=="string"&&j.kind.trim()?j.kind.trim():"standard")==="standard"&&((N=j.meta)==null?void 0:N.streaming)!==!0})})();if(n==="idle"&&this.isWaitingForResponse&&!!this.currentTurnScope&&!a&&!m){this.applyHoldGenerating(p);return}if(n==="error"){if(this.maybeScheduleProviderErrorRetry(p,s,e))return;this.applyError(p,s);return}if(n==="waiting_approval"){this.applyWaitingApproval(p);return}if(n==="generating"){this.applyGenerating(p);return}n==="idle"&&this.applyIdle(p,e,t)}applyPendingScriptStatusDebounce(e){const{now:t,status:s,prevStatus:n}=e;if(!(n==="idle"&&!this.isWaitingForResponse&&!this.currentTurnScope&&(s==="generating"||s==="waiting_approval")))return this.pendingScriptStatus=null,this.pendingScriptStatusSince=0,this.pendingScriptStatusTimer&&(clearTimeout(this.pendingScriptStatusTimer),this.pendingScriptStatusTimer=null),!0;const a=l=>{this.pendingScriptStatusTimer&&clearTimeout(this.pendingScriptStatusTimer),this.pendingScriptStatusTimer=setTimeout(()=>{this.pendingScriptStatusTimer=null,this.evaluateSettled(this.transport.getSnapshot())},l)};if(this.pendingScriptStatus!==s)return this.pendingScriptStatus=s,this.pendingScriptStatusSince=t,a(Va),!1;const o=t-this.pendingScriptStatusSince;return o<Va?(a(Va-o),!1):!0}applyHoldGenerating(e){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.callbacks.onStatusChange()}applyWaitingApproval(e){const{modal:t}=e;this.clearIdleFinishCandidate("waiting_approval");const s=this.lastApprovalResolvedAt&&Date.now()-this.lastApprovalResolvedAt<this.timeouts.approvalCooldown;if(s&&!t){this.approvalExitTimeout&&(clearTimeout(this.approvalExitTimeout),this.approvalExitTimeout=null),this.activeModal=null;const n=s?"approval_cooldown_non_actionable":"approval_prompt_gone_non_actionable";this.isWaitingForResponse?(this.setStatus("idle",n),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",n),this.callbacks.onStatusChange();return}if(!s||t){if(!t){if(_e.warn("CLI",`[${this.provider.type}] detectStatus=waiting_approval but parseApproval returned null; ignoring`),this.currentStatus==="waiting_approval"&&this.activeModal){const o=this.modalLostAt||Date.now();this.modalLostAt||(this.modalLostAt=o),Date.now()-o>=this.timeouts.approvalCooldown&&(this.activeModal=null,this.modalLostAt=0,this.setStatus("generating","approval_lost_modal"),this.callbacks.onStatusChange())}return}this.modalLostAt=0,this.isWaitingForResponse=!0,this.setStatus("waiting_approval","script_detect");const n=this.activeModal,i=Array.isArray(n==null?void 0:n.buttons)?n.buttons.length:0,a=Array.isArray(t.buttons)?t.buttons.length:0;(!n||i!==a)&&(this.activeModal=t,this.approvalEntrySeq++,this.callbacks.onStatusChange()),this.idleTimeout&&clearTimeout(this.idleTimeout),this.armApprovalExitTimeout()}}applyGenerating(e){const{modal:t,parsedMessages:s,lastParsedAssistant:n,parsedStatus:i,prevStatus:a}=e,o=!this.currentTurnScope;if(!this.isWaitingForResponse&&o&&!t)return;this.clearIdleFinishCandidate("generating"),this.cancelPendingIdleFinish("generating_signal_returned");const l=this.transport.getSnapshot(),c=l.screenText||l.accumulatedBuffer,d=/(^|\n)\s*[❯›>]\s*(?:\n|$)/m.test(c),p=i==="generating"&&!!n;a==="idle"&&!this.isWaitingForResponse&&o&&!t&&d&&!p||(a==="waiting_approval"&&(this.approvalExitTimeout&&(clearTimeout(this.approvalExitTimeout),this.approvalExitTimeout=null),this.activeModal=null,this.lastApprovalResolvedAt=Date.now()),this.isWaitingForResponse||(this.isWaitingForResponse=!0),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),this.callbacks.onStatusChange())}applyError(e,t){this.clearIdleFinishCandidate("provider_error"),this.clearAllTimers(),this.isWaitingForResponse=!1,this.responseSettleIgnoreUntil=0,this.submitRetryUsed=!1,this.submitRetryPromptSnippet="",this.finishRetryCount=0,this.currentTurnScope=null,this.activeModal=null,this.providerErrorMessage=typeof t.errorMessage=="string"&&t.errorMessage.trim()?t.errorMessage.trim():"Provider reported an error",this.providerErrorReason=typeof t.errorReason=="string"&&t.errorReason.trim()?t.errorReason.trim():"provider_error",this.setStatus("error",this.providerErrorReason),this.callbacks.onStatusChange()}maybeScheduleProviderErrorRetry(e,t,s){const n=typeof t.retryPrompt=="string"?String(t.retryPrompt).trim():"",i=typeof t.retryDelayMs=="number"?Number(t.retryDelayMs):NaN;if(!n||!Number.isFinite(i)||i<0||!this.transport.isAlive())return!1;const a=typeof t.retryAttempt=="number"?Number(t.retryAttempt):0,o=typeof t.errorReason=="string"&&t.errorReason.trim()?t.errorReason.trim():"provider_error",l=`${o}:${a}:${n}`;return this.providerErrorRetryTimer&&this.providerErrorRetryKey===l||(this.providerErrorRetryTimer&&clearTimeout(this.providerErrorRetryTimer),this.providerErrorRetryKey=l,this.clearIdleFinishCandidate("provider_error_retry"),this.idleTimeout&&(clearTimeout(this.idleTimeout),this.idleTimeout=null),this.approvalExitTimeout&&(clearTimeout(this.approvalExitTimeout),this.approvalExitTimeout=null),this.providerErrorMessage=typeof t.errorMessage=="string"&&t.errorMessage.trim()?t.errorMessage.trim():"Provider reported an error",this.providerErrorReason=o,this.activeModal=null,this.responseSettleIgnoreUntil=Date.now()+i+this.timeouts.outputSettle+400,this.setStatus("generating","provider_error_retry_scheduled"),this.callbacks.onStatusChange(),this.providerErrorRetryTimer=setTimeout(()=>{this.providerErrorRetryTimer=null,this.providerErrorRetryKey="",this.transport.isAlive()&&(this.responseSettleIgnoreUntil=Date.now()+this.timeouts.outputSettle+400,this.submitRetryUsed=!1,this.transport.writeRaw(`${n}\r`),this.settleTimer&&clearTimeout(this.settleTimer),this.settleTimer=setTimeout(()=>{this.settleTimer=null,this.evaluateSettled(this.transport.getSnapshot())},this.timeouts.outputSettle+150))},i)),!0}applyIdle(e,t,s){var f;const{modal:n,lastParsedAssistant:i,prevStatus:a}=e;if(a==="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){a!=="idle"&&(this.clearIdleFinishCandidate("idle_without_response"),this.setStatus("idle","script_detect"),this.callbacks.onStatusChange());return}const o=t.lastNonEmptyOutputAt?s-t.lastNonEmptyOutputAt:Number.MAX_SAFE_INTEGER,l=t.lastScreenChangeAt?s-t.lastScreenChangeAt:0,c=!!i,d=((f=i==null?void 0:i.content)==null?void 0:f.length)||0,p=this.timeouts.idleFinishConfirm,h=Math.max(p,this.timeouts.outputSettle),m=!n&&c&&o>=h&&l>=p,g=this.idleFinishCandidate,b=!!g&&g.responseEpoch===this.responseEpoch&&g.lastOutputAt===t.lastOutputAt&&g.lastScreenChangeAt===t.lastScreenChangeAt&&d>=g.assistantLength&&s-g.armedAt>=p;if(m&&b){this.clearIdleFinishCandidate("finish_response"),this.idleTimeout&&clearTimeout(this.idleTimeout),this.finishResponse();return}if(m){if(!g){this.armIdleFinishCandidate(t,d);return}}else this.clearIdleFinishCandidate("idle_not_ready");this.idleTimeout&&clearTimeout(this.idleTimeout),this.idleTimeout=setTimeout(()=>{if(this.isWaitingForResponse&&!this.hasActionableApproval()){if(this.shouldDeferIdleTimeoutFinish())return;const v=this.runParseSession(this.transport.getSnapshot());if(this.shouldDeferFinishForTranscript(v)){this.rescheduleTranscriptFinishCheck("transcript_idle_timeout_not_final");return}this.clearIdleFinishCandidate("idle_timeout_finish"),this.finishResponse()}},this.timeouts.idleFinish)}finishResponse(){if(this.submitPendingUntil>Date.now()||this.responseSettleIgnoreUntil>Date.now())return;const e=this.transport.getSnapshot(),t=this.runParseSession(e);if(this.shouldDeferFinishForTranscript(t)){this.rescheduleTranscriptFinishCheck("transcript_finish_not_final");return}this.clearIdleFinishCandidate("finish_response_enter");const s=this.commitCurrentTranscript(e);if(this.shouldRetryFinishResponse(e,s)){this.finishRetryCount+=1,this.finishRetryTimer&&clearTimeout(this.finishRetryTimer),this.finishRetryTimer=setTimeout(()=>{this.finishRetryTimer=null,this.isWaitingForResponse&&!this.hasActionableApproval()&&this.finishResponse()},bf);return}this.resetActiveTurnState(),this.callbacks.onTurnCompleted(),this.scheduleIdleFinish("response_finished"),this.transport.flushOutboundQueue()}scheduleIdleFinish(e){this.pendingIdleFinishTimer&&clearTimeout(this.pendingIdleFinishTimer),this.pendingIdleFinishAt=Date.now()+Dc,this.pendingIdleFinishTimer=setTimeout(()=>{this.pendingIdleFinishTimer=null,this.pendingIdleFinishAt=0,!this.isWaitingForResponse&&(this.setStatus("idle",e),this.callbacks.onStatusChange())},Dc)}cancelPendingIdleFinish(e){this.pendingIdleFinishTimer&&(clearTimeout(this.pendingIdleFinishTimer),this.pendingIdleFinishTimer=null,this.pendingIdleFinishAt=0,this.recordTrace("idle_finish_cancelled",{trigger:e}))}armApprovalExitTimeout(){this.approvalExitTimeout&&clearTimeout(this.approvalExitTimeout),this.approvalExitTimeout=setTimeout(()=>{if(!this.hasActionableApproval())return;const e=this.transport.getSnapshot(),t=typeof this.transport.runParseApproval=="function"?this.transport.runParseApproval(e.recentOutputBuffer.slice(-500)):this.runParseApproval(e);if((typeof this.transport.runDetectStatus=="function"?this.transport.runDetectStatus(e.recentOutputBuffer):this.runDetectStatus(e))==="waiting_approval"||!!t){if(!t){_e.warn("CLI",`[${this.provider.type}] approval timeout: no actionable modal; keeping fail-closed`),this.activeModal=null,this.callbacks.onStatusChange(),this.armApprovalExitTimeout();return}this.activeModal=t,this.callbacks.onStatusChange(),this.armApprovalExitTimeout();return}_e.warn("CLI",`[${this.provider.type}] Approval timeout — auto-clearing`),this.activeModal=null,this.lastApprovalResolvedAt=Date.now(),this.setStatus("idle","approval_timeout"),this.callbacks.onStatusChange()},yf)}armIdleFinishCandidate(e,t){const s=Date.now();this.idleFinishCandidate={armedAt:s,lastOutputAt:e.lastOutputAt,lastScreenChangeAt:e.lastScreenChangeAt,responseEpoch:this.responseEpoch,assistantLength:t},this.settleTimer&&clearTimeout(this.settleTimer),this.settleTimer=setTimeout(()=>{this.settleTimer=null,this.evaluateSettled(this.transport.getSnapshot())},this.timeouts.idleFinishConfirm)}shouldDeferIdleTimeoutFinish(){if(!this.isWaitingForResponse||this.hasActionableApproval())return!1;const e=this.transport.getSnapshot();return((typeof this.transport.runDetectStatus=="function"?()=>this.transport.runDetectStatus(e.recentOutputBuffer):()=>this.runDetectStatus(e))()||this.currentStatus)==="generating"?(this.evaluateSettled(e),!0):!1}hasRecentInteractiveActivity(e,t){const s=e.lastNonEmptyOutputAt?t-e.lastNonEmptyOutputAt:Number.MAX_SAFE_INTEGER,n=e.lastScreenChangeAt?t-e.lastScreenChangeAt:Number.MAX_SAFE_INTEGER;return s<this.timeouts.statusActivityHold||n<this.timeouts.statusActivityHold}hasMeaningfulResponseBuffer(e,t){const s=String(e.responseBuffer||"").trim();if(!s)return!1;const n=Pr(t);if(!n)return!0;const i=Pr(s);return!i||i===n?!1:i.startsWith(n)?i.slice(n.length).replace(/[─═\-]+/g,"").replace(/⏵⏵accepteditson\([^)]*\)/gi,"").replace(/esctointerrupt/gi,"").replace(/❯/g,"").replace(/^[\s\-–—:;,.!/?]+/,"").trim().length>0:!0}shouldDeferFinishForTranscript(e){var o;if(!!!this.provider.requiresFinalAssistantBeforeIdle||!this.isWaitingForResponse||!this.currentTurnScope||this.hasActionableApproval())return!1;if((typeof(e==null?void 0:e.status)=="string"?e.status.trim():"")!=="idle"||e!=null&&e.activeModal||e!=null&&e.modal)return!0;const n=Array.isArray(e==null?void 0:e.messages)?e.messages:[];let i=-1;for(let l=n.length-1;l>=0;l--)if(((o=n[l])==null?void 0:o.role)==="user"){i=l;break}return i<0?n.length===0?!1:!this.parsedStatusHasFinalStandardAssistantMessage(e):!n.slice(i+1).some(l=>{var d;return!l||l.role!=="assistant"||typeof l.content!="string"||!l.content.trim()?!1:(typeof l.kind=="string"&&l.kind.trim()?l.kind.trim():"standard")==="standard"&&((d=l.meta)==null?void 0:d.streaming)!==!0})}rescheduleTranscriptFinishCheck(e){this.clearIdleFinishCandidate(e),this.setStatus("generating",e),this.idleTimeout&&clearTimeout(this.idleTimeout),this.idleTimeout=setTimeout(()=>{!this.isWaitingForResponse||this.hasActionableApproval()||this.evaluateSettled(this.transport.getSnapshot())},this.timeouts.idleFinishConfirm),this.recordTrace("transcript_finish_deferred",{reason:e})}shouldRetryFinishResponse(e,t){if(!this.currentTurnScope||this.hasActionableApproval()||this.finishRetryCount>=xf||t.hasAssistant&&t.assistantContent.trim()||this.runDetectStatus(e)!=="idle")return!1;const s=Date.now(),n=e.lastNonEmptyOutputAt?s-e.lastNonEmptyOutputAt:Number.MAX_SAFE_INTEGER,i=e.lastScreenChangeAt?s-e.lastScreenChangeAt:0;return n<1200||i<1200||!t.hasAssistant}commitCurrentTranscript(e){const t=this.runParseSession(e);if(t&&Array.isArray(t.messages)){const n=[...Pd(t.messages,{lastOutputAt:e.lastOutputAt})].reverse().find(i=>i.role==="assistant");if(n)return{hasAssistant:!0,assistantContent:n.content||""}}return{hasAssistant:!1,assistantContent:""}}maybeCommitVisibleIdleTranscript(e,t,s){return!this.provider.allowInputDuringGeneration||!e||e.status!=="idle"||!this.isWaitingForResponse||!this.currentTurnScope||this.activeModal||e.modal||![...t].reverse().find(i=>i.role==="assistant"&&String(i.content||"").trim())?!1:(this.resetActiveTurnState(),this.callbacks.onTurnCompleted(),this.setStatus("idle","script_idle_commit"),this.callbacks.onStatusChange(),this.transport.flushOutboundQueue(),!0)}parsedStatusHasFinalAssistantMessage(e){return!![...Array.isArray(e==null?void 0:e.messages)?e.messages:[]].reverse().find(n=>!n||n.role!=="assistant"?!1:typeof n.content=="string"&&n.content.trim().length>0)}parsedStatusHasFinalStandardAssistantMessage(e){return!![...Array.isArray(e==null?void 0:e.messages)?e.messages:[]].reverse().find(n=>{var a;return!n||n.role!=="assistant"||typeof n.content!="string"||!n.content.trim()?!1:(typeof n.kind=="string"&&n.kind.trim()?n.kind.trim():"standard")==="standard"&&((a=n.meta)==null?void 0:a.streaming)!==!0})}recordTrace(e,t={}){const s={id:++this.traceSeq,at:Date.now(),type:e,status:this.currentStatus,isWaitingForResponse:this.isWaitingForResponse,activeModal:this.activeModal?{message:this.activeModal.message,buttons:[...this.activeModal.buttons]}:null,payload:t};this.traceEntries.push(s),this.traceEntries.length>Pc&&this.traceEntries.splice(0,this.traceEntries.length-Pc)}}}});function T$(e){const t=e.timeouts||{},s=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:s&&typeof s=="object"?s:{},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 M$=We({"src/cli-adapters/provider-cli-config.ts"(){}});function vf(e){const{provider:t,runtimeSettings:s,workingDir:n,extraArgs:i,extraEnv:a}=e,{spawn:o}=t,l=typeof s.executablePath=="string"&&s.executablePath.trim()?s.executablePath.trim():o.command,c=a$(l),d=ot.platform()==="win32",p=[...o.args,...i].map(x=>typeof x=="string"?x.replace(/\{\{workingDir\}\}/g,n):x);let h,m;const g=!d&&(!!o.shell||!Ee.isAbsolute(c)||lf(c)||!o$(c)),b=d&&/\.(cmd|bat)$/i.test(c),f=!!o.shell||b||!Ee.isAbsolute(c)||lf(c),v=d?f:g;v?(h=d?"cmd.exe":bt.SHELL||"/bin/zsh",d?m=["/c",c,...p]:m=["-l","-c",[c,...p].map(bv).join(" ")]):(h=c,m=p);const w=yv(bt,{...o.env||{},...a||{}});return w.TERMINAL_CWD=n,{binaryPath:c,allArgs:p,shellCmd:h,shellArgs:m,isWin:d,useShell:v,ptyOptions:{cols:Ti,rows:Mi,cwd:n,env:w}}}function E$(e){const t=bt.SHELL||"/bin/zsh",s=[e.binaryPath,...e.allArgs].map(bv).join(" ");return{shellCmd:t,shellArgs:["-l","-c",s]}}function R$(e,t,s){return s?/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 P$(e){const{ptyProcess:t,pendingTail:s,data:n,terminalScreen:i}=e;if(!t||!n)return s;const a=s+n,o=/\x1b\[(\?)?6n/g;let l;for(;(l=o.exec(a))!==null;){const h=i.getCursorPosition(),m=Math.max(1,(h.row|0)+1),g=Math.max(1,(h.col|0)+1),b=l[1]?`\x1B[?${m};${g}R`:`\x1B[${m};${g}R`;t.write(b)}const c=["\x1B[6n","\x1B[?6n"],d=c.reduce((h,m)=>Math.max(h,m.length),0)-1,p=Math.max(0,a.length-d);for(let h=p;h<a.length;h++){const m=a.slice(h);if(c.some(g=>m.length<g.length&&g.startsWith(m)))return m}return""}var D$=We({"src/cli-adapters/provider-cli-runtime.ts"(){Hr()}}),L$={};Tt(L$,{ProviderCliAdapter:()=>Mv,appendBoundedText:()=>Ld,normalizeCliProviderForRuntime:()=>p$});function Ld(e,t,s){if(!t)return e.length<=s?e:e.slice(-s);if(s<=0)return"";if(t.length>=s)return t.slice(-s);const n=s-t.length;return e.length<=n?e+t:e.slice(-n)+t}var Mv,Ip=We({"src/cli-adapters/provider-cli-adapter.ts"(){var e;Ve(),wp(),Sp(),xv(),Hr(),I$(),A$(),Av(),M$(),D$(),Hr(),Mv=(e=class{constructor(s,n,i=[],a={},o=new kp){re(this,"cliType");re(this,"cliName");re(this,"workingDir");re(this,"provider");re(this,"ptyProcess",null);re(this,"transportFactory");re(this,"onStatusChange",null);re(this,"engine");re(this,"responseBuffer","");re(this,"recentOutputBuffer","");re(this,"providerSessionId",null);re(this,"responseTimeout",null);re(this,"ready",!1);re(this,"startupBuffer","");re(this,"startupParseGate",!1);re(this,"startupSettleTimer",null);re(this,"spawnAt",0);re(this,"startupFirstOutputAt",0);re(this,"onPtyDataCallback",null);re(this,"pendingOutputParseChunks",[]);re(this,"pendingOutputParseTimer",null);re(this,"ptyOutputChunks",[]);re(this,"ptyOutputFlushTimer",null);re(this,"pendingTerminalQueryTail","");re(this,"lastOutputAt",0);re(this,"lastNonEmptyOutputAt",0);re(this,"lastScreenChangeAt",0);re(this,"lastScreenSnapshot","");re(this,"lastScreenText","");re(this,"lastScreenSnapshotReadAt",Number.NEGATIVE_INFINITY);re(this,"serverConn",null);re(this,"logBuffer",[]);re(this,"pendingOutboundQueue",[]);re(this,"pendingOutboundFlushTimer",null);re(this,"pendingOutboundFlushInFlight",!1);re(this,"submitRetryTimer",null);re(this,"resizeSuppressUntil",0);re(this,"runner");re(this,"runtimeSettings",{});re(this,"accumulatedBuffer","");re(this,"transcriptAccumulator",new jp);re(this,"accumulatedRawBuffer","");re(this,"terminalScreen",new hv(Mi,Ti));re(this,"responseBufferDroppedChars",0);re(this,"recentOutputDroppedChars",0);re(this,"accumulatedBufferDroppedChars",0);re(this,"accumulatedRawBufferDroppedChars",0);re(this,"parsedStatusCache",null);re(this,"providerResolutionMeta");re(this,"timeouts");re(this,"approvalKeys");re(this,"sendDelayMs");re(this,"sendKey");re(this,"submitStrategy");re(this,"requirePromptEchoBeforeSubmit");this.extraArgs=i,this.extraEnv=a,this.runner=new Iv(s.type),this.provider=s,this.transportFactory=o,this.cliType=s.type,this.cliName=s.name,this.workingDir=n.startsWith("~")?n.replace(/^~/,ot.homedir()):n;const l=T$(s);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.engine=new Tv(s,this.runner,this,{onStatusChange:()=>{var d;(d=this.onStatusChange)==null||d.call(this)},onApplyParsedSession:d=>{this.applyParsedSessionMetadata(d)},onTurnCompleted:()=>{this.responseBuffer=""}},l.timeouts),this.runner.setScripts(s.scripts||{},s.tui),this.runner.setScriptCallBudget(s.scriptCallBudgetMs??50);const c=this.runner.getScriptNames();if(c.length>0)_e.info("CLI",`[${this.cliType}] CLI scripts: [${c.join(", ")}]`),_e.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 d=`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)?_e.warn("CLI",`[${this.cliType}] ⚠ No CLI scripts loaded! Provider needs scripts/{version}/scripts.js (${d})`):_e.info("CLI",`[${this.cliType}] CLI scripts not yet resolved (${d})`)}}get parseErrorMessage(){return this.runner.parseErrorMessage}get cliScripts(){return this.runner.cliScripts}getScriptInvocationTrace(){return this.runner.getInvocationTrace()}getAccumulatedRawBuffer(){return{text:this.accumulatedRawBuffer,droppedChars:this.accumulatedRawBufferDroppedChars}}set cliScripts(s){this.setCliScripts(s)}getBufferState(){const s=(l,c)=>l>0?{truncated:!0,droppedChars:l,maxChars:c}:void 0,n=s(this.responseBufferDroppedChars,e.MAX_RESPONSE_BUFFER),i=s(this.recentOutputDroppedChars,e.MAX_RECENT_OUTPUT_BUFFER),a=s(this.accumulatedBufferDroppedChars,e.MAX_ACCUMULATED_BUFFER),o=s(this.accumulatedRawBufferDroppedChars,e.MAX_ACCUMULATED_BUFFER);if(!(!n&&!i&&!a&&!o))return{...n?{responseBuffer:n}:{},...i?{recentOutputBuffer:i}:{},...a?{accumulatedBuffer:a}:{},...o?{accumulatedRawBuffer:o}:{}}}recordBoundedAppendDrop(s,n,i){return Math.max(0,s+n-i)}readTerminalScreenText(s=Date.now()){const n=this.terminalScreen.getText()||"";return this.lastScreenText=n,this.lastScreenSnapshotReadAt=s,n}getParseScreenText(s){const n=Mc(s),i=this.lastScreenSnapshot;if(!i||i===n)return s;const a=/\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=a.test(i),l=/(?:^|\n|\r)\s*[❯›>]\s*(?:Try\s+["“][^\n\r"”]+["”])?\s*(?:\n|\r|$)/.test(s)&&!a.test(s);return o&&l||n.length>=i.length?s:`${s}
|
|
600
|
+
${i}`}shouldReadTerminalScreenSnapshot(s){return this.lastScreenText?s-this.lastScreenSnapshotReadAt>=e.SCREEN_SNAPSHOT_MIN_INTERVAL_MS:!0}resetTerminalScreen(s,n){this.terminalScreen.reset(s,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 s=this.parsedStatusCache,n=this.getAccumulatedRawBufferCacheKey();return s&&s.responseBuffer===this.responseBuffer&&s.currentTurnScope===this.engine.currentTurnScope&&s.recentOutputBuffer===this.recentOutputBuffer&&s.accumulatedBuffer===this.accumulatedBuffer&&s.accumulatedRawBufferKey===n&&s.screenText===this.lastScreenText&&s.currentStatus===this.engine.currentStatus&&s.activeModal===this.engine.activeModal&&s.cliName===this.cliName?s.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}setCliScripts(s){this.runner.setScripts(s),this.parsedStatusCache=null,_e.info("CLI",`[${this.cliType}] CLI scripts injected: [${this.runner.getScriptNames().join(", ")}]`)}refreshProviderDefinition(s){this.provider=s,this.setCliScripts(s.scripts||{})}updateRuntimeSettings(s){this.runtimeSettings={...s}}setServerConn(s){this.serverConn=s,this.serverConn&&this.logBuffer.length>0&&(this.logBuffer.forEach(n=>this.serverConn.sendMessage("log",n)),this.logBuffer=[])}setOnStatusChange(s){this.onStatusChange=s}setOnPtyData(s){this.onPtyDataCallback=s}flushPendingOutputParse(){if(this.pendingOutputParseTimer&&(clearTimeout(this.pendingOutputParseTimer),this.pendingOutputParseTimer=null),this.pendingOutputParseChunks.length===0)return;const s=this.pendingOutputParseChunks.join("");this.pendingOutputParseChunks=[],this.handleOutput(s)}async spawn(){var n;if(this.ptyProcess)return;const s=vf({provider:this.provider,runtimeSettings:this.runtimeSettings,workingDir:this.workingDir,extraArgs:this.extraArgs,extraEnv:this.extraEnv});_e.info("CLI",`[${this.cliType}] Spawning in ${this.workingDir}`);try{this.ptyProcess=this.transportFactory.spawn(s.shellCmd,s.shellArgs,s.ptyOptions)}catch(i){const a=(i==null?void 0:i.message)||String(i);if(!s.isWin&&!s.useShell&&/posix_spawn|spawn/i.test(a)){_e.warn("CLI",`[${this.cliType}] Direct spawn failed (${a}), retrying via login shell`);const o=E$(s);this.ptyProcess=this.transportFactory.spawn(o.shellCmd,o.shellArgs,s.ptyOptions)}else{const o=R$(a,s.shellCmd,s.isWin);throw o?new Error(`Failed to spawn CLI${o}: ${a}`):i}}this.ptyProcess.onData(i=>{var a;Date.now()<this.resizeSuppressUntil||((a=this.ptyProcess)!=null&&a.terminalQueriesHandled||(this.pendingTerminalQueryTail=P$({ptyProcess:this.ptyProcess,pendingTail:this.pendingTerminalQueryTail,data:i,terminalScreen:this.terminalScreen})),this.pendingOutputParseChunks.push(i),this.pendingOutputParseTimer||(this.pendingOutputParseTimer=setTimeout(()=>{this.pendingOutputParseTimer=null,this.flushPendingOutputParse()},this.timeouts.ptyFlush)),this.onPtyDataCallback&&(this.ptyOutputChunks.push(i),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:i})=>{var a;_e.info("CLI",`[${this.cliType}] Exit code ${i}`),this.flushPendingOutputParse(),this.ptyProcess=null,this.engine.onPtyExit(),this.ready=!1,this.startupParseGate=!1,this.spawnAt=0,this.runner.resetSessionState(),(a=this.onStatusChange)==null||a.call(this)}),this.spawnAt=Date.now(),this.startupParseGate=!0,this.startupBuffer="",this.startupFirstOutputAt=0,this.startupSettleTimer&&(clearTimeout(this.startupSettleTimer),this.startupSettleTimer=null),this.resetTerminalScreen(Mi,Ti),this.pendingTerminalQueryTail="",this.ready=!1,await this.ptyProcess.ready,this.engine.onSpawnReady(),this.scheduleStartupSettleCheck(),(n=this.onStatusChange)==null||n.call(this)}handleOutput(s){this.terminalScreen.write(s);const n=bi(s),i=this.transcriptAccumulator.append(s),a=Date.now(),o=this.shouldReadTerminalScreenSnapshot(a),l=o?this.readTerminalScreenText(a):this.lastScreenText,c=o?Mc(l):this.lastScreenSnapshot;if(this.lastOutputAt=a,n.trim()&&(this.lastNonEmptyOutputAt=a),o&&c!==this.lastScreenSnapshot&&(this.lastScreenSnapshot=c,this.lastScreenChangeAt=a),this.startupParseGate&&!this.startupFirstOutputAt&&(n.trim()||c.trim())&&(this.startupFirstOutputAt=a),(s.length>0||n.length>0)&&this.engine.clearIdleFinishCandidate("new_output"),sv().collectDebugTrace&&this.engine.recordExternalTrace("output",{rawLength:s.length,cleanLength:n.length,rawPreview:sr(s,300),cleanPreview:sr(n,300)}),this.startupParseGate&&this.scheduleStartupSettleCheck(),this.engine.isWaitingForResponse&&n){const f=this.responseBuffer.length;this.responseBuffer=Ld(this.responseBuffer,n,e.MAX_RESPONSE_BUFFER),this.responseBufferDroppedChars+=this.recordBoundedAppendDrop(f,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 d=this.accumulatedRawBuffer.length,p=i.length<=e.MAX_ACCUMULATED_BUFFER?i:i.slice(-e.MAX_ACCUMULATED_BUFFER),h=p.slice(-e.MAX_RECENT_OUTPUT_BUFFER);this.recentOutputBuffer=h,this.accumulatedBuffer=p,this.accumulatedRawBuffer=Ld(this.accumulatedRawBuffer,s,e.MAX_ACCUMULATED_BUFFER);const m=Math.max(0,i.length-e.MAX_RECENT_OUTPUT_BUFFER),g=Math.max(0,i.length-this.accumulatedBuffer.length),b=this.recordBoundedAppendDrop(d,s.length,this.accumulatedRawBuffer.length);this.recentOutputDroppedChars+=m,this.accumulatedBufferDroppedChars+=g,this.accumulatedRawBufferDroppedChars+=b,this.engine.currentTurnScope&&(g>0&&(this.engine.currentTurnScope.bufferStart=Math.max(0,this.engine.currentTurnScope.bufferStart-g)),b>0&&(this.engine.currentTurnScope.rawBufferStart=Math.max(0,this.engine.currentTurnScope.rawBufferStart-b))),this.resolveStartupState("output",l,c,a),this.engine.scheduleSettle()}resolveStartupState(s,n,i,a){var g;if(!this.startupParseGate)return;const o=typeof a=="number"?a:Date.now(),l=typeof n=="string"?n:this.readTerminalScreenText(),c=typeof i=="string"?i:Mc(l);if(!(!!this.startupFirstOutputAt||!!c.trim()))return;const p=this.lastScreenChangeAt?o-this.lastScreenChangeAt:0;if(p<2e3)return;const h=this.runParseApproval(this.recentOutputBuffer),m=this.runDetectStatus(l||this.recentOutputBuffer);if(!h&&m!=="idle"){this.scheduleStartupSettleCheck();return}this.startupParseGate=!1,this.startupSettleTimer&&(clearTimeout(this.startupSettleTimer),this.startupSettleTimer=null),this.ready=!0,h?(this.engine.activeModal=h,this.engine.setStatus("waiting_approval",`startup_ready:${s}`)):((this.engine.currentStatus==="waiting_approval"||this.engine.activeModal)&&(this.engine.lastApprovalResolvedAt=Date.now()),this.engine.activeModal=null,this.engine.isWaitingForResponse=!1,this.engine.currentTurnScope=null,this.engine.setStatus("idle",`startup_ready:${s}`)),_e.info("CLI",`[${this.cliType}] Startup settled (${s}, stableMs=${p}, modal=${!!h}) providerDir=${this.providerResolutionMeta.providerDir||"-"} scriptDir=${this.providerResolutionMeta.scriptDir||"-"} scriptsPath=${this.providerResolutionMeta.scriptsPath||"-"}`),(g=this.onStatusChange)==null||g.call(this)}scheduleStartupSettleCheck(){if(!this.startupParseGate)return;this.startupSettleTimer&&clearTimeout(this.startupSettleTimer);const s=Date.now(),n=this.lastScreenChangeAt?s-this.lastScreenChangeAt:0,i=Math.max(250,2050-n);this.startupSettleTimer=setTimeout(()=>{this.startupSettleTimer=null,this.resolveStartupState("startup_timer"),this.startupParseGate&&Date.now()-this.spawnAt<1e4&&this.scheduleStartupSettleCheck()},i)}async waitForInteractivePrompt(s=5e3){const n=Date.now();let i=!1;for(;Date.now()-n<s;){this.resolveStartupState("interactive_wait");const o=this.terminalScreen.getText()||"",l=this.lastScreenChangeAt?Date.now()-this.lastScreenChangeAt:0,c=this.lastNonEmptyOutputAt?Date.now()-this.lastNonEmptyOutputAt:Number.MAX_SAFE_INTEGER,d=this.runDetectStatus(this.recentOutputBuffer)||this.engine.currentStatus;if(d==="idle"&&l>=700&&c>=350){i&&_e.info("CLI",`[${this.cliType}] Interactive prompt ready after ${Date.now()-n}ms (stableMs=${l}, recentOutputMs=${c})`);return}!i&&Date.now()-n>=400&&(i=!0,_e.info("CLI",`[${this.cliType}] Waiting for interactive prompt: status=${d} stableMs=${l} recentOutputMs=${c} screen=${JSON.stringify(sr(o,220)).slice(0,260)}`)),await new Promise(h=>setTimeout(h,50))}const a=this.terminalScreen.getText()||"";_e.warn("CLI",`[${this.cliType}] Interactive prompt wait timed out after ${s}ms; proceeding with screen=${JSON.stringify(sr(a,240)).slice(0,280)}`)}clearAllTimers(){this.responseTimeout&&(clearTimeout(this.responseTimeout),this.responseTimeout=null),this.submitRetryTimer&&(clearTimeout(this.submitRetryTimer),this.submitRetryTimer=null),this.pendingOutputParseTimer&&(clearTimeout(this.pendingOutputParseTimer),this.pendingOutputParseTimer=null),this.ptyOutputFlushTimer&&(clearTimeout(this.ptyOutputFlushTimer),this.ptyOutputFlushTimer=null),this.engine.clearAllTimers()}runParseSession(){const s=this.terminalScreen.getText(),n=this.getParseScreenText(s),i=this.recentOutputBuffer.slice(-500),a=Dd({accumulatedBuffer:this.accumulatedBuffer,accumulatedRawBuffer:this.accumulatedRawBuffer,recentOutputBuffer:this.recentOutputBuffer,terminalScreenText:n,workingDir:this.workingDir,providerSessionId:this.providerSessionId||void 0,historySessionId:this.providerSessionId||void 0,baseMessages:[],partialResponse:this.responseBuffer,isWaitingForResponse:this.engine.isWaitingForResponse,scope:this.engine.currentTurnScope,runtimeSettings:this.runtimeSettings,spawnAt:this.spawnAt}),o=this.runner.parseSession({...a,tail:i,tailScreen:ts(i)});return o&&typeof o=="object"&&this.applyParsedSessionMetadata(o),o}runDetectStatus(s){const n=this.terminalScreen.getText(),i=s.slice(-500);return this.runner.detectStatus({tail:i,screenText:n,rawBuffer:this.accumulatedRawBuffer,isWaitingForResponse:this.engine.isWaitingForResponse,screen:ts(n),tailScreen:ts(i)})}runParseApproval(s){const n=this.terminalScreen.getText(),i=n||this.accumulatedBuffer;return this.runner.parseApproval({buffer:i,screenText:n,rawBuffer:this.accumulatedRawBuffer,tail:s,screen:ts(n),bufferScreen:ts(i),tailScreen:ts(s)})}applyParsedSessionMetadata(s){const n=typeof(s==null?void 0:s.providerSessionId)=="string"&&s.providerSessionId.trim()?s.providerSessionId.trim():"";n&&n!==this.providerSessionId&&(this.providerSessionId=n,this.updateRuntimeMeta({providerSessionId:n}))}projectEffectiveStatus(s=null){return this.parseErrorMessage?"error":s||this.engine.activeModal?"waiting_approval":this.engine.isWaitingForResponse&&this.engine.currentTurnScope&&this.engine.currentStatus!=="stopped"?"generating":this.engine.currentStatus}getStatus(s={}){const n=s.allowParse!==!1,i=n&&this.startupParseGate?this.runParseApproval(this.recentOutputBuffer):null,a=n&&this.startupParseGate&&!i?this.runDetectStatus(this.recentOutputBuffer||this.terminalScreen.getText()):null;let o=this.projectEffectiveStatus(i),l=i||this.engine.activeModal;if(n&&!l&&this.engine.isWaitingForResponse&&this.runDetectStatus(this.recentOutputBuffer||this.terminalScreen.getText())==="waiting_approval"){const p=this.runParseApproval(this.terminalScreen.getText())||this.runParseApproval(this.recentOutputBuffer),h=p&&Array.isArray(p.buttons)&&p.buttons.some(m=>typeof m=="string"&&m.trim());p&&h&&(l=p,this.engine.activeModal||(this.engine.activeModal=p))}if(a==="waiting_approval"&&l?o="waiting_approval":a==="idle"&&!i&&!l&&(o="idle"),n&&!i&&!l){const d=this.getFreshParsedStatusCache(),p=d!=null&&d.activeModal&&Array.isArray(d.activeModal.buttons)&&d.activeModal.buttons.some(m=>typeof m=="string"&&m.trim())?d.activeModal:null,h=m=>(Array.isArray(m==null?void 0:m.messages)?m.messages:[]).some(b=>(b==null?void 0:b.role)==="assistant"&&typeof b.content=="string"&&b.content.trim());(d==null?void 0:d.status)==="waiting_approval"&&p?(o="waiting_approval",l=p):o==="idle"&&(d==null?void 0:d.status)==="generating"&&!h(d)?o="generating":o==="generating"&&(d==null?void 0:d.status)==="idle"&&h(d)&&(o="idle")}const c=this.getBufferState();return{status:o,messages:[],workingDir:this.workingDir,activeModal:l,approvalEntrySeq:this.engine.approvalEntrySeq,pendingOutboundCount:this.pendingOutboundQueue.length,pendingOutboundMessages:this.pendingOutboundQueue.map(d=>({id:d.id,role:d.role,content:d.content,queuedAt:d.queuedAt,source:d.source})),errorMessage:this.parseErrorMessage||this.engine.providerErrorMessage||void 0,errorReason:this.parseErrorMessage?"parse_error":this.engine.providerErrorReason||void 0,providerSessionId:this.providerSessionId||void 0,...c?{bufferState:c}:{}}}getScriptParsedStatus(){const s=this.readTerminalScreenText(),n=this.getParseScreenText(s),i=this.parsedStatusCache,a=this.getAccumulatedRawBufferCacheKey();if(!this.providerOwnsTranscript()&&i&&i.responseBuffer===this.responseBuffer&&i.currentTurnScope===this.engine.currentTurnScope&&i.recentOutputBuffer===this.recentOutputBuffer&&i.accumulatedBuffer===this.accumulatedBuffer&&i.accumulatedRawBufferKey===a&&i.screenText===n&&i.currentStatus===this.engine.currentStatus&&i.activeModal===this.engine.activeModal&&i.cliName===this.cliName)return i.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,c=this.getBufferState(),d={id:o.id||"cli_session",status:o.status||this.engine.currentStatus,title:o.title||this.cliName,messages:Pd(o.messages,{lastOutputAt:this.lastOutputAt}),activeModal:l,providerSessionId:this.providerSessionId||(typeof o.providerSessionId=="string"?o.providerSessionId:void 0),errorMessage:typeof o.errorMessage=="string"&&o.errorMessage.trim()?o.errorMessage.trim():void 0,errorReason:typeof o.errorReason=="string"&&o.errorReason.trim()?o.errorReason.trim():void 0,...c?{bufferState:c}:{},...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.engine.currentTurnScope,recentOutputBuffer:this.recentOutputBuffer,accumulatedBuffer:this.accumulatedBuffer,accumulatedRawBufferKey:a,screenText:n,currentStatus:this.engine.currentStatus,activeModal:this.engine.activeModal,cliName:this.cliName,result:d},d}async invokeScript(s,n){const i=Dd({accumulatedBuffer:this.accumulatedBuffer,accumulatedRawBuffer:this.accumulatedRawBuffer,recentOutputBuffer:this.recentOutputBuffer,terminalScreenText:this.getParseScreenText(this.terminalScreen.getText()),workingDir:this.workingDir,providerSessionId:this.providerSessionId||void 0,historySessionId:this.providerSessionId||void 0,baseMessages:[],partialResponse:this.responseBuffer,isWaitingForResponse:this.engine.isWaitingForResponse,scope:this.engine.currentTurnScope,runtimeSettings:this.runtimeSettings,spawnAt:this.spawnAt});return await Promise.resolve(this.runner.invokeByName(s,{...i,args:n&&typeof n=="object"?{...n}:{}}))}parseCurrentTranscript(s,n,i,a){return this.runParseSession()}hasCliScripts(){return this.runner.hasDetectStatus()}async resolveAction(s){let n="";try{n=this.runner.invokeByName("resolveAction",s)}catch{_e.warn("CLI",`[${this.cliType}] resolveAction skipped: provider script not available`);return}if(!n){_e.warn("CLI",`[${this.cliType}] resolveAction skipped: provider script did not return a prompt`);return}await this.sendMessage(n)}async setInteractivePromptResponse(s){}isSubmitStuck(s){if(!this.ptyProcess||!this.engine.isWaitingForResponse||this.engine.submitRetryUsed||this.engine.hasActionableApproval()||this.hasMeaningfulResponseBufferLocal(s))return!1;const n=this.terminalScreen.getText();if(!Rd(n,s)||this.runParseApproval(n)||this.runParseApproval(this.recentOutputBuffer))return!1;const a=this.runDetectStatus(n)||this.runDetectStatus(this.recentOutputBuffer);return a!=="generating"&&a!=="waiting_approval"}hasMeaningfulResponseBufferLocal(s){const n=String(this.responseBuffer||"").trim();if(!n)return!1;const i=Pr(s);if(!i)return!0;const a=Pr(n);return!a||a===i?!1:a.startsWith(i)?a.slice(i.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}async writeToPty(s){if(!this.ptyProcess)throw new Error(`${this.cliName} is not running`);await this.ptyProcess.write(s)}resetPendingSendState(s){this.responseBuffer="",this.responseTimeout&&(clearTimeout(this.responseTimeout),this.responseTimeout=null),this.engine.resetActiveTurnState(),this.engine.clearIdleFinishCandidate(s)}commitSendUserTurn(s){s.didCommitUserTurn||(s.didCommitUserTurn=!0)}armResponseTimeout(){this.responseTimeout&&clearTimeout(this.responseTimeout);const s=this.timeouts.maxResponse;if(!Number.isFinite(s)||s<=0){this.responseTimeout=null;return}this.responseTimeout=setTimeout(()=>{this.responseTimeout=null,this.engine.isWaitingForResponse&&(this.engine.evaluateSettled(this.getSnapshot()),this.engine.isWaitingForResponse&&!this.engine.hasActionableApproval()&&this.armResponseTimeout())},s)}writeSubmitKeyForRetry(s){this.writeToPty(this.sendKey).catch(n=>{_e.warn("CLI",`[${this.cliType}] ${s} write failed: ${(n==null?void 0:n.message)||n}`)})}retrySubmitIfStuck(s,n){if(this.submitRetryTimer=null,!!this.isSubmitStuck(s.normalizedPromptSnippet)){if(this.engine.responseSettleIgnoreUntil=Date.now()+this.timeouts.outputSettle+400,_e.info("CLI",`[${this.cliType}] Retrying submit key for stuck prompt (attempt ${n})`),this.writeSubmitKeyForRetry("submit_retry"),n>=3){this.engine.submitRetryUsed=!0;return}this.submitRetryTimer=setTimeout(()=>this.retrySubmitIfStuck(s,n+1),s.retryDelayMs)}}retryImmediateSubmitIfStuck(s){this.submitRetryTimer=null,this.isSubmitStuck(s.normalizedPromptSnippet)&&(this.engine.responseSettleIgnoreUntil=Date.now()+this.timeouts.outputSettle+400,_e.info("CLI",`[${this.cliType}] Retrying submit key for stuck prompt (attempt 1)`),this.writeSubmitKeyForRetry("immediate_retry"),this.engine.submitRetryUsed=!0)}submitSendKey(s,n){if(!this.ptyProcess){n.resolveOnce();return}this.engine.submitPendingUntil=0,this.writeToPty(this.sendKey).then(()=>{this.commitSendUserTurn(s),this.submitRetryTimer=setTimeout(()=>this.retrySubmitIfStuck(s,1),s.retryDelayMs),this.armResponseTimeout(),n.resolveOnce()},n.rejectOnce)}submitImmediatePrompt(s,n){this.engine.submitPendingUntil=0,this.writeToPty(s.text+this.sendKey).then(()=>{this.commitSendUserTurn(s),this.submitRetryTimer=setTimeout(()=>this.retryImmediateSubmitIfStuck(s),s.retryDelayMs),this.armResponseTimeout(),n.resolveOnce()},n.rejectOnce)}waitForEchoAndSubmit(s,n,i,a="",o=i){if(!this.ptyProcess){n.resolveOnce();return}const l=Date.now(),c=l-i,d=this.terminalScreen.getText(),p=Cn(d),h=p!==a?l:o;if(!s.normalizedPromptSnippet||Rd(d,s.normalizedPromptSnippet)){const g=l-h>=500;if(c>=s.submitDelayMs&&g){this.submitSendKey(s,n);return}}if(c>=s.maxEchoWaitMs){const g={elapsed:c,maxEchoWaitMs:s.maxEchoWaitMs,submitDelayMs:s.submitDelayMs,promptSnippet:s.normalizedPromptSnippet,requirePromptEchoBeforeSubmit:this.requirePromptEchoBeforeSubmit,screenText:sr(d,1e3)};if(_e.warn("CLI",`[${this.cliType}] submit_echo_missing: ${JSON.stringify(g)}`),this.requirePromptEchoBeforeSubmit){_e.warn("CLI",`[${this.cliType}] prompt echo was not observed before submit; sending guarded submit key anyway elapsed=${c}ms maxEchoWaitMs=${s.maxEchoWaitMs} screen=${JSON.stringify(g.screenText).slice(0,240)}`),this.submitSendKey(s,n);return}_e.warn("CLI",`[${this.cliType}] prompt echo was not observed before submit; sending submit key anyway elapsed=${c}ms maxEchoWaitMs=${s.maxEchoWaitMs}`),this.submitSendKey(s,n);return}setTimeout(()=>this.waitForEchoAndSubmit(s,n,i,p,h),50)}async sendMessage(s,n={}){if(n.force===!0){await this.forceSendMessage(s);return}await this.sendMessageNow(s,!0)}async forceSendMessage(s){var i;if(!this.ptyProcess)throw new Error(`${this.cliName} is not running`);const n=String(s||"");n.trim()&&(_e.info("CLI",`[${this.cliType}] force-sending prompt while status=${this.engine.currentStatus}`),await this.writeToPty(n+this.sendKey),(i=this.onStatusChange)==null||i.call(this))}enqueuePendingOutboundMessage(s,n){var c;const i=String(s||"");if(this.pendingOutboundQueue.some(d=>d.content===i))return;const o=Date.now(),l={id:`${o}:${this.pendingOutboundQueue.length}:${Math.random().toString(36).slice(2,10)}`,role:"user",content:i,queuedAt:o,source:"sendMessage"};this.pendingOutboundQueue.push(l),_e.info("CLI",`[${this.cliType}] queued outbound message while busy (${n}); queue=${this.pendingOutboundQueue.length}`),(c=this.onStatusChange)==null||c.call(this)}shouldQueuePendingOutboundMessage(s=null){if(this.provider.allowInputDuringGeneration===!0||this.engine.hasActionableApproval())return null;const n=typeof(s==null?void 0:s.status)=="string"?String(s.status):"";if(n==="idle"&&(a=>(Array.isArray(a==null?void 0:a.messages)?a.messages:[]).some(l=>(l==null?void 0:l.role)==="assistant"&&typeof l.content=="string"&&l.content.trim()))(s))return null;if(this.engine.currentStatus==="generating")return"current_status_generating";if(n==="generating"||n==="long_generating"){const a=(s==null?void 0:s.activeModal)??(s==null?void 0:s.modal)??null,o=!!(a&&Array.isArray(a.buttons)&&a.buttons.some(c=>typeof c=="string"&&c.trim()));return this.engine.currentStatus==="idle"&&this.runDetectStatus(this.recentOutputBuffer)==="idle"&&!this.engine.isWaitingForResponse&&!this.engine.currentTurnScope&&!this.engine.hasActionableApproval()&&!o?null:`parsed_status_${n}`}return this.engine.isWaitingForResponse&&this.engine.currentTurnScope?"active_turn_in_progress":null}schedulePendingOutboundFlush(s=0){this.pendingOutboundFlushTimer&&clearTimeout(this.pendingOutboundFlushTimer),this.pendingOutboundFlushTimer=setTimeout(()=>{this.pendingOutboundFlushTimer=null,this.flushPendingOutboundQueue()},Math.max(0,s))}async flushPendingOutboundQueue(){var s;if(!(this.pendingOutboundFlushInFlight||this.pendingOutboundQueue.length===0)&&!(this.engine.currentStatus!=="idle"||this.engine.isWaitingForResponse||this.engine.hasActionableApproval())){this.pendingOutboundFlushInFlight=!0;try{for(;this.pendingOutboundQueue.length>0&&!(this.engine.currentStatus!=="idle"||this.engine.isWaitingForResponse||this.engine.hasActionableApproval());){const n=this.pendingOutboundQueue[0];try{await this.sendMessageNow(n.content,!1),this.pendingOutboundQueue.shift(),(s=this.onStatusChange)==null||s.call(this)}catch(i){_e.warn("CLI",`[${this.cliType}] queued outbound flush failed: ${(i==null?void 0:i.message)||i}`),this.schedulePendingOutboundFlush(1e3);break}}}finally{this.pendingOutboundFlushInFlight=!1}}}async sendMessageNow(s,n){if(!this.ptyProcess)throw new Error(`${this.cliName} is not running`);const i=this.provider.allowInputDuringGeneration===!0,a=i&&this.engine.isWaitingForResponse&&!this.engine.hasActionableApproval();if(this.startupParseGate){const v=Date.now()+1e4;for(;this.startupParseGate&&Date.now()<v;)this.resolveStartupState("send_wait"),await new Promise(w=>setTimeout(w,50))}const o=i?null:(()=>{var v;try{return((v=this.getScriptParsedStatus)==null?void 0:v.call(this))||null}catch{return null}})(),l=this.shouldQueuePendingOutboundMessage(o);if(n&&l){this.enqueuePendingOutboundMessage(s,l);return}if(a||await this.waitForInteractivePrompt(),this.ready||(this.resolveStartupState("send_precheck"),this.runDetectStatus(this.recentOutputBuffer)==="idle"&&(this.ready=!0,this.startupParseGate=!1,this.engine.setStatus("idle","send_message_idle_prompt_recovery"),_e.info("CLI",`[${this.cliType}] sendMessage recovered idle prompt readiness`))),!this.ready)throw new Error(`${this.cliName} not ready (status: ${this.engine.currentStatus})`);const c=typeof(o==null?void 0:o.status)=="string"?String(o.status):"";if(!i&&(c==="generating"||c==="long_generating")){const v=(o==null?void 0:o.activeModal)??(o==null?void 0:o.modal)??null,w=!!(v&&Array.isArray(v.buttons)&&v.buttons.some(S=>typeof S=="string"&&S.trim()));if(!(this.engine.currentStatus==="idle"&&this.runDetectStatus(this.recentOutputBuffer)==="idle"&&!this.engine.isWaitingForResponse&&!this.engine.currentTurnScope&&!this.engine.hasActionableApproval()&&!w)){if(n){this.enqueuePendingOutboundMessage(s,`parsed_status_${c}`);return}throw new Error(`${this.cliName} is still processing the previous prompt`)}}if(this.engine.isWaitingForResponse&&!i){const v=this.getSnapshot();if(!this.engine.clearStaleIdleResponseGuard("send_message_guard",v)&&!this.engine.clearParsedIdleResponseGuard("send_message_parsed_idle_guard",o,v)){if(n){this.enqueuePendingOutboundMessage(s,"waiting_for_response");return}throw new Error(`${this.cliName} is still processing the previous prompt`)}}this.responseBuffer="";const d={prompt:s,startedAt:Date.now(),bufferStart:this.accumulatedBuffer.length,rawBufferStart:this.accumulatedRawBuffer.length};_e.info("CLI",`[${this.cliType}] sendMessage turn scope buffer=${d.bufferStart} raw=${d.rawBufferStart} prompt=${JSON.stringify(s).slice(0,120)}`),this.submitRetryTimer&&(clearTimeout(this.submitRetryTimer),this.submitRetryTimer=null),this.engine.onTurnStarted(d),this.engine.submitRetryPromptSnippet=c$(s);const p=Cn(this.engine.submitRetryPromptSnippet),h=l$(s),m=this.sendDelayMs+Math.min(2e3,Math.max(0,h-1)*350),g=m+Math.max(1500,Math.min(5e3,h*500)),b=Math.max(350,Math.min(1500,Math.max(this.sendDelayMs,m))),f={text:s,normalizedPromptSnippet:p,submitDelayMs:m,maxEchoWaitMs:g,retryDelayMs:b,didCommitUserTurn:!1};this.engine.responseSettleIgnoreUntil=Date.now()+m+this.timeouts.outputSettle+250,await new Promise((v,w)=>{let x=!1;const S={resolveOnce:()=>{x||(x=!0,v())},rejectOnce:j=>{x||(this.resetPendingSendState("send_write_failed"),x=!0,w(j))}};if(this.submitStrategy==="immediate"){this.submitImmediatePrompt(f,S);return}m>0&&(this.engine.submitPendingUntil=Date.now()+m);const k=Date.now();this.writeToPty(s).then(()=>this.waitForEchoAndSubmit(f,S,k),S.rejectOnce)}),this.engine.scheduleSettle()}getPartialResponse(){return this.engine.isWaitingForResponse?this.responseBuffer:""}getDebugSnapshot(){var i;const s=this.readTerminalScreenText(),n=(i=this.parsedStatusCache)!=null&&i.result&&typeof this.parsedStatusCache.result=="object"?this.parsedStatusCache.result:null;return{cliType:this.cliType,cliName:this.cliName,workingDir:this.workingDir,currentStatus:this.engine.currentStatus,ready:this.ready,isWaitingForResponse:this.engine.isWaitingForResponse,activeModal:this.engine.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:s,lastScreenSnapshot:this.lastScreenSnapshot,lastScreenText:this.lastScreenText,lastOutputAt:this.lastOutputAt,lastNonEmptyOutputAt:this.lastNonEmptyOutputAt,lastScreenChangeAt:this.lastScreenChangeAt,lastScreenSnapshotReadAt:this.lastScreenSnapshotReadAt},parser:{scriptNames:this.runner.getScriptNames(),traceSessionId:this.engine.getTraceSessionId(),traceSeq:this.engine.getTraceEntries().length,currentTurnScope:this.engine.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.engine.pendingScriptStatus,pendingScriptStatusSince:this.engine.pendingScriptStatusSince},runtimeMetadata:this.getRuntimeMetadata(),statusHistory:this.engine.getStatusHistory().slice(-80),traceEntries:this.engine.getTraceEntries().slice(-120),timing:{spawnAt:this.spawnAt,startupFirstOutputAt:this.startupFirstOutputAt,submitPendingUntil:this.engine.submitPendingUntil,responseSettleIgnoreUntil:this.engine.responseSettleIgnoreUntil,responseEpoch:this.engine.responseEpoch,resizeSuppressUntil:this.resizeSuppressUntil,lastApprovalResolvedAt:this.engine.lastApprovalResolvedAt},finish:{finishRetryCount:this.engine.finishRetryCount,submitRetryUsed:this.engine.submitRetryUsed,submitRetryPromptSnippet:this.engine.submitRetryPromptSnippet}}}getRuntimeMetadata(){return!this.ptyProcess||typeof this.ptyProcess.getMetadata!="function"?null:this.ptyProcess.getMetadata()}getLaunchInfo(){let s,n=[...this.extraArgs];try{const i=vf({provider:this.provider,runtimeSettings:this.runtimeSettings,workingDir:this.workingDir,extraArgs:this.extraArgs,extraEnv:this.extraEnv});s=i.binaryPath,n=i.allArgs}catch{}return{command:s,args:n,extraArgs:[...this.extraArgs],cwd:this.workingDir,extraEnvKeys:Object.keys(this.extraEnv||{}),providerSessionId:this.providerSessionId||void 0}}updateRuntimeMeta(s,n=!1){const i=typeof(s==null?void 0:s.providerSessionId)=="string"?s.providerSessionId.trim():"";i&&(this.providerSessionId=i),!(!this.ptyProcess||typeof this.ptyProcess.updateMeta!="function")&&this.ptyProcess.updateMeta(s,n)}cancel(){this.shutdown()}async saveAndStop(){if(!this.ptyProcess)return;const s=this.provider.resume;if(!(s!=null&&s.supported)){this.shutdown();return}const n=s.stopStrategy||"command",i=typeof s.stopCommand=="string"?s.stopCommand.trim():"",a=Math.max(this.timeouts.shutdownGrace,typeof s.shutdownGraceMs=="number"?s.shutdownGraceMs:3e3),o=this.engine.currentStatus==="generating"||this.engine.currentStatus==="waiting_approval";try{if(o&&this.ptyProcess.write(""),n==="command"&&i){const c=()=>{if(!this.ptyProcess)return;const p=i.endsWith("\r")||i.endsWith(`
|
|
601
|
+
`)?i:`${i}${this.sendKey}`;this.ptyProcess.write(p)},d=typeof s.interruptGraceMs=="number"?Math.max(100,s.interruptGraceMs):500;o?setTimeout(c,d):c()}else this.ptyProcess.write("")}catch(c){_e.warn("CLI",`[${this.cliType}] saveAndStop signal failed: ${(c==null?void 0:c.message)||c}`)}await this.waitForStopped(a)||(_e.warn("CLI",`[${this.cliType}] graceful stop timed out, forcing shutdown`),this.shutdown(),await this.waitForStopped(this.timeouts.shutdownGrace+500))}waitForStopped(s){return new Promise(n=>{const i=Date.now(),a=setInterval(()=>{if(!this.ptyProcess||this.engine.currentStatus==="stopped"){clearInterval(a),n(!0);return}Date.now()-i>=s&&(clearInterval(a),n(!1))},100)})}shutdown(){this.engine.clearIdleFinishCandidate("shutdown"),this.clearAllTimers(),this.pendingOutputParseChunks=[],this.pendingTerminalQueryTail="",this.ptyOutputChunks=[],this.pendingOutboundFlushTimer&&(clearTimeout(this.pendingOutboundFlushTimer),this.pendingOutboundFlushTimer=null),this.pendingOutboundQueue=[],this.pendingOutboundFlushInFlight=!1,this.ptyProcess&&(this.ptyProcess.write(""),setTimeout(()=>{var s,n;try{(s=this.ptyProcess)==null||s.kill()}catch{}this.ptyProcess=null,this.engine.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 s;if(this.engine.clearIdleFinishCandidate("detach"),this.clearAllTimers(),this.pendingOutputParseChunks=[],this.pendingTerminalQueryTail="",this.ptyOutputChunks=[],this.pendingOutboundFlushTimer&&(clearTimeout(this.pendingOutboundFlushTimer),this.pendingOutboundFlushTimer=null),this.pendingOutboundQueue=[],this.pendingOutboundFlushInFlight=!1,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,(s=this.onStatusChange)==null||s.call(this)}clearHistory(){var s,n,i;this.engine.clearIdleFinishCandidate("clear_history"),this.accumulatedBuffer="",this.accumulatedRawBuffer="",this.engine.currentTurnScope=null,this.engine.submitRetryUsed=!1,this.engine.submitRetryPromptSnippet="",this.pendingOutputParseTimer&&(clearTimeout(this.pendingOutputParseTimer),this.pendingOutputParseTimer=null),this.pendingOutputParseChunks=[],this.pendingTerminalQueryTail="",this.ptyOutputFlushTimer&&(clearTimeout(this.ptyOutputFlushTimer),this.ptyOutputFlushTimer=null),this.ptyOutputChunks=[],this.pendingOutboundFlushTimer&&(clearTimeout(this.pendingOutboundFlushTimer),this.pendingOutboundFlushTimer=null),this.pendingOutboundQueue=[],this.pendingOutboundFlushInFlight=!1,this.resetTerminalScreen(),(n=(s=this.ptyProcess)==null?void 0:s.clearBuffer)==null||n.call(s),(i=this.onStatusChange)==null||i.call(this)}isProcessing(){return this.engine.isWaitingForResponse}isReady(){return this.ready}get currentStatus(){return this.engine.currentStatus}set currentStatus(s){this.engine.setStatus(s)}get isWaitingForResponse(){return this.engine.isWaitingForResponse}set isWaitingForResponse(s){this.engine.isWaitingForResponse=s}get activeModal(){return this.engine.activeModal}set activeModal(s){this.engine.activeModal=s}get currentTurnScope(){return this.engine.currentTurnScope}set currentTurnScope(s){this.engine.currentTurnScope=s}get responseEpoch(){return this.engine.responseEpoch}set responseEpoch(s){this.engine.responseEpoch=s}get submitRetryUsed(){return this.engine.submitRetryUsed}set submitRetryUsed(s){this.engine.submitRetryUsed=s}get submitRetryPromptSnippet(){return this.engine.submitRetryPromptSnippet}set submitRetryPromptSnippet(s){this.engine.submitRetryPromptSnippet=s}get responseSettleIgnoreUntil(){return this.engine.responseSettleIgnoreUntil}set responseSettleIgnoreUntil(s){this.engine.responseSettleIgnoreUntil=s}get submitPendingUntil(){return this.engine.submitPendingUntil}set submitPendingUntil(s){this.engine.submitPendingUntil=s}get lastApprovalResolvedAt(){return this.engine.lastApprovalResolvedAt}set lastApprovalResolvedAt(s){this.engine.lastApprovalResolvedAt=s}get providerErrorMessage(){return this.engine.providerErrorMessage}get providerErrorReason(){return this.engine.providerErrorReason}get pendingScriptStatus(){return this.engine.pendingScriptStatus}get pendingScriptStatusSince(){return this.engine.pendingScriptStatusSince}get finishRetryCount(){return this.engine.finishRetryCount}set finishRetryCount(s){this.engine.finishRetryCount=s}get traceSessionId(){return this.engine.getTraceSessionId()}get traceEntries(){return this.engine.getTraceEntries()}get statusHistory(){return this.engine.getStatusHistory()}get traceSeq(){return this.engine.getTraceEntries().length}evaluateSettled(){_e.debug("CLI",`[${this.cliType}] settled diagnostics delegated to state engine`),this.engine.evaluateSettled(this.getSnapshot())}scheduleSettle(){this.engine.scheduleSettle()}clearIdleFinishCandidate(s){this.engine.clearIdleFinishCandidate(s)}finishResponse(){this.engine.finishResponse()}getSnapshot(){const s=this.terminalScreen.getText()||"";return{accumulatedBuffer:this.accumulatedBuffer,accumulatedRawBuffer:this.accumulatedRawBuffer,recentOutputBuffer:this.recentOutputBuffer,responseBuffer:this.responseBuffer,screenText:s,parseScreenText:this.getParseScreenText(s),workingDir:this.workingDir,providerSessionId:this.providerSessionId,runtimeSettings:this.runtimeSettings,isWaitingForResponse:this.engine.isWaitingForResponse,currentTurnScope:this.engine.currentTurnScope,lastOutputAt:this.lastOutputAt,lastNonEmptyOutputAt:this.lastNonEmptyOutputAt,lastScreenChangeAt:this.lastScreenChangeAt,lastScreenSnapshot:this.lastScreenSnapshot}}isAlive(){return this.ptyProcess!==null}flushOutboundQueue(){this.schedulePendingOutboundFlush()}async writeRaw(s){const n=Buffer.isBuffer(s)?s.toString("utf8"):s;await this.writeToPty(n)}resolveModal(s){this.engine.resolveModal(s)}getApprovalKeyForIndex(s){return s in this.approvalKeys?this.approvalKeys[s]:void 0}isApprovalRecentlyResolved(){return this.engine.isApprovalRecentlyResolved()}resize(s,n){if(this.ptyProcess)try{this.ptyProcess.resize(s,n),this.terminalScreen.resize(n,s),this.resizeSuppressUntil=Date.now()+300}catch{}}getParsedDebugState(){if(this.startupParseGate||!this.runner.hasParseSession())return null;try{const s=this.getScriptParsedStatus();return s&&typeof s=="object"?s:null}catch{return null}}getDebugState(){const s=bi(this.terminalScreen.getText()),n=this.startupParseGate?this.runParseApproval(this.recentOutputBuffer):null,i=this.startupParseGate&&!n?this.runDetectStatus(this.recentOutputBuffer||s):null,a=this.ready||!!n||i==="waiting_approval",o=this.getParsedDebugState(),l=Array.isArray(o==null?void 0:o.messages)?o.messages:[],c=h=>(Array.isArray(h==null?void 0:h.messages)?h.messages:[]).some(g=>(g==null?void 0:g.role)==="assistant"&&typeof g.content=="string"&&g.content.trim());let d=this.projectEffectiveStatus(n);(o==null?void 0:o.status)==="error"&&(d="error");const p=n||this.engine.activeModal;return i==="waiting_approval"&&p&&(d="waiting_approval"),d==="idle"&&(o==null?void 0:o.status)==="generating"&&!c(o)&&(d="generating"),{type:this.cliType,name:this.cliName,providerResolution:this.providerResolutionMeta,status:d,projectedStatus:d,rawStatus:this.engine.currentStatus,lifecycleStatus:this.engine.isWaitingForResponse?"awaiting_response":"idle",ready:a,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,errorMessage:o.errorMessage,errorReason:o.errorReason,activeModal:o.activeModal,messageCount:l.length}:null,screenText:s.slice(-4e3),currentTurnScope:this.engine.currentTurnScope,startupBuffer:this.startupBuffer.slice(-4e3),recentOutputBuffer:this.recentOutputBuffer.slice(-500),accumulatedBufferLength:this.accumulatedBuffer.length,accumulatedRawBufferLength:this.accumulatedRawBuffer.length,rawBufferPreview:this.accumulatedRawBuffer.slice(-1e3),sanitizedRawPreview:bi(this.accumulatedRawBuffer).slice(-1e3),responseBuffer:this.responseBuffer.slice(-1e3),pendingOutboundQueue:this.pendingOutboundQueue.map(h=>({id:h.id,role:h.role,content:h.content,queuedAt:h.queuedAt,source:h.source})),pendingOutboundCount:this.pendingOutboundQueue.length,lastOutputAt:this.lastOutputAt,lastNonEmptyOutputAt:this.lastNonEmptyOutputAt,lastScreenChangeAt:this.lastScreenChangeAt,lastScreenSnapshot:this.lastScreenSnapshot.slice(-500),isWaitingForResponse:this.engine.isWaitingForResponse,activeModal:n||this.engine.activeModal,lastApprovalResolvedAt:this.engine.lastApprovalResolvedAt,sendDelayMs:this.sendDelayMs,sendKey:this.sendKey,submitStrategy:this.submitStrategy,requirePromptEchoBeforeSubmit:this.requirePromptEchoBeforeSubmit,submitPendingUntil:this.engine.submitPendingUntil,responseSettleIgnoreUntil:this.engine.responseSettleIgnoreUntil,resizeSuppressUntil:this.resizeSuppressUntil,hasCliScripts:this.hasCliScripts(),scriptNames:this.runner.getScriptNames(),traceSessionId:this.engine.getTraceSessionId(),traceEntryCount:this.engine.getTraceEntries().length,statusHistory:this.engine.getStatusHistory().slice(-30),timeouts:this.timeouts,pendingOutputParseBufferLength:this.pendingOutputParseChunks.reduce((h,m)=>h+m.length,0),pendingOutputParseScheduled:!!this.pendingOutputParseTimer,ptyAlive:!!this.ptyProcess}}getTraceState(s=120){const n=Math.max(1,Math.min(500,Number.isFinite(s)?Math.floor(s):120)),i=this.engine.getTraceEntries();return{sessionId:this.engine.getTraceSessionId(),providerResolution:this.providerResolutionMeta,entryCount:i.length,entries:i.slice(-n),screenText:sr(this.terminalScreen.getText(),4e3),recentOutputBuffer:sr(this.recentOutputBuffer,1e3),responseBuffer:sr(this.responseBuffer,1200),status:this.projectEffectiveStatus(),projectedStatus:this.projectEffectiveStatus(),rawStatus:this.engine.currentStatus,lifecycleStatus:this.engine.isWaitingForResponse?"awaiting_response":"idle",activeModal:this.engine.activeModal,currentTurnScope:this.engine.currentTurnScope,messages:[]}}getProviderResolutionMeta(){return{...this.providerResolutionMeta}}},re(e,"MAX_RESPONSE_BUFFER",8e3),re(e,"MAX_RECENT_OUTPUT_BUFFER",1e3),re(e,"MAX_ACCUMULATED_BUFFER",262144),re(e,"SCREEN_SNAPSHOT_MIN_INTERVAL_MS",250),e)}}),$$={};Tt($$,{evaluateCondition:()=>Yo,extractButtonsFromRule:()=>K$,extractTitle:()=>U$,resolveSections:()=>Ap,sectionText:()=>Tp});function wf(e,t){if(e===void 0)return 0;if(typeof e=="number")return Math.max(0,Math.min(t,e));const s=/^(\d+(?:\.\d+)?)%$/.exec(e);if(!s)return 0;const n=Number(s[1]);return Math.max(0,Math.min(t,Math.round(t*n/100)))}function Ap(e,t){const s=t.length,n=new Map,i=Object.entries(e);for(const[o,l]of i){let c=0,d=s;if(l.anchor!==void 0)try{const p=Array.isArray(l.anchor)?l.anchor:[l.anchor],h=Array.isArray(l.anchor_context)?null:l.anchor_context??null,m=Array.isArray(l.anchor_context)?l.anchor_context:p.map(()=>h),g=p.map((v,w)=>{const x=m[w]??null;return{re:new RegExp(v,l.anchor_flags??""),prevRe:(x==null?void 0:x.prev)!==void 0?new RegExp(x.prev,x.prev_flags??""):null,nextRe:(x==null?void 0:x.next)!==void 0?new RegExp(x.next,x.next_flags??""):null}}),b=(v,w)=>v.re.test(t[w])&&(v.prevRe===null||w>0&&v.prevRe.test(t[w-1]))&&(v.nextRe===null||w<s-1&&v.nextRe.test(t[w+1]));let f=-1;for(const v of g){if(l.anchor_last){for(let w=s-1;w>=0;w--)if(b(v,w)){f=w;break}}else for(let w=0;w<s;w++)if(b(v,w)){f=w;break}if(f!==-1)break}if(f!==-1)if(c=f,d=s,l.until_regex!==void 0)try{const v=new RegExp(l.until_regex,l.until_regex_flags??""),w=t.findIndex((x,S)=>S>f&&v.test(x));w!==-1&&(d=w)}catch{}else l.lines!==void 0&&(d=Math.min(s,c+l.lines))}catch{}else if(l.from_top!==void 0)c=wf(l.from_top,s),d=s;else if(l.from_bottom!==void 0){const p=wf(l.from_bottom,s);c=s-p,d=s}n.set(o,{fromLine:c,toLine:d})}const a=[];for(const[o,l]of i){let{fromLine:c,toLine:d}=n.get(o);if(l.until!==void 0)if(l.until.startsWith("^"))try{const h=new RegExp(l.until),m=t.findIndex((g,b)=>b>c&&h.test(g));m!==-1&&(d=m)}catch{}else{const h=n.get(l.until);h&&(d=h.fromLine)}d<c&&(d=c);const p=t.slice(c,d).join(`
|
|
602
|
+
`);a.push({id:o,fromLine:c,toLine:d,text:p})}return a}function Tp(e,t,s){if(!t)return s;const n=e.find(i=>i.id===t);return n?n.text:""}function O$(e){return"matches"in e}function F$(e){return"cursor_above"in e&&"changed"in e}function B$(e){return"all"in e}function W$(e){return"any"in e}function Yo(e,t,s,n,i,a,o){if(B$(e)){for(const l of e.all)if(!Yo(l,t,s,n,i,a,o))return!1;return!0}if(W$(e)){for(const l of e.any)if(Yo(l,t,s,n,i,a,o))return!0;return!1}if(F$(e)){if(!n||!i||i.length===0)return!1;const l=s.split(`
|
|
603
|
+
`),c=Math.max(0,n.row-e.cursor_above),d=n.row,p=l.slice(c,d).join(`
|
|
604
|
+
`),h=i.slice(c,d).join(`
|
|
605
|
+
`),m=p!==h,g=e.changed?m:!m,b=e.stable_ms!=null?` stable_ms=${e.stable_ms}`:"";return a.push({kind:g?"state_match":"state_skip",text:`state[${o}] changed cond cursor_above=${e.cursor_above} rows[${c},${d}) changed=${m} expected=${e.changed}${b} result=${g}`}),g}if(O$(e)){const l=Tp(t,e.section,s);let c=!1;try{c=new RegExp(e.matches,e.flags??"i").test(l)}catch{c=!1}if(!c)return a.push({kind:"state_skip",text:`state[${o}] regex cond ${e.section??"*"}~/${e.matches}/ no match`}),!1;if(n!==void 0){if(e.cursor_row_min!==void 0&&n.row<e.cursor_row_min)return a.push({kind:"state_skip",text:`state[${o}] cursor row ${n.row} < cursor_row_min ${e.cursor_row_min}`}),!1;if(e.cursor_row_max!==void 0&&n.row>e.cursor_row_max)return a.push({kind:"state_skip",text:`state[${o}] cursor row ${n.row} > cursor_row_max ${e.cursor_row_max}`}),!1;if(e.cursor_col_min!==void 0&&n.col<e.cursor_col_min)return a.push({kind:"state_skip",text:`state[${o}] cursor col ${n.col} < cursor_col_min ${e.cursor_col_min}`}),!1;if(e.cursor_col_max!==void 0&&n.col>e.cursor_col_max)return a.push({kind:"state_skip",text:`state[${o}] cursor col ${n.col} > cursor_col_max ${e.cursor_col_max}`}),!1}return a.push({kind:"state_match",text:`state[${o}] regex cond ${e.section??"*"}~/${e.matches}/ matched${n!==void 0?` cursor=(${n.row},${n.col})`:""}`}),!0}return!1}function U$(e,t,s){const n=Tp(t,e.section,s);if(!n)return null;if(e.first_line){const i=n.split(`
|
|
606
|
+
`);for(const a of i){const o=a.trim();if(o&&!/^[─╌═─\s]+$/.test(o))return o}return null}if(e.regex)try{const a=new RegExp(e.regex,e.flags??"i").exec(n);if(a)return(a[1]??a[0]).trim()}catch{}return null}function H$(e){const t=e.flags??"gm";return new RegExp(e.pattern,t.includes("g")?t:t+"g")}function z$(e){const t=(e.flags??"m").replace(/g/g,"");return new RegExp(e.pattern,t)}function K$(e,t){const s=e.key_for_index,n=e.continuation_lines??!1,i=[];if(n){const a=z$(e),o=t.split(`
|
|
607
|
+
`);for(let l=0;l<o.length;l+=1){const c=a.exec(o[l]);if(!c)continue;const d=Number(c[1]);let p=String(c[2]??"").trim();if(!Number.isFinite(d)||d<=0||!p)continue;let h=l+1;for(;h<o.length;){const g=o[h];if(!g.trim()||a.test(g)||!/^\s+/.test(g))break;p+=" "+g.trim(),h+=1}if(i.some(g=>g.index===d))continue;const m=s.replace(/\{index\}/g,String(d));i.push({index:d,label:p,key:m}),l=h-1}}else{const a=H$(e);let o;for(;(o=a.exec(t))!==null;){const l=Number(o[1]),c=String(o[2]??"").trim();if(!Number.isFinite(l)||l<=0||!c||i.some(p=>p.index===l))continue;const d=s.replace(/\{index\}/g,String(l));i.push({index:l,label:c,key:d})}}return i.sort((a,o)=>a.index-o.index),i}var Ev=We({"src/providers/spec/evaluator.ts"(){}});function G$(e){return!!e&&typeof e=="object"&&e.$schema==="adhdev:cli/spec@4"}function q$(e,t){return e.states.find(s=>s.id===t)}function V$(e,t){return e.transitions.filter(n=>n.from==="*"?!0:Array.isArray(n.from)?n.from.includes(t):n.from===t).map((n,i)=>({t:n,i})).sort((n,i)=>(i.t.priority??0)-(n.t.priority??0)||n.i-i.i).map(n=>n.t)}var Mp=We({"src/providers/spec/fsm-types.ts"(){}}),X$={};Tt(X$,{evaluateConditionPreview:()=>iO,evaluateFsm:()=>nO});function Y$(e){return e&&e>0?e:Ep}function Lc(e){return"matches"in e}function Q$(e){return"cursor_above"in e&&"changed"in e}function J$(e){return"elapsed_ms"in e}function Z$(e){return"stable_ms"in e}function eO(e){return"all"in e}function tO(e){return"any"in e}function sO(e){return"not"in e}function yi(e,t,s,n,i,a,o,l){if(eO(e)){const c=e.all.map(h=>yi(h,t,s,n,i,a,o,l)),d=c.every(h=>h.result),p=d?0:Math.max(0,...c.filter(h=>!h.result).map(h=>h.remainingMs??0));return{kind:"all",result:d,detail:`all(${c.length})`,remainingMs:p,children:c}}if(tO(e)){const c=e.any.map(m=>yi(m,t,s,n,i,a,o,l)),d=c.some(m=>m.result),p=c.filter(m=>!m.result).map(m=>m.remainingMs??1/0),h=d?0:p.length?Math.min(...p):0;return{kind:"any",result:d,detail:`any(${c.length})`,remainingMs:Number.isFinite(h)?h:0,children:c}}if(sO(e)){const c=yi(e.not,t,s,n,i,a,o,l);return{kind:"not",result:!c.result,detail:"not",remainingMs:0,children:[c]}}if(J$(e)){const c=a.now-a.stateEnteredAt,d=c>=e.elapsed_ms,p=d?0:e.elapsed_ms-c;return{kind:"elapsed",result:d,detail:`elapsed ${c}ms / ${e.elapsed_ms}ms`,remainingMs:p}}if(Z$(e)){const c=Y$(e.cursor_above),d=a.regionLastChangedAt.get(c)??a.stateEnteredAt,p=a.now-d,h=p>=e.stable_ms,m=h?0:e.stable_ms-p,g=c===Ep?"screen":`cursor_above=${e.cursor_above}`;return{kind:"stable",result:h,detail:`stable ${g} ${p}ms / ${e.stable_ms}ms`,remainingMs:m}}if(Lc(e)||Q$(e)){const c=Yo(e,t,s,n,i,o,l),d=Lc(e)?"regex":"changed",p=Lc(e)?`${e.section??"*"}~/${e.matches}/`:`cursor_above=${e.cursor_above} changed=${e.changed}`;return{kind:d,result:c,detail:p}}return{kind:"all",result:!1,detail:"unknown condition"}}function rO(e){const t=Array.isArray(e.from)?e.from.join("|"):e.from;return e.label??`${t}→${e.to}`}function nO(e,t,s,n,i,a){const o=[],l=s.split(`
|
|
608
|
+
`).map(g=>g.endsWith("\r")?g.slice(0,-1):g),c=l.join(`
|
|
609
|
+
`),d=Ap(e.sections??{},l),p=V$(e,t),h=[];let m=null;for(const g of p){const b=g.min_hold_ms??0,f=a.now-a.stateEnteredAt,v=f>=b,w=v?0:b-f;let x,S=!0;g.when&&(x=yi(g.when,d,c,n,i,a,o,`${t}→${g.to}`),S=x.result);const k=v&&S,j={to:g.to,label:rO(g),eligible:!0,holdSatisfied:v,holdRemainingMs:w,condResult:S,cond:x,fires:k,priority:g.priority??0};h.push(j),k&&!m&&(m=j)}return m&&!q$(e,m.to)&&(o.push({kind:"state_skip",text:`transition target ${m.to} not found`}),m=null),{sections:d,transitions:h,fired:m,trace:o}}function iO(e,t,s,n){const i=s.split(`
|
|
610
|
+
`).map(c=>c.endsWith("\r")?c.slice(0,-1):c),a=i.join(`
|
|
611
|
+
`),o=Ap(t??{},i);return yi(e,o,a,n,void 0,{now:0,stateEnteredAt:0,regionLastChangedAt:new Map},[],"preview")}var Ep,Rv=We({"src/providers/spec/fsm-evaluator.ts"(){Ev(),Mp(),Ep=-1}}),aO={};Tt(aO,{loadFsmSpec:()=>oO,validateFsmSpec:()=>Pv});function oO(e){let t;try{t=JSON.parse(Qe.readFileSync(e,"utf8"))}catch(n){return{ok:!1,errors:[`Failed to read/parse spec: ${n.message}`],sourcePath:e}}const s=Pv(t);return s.length?{ok:!1,errors:s,sourcePath:e}:{ok:!0,spec:t,sourcePath:e}}function Pv(e){var o,l,c,d,p;const t=[];if(!G$(e))return['$schema must be "adhdev:cli/spec@4"'];const s=e;if(s.id||t.push("id is required"),s.binary||t.push("binary is required"),(o=s.send_message)!=null&&o.submit_key||t.push("send_message.submit_key is required"),s.pre_launch_trust!==void 0){const h=s.pre_launch_trust;!h||typeof h!="object"||Array.isArray(h)?t.push("pre_launch_trust must be an object"):((typeof h.settings_path!="string"||!h.settings_path)&&t.push("pre_launch_trust.settings_path is required"),(typeof h.key!="string"||!h.key)&&t.push("pre_launch_trust.key is required"))}if(!Array.isArray(s.states)||s.states.length===0)return t.push("states[] must be a non-empty array"),t;if(!Array.isArray(s.transitions))return t.push("transitions[] must be an array"),t;const n=new Set;let i=0;for(const[h,m]of s.states.entries()){if(!m.id){t.push(`states[${h}].id is required`);continue}n.has(m.id)&&t.push(`states[${h}].id "${m.id}" is duplicated`),n.add(m.id),m.label||t.push(`states[${h}].label is required`),m.initial&&(i+=1),m.status&&!["idle","generating","approval"].includes(m.status)&&t.push(`states[${h}].status "${m.status}" must be idle|generating|approval`)}i===0&&t.push("exactly one state must have initial:true (none found)"),i>1&&t.push(`exactly one state must have initial:true (${i} found)`);const a=new Set(Object.keys(s.sections??{}));for(const[h,m]of s.transitions.entries()){const g=m.from==="*"?[]:Array.isArray(m.from)?m.from:[m.from];for(const b of g)n.has(b)||t.push(`transitions[${h}].from references unknown state "${b}"`);m.from!=="*"&&g.length===0&&t.push(`transitions[${h}].from is required`),m.to?n.has(m.to)||t.push(`transitions[${h}].to references unknown state "${m.to}"`):t.push(`transitions[${h}].to is required`),m.when&&t.push(...ho(m.when,a,`transitions[${h}].when`))}for(const[h,m]of s.states.entries()){const g=(c=(l=m.extract)==null?void 0:l.title)==null?void 0:c.section;g&&!a.has(g)&&t.push(`states[${h}].extract.title.section "${g}" unknown`);const b=(p=(d=m.extract)==null?void 0:d.buttons)==null?void 0:p.section;b&&!a.has(b)&&t.push(`states[${h}].extract.buttons.section "${b}" unknown`)}return t}function ho(e,t,s){const n=[],i=e;if("all"in i)return i.all.forEach((a,o)=>n.push(...ho(a,t,`${s}.all[${o}]`))),n;if("any"in i)return i.any.forEach((a,o)=>n.push(...ho(a,t,`${s}.any[${o}]`))),n;if("not"in i)return n.push(...ho(i.not,t,`${s}.not`)),n;if("matches"in i){i.section&&!t.has(i.section)&&n.push(`${s}.section "${i.section}" unknown`);try{new RegExp(i.matches,i.flags??"i")}catch(a){n.push(`${s}.matches invalid regex: ${a.message}`)}return n}return"cursor_above"in i&&"changed"in i?n:"elapsed_ms"in i?(typeof i.elapsed_ms!="number"&&n.push(`${s}.elapsed_ms must be a number`),n):"stable_ms"in i?(typeof i.stable_ms!="number"&&n.push(`${s}.stable_ms must be a number`),n):(n.push(`${s} is not a recognized condition`),n)}var Dv=We({"src/providers/spec/fsm-loader.ts"(){Mp()}}),lO={};Tt(lO,{PROVIDER_REQUIRE_POLICY:()=>Wv,_getRegisteredRoots:()=>yO,_resetProviderScriptRoots:()=>bO,_uninstallProviderProcessShimForTest:()=>mO,installProviderProcessShim:()=>hO,registerProviderScriptRoot:()=>gO,unregisterProviderScriptRoot:()=>xO});function cO(e){return e.startsWith("node:")?e.slice(5):e}function dO(){const e={};for(const n of $d){if(n==="promises")continue;const i=Qe[n];i!==void 0&&(e[n]=i)}const t=Qe.promises||{},s={};for(const n of $v){const i=t[n];i!==void 0&&(s[n]=i)}return e.promises=s,e}function uO(e,t,s){if(typeof e!="string"||e.length===0)throw new TypeError("execFileSync: `file` must be a non-empty string");let n=[];if(t!=null){if(!Array.isArray(t)||!t.every(a=>typeof a=="string"))throw new TypeError("execFileSync: `args` must be a string[] (no shell expansion).");n=t}const i={};if(s&&typeof s=="object"){const a=s;typeof a.cwd=="string"&&(i.cwd=a.cwd),typeof a.timeout=="number"&&(i.timeout=a.timeout),typeof a.encoding=="string"&&(i.encoding=a.encoding),typeof a.maxBuffer=="number"&&(i.maxBuffer=a.maxBuffer),(typeof a.input=="string"||a.input instanceof Buffer)&&(i.input=a.input)}return Uw.execFileSync(e,n,i)}function pO(){if(Ws.length===0)return!1;const e=new Error().stack||"";for(const t of Ws)if(e.includes(t.rootPath))return!0;return!1}function hO(){if(Ui)return;Ui=!0;const e=globalThis.process;if(e){fn=new Map;for(const t of Wi){const s=e[t];if(typeof s!="function")continue;fn.set(t,s);const n=function(...a){if(pO()){const o=new Error(`process.${t}() denied: provider scripts cannot terminate, signal, or extend the daemon process.`);throw o.code="PROVIDER_PROCESS_DENIED",o.method=t,o}return s.apply(this,a)};try{Object.defineProperty(n,"name",{value:t,configurable:!0}),e[t]=n}catch{}}}}function mO(){if(!fn){Ui=!1;return}const e=globalThis.process;for(const[t,s]of fn)try{e[t]=s}catch{}fn=null,Ui=!1}function fO(){const e=globalThis.process,t=Object.create(null);for(const s of Object.keys(e))if(!Wi.has(String(s)))try{t[s]=e[s]}catch{}for(const s of Wi)t[s]=function(){const i=new Error(`process.${s}() denied via require('process'): provider scripts cannot terminate, signal, or extend the daemon.`);throw i.code="PROVIDER_PROCESS_DENIED",i.method=s,i};return Object.freeze(t)}function gO(e){const t=Pl(e);t&&(Ws.some(s=>s.rootPath===t)||(Ws.push({rootPath:t}),wO()))}function xO(e){const t=Pl(e);if(!t)return;const s=Ws.findIndex(n=>n.rootPath===t);s>=0&&Ws.splice(s,1)}function bO(){Ws.length=0}function yO(){return Ws.map(e=>e.rootPath)}function Pl(e){try{const t=Ee.resolve(e);try{return Qe.realpathSync.native?Qe.realpathSync.native(t):Qe.realpathSync(t)}catch{return t}}catch{return null}}function vO(e){if(!e)return null;let t;try{t=Pl(e)||e}catch{t=e}for(const s of Ws)if(t===s.rootPath||t.startsWith(s.rootPath+Ee.sep))return s;return null}function wO(){if(Od)return;Od=!0;const e=Cs("module"),t=e._load;e._load=function(n,i,a){const o=(i==null?void 0:i.filename)||"",l=vO(o);return l?SO.call(this,n,i,a,l,t):t.call(this,n,i,a)}}function SO(e,t,s,n,i){if(e.startsWith("./")||e.startsWith("../")||Ee.isAbsolute(e)){let o;try{o=(t!=null&&t.filename?Gc(t.filename):Gc(Ee.join(n.rootPath,"__entry__.js"))).resolve(e)}catch{return i.call(this,e,t,s)}const l=Pl(o)||o;return l===n.rootPath||l.startsWith(n.rootPath+Ee.sep)||Sf(e,t,`relative path escapes provider root (resolved to ${l})`),i.call(this,e,t,s)}const a=cO(e);return Lv.has(a)||Sf(e,t,"module not on the provider script whitelist"),a==="fs"?Ov:a==="child_process"?Fv:a==="process"?Bv:i.call(this,e,t,s)}function Sf(e,t,s){const n=(t==null?void 0:t.filename)||"<unknown>",i=`Provider script require('${e}') denied: ${s}. Caller: ${n}`;_e.warn("ProviderScript",`[require-whitelist] ${i}`);const a=new Error(i);throw a.code="PROVIDER_REQUIRE_DENIED",a.deniedModule=e,a.callerFilename=n,a}var $c,Oc,Lv,$d,$v,Ov,Fv,Wi,Ui,fn,Bv,Ws,Od,Wv,kO=We({"src/providers/sdk/v1/sandbox/require-whitelist.ts"(){Ve(),$c=new Set(["path","os","util","url","querystring","buffer","events","stream","string_decoder","assert","crypto","timers","punycode","zlib"]),Oc=new Set(["fs","child_process","process"]),Lv=new Set([...$c,...Oc]),$d=["existsSync","statSync","lstatSync","realpathSync","readFileSync","readdirSync","readlinkSync","accessSync","constants","exists","stat","lstat","realpath","readFile","readdir","readlink","access","promises"],$v=["stat","lstat","realpath","readFile","readdir","readlink","access"],Ov=Object.freeze(dO()),Fv=Object.freeze({execFileSync:uO}),Wi=new Set(["exit","kill","abort","binding","dlopen","_kill","_exit","reallyExit","_fatalException"]),Ui=!1,fn=null,Bv=fO(),Ws=[],Od=!1,Wv=Object.freeze({safeStdlib:Array.from($c).sort(),shimmedStdlib:Array.from(Oc).sort(),fsAllowedMembers:Array.from($d),childProcessAllowedMembers:["execFileSync"],processDeniedMembers:Array.from(Wi).sort()})}});Mn();ra();na();zu();function jO(e){return Math.max(1,Math.floor(e??100))}function NO(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 kf(e){return`${e.oldPath??""}\0${e.path}`}function Xn(e){return Array.from(new Set(Array.from(e).filter(Boolean))).sort((t,s)=>t.localeCompare(s))}function jf(e,t,s=`${t}s`){return e===1?t:s}function _O(e,t){const s=new Set(e.diffSummary.files.map(kf)),n=t.diffSummary.files.filter(v=>!s.has(kf(v))),i=[],a=[],o=[],l=[],c=[],d=[];let p=0,h=0;for(const v of n)switch(p+=v.insertions,h+=v.deletions,v.status){case"added":case"copied":i.push(v.path);break;case"modified":a.push(v.path);break;case"deleted":o.push(v.path);break;case"renamed":l.push({oldPath:v.oldPath??v.path,path:v.path});break;case"untracked":c.push(v.path);break;case"conflict":d.push(v.path);break}l.sort((v,w)=>`${v.oldPath}\0${v.path}`.localeCompare(`${w.oldPath}\0${w.path}`));const m=Xn([...t.status.conflictFiles,...d]),g=n.length,b=t.status.hasConflicts||m.length>0,f=[];return g>0&&f.push(`${g} ${jf(g,"file")} changed`),i.length>0&&f.push(`${i.length} added`),a.length>0&&f.push(`${a.length} modified`),o.length>0&&f.push(`${o.length} deleted`),l.length>0&&f.push(`${l.length} renamed`),c.length>0&&f.push(`${c.length} untracked`),b&&f.push(`${m.length||1} ${jf(m.length||1,"conflict")}`),{beforeSnapshotId:e.id,afterSnapshotId:t.id,workspace:t.workspace,repoRoot:t.repoRoot,changedFiles:g,addedFiles:Xn(i),modifiedFiles:Xn(a),deletedFiles:Xn(o),renamedFiles:l,untrackedFiles:Xn(c),conflictFiles:m,totalInsertions:p,totalDeletions:h,hasConflicts:b,currentStatus:t.status,summaryText:f.length>0?f.join(", "):"No file-set changes between snapshots."}}var CO=class{constructor(e={}){re(this,"snapshots",new Map);re(this,"order",[]);re(this,"capacity");re(this,"now");re(this,"idPrefix");re(this,"getStatusProvider");re(this,"getDiffSummaryProvider");re(this,"counter",0);this.capacity=jO(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 s=await t(e.workspace),n=e.getDiffSummary??this.getDiffSummaryProvider,i=n?await n(e.workspace,s):NO(s),a=this.now(),o=`${this.idPrefix}-${a}-${++this.counter}`,l={id:o,workspace:e.workspace,repoRoot:s.repoRoot??e.workspace,sessionId:e.sessionId,turnId:e.turnId,reason:e.reason,status:s,diffSummary:i,createdAt:a};return this.snapshots.set(o,l),this.order.push(o),this.enforceCapacity(),l}get(e){return this.snapshots.get(e)}compare(e,t){const s=this.snapshots.get(e);if(!s)throw new Error(`Unknown before snapshot: ${e}`);const n=this.snapshots.get(t);if(!n)throw new Error(`Unknown after snapshot: ${t}`);return _O(s,n)}list(e={}){const t=Math.max(1,Math.floor(e.limit??this.capacity));return this.order.map(s=>this.snapshots.get(s)).filter(s=>!!s).filter(s=>!e.workspace||s.workspace===e.workspace).filter(s=>!e.sessionId||s.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 IO(e={}){return new CO(e)}zu();na();zu();ra();na();IO({getStatus:e=>mi(e),getDiffSummary:e=>ty(e)});RR();rs();wl();oP();aD();Zy();yD();rs();var AO=[".adhdev/refine.json",".adhdev/refine.yaml",".adhdev/refine.yml",".adhdev/repo-mesh-refine.json",".adhdev/repo-mesh-refine.yaml",".adhdev/repo-mesh-refine.yml","repo-mesh.refine.json","repo-mesh.refine.yaml","repo-mesh.refine.yml"],TO=[".adhdev/worktree_bootstrap.json",".adhdev/worktree_bootstrap.yaml",".adhdev/worktree_bootstrap.yml",".adhdev/worktree-bootstrap.json",".adhdev/worktree-bootstrap.yaml",".adhdev/worktree-bootstrap.yml"];fr();ip();Ys();da();tp();vl();vp();dp();rs();In(el);pa();In(el);Ve();var MO=["standard","thought","tool","terminal","system"],EO=["tool_call","terminal_command","runtime_activity"],RO=["runtime_status","provider_chrome","control"];new Set(MO);new Set(EO);new Set(RO);Ee.join(ot.homedir(),".adhdev","history");Ve();Ve();Ve();Ys();Ve();Ve();wp();function PO(e){const t=[];return{record(s){return null},list(s={}){const n=Math.max(1,Math.floor(s.limit||100));return t.filter(i=>!s.interactionId||i.interactionId===s.interactionId).filter(i=>!s.category||i.category===s.category).slice(-n).map(i=>({...i,payload:i.payload?{...i.payload}:{}}))},clear(){t.splice(0,t.length)}}}PO({capacity:sv().traceBufferSize});Object.freeze({name:"Booting",nativeSequencePeak:void 0,committedUnitKeys:Object.freeze(new Set),recoveringMisses:0});rs();Ve();rs();Ip();pa();rs();Ip();Sp();Ev();Rv();Mp();Dv();Ve();Ve();Ve();Ve();Ve();Ve();Ve();Ve();var Fc=Lw;typeof Fc.yellow=="function"||Fc.default;Ve();H5();Ee.join(ot.homedir(),".hermes","state.db");Ee.join(ot.homedir(),".hermes","sessions");rs();pa();na();da();Ve();var Qo=process.platform==="win32"?Ee.join(bt.LOCALAPPDATA||bt.APPDATA||Ee.join(ot.homedir(),"AppData","Local"),"adhdev","logs"):process.platform==="darwin"?Ee.join(ot.homedir(),"Library","Logs","adhdev"):Ee.join(ot.homedir(),".local","share","adhdev","logs"),DO=7;try{Qe.mkdirSync(Qo,{recursive:!0})}catch{}function LO(){return new Date().toISOString().slice(0,10)}var $O=LO();Ee.join(Qo,`commands-${$O}.jsonl`);function OO(){try{const e=Qe.readdirSync(Qo).filter(n=>n.startsWith("commands-")&&n.endsWith(".jsonl")),t=new Date;t.setDate(t.getDate()-DO);const s=t.toISOString().slice(0,10);for(const n of e){const i=n.match(/commands-(\d{4}-\d{2}-\d{2})/);if(i&&i[1]<s)try{Qe.unlinkSync(Ee.join(Qo,n))}catch{}}}catch{}}OO();Ve();Ve();var dn="••••redacted";function Nf(e){return e.length<=8?dn:`${dn}${e.slice(-4)}`}var FO=[{name:"key_value_secret",pattern:/\b([A-Z0-9_]*(?:SECRET|TOKEN|API[_-]?KEY|PASSWORD|PASSWD|PRIVATE[_-]?KEY|CREDENTIAL|CLIENT[_-]?SECRET)[A-Z0-9_]*)(\s*[:=]\s*)(["']?)([^\s"',;]+)\3/gi,replace:(e,t,s,n)=>`${t}${s}${n}${dn}${n}`},{name:"bearer_token",pattern:/\b(Bearer\s+)([A-Za-z0-9._\-+/=]{8,})/g,replace:(e,t,s)=>`${t}${Nf(s)}`},{name:"adhdev_prefixed_secret",pattern:/\b(ad[kmp]_)([A-Za-z0-9]{6,})/g,replace:(e,t,s)=>`${t}${Nf(t+s)}`},{name:"jwt",pattern:/\beyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}/g,replace:()=>dn},{name:"turn_credential",pattern:/\b(credential["']?\s*(?:[:=]\s*)?["']?)([^\s"',;]{6,})/gi,replace:(e,t)=>`${t}${dn}`},{name:"turn_rest_pair",pattern:/\b(\d{10,}:)([A-Za-z0-9+/]{20,}={0,2})\b/g,replace:(e,t)=>`${t}${dn}`}];FO.map(e=>e.name);VD();vp();E0();Yr();vl();ip();In(Hd);tp();AO[0];TO[0];rs();Sp();Ve();process.argv.includes("--dev")||bt.ADHDEV_READ_DEBUG;Hu();Ys();Mn();function Rp(e,t){var i;const s=(i=bt[e])==null?void 0:i.trim();if(!s)return t;const n=Number.parseInt(s,10);return Number.isFinite(n)&&n>=1e3&&n<=12e4?n:t}Rp("MESH_DIRECT_PROBE_TIMEOUT_MS",25e3);Rp("MESH_DIRECT_PROBE_RETRY_TIMEOUT_MS",25e3);Rp("MESH_DIRECT_PROBE_REUSE_MS",12e3);process.argv.includes("--dev")||bt.ADHDEV_READ_DEBUG;Ve();Hu();Ve();wp();Ve();Ve();Ve();Ee.join(ot.homedir(),".adhdev","version-history.json");rs();Ve();Ve();Ip();xv();Ve();gv();In(el);pa();Ve();rs();vp();tv();kO();Ve();Rv();Dv();_p();Cp();Np();Cv();Hr();D5();var BO=Object.freeze({acp:["adhdev:acp/session-protocol@1"],tui:["adhdev:tui/prompt-marker@1","adhdev:tui/spinner@1","adhdev:tui/settled-prompt@1","adhdev:tui/assistant-block@1","adhdev:tui/tool-block@1","adhdev:tui/thinking-block@1","adhdev:tui/user-echo@1","adhdev:tui/modal@1","adhdev:tui/modal-as-message@1","adhdev:tui/footer-chrome@1","adhdev:tui/welcome-screen@1","adhdev:tui/visible-region@1","adhdev:tui/cue-ordering@1","adhdev:tui/dispatch-order@1","adhdev:tui/index-finder@1","adhdev:tui/status-downgrade@1","adhdev:tui/approval-stitching@1","adhdev:tui/approval-squash@1","adhdev:tui/media-input@1","adhdev:tui/session-id-extraction@1","adhdev:tui/error-detection@1"],nativeHistory:["adhdev:native-history/codex-rollout@1","adhdev:native-history/claude-jsonl@1","adhdev:native-history/anthropic-cli-transcript@1","adhdev:native-history/hermes-session@1"],cliCapability:["adhdev:cli/capability-list@1","adhdev:cli/control-state@1","adhdev:cli/capability-action@1","adhdev:cli/control-toggle@1","adhdev:cli/picker-open@1","adhdev:cli/picker-set@1"],common:["adhdev:common/setting-boolean@1","adhdev:common/setting-number@1","adhdev:common/setting-string@1","adhdev:common/setting-select@1","adhdev:common/capability-input@1","adhdev:common/capability-output@1","adhdev:common/capability-controls@1","adhdev:common/auth-env-var@1","adhdev:common/auth-cli-command@1","adhdev:common/spawn@1","adhdev:common/timeouts@1","adhdev:common/resume@1","adhdev:common/mesh-coordinator@1"],override:["adhdev:override/cli-parse-session@1","adhdev:override/cli-detect-status@1","adhdev:override/cli-parse-approval@1","adhdev:override/cli-parse-output@1","adhdev:override/cli-read-native-history@1","adhdev:override/cli-list-native-history@1","adhdev:override/cli-capability-handler@1"]});Object.freeze(Object.values(BO).flat());function _f(e){if(e.status!=="completed"&&e.status!=="failed")return null;const t=e.dispatchTimestamp?new Date(e.dispatchTimestamp).getTime():NaN,s=e.updatedAt?new Date(e.updatedAt).getTime():NaN;if(!Number.isFinite(t)||!Number.isFinite(s)||s<t)return null;const n=Math.round((s-t)/1e3);if(n<60)return`${n}s`;const i=Math.floor(n/60);return i<60?`${i}m ${n%60}s`:`${Math.floor(i/60)}h ${i%60}m`}function WO({queueSummary:e,queueLoading:t,queueError:s,activeDaemonId:n,onRefresh:i}){return r.jsxs(wt,{title:"Queue",description:"Inspect active queue work separately from historical completed, failed, and cancelled task records.",children:[r.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[r.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-7 gap-2 flex-1 min-w-[260px]",children:[["Active",(e==null?void 0:e.active)??0,"text-accent-primary"],["Pending",(e==null?void 0:e.activeCounts.pending)??(e==null?void 0:e.counts.pending)??0,"text-text-primary"],["Assigned",(e==null?void 0:e.activeCounts.assigned)??(e==null?void 0:e.counts.assigned)??0,"text-blue-400"],["Stale",(e==null?void 0:e.staleAssignedCount)??0,"text-amber-400"],["Historical",(e==null?void 0:e.historical)??0,"text-text-muted"],["Completed",(e==null?void 0:e.historicalCounts.completed)??(e==null?void 0:e.counts.completed)??0,"text-green-400"],["Failed",(e==null?void 0:e.historicalCounts.failed)??(e==null?void 0:e.counts.failed)??0,"text-red-400"]].map(([a,o,l])=>r.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wide text-text-muted",children:a}),r.jsx("div",{className:`text-lg font-bold ${l}`,children:o})]},String(a)))}),r.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:i,disabled:t||!n,children:[r.jsx(Bu,{size:13}),t?"Loading...":"Refresh Queue"]})]}),s&&r.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:s}),e?e.recent.length===0?r.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:"Queue is empty."}):r.jsx("div",{className:"flex flex-col gap-2",children:e.recent.map(a=>{var o;return r.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:r.jsxs("div",{className:"flex items-center justify-between gap-3",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[r.jsx("span",{className:"font-mono text-[11px] text-text-muted",children:a.id.slice(0,12)}),r.jsx(Fb,{status:a.status}),a.staleAssigned&&r.jsx("span",{className:"text-[10px] text-amber-300 bg-amber-500/10 border border-amber-500/20 rounded-full px-2 py-0.5",title:a.staleReason||"Stale assignment",children:"stale"}),(((o=a.waitingOn)==null?void 0:o.length)??0)>0&&r.jsxs("span",{className:"text-[10px] text-sky-300 bg-sky-500/10 border border-sky-500/20 rounded-full px-2 py-0.5",title:`Waiting on: ${a.waitingOn.join(", ")}`,children:["waits on ",a.waitingOn.length," task",a.waitingOn.length>1?"s":""]}),a.blockedReason&&r.jsx("span",{className:"text-[10px] text-red-300 bg-red-500/10 border border-red-500/20 rounded-full px-2 py-0.5",title:a.blockedReason,children:"blocked"}),_f(a)&&r.jsxs("span",{className:"text-[10px] text-text-muted bg-bg-tertiary border border-border-subtle rounded-full px-2 py-0.5",title:"Dispatched → terminal wall clock",children:[_f(a),(a.requeueCount??0)>0?` · ${a.requeueCount} retr${a.requeueCount===1?"y":"ies"}`:""]})]}),a.message&&r.jsx("div",{className:"text-[12px] text-text-primary truncate",children:a.message})]}),r.jsxs("div",{className:"text-right text-[10px] text-text-muted shrink-0",children:[a.nodeId&&r.jsxs("div",{children:["node ",a.nodeId.slice(0,10)]}),a.sessionId&&r.jsxs("div",{children:["session ",a.sessionId.slice(0,10)]}),a.updatedAt&&r.jsx("div",{children:new Date(a.updatedAt).toLocaleTimeString()})]})]})},a.id)})}):r.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:"Refresh the queue to view host-owned task counts and recent assignments."})]})}function UO(e){return e==="refine_blocked_review"?{label:"Blocked review",color:"text-amber-400 bg-amber-500/10 border-amber-500/20"}:{label:"Merge candidate",color:"text-blue-400 bg-blue-500/10 border-blue-500/20"}}function HO(e){if(!e)return null;const t=typeof e.stage=="string"?e.stage:null,s=e.passed===!0;if(!t)return null;const n={ran:s?"text-green-400 bg-green-500/10 border-green-500/20":"text-red-400 bg-red-500/10 border-red-500/20",cached:"text-blue-400 bg-blue-500/10 border-blue-500/20",failed:"text-red-400 bg-red-500/10 border-red-500/20",skipped:"text-text-muted bg-bg-secondary border-border-subtle",legacy:"text-text-muted bg-bg-secondary border-border-subtle",not_configured:"text-text-muted bg-bg-secondary border-border-subtle"};return{label:`bootstrap: ${t}`,color:n[t]??"text-text-muted bg-bg-secondary border-border-subtle"}}function zO({file:e}){const s={added:"text-green-400",deleted:"text-red-400",modified:"text-amber-400",renamed:"text-blue-400"}[e.status??""]??"text-text-muted";return r.jsxs("div",{className:"flex items-center justify-between gap-2 py-0.5",children:[r.jsx("span",{className:`text-[11px] font-mono truncate flex-1 ${s}`,children:e.path}),(e.insertions!=null||e.deletions!=null)&&r.jsxs("span",{className:"text-[10px] text-text-muted shrink-0",children:[e.insertions!=null&&r.jsxs("span",{className:"text-green-400",children:["+",e.insertions]}),e.deletions!=null&&r.jsxs("span",{className:"text-red-400 ml-1",children:["-",e.deletions]})]})]})}function KO({item:e,activeDaemonId:t,sendCommand:s,onDismiss:n,onRefineNode:i,onRequeueLast:a}){var k,j,y;const[o,l]=u.useState(null),[c,d]=u.useState(null),[p,h]=u.useState(!1),[m,g]=u.useState(null),{label:b,color:f}=UO(e.reviewReason),v=HO(e.evidence.bootstrap),w=((k=e.diffSummary)==null?void 0:k.files)??[],x=((j=e.diffSummary)==null?void 0:j.baseRef)??null,S=u.useCallback(async N=>{if(!(!e.workspace||!t)){if(o===N){l(null),d(null);return}l(N),d(null),h(!0),g(null);try{const _=await s(t,"git_diff_file",{workspace:e.workspace,path:N,...x?{base:x}:{}});(_==null?void 0:_.success)!==!1&&typeof(_==null?void 0:_.diff)=="string"?d(_.diff):(_==null?void 0:_.diff)!=null?d(String(_.diff)):g((_==null?void 0:_.error)||"No diff available")}catch(_){g((_==null?void 0:_.message)||"Failed to load diff")}finally{h(!1)}}},[e.workspace,t,s,o,x]);return r.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary p-4 space-y-3",children:[r.jsxs("div",{className:"flex flex-wrap items-start gap-2 justify-between",children:[r.jsxs("div",{className:"flex flex-wrap items-center gap-2 min-w-0",children:[r.jsx("span",{className:"text-[12px] font-semibold text-text-primary font-mono truncate max-w-[240px]",children:e.branch??e.nodeId}),r.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${f}`,children:b}),v&&r.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${v.color}`,children:v.label}),e.activeRefineJob&&r.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded border text-blue-400 bg-blue-500/10 border-blue-500/20",children:"refine running"})]}),r.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[r.jsx("button",{className:"btn btn-primary btn-sm text-[11px]",onClick:()=>i(e.nodeId),disabled:!!e.activeRefineJob,children:"Refine"}),r.jsx("button",{className:"btn btn-secondary btn-sm text-[11px]",onClick:()=>a(e.nodeId),children:"Requeue"}),r.jsx("button",{className:"btn btn-secondary btn-sm text-[11px]",onClick:()=>n(e.nodeId),children:"Dismiss"})]})]}),e.workspace&&r.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate",children:e.workspace}),e.evidence.available&&r.jsxs("div",{className:"text-[11px] text-text-secondary space-y-0.5",children:[e.evidence.source==="task_completion"&&e.evidence.worker&&r.jsxs("span",{children:["Last task: ",r.jsx("span",{className:e.evidence.worker.status==="success"?"text-green-400":"text-red-400",children:e.evidence.worker.status}),e.evidence.worker.classification&&r.jsxs("span",{className:"text-text-muted ml-1",children:["(",e.evidence.worker.classification,")"]}),e.evidence.worker.errors.length>0&&r.jsxs("span",{className:"text-red-400 ml-1",children:["· ",e.evidence.worker.errors[0]]})]}),e.evidence.source==="refine_job"&&r.jsxs("span",{children:["Refinery: ",r.jsx("span",{className:"text-amber-400",children:e.convergence.status}),e.convergence.nextStep&&r.jsxs("span",{className:"text-text-muted ml-1",children:["→ ",e.convergence.nextStep]})]})]}),e.diffSummary&&e.diffSummary.files.length>0&&r.jsxs("div",{className:"space-y-1",children:[r.jsxs("div",{className:"text-[10px] text-text-muted flex gap-3",children:[r.jsxs("span",{children:[e.diffSummary.totalFiles," file",e.diffSummary.totalFiles!==1?"s":""]}),r.jsxs("span",{className:"text-green-400",children:["+",e.diffSummary.totalInsertions]}),r.jsxs("span",{className:"text-red-400",children:["-",e.diffSummary.totalDeletions]}),e.diffSummary.truncated&&r.jsx("span",{className:"text-amber-400",children:"truncated"}),x&&r.jsxs("span",{className:"font-mono",children:["vs ",x]})]}),r.jsxs("div",{className:"border border-border-subtle rounded px-2 py-1 bg-bg-primary space-y-0.5",children:[w.slice(0,20).map(N=>r.jsxs("div",{children:[r.jsx("button",{className:"w-full text-left hover:bg-bg-secondary rounded px-1 transition-colors",onClick:()=>S(N.path),children:r.jsx(zO,{file:N})}),o===N.path&&r.jsx("div",{className:"mt-1 mb-1",children:r.jsx(Rb,{diff:c??"",loading:p,error:m??void 0,truncated:!1,className:"text-[10px]"})})]},N.path)),w.length>20&&r.jsxs("div",{className:"text-[10px] text-text-muted px-1 pt-0.5",children:["+",w.length-20," more files"]})]})]}),((y=e.diffSummary)==null?void 0:y.error)&&r.jsxs("div",{className:"text-[11px] text-amber-400",children:["Diff probe: ",e.diffSummary.error]})]})}function GO({items:e,loading:t,error:s,remoteNodesExcluded:n,meshId:i,activeDaemonId:a,onRefresh:o,onDismiss:l,onRefineNode:c,onRequeueLast:d,sendCommand:p}){return r.jsxs(wt,{title:"Review Inbox",description:"Local worktree nodes that need review: merge candidates and Refinery-blocked results. Click a file to preview its diff.",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[e.length>0&&r.jsxs("span",{className:"text-[12px] font-semibold text-accent-primary",children:[e.length," item",e.length!==1?"s":""]}),n&&r.jsx("span",{className:"text-[10px] text-text-muted px-1.5 py-0.5 rounded border border-border-subtle bg-bg-secondary",children:"remote nodes excluded"})]}),r.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:o,disabled:t,children:[r.jsx(Bu,{size:12}),t?"Loading...":"Refresh"]})]}),s&&r.jsx("div",{className:"mb-3 text-[12px] text-red-400 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2",children:s}),!t&&!s&&e.length===0&&r.jsxs("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:["No local nodes require review.",n&&" Remote nodes are excluded in this view."]}),r.jsx("div",{className:"space-y-3",children:e.map(h=>r.jsx(KO,{item:h,activeDaemonId:a,sendCommand:p,onDismiss:l,onRefineNode:c,onRequeueLast:d},h.nodeId))})]})}function qO(e){const t=new Map;for(const s of e)s!=null&&s.id&&t.set(s.id,Sn(s.availableProviders||[]));return t}function VO(e,t){const s=String(e.daemon_id||e.daemonId||"");return s&&t.has(s)?t.get(s):[]}function XO(e,t){return t.filter(s=>s.status!=="assigned"?!1:(s.assignedNodeId||s.nodeId)===e.id)}function YO(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",s=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${s}`}function Uv(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],s=new Set;return t.map(i=>typeof i=="string"?i.trim():"").filter(Boolean).filter(i=>s.has(i)?!1:(s.add(i),!0))}function QO(e){const t=Uv(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 JO(e){return e.isLocalWorktree===!0}function ZO(e){var s;const t=Number((s=e.policy)==null?void 0:s.schedulingPriority);return Number.isFinite(t)?t:0}function e3(e){var s;const t=(s=e.policy)==null?void 0:s.providerRoles;return Array.isArray(t)?t.filter(n=>!!n&&typeof n=="object"&&typeof n.providerType=="string"&&n.providerType.trim().length>0).map(n=>({providerType:n.providerType.trim(),role:typeof n.role=="string"&&n.role.trim()?n.role.trim():void 0,maxParallel:Number.isFinite(Number(n.maxParallel))&&Number(n.maxParallel)>=0?Math.floor(Number(n.maxParallel)):void 0})):[]}function t3(e,t){const s=t;return[...Array.isArray(s==null?void 0:s.cliSessions)?s.cliSessions:[],...Array.isArray(s==null?void 0:s.acpSessions)?s.acpSessions:[],...Array.isArray(s==null?void 0:s.sessions)?s.sessions:[]].filter(i=>{var a;return((a=i==null?void 0:i.settings)==null?void 0:a.meshNodeId)===e.id||(i==null?void 0:i.workspace)===e.workspace}).map(i=>{var a;return{id:i.sessionId||i.id||i.instanceId||"unknown",provider:i.providerType||i.cliType||i.acpType||i.type||"unknown",status:i.status||((a=i.activeChat)==null?void 0:a.status)||"unknown"}})}function Cf(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function s3(e,t){var s;return(e==null?void 0:e.ownerName)||(e==null?void 0:e.userName)||((s=e==null?void 0:e.user)==null?void 0:s.name)||t||"You"}function r3({nodes:e,meshQueue:t,activeDaemon:s,daemons:n,selectedMeshId:i,userName:a,features:o,coordinatorDaemonId:l,schedulingStrategy:c,roleOptions:d,nodeProviderPriorityDrafts:p,onNodeProviderPriorityDraftChange:h,availableCliProviders:m,savingNodePolicyId:g,onUpdateNodeProviderPriority:b,savingNodeSchedulingId:f,onUpdateNodeScheduling:v,nodeSystemPromptDrafts:w,onNodeSystemPromptDraftChange:x,savingNodeSystemPromptId:S,onSaveNodeSystemPrompt:k,selectedNodeId:j,onSelectNode:y,showAddNode:N,onShowAddNode:_,onCancelAddNode:C,nodeWorkspace:D,onNodeWorkspaceChange:T,nodeProviderPriority:A,onNodeProviderPriorityChange:P,nodeDaemonId:F,onNodeDaemonIdChange:J,nodeCustomPath:R,onNodeCustomPathChange:I,nodePickerWorkspaces:E,nodePickerProviders:$,attachableDaemons:M,onAddNode:O,onRemoveNode:H}){const ae=u.useMemo(()=>qO(n),[n]);return r.jsxs(wt,{title:o.addNodeDaemonPicker?`Nodes & Providers (${e.length})`:"Nodes & Providers",description:o.addNodeDaemonPicker?"Workspaces in this mesh and their preferred AI tools. Setup inventory only — live graph/git/session truth is owned by the Mesh Host status above.":"Workspaces participating in this mesh and their preferred AI tools.",children:[o.addNodeDaemonPicker&&r.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[r.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Machine daemon candidates"}),r.jsx("div",{className:"text-[12px] text-text-muted",children:"Choose connected daemons to attach to the selected Mesh Host setup."})]}),r.jsxs("span",{className:"text-[11px] text-text-muted",children:[M.length," available"]})]}),n.length===0?r.jsx("div",{className:"text-[12px] text-text-muted",children:"No connected machine daemons are currently available."}):M.length===0?r.jsx("div",{className:"text-[12px] text-text-muted",children:"All connected machine daemons are already attached."}):r.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:M.map(z=>r.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${z.id===l?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{J(z.id),T(""),I(!1),P(Ci(Sn(z.availableProviders||[]))),_()},children:[r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:"text-sm font-medium truncate",children:Cf(z)}),z.id===l&&r.jsx("span",{className:"text-[10px] text-accent-primary",children:"selected host"})]}),r.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:z.id}),r.jsxs("div",{className:"mt-1 text-[11px] text-text-muted",children:[(z.workspaces||[]).length," workspace(s) detected"]})]},z.id))})]}),!N&&r.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:_,children:[r.jsx(Ob,{size:13})," ",o.addNodeDaemonPicker?"Attach Machine Daemon":"+ Add Node"]}),N&&r.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[r.jsxs("div",{className:"flex justify-between items-center mb-3",children:[r.jsx("h4",{className:"text-sm font-bold",children:o.addNodeDaemonPicker?"Attach Machine Daemon":"Add Node"}),r.jsx("button",{onClick:()=>{C(),J(""),I(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:r.jsx(Ot,{size:16})})]}),o.addNodeDaemonPicker&&r.jsx(Wt,{label:"Machine",children:r.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:F,onChange:z=>{var X;J(z.target.value),T(""),I(!1),P(Ci(Sn(((X=n.find(te=>te.id===z.target.value))==null?void 0:X.availableProviders)||[])))},children:[r.jsx("option",{value:"",children:"Select a machine..."}),n.map(z=>r.jsx("option",{value:z.id,children:Cf(z)},z.id))]})}),(o.addNodeDaemonPicker?F:!0)&&r.jsx(Wt,{label:"Workspace Path",children:o.addNodeDaemonPicker&&!R&&E.length>0?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:E.map(z=>r.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${D===z.path?"border-accent-primary bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-primary hover:bg-violet-500/10 text-text-primary"}`,onClick:()=>T(z.path),children:[r.jsx("span",{className:"font-medium block truncate",children:z.label||z.path.split("/").pop()}),r.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:z.path})]},z.id||z.path))}),r.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{I(!0),T("")},children:"Or enter a custom path →"})]}):r.jsx(r.Fragment,{children:o.addNodeDaemonPicker?r.jsxs(r.Fragment,{children:[r.jsx(di,{value:D,onChange:z=>T(z.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:z=>{z.key==="Enter"&&O()}}),E.length>0&&r.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{I(!1),T("")},children:"← Pick from saved workspaces"})]}):(()=>{var te;const z=Array.isArray(s==null?void 0:s.workspaces)?s.workspaces:[],X=`mesh-add-node-workspaces-${i||"new"}`;return r.jsxs(r.Fragment,{children:[r.jsx(di,{value:D,onChange:he=>T(he.target.value),placeholder:((te=z[0])==null?void 0:te.path)||"/Users/dev/projects/myapp",list:z.length>0?X:void 0,autoFocus:!0}),z.length>0&&r.jsxs(r.Fragment,{children:[r.jsx("datalist",{id:X,children:z.map(he=>r.jsx("option",{value:he.path,children:he.label||he.path},he.id||he.path))}),r.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:z.slice(0,6).map(he=>r.jsx("button",{type:"button",onClick:()=>T(he.path),className:"text-[11px] px-2 py-0.5 rounded-full border border-border-subtle hover:border-accent-primary/50 text-text-muted hover:text-text-primary transition-colors bg-transparent cursor-pointer",title:he.path,children:he.label||he.path.split("/").filter(Boolean).pop()||he.path},he.id||he.path))})]})]})})()})}),r.jsx(Wt,{label:"Preferred AI tools (in order)",hint:"Order used when launching without an explicit provider.",children:r.jsx(Oh,{value:A,availableProviders:o.addNodeDaemonPicker?$:m,onChange:P})}),r.jsxs("div",{className:"flex gap-2 mt-3",children:[r.jsx("button",{onClick:O,disabled:!D.trim()||o.addNodeDaemonPicker&&!F,className:"btn btn-primary btn-sm",children:"Add"}),r.jsx("button",{onClick:()=>{C(),J(""),I(!1)},className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),o.addNodeDaemonPicker&&r.jsx("div",{className:"mb-3 text-[12px] text-amber-300 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:"Setup inventory only — live git/session/branch detail is shown in the graph popup after direct aggregate mesh_status truth is available from the Mesh Host."}),e.length===0?r.jsx(ul,{icon:r.jsx(bn,{}),title:"No nodes",description:"Add a workspace to this mesh."}):r.jsx("div",{className:"flex flex-col gap-2",children:e.map(z=>{const X=QO(z),te=XO(z,t),he=t3(z,s),ke=j===z.id,Q=JO(z),q=z.status||z.machine_status||(te.length>0||he.length>0?"active":"enabled");return r.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${o.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${ke?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:o.addNodeDaemonPicker?void 0:"button",tabIndex:o.addNodeDaemonPicker?void 0:0,onClick:o.addNodeDaemonPicker?void 0:()=>y(ke?null:z.id),onKeyDown:o.addNodeDaemonPicker?void 0:me=>{(me.key==="Enter"||me.key===" ")&&(me.preventDefault(),y(ke?null:z.id))},children:[r.jsxs("div",{className:"flex items-start justify-between gap-3",children:[r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[o.addNodeDaemonPicker?r.jsx("span",{className:"font-semibold text-sm text-text-primary truncate",children:z.machine_label||z.machine_nickname||z.hostname||z.workspace}):r.jsx("span",{className:"text-sm font-medium",children:z.workspace.split("/").pop()}),o.addNodeDaemonPicker&&r.jsx(Fb,{status:q}),te.length>0&&!o.addNodeDaemonPicker&&r.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:[te.length," active task",te.length===1?"":"s"]}),Q&&r.jsx("span",{className:`text-[10px] px-2 py-0.5 rounded-full ${o.addNodeDaemonPicker?"bg-cyan-400/10 text-cyan-300 border border-cyan-400/30":"bg-cyan-500/15 text-cyan-300 border border-cyan-500/25"}`,children:"worktree"}),o.addNodeDaemonPicker&&r.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:"setup inventory"})]}),o.addNodeDaemonPicker&&r.jsxs("div",{className:"text-[11px] text-text-muted",children:["Owner: ",s3(n.find(me=>me.id===String(z.daemon_id||"")),a)," · Machine: ",z.machine_label||z.daemon_id||z.workspace]}),r.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:z.workspace}),Q&&r.jsxs("div",{className:`mt-2 rounded-lg px-3 py-2 text-[11px] ${o.addNodeDaemonPicker?"border border-cyan-400/20 bg-cyan-400/10 text-cyan-200":"border border-cyan-500/20 bg-cyan-500/10 text-cyan-200"}`,children:["Worktree node",z.worktreeBranch?` · ${z.worktreeBranch}`:"",". Provider priority saved here is node-local and disappears when removed."]}),o.addNodeDaemonPicker&&r.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:"Live branch/git/session detail is graph-owned; use the node popup in the live graph above."}),r.jsxs("div",{className:`mt-3 max-w-2xl ${o.addNodeDaemonPicker,""}`,onClick:me=>me.stopPropagation(),children:[r.jsxs(Wt,{label:"Preferred AI tools (in order)",hint:Q?"Worktree-local launch defaults. Configure the source node for durable defaults.":o.addNodeDaemonPicker?"Used for coordinator/session launches when no tool is selected explicitly.":"Used when launches omit an explicit tool.",children:[r.jsx(Oh,{value:p[z.id]??Uv(z),availableProviders:VO(z,ae),onChange:me=>h(z.id,me),disabled:g===z.id,saveButton:r.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:me=>{me.stopPropagation(),b(z)},disabled:g===z.id,children:g===z.id?"Saving…":"Save"})}),r.jsxs("div",{className:"mt-2 text-[12px]",children:[r.jsx("span",{className:"text-text-muted",children:"Effective order: "}),r.jsx("span",{className:X.configured?"text-text-primary font-mono":"text-amber-400",children:X.label}),!X.configured&&X.launchBlockedMessage&&r.jsxs("span",{className:"ml-2 text-amber-400",children:["(",X.launchBlockedMessage,")"]})]})]}),o.nodeInstruction&&r.jsxs(Wt,{label:"Node instruction (optional)",hint:"Surfaced in the coordinator system prompt as 📌 Node instruction.",children:[r.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:w[z.id]??"",onChange:me=>{const we=me.target.value;x(z.id,we)},onClick:me=>me.stopPropagation(),disabled:S===z.id,placeholder:"e.g. 'Run only smoke tests here', 'Use opus on this node'"}),r.jsx("div",{className:"mt-2 flex items-center gap-2",children:r.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:me=>{me.stopPropagation(),k(z)},disabled:S===z.id,children:S===z.id?"Saving…":"Save instruction"})})]}),r.jsx(n3,{node:z,schedulingStrategy:c,roleOptions:d,saving:f===z.id,onSave:me=>v(z,me)})]})]}),r.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${o.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:me=>{me.stopPropagation(),H(z.id)},title:"Remove node",children:o.addNodeDaemonPicker?r.jsx(H2,{size:14}):r.jsx(Ot,{size:14})})]}),r.jsxs("details",{className:"mt-3 group",onClick:me=>me.stopPropagation(),children:[r.jsxs("summary",{className:"cursor-pointer select-none text-[12px] text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[r.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," Details"]}),r.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[r.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[r.jsxs("div",{children:[r.jsx("span",{className:"text-text-secondary",children:"Node ID:"})," ",r.jsx("span",{className:"font-mono break-all",children:z.id})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",r.jsx("span",{className:X.configured?"text-green-400":"text-amber-400",children:X.configured?"yes":"no preferred tool configured"})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-secondary",children:"Repo root:"})," ",r.jsx("span",{className:"font-mono break-all",children:z.repoRoot||z.workspace})]}),r.jsxs("div",{children:[r.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",he.length]}),o.addNodeDaemonPicker&&r.jsxs("div",{children:[r.jsx("span",{className:"text-text-secondary",children:"Added:"})," ",new Date(z.created_at||z.createdAt||Date.now()).toLocaleDateString()]})]}),r.jsxs("div",{className:"mt-3",children:[r.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),te.length===0?r.jsx("div",{children:"No active assigned queue task for this node."}):r.jsx("ul",{className:"m-0 pl-4",children:te.map(me=>r.jsx("li",{className:"font-mono",children:YO(me)},me.id))})]}),he.length>0&&r.jsxs("div",{className:"mt-3",children:[r.jsx("div",{className:"text-text-secondary mb-1",children:"Active sessions"}),r.jsx("ul",{className:"m-0 pl-4",children:he.map(me=>r.jsxs("li",{className:"font-mono",children:[me.provider," / ",me.status," / ",me.id]},me.id))})]})]})]})]},z.id)})})]})}function n3({node:e,schedulingStrategy:t,roleOptions:s,saving:n,onSave:i}){const a=`mesh-role-options-${e.id}`,o=ZO(e),l=u.useMemo(()=>e3(e),[e]),[c,d]=u.useState(String(o)),[p,h]=u.useState(l),m=t!=="first_eligible";function g(){h(w=>[...w,{providerType:""}])}function b(w,x){h(S=>S.map((k,j)=>j===w?{...k,...x}:k))}function f(w){h(x=>x.filter((S,k)=>k!==w))}function v(){const w=p.map(S=>({providerType:S.providerType.trim(),role:S.role&&S.role.trim()?S.role.trim():void 0,maxParallel:Number.isFinite(Number(S.maxParallel))&&Number(S.maxParallel)>=0?Math.floor(Number(S.maxParallel)):void 0})).filter(S=>S.providerType.length>0),x=Number(c);i({schedulingPriority:Number.isFinite(x)?x:0,providerRoles:w})}return r.jsxs("details",{className:"mt-3 group",onClick:w=>w.stopPropagation(),children:[r.jsxs("summary",{className:"cursor-pointer select-none text-[12px] text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[r.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," Advanced",(o!==0||l.length>0)&&r.jsxs("span",{className:"ml-1 rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 text-[10px] text-text-muted",children:[o!==0?`priority ${o}`:"",o!==0&&l.length>0?" · ":"",l.length>0?`${l.length} role${l.length===1?"":"s"}`:""]})]}),r.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[r.jsx(Wt,{label:"Scheduling priority",hint:m?"Higher = preferred when the mesh distributes work. Not an eligibility gate.":"Used only when the mesh Distribution strategy spreads work (currently First available — no effect).",children:r.jsx("input",{type:"number",step:1,className:"w-32 px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:c,onChange:w=>d(w.target.value),onClick:w=>w.stopPropagation(),disabled:n})}),r.jsx(Wt,{label:"Provider roles (optional)",hint:"Tag a tool on this node with a role (routable as role=<x>) and an optional max-parallel cap. Standard roles auto-route by task mode; pick one or type a custom role.",children:r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx("datalist",{id:a,children:s.map(w=>r.jsx("option",{value:w},w))}),p.length===0&&r.jsx("div",{className:"text-[12px] text-text-muted",children:"No role declarations. This node uses global caps only."}),p.map((w,x)=>r.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.jsx("input",{type:"text",placeholder:"provider type (e.g. claude-cli)",className:"flex-1 min-w-[10rem] px-2 py-1.5 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary",value:w.providerType,onChange:S=>b(x,{providerType:S.target.value}),onClick:S=>S.stopPropagation(),disabled:n}),r.jsx("input",{type:"text",placeholder:"role (e.g. coder)",list:a,className:"flex-1 min-w-[8rem] px-2 py-1.5 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary",value:w.role??"",onChange:S=>b(x,{role:S.target.value}),onClick:S=>S.stopPropagation(),disabled:n}),r.jsx("input",{type:"number",min:0,step:1,placeholder:"max ∥",className:"w-20 px-2 py-1.5 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary",value:w.maxParallel??"",onChange:S=>b(x,{maxParallel:S.target.value===""?void 0:Number(S.target.value)}),onClick:S=>S.stopPropagation(),disabled:n}),r.jsx("button",{type:"button",className:"text-text-muted hover:text-red-400 bg-transparent border-none cursor-pointer",onClick:S=>{S.stopPropagation(),f(x)},title:"Remove role",disabled:n,children:r.jsx(Ot,{size:13})})]},x)),r.jsxs("button",{type:"button",className:"self-start text-[12px] text-accent-primary bg-transparent border-none cursor-pointer p-0 inline-flex items-center gap-1",onClick:w=>{w.stopPropagation(),g()},disabled:n,children:[r.jsx(Ob,{size:12})," Add role"]})]})}),r.jsx("div",{className:"mt-2 flex items-center gap-2",children:r.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:w=>{w.stopPropagation(),v()},disabled:n,children:n?"Saving…":"Save advanced"})})]})]})}function i3(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function a3({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:s,coordinatorCliType:n,onCoordinatorCliTypeChange:i,launchingCoordinator:a,launchResult:o,attachedDaemonIds:l,isHostNodeAttached:c,selectedHostNode:d,onLaunchCoordinator:p,onAttachSelectedHost:h}){return r.jsxs(wt,{title:"Mesh Host daemon",description:"Choose the daemon that will own the coordinator. Host-owned live truth is required before cloud renders status, queue, graph, or node detail.",children:[r.jsxs(or,{variant:"info",className:"mb-4",children:[r.jsx("strong",{children:"Start with one host workspace."})," ","Create a mesh on a connected daemon, then attach additional machine workspaces below. Live status, queue, and graph data come from the selected host daemon."]}),r.jsxs("div",{className:"grid gap-3 sm:grid-cols-[1fr_180px_auto] items-end",children:[r.jsx(Wt,{label:"Mesh Host daemon",hint:"Cloud selects the connected daemon to command over P2P; the host must be attached before it can own a coordinator.",children:r.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:t,onChange:m=>s(m.target.value),children:[r.jsx("option",{value:"",children:"Select a Mesh Host..."}),e.map(m=>r.jsxs("option",{value:m.id,children:[i3(m)," · ",l.has(m.id)?"attached":"not attached"]},m.id))]})}),r.jsx(Wt,{label:"CLI provider",children:r.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:n,onChange:m=>i(m.target.value),children:[r.jsx("option",{value:"",children:"Use node provider priority"}),r.jsx("option",{value:"claude-cli",children:"Claude Code"}),r.jsx("option",{value:"codex-cli",children:"Codex"}),r.jsx("option",{value:"gemini-cli",children:"Gemini"}),r.jsx("option",{value:"hermes-cli",children:"Hermes"})]})}),r.jsx("button",{className:"btn btn-primary btn-sm",onClick:p,disabled:!t||!c||a,title:!c&&t?"Attach this Mesh Host daemon first.":void 0,children:a?"Launching...":"Launch Host Coordinator"})]}),r.jsx("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:t?c?r.jsxs(r.Fragment,{children:["Host setup node: ",r.jsx("span",{className:"font-mono text-text-primary",children:d==null?void 0:d.workspace}),". Live graph/status/detail renders only from this daemon."]}):r.jsx(r.Fragment,{children:"Selected host is not attached yet. Attach one of its workspaces below before launching."}):"Select a connected daemon to become the Mesh Host."}),!c&&t&&r.jsx("button",{type:"button",className:"btn btn-secondary btn-sm mt-3",onClick:h,children:"Attach selected host daemon"}),o&&r.jsx("div",{className:"mt-3 text-[12px] text-green-400 bg-green-500/10 border border-green-500/20 rounded-lg px-3 py-2",children:o})]})}function o3({meshId:e,availableCliAgents:t}){const s=t.find(i=>{const a=i.id.toLowerCase();return a==="hermes-cli"||a.includes("hermes")||i.name.toLowerCase().includes("hermes")}),n=Ex(s==null?void 0:s.meshCoordinator,{meshId:e});return n?r.jsx(wt,{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:r.jsx(tb,{setup:n,providerName:(s==null?void 0:s.name)||"Hermes CLI"})}):null}const Bc=[{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."}],l3=[{value:"first_eligible",label:"First available (default)",description:"Send work to the first eligible node in order. No load-spreading — preserves the original behavior."},{value:"least_loaded",label:"Spread evenly (least-loaded)",description:"Prefer the eligible node with the fewest active tasks so work spreads instead of piling on one node."},{value:"round_robin",label:"Round-robin",description:"Among the least-loaded nodes, rotate the winner each pass for fair distribution."},{value:"priority_only",label:"Priority order",description:"Always send to the highest-priority eligible node (see each node's scheduling priority), ignoring load."}],c3={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function Jo(e){return{...c3,...(e==null?void 0:e.policy)||{}}}function d3({selectedMesh:e,error:t,onDismissError:s,onBack:n,onDelete:i,displayedMeshStatus:a,graphLoading:o,graphError:l,graphProvenance:c,graphBootstrapFallback:d=!1,onRefreshGraph:p,queueSummary:h,queueLoading:m,queueError:g,onLoadQueue:b,savingPolicy:f,onUpdatePolicy:v,coordinatorPromptDraft:w,onCoordinatorPromptDraftChange:x,savingCoordinatorPrompt:S,onSaveCoordinatorPrompt:k,daemons:j,coordinatorDaemonId:y,onCoordinatorDaemonIdChange:N,coordinatorCliType:_,onCoordinatorCliTypeChange:C,launchingCoordinator:D,launchResult:T,attachedDaemonIds:A,isHostNodeAttached:P,selectedHostNode:F,onLaunchCoordinator:J,activeDaemon:R,activeDaemonId:I,meshQueue:E,userName:$,nodeProviderPriorityDrafts:M,onNodeProviderPriorityDraftChange:O,availableCliProviders:H,savingNodePolicyId:ae,onUpdateNodeProviderPriority:z,savingNodeSchedulingId:X,onUpdateNodeScheduling:te,schedulingStrategy:he,nodeSystemPromptDrafts:ke,onNodeSystemPromptDraftChange:Q,savingNodeSystemPromptId:q,onSaveNodeSystemPrompt:me,selectedNodeId:we,onSelectNode:ye,showAddNode:Te,onShowAddNode:le,onCancelAddNode:Se,nodeWorkspace:ge,onNodeWorkspaceChange:G,nodeProviderPriority:W,onNodeProviderPriorityChange:Z,nodeDaemonId:oe,onNodeDaemonIdChange:ue,nodeCustomPath:ce,onNodeCustomPathChange:L,nodePickerWorkspaces:de,nodePickerProviders:U,attachableDaemons:ie,onAddNode:Y,onRemoveNode:Ae,availableCliAgents:Ce,features:je,reviewInboxItems:qe,reviewInboxLoading:it,reviewInboxError:lt,reviewInboxRemoteNodesExcluded:ft,onLoadReviewInbox:ct,onDismissReviewInboxItem:_t,onRefineNode:Mt,onRequeueLast:Et,sendCommand:De}){var Lt;const He=Jo(e),pt=e.nodes||[],Ze=J2(He.taskAffinity);return r.jsxs(Zi,{icon:r.jsx(qs,{}),title:e.name,subtitle:e.repoIdentity||e.repo_identity||"Repo Mesh",widthClassName:"max-w-5xl",actions:r.jsxs("div",{className:"flex gap-2",children:[r.jsx("button",{className:"btn btn-secondary btn-sm",onClick:n,children:"← Back"}),r.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>p(!0),disabled:o,children:[r.jsx(Bu,{size:13}),o?"Probing…":"Refresh"]}),r.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>i(e.id),children:"Delete"})]}),children:[t&&r.jsx(or,{variant:"error",onDismiss:s,className:"mb-4",children:t}),je.meshHostDaemonSection&&r.jsx(a3,{daemons:j,coordinatorDaemonId:y,onCoordinatorDaemonIdChange:B=>{N(B),p()},coordinatorCliType:_,onCoordinatorCliTypeChange:C,launchingCoordinator:D,launchResult:T,attachedDaemonIds:A,isHostNodeAttached:P,selectedHostNode:F,onLaunchCoordinator:J,onAttachSelectedHost:()=>{ue(y),le()}}),je.queueSection&&r.jsx(WO,{queueSummary:h,queueLoading:m,queueError:g,activeDaemonId:I,onRefresh:b}),r.jsxs(wt,{title:"Mesh",description:"Overview cards (missions, ledger, queue, nodes, sessions) with the live topology graph behind the Graph tab.",children:[r.jsx("div",{className:"mb-4 text-[12px] text-text-muted max-w-2xl",children:je.meshHostDaemonSection?r.jsxs(r.Fragment,{children:["Direct aggregate mesh_status from the selected Mesh Host is preferred. Use Refresh above to ask the host for the latest peer git provenance.",c==="settling"&&r.jsx("span",{className:"ml-1 text-amber-300",children:"Refreshing peer data…"})]}):r.jsx(r.Fragment,{children:"Overview shows live mesh state as cards; switch to the Graph tab for the topology view."})}),d&&r.jsxs("div",{className:"mb-3 flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2.5 text-[12px] text-amber-200",children:[r.jsx("span",{className:"mt-0.5 shrink-0 text-amber-400","aria-hidden":!0,children:"⚠"}),r.jsx("span",{children:"Connecting to coordinator — showing setup inventory. Live data will appear shortly."})]}),l&&r.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:l}),a?r.jsx(Ab,{status:a,emptyMessage:je.meshHostDaemonSection?"No mesh graph data is available yet. Refresh after the selected Mesh Host is reachable.":"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology.",daemonId:I,sendDaemonCommand:De,bootstrapFallback:d}):r.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...":je.meshHostDaemonSection?"No mesh graph data is available yet. Refresh after the selected Mesh Host is reachable.":"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology."})]}),je.reviewInbox&&r.jsx(GO,{items:qe,loading:it,error:lt,remoteNodesExcluded:ft,meshId:e.id,activeDaemonId:I,onRefresh:ct,onDismiss:_t,onRefineNode:Mt,onRequeueLast:Et,sendCommand:De}),r.jsx(r3,{nodes:pt,meshQueue:E,activeDaemon:R,daemons:j,selectedMeshId:e.id,userName:$,features:{addNodeDaemonPicker:je.addNodeDaemonPicker,nodeInstruction:je.nodeInstruction},coordinatorDaemonId:y,schedulingStrategy:he,roleOptions:Ze,nodeProviderPriorityDrafts:M,onNodeProviderPriorityDraftChange:O,availableCliProviders:H,savingNodePolicyId:ae,onUpdateNodeProviderPriority:z,savingNodeSchedulingId:X,onUpdateNodeScheduling:te,nodeSystemPromptDrafts:ke,onNodeSystemPromptDraftChange:Q,savingNodeSystemPromptId:q,onSaveNodeSystemPrompt:me,selectedNodeId:we,onSelectNode:ye,showAddNode:Te,onShowAddNode:le,onCancelAddNode:Se,nodeWorkspace:ge,onNodeWorkspaceChange:G,nodeProviderPriority:W,onNodeProviderPriorityChange:Z,nodeDaemonId:oe,onNodeDaemonIdChange:ue,nodeCustomPath:ce,onNodeCustomPathChange:L,nodePickerWorkspaces:de,nodePickerProviders:U,attachableDaemons:ie,onAddNode:Y,onRemoveNode:Ae}),r.jsxs(wt,{title:"Scheduling",description:"How untargeted queue work is distributed across eligible nodes.",children:[r.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:r.jsx(Wt,{label:"Max parallel tasks",hint:"Cap on concurrently assigned tasks across the mesh.",children:r.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(He.maxParallelTasks??2),onChange:B=>v({maxParallelTasks:Number(B.target.value)}),disabled:f,children:[1,2,3,4,5,6,7,8].map(B=>r.jsx("option",{value:B,children:B},B))})})}),r.jsxs("fieldset",{className:"mt-4 border-none p-0 m-0",children:[r.jsx("legend",{className:"text-[13px] font-medium text-text-secondary mb-2",children:"Distribution strategy"}),r.jsx("div",{className:"flex flex-col gap-2",children:l3.map(B=>{const V=(He.schedulingStrategy||"first_eligible")===B.value;return r.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${V?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:[r.jsx("input",{type:"radio",name:"mesh-scheduling-strategy",className:"mt-0.5 accent-[var(--accent-primary)]",value:B.value,checked:V,disabled:f,onChange:()=>v({schedulingStrategy:B.value})}),r.jsxs("span",{className:"min-w-0",children:[r.jsx("span",{className:"block text-sm text-text-primary",children:B.label}),r.jsx("span",{className:"block text-[12px] text-text-muted",children:B.description})]})]},B.value)})}),(He.schedulingStrategy==="priority_only"||He.schedulingStrategy==="least_loaded"||He.schedulingStrategy==="round_robin")&&r.jsxs("div",{className:"mt-2 text-[12px] text-text-muted",children:["Per-node scheduling priority is set in each node's ",r.jsx("span",{className:"text-text-secondary",children:"Advanced"})," panel above."]})]}),f&&r.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving…"})]}),je.coordinatorPrompt&&r.jsxs(wt,{title:"Coordinator prompt",collapsible:!0,defaultOpen:!1,badge:r.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:"advanced"}),description:"Customize the system prompt for coordinator sessions. Leave empty to use the daemon default.",children:[r.jsx(Wt,{label:"Override (replaces default)",hint:"When set, replaces the daemon's default base prompt. Leave empty to keep the default.",children:r.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:w.override,onChange:B=>x({...w,override:B.target.value}),disabled:S,placeholder:"(empty — daemon default applies)"})}),r.jsx(Wt,{label:"Append (added after the base)",hint:"Always added after whichever base prompt wins.",children:r.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:4,value:w.append,onChange:B=>x({...w,append:B.target.value}),disabled:S,placeholder:"(empty — nothing appended)"})}),r.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[r.jsx("summary",{className:"cursor-pointer select-none",children:"Available placeholders"}),r.jsx("p",{className:"mt-1 font-mono break-words",children:"{{meshName}}, {{repo}}, {{defaultBranch}}, {{cliType}}, {{nodes}}, {{policy}}, {{tools}}, {{workflow}}, {{rules}}, {{toolExposurePreflight}}"})]}),r.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[r.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:k,disabled:S,children:S?"Saving…":"Save coordinator prompt"}),r.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>x({override:"",append:""}),disabled:S,title:"Clear both fields. Click Save to commit.",children:"Clear"})]})]}),r.jsxs(wt,{title:"Safety & Git",collapsible:!0,defaultOpen:!1,badge:r.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:"advanced"}),description:"Checkpointing, approval gates, and git safety behavior for coordinator-driven tasks.",children:[r.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:"Auto-commit a checkpoint before each task",key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:B=>B?"yes":"no",parse:B=>B==="yes"},{label:"Auto-commit a checkpoint after each task",key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:B=>B?"yes":"no",parse:B=>B==="yes"},{label:"Push approval",key:"requireApprovalForPush",opts:[["required","Require approval before push"],["not_required","Do not require approval"]],val:B=>B?"required":"not_required",parse:B=>B==="required"},{label:"Destructive git approval",key:"requireApprovalForDestructiveGit",opts:[["required","Require approval"],["not_required","Do not require approval"]],val:B=>B?"required":"not_required",parse:B=>B==="required"},{label:"When the workspace has uncommitted changes",key:"dirtyWorkspaceBehavior",opts:[["warn","Warn and continue"],["block","Block task"],["checkpoint_then_continue","Checkpoint then continue"]],val:B=>B||"warn",parse:B=>B},{label:"Auto-publish submodule commits (advanced)",key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled","Require explicit approval"],["enabled","Allow Refinery non-force publish"]],val:B=>B?"enabled":"disabled",parse:B=>B==="enabled"}].map(({label:B,key:V,opts:ne,val:xe,parse:ve})=>r.jsx(Wt,{label:B,children:r.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:xe(He[V]),onChange:Ne=>v({[V]:ve(Ne.target.value)}),disabled:f,children:ne.map(([Ne,ee])=>r.jsx("option",{value:Ne,children:ee},Ne))})},V))}),r.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[r.jsx(Wt,{label:"When removing a node, its sessions…",hint:"Separate transcript cleanup from runtime/process cleanup.",children:r.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:He.sessionCleanupOnNodeRemove||"preserve",onChange:B=>v({sessionCleanupOnNodeRemove:B.target.value}),disabled:f,children:Bc.map(B=>r.jsx("option",{value:B.value,children:B.label},B.value))})}),r.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((Lt=Bc.find(B=>B.value===He.sessionCleanupOnNodeRemove))==null?void 0:Lt.description)||Bc[0].description})]}),f&&r.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving…"})]}),je.hermesMcpConfig&&r.jsx(o3,{meshId:e.id,availableCliAgents:Ce}),je.meshHostDaemonSection&&r.jsxs(or,{variant:"info",className:"mt-4",children:[r.jsx("strong",{children:"MCP Mode:"})," ",r.jsxs("code",{className:"bg-bg-secondary px-1 rounded text-xs",children:["adhdev mcp --repo-mesh ",e.id]})," · The mesh MCP server can be used directly from your CLI agent."]})]})}function u3({daemons:e,primaryDaemonId:t,sendCommand:s,unwrapResult:n,normalizeMesh:i,features:a}){const[o,l]=u.useState([]),[c,d]=u.useState(null),[p,h]=u.useState(!0),[m,g]=u.useState(null),[b,f]=u.useState(!1),[v,w]=u.useState(""),[x,S]=u.useState(""),[k,j]=u.useState(""),[y,N]=u.useState(""),[_,C]=u.useState(""),D=u.useMemo(()=>e.find(I=>I.id===y),[e,y]),T=(D==null?void 0:D.workspaces)||[],A=u.useMemo(()=>Sn((D==null?void 0:D.availableProviders)||[]),[D]),P=u.useCallback(async()=>{h(!0);try{if(a.createDaemonPicker){const I=await Promise.allSettled(e.map(async $=>{if(!$.id)return[];const M=await s($.id,"list_meshes",{}),O=n(M);if((O==null?void 0:O.success)===!1)throw new Error(O.error||"Failed to load meshes");return(Array.isArray(O==null?void 0:O.meshes)?O.meshes:[]).map(H=>i(H,$.id)).filter(H=>H.id)})),E=new Map;for(const $ of I)if($.status==="fulfilled")for(const M of $.value)E.has(M.id)||E.set(M.id,M);l(Array.from(E.values()))}else{if(!t)return;const I=await s(t,"list_meshes");I!=null&&I.success?(l((I.meshes||[]).map(E=>i(E,t))),g(null)):g((I==null?void 0:I.error)||"Failed to load meshes")}}catch(I){g((I==null?void 0:I.message)||"Failed to load meshes")}finally{h(!1)}},[e,t,s,n,i,a.createDaemonPicker]);async function F(){var M,O;const I=a.createDaemonPicker?y:t;if(!I||!v.trim())return;const E=k.trim(),$=x.trim();if(!(!E&&!$))try{const H={name:v.trim()};E&&(H.repoRemoteUrl=E),$&&(H.repoIdentity=$);const ae=await s(I,"create_mesh",H),z=n(ae);if((z==null?void 0:z.success)===!1)throw new Error(z.error||"Create failed");const X=typeof((M=z==null?void 0:z.mesh)==null?void 0:M.id)=="string"?z.mesh.id:"";if(X&&a.createDaemonPicker&&_){const te=await s(I,"add_mesh_node",{meshId:X,daemonId:I,machineId:D==null?void 0:D.machineId,workspace:_,role:"host",providerPriority:Ci(A)}),he=n(te);if((he==null?void 0:he.success)===!1)throw new Error(he.error||"Mesh created but failed to attach workspace")}f(!1),w(""),S(""),j(""),C(""),await P(),(O=z==null?void 0:z.mesh)!=null&&O.id&&d(z.mesh.id)}catch(H){g((H==null?void 0:H.message)||"Create failed")}}async function J(I){var $;if(!confirm("Delete this mesh? This cannot be undone."))return;const E=(($=o.find(M=>M.id===I))==null?void 0:$.__sourceDaemonId)||t;try{const M=await s(E,"delete_mesh",{meshId:I}),O=n(M);if((O==null?void 0:O.success)===!1)throw new Error(O.error||"Failed to delete");c===I&&d(null),await P()}catch(M){g((M==null?void 0:M.message)||"Delete failed")}}function R(){f(!1),w(""),S(""),j("")}return{meshes:o,setMeshes:l,selectedMeshId:c,setSelectedMeshId:d,loading:p,error:m,setError:g,showCreate:b,setShowCreate:f,createName:v,setCreateName:w,createRepoIdentity:x,setCreateRepoIdentity:S,createRepoRemoteUrl:k,setCreateRepoRemoteUrl:j,newMeshDaemonId:y,setNewMeshDaemonId:N,newMeshWorkspace:_,setNewMeshWorkspace:C,createPickerWorkspaces:T,createPickerProviders:A,loadMeshes:P,handleCreate:F,handleDelete:J,cancelCreate:R}}function p3({selectedMesh:e,selectedMeshId:t,primaryDaemonId:s,activeDaemonId:n,daemons:i,availableCliProviders:a,sendCommand:o,unwrapResult:l,loadLiveMesh:c,resolveCommandTarget:d,launchCoordinator:p,features:h,loadMeshes:m,loadQueue:g,queueSection:b,setError:f}){const[v,w]=u.useState({}),[x,S]=u.useState(null),[k,j]=u.useState(null),[y,N]=u.useState(!1),[_,C]=u.useState(""),[D,T]=u.useState([]),[A,P]=u.useState(""),[F,J]=u.useState(!1),[R,I]=u.useState(""),[E,$]=u.useState(!1),[M,O]=u.useState(null),[H,ae]=u.useState(!1),[z,X]=u.useState({override:"",append:""}),[te,he]=u.useState(!1),[ke,Q]=u.useState({}),[q,me]=u.useState(null),we=u.useMemo(()=>i.find(de=>de.id===A),[i,A]),ye=(we==null?void 0:we.workspaces)||[],Te=u.useMemo(()=>Sn((we==null?void 0:we.availableProviders)||[]),[we]);async function le(){const de=(e==null?void 0:e.__sourceDaemonId)||s;if(!t||!de)return;const U=_.trim();if(U)try{const ie={meshId:t,workspace:U};h.addNodeDaemonPicker&&A?(ie.daemonId=A,ie.machineId=we==null?void 0:we.machineId,ie.providerPriority=eo(D,Te)):ie.providerPriority=eo(D,a);const Y=await o(de,"add_mesh_node",ie),Ae=l(Y);if((Ae==null?void 0:Ae.success)===!1)throw new Error(Ae.error||"Add node failed");N(!1),C(""),T([]),P(""),J(!1),await m(),b||await g(t)}catch(ie){f((ie==null?void 0:ie.message)||"Add node failed")}}async function Se(de){var Ae;if(!e)return;const U=Jo(e),ie=((Ae=[{value:"preserve",label:"Preserve history and runtimes"},{value:"stop",label:"Stop live runtimes only"},{value:"delete_stopped",label:"Delete stopped sessions only"},{value:"stop_and_delete",label:"Stop and delete sessions"}].find(Ce=>Ce.value===U.sessionCleanupOnNodeRemove))==null?void 0:Ae.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
|
|
612
|
+
|
|
613
|
+
Node removal cleanup policy: ${ie}`))return;const Y=e.__sourceDaemonId||s;try{const Ce=await o(Y,"remove_mesh_node",{meshId:e.id,nodeId:de}),je=l(Ce);if((je==null?void 0:je.success)===!1)throw new Error(je.error||"Remove failed");k===de&&j(null),await m(),b||await g(t)}catch(Ce){f((Ce==null?void 0:Ce.message)||"Remove node failed")}}async function ge(de){if(!e)return;const U={...Jo(e),...de},ie=e.__sourceDaemonId||s;try{ae(!0),f(null);const Y=await o(ie,"update_mesh",{meshId:e.id,policy:U}),Ae=l(Y);if((Ae==null?void 0:Ae.success)===!1)throw new Error(Ae.error||"Policy update failed");await m()}catch(Y){f((Y==null?void 0:Y.message)||"Policy update failed")}finally{ae(!1)}}async function G(de){if(!t)return;const U=(e==null?void 0:e.__sourceDaemonId)||s,ie=h.addNodeDaemonPicker?Te:a,Y=v[de.id]||h3(de),Ae=ie.length>0?eo(Y,ie):Ji(Y),Ce={...de.policy||{}};delete Ce.provider_priority,Ae.length?Ce.providerPriority=Ae:delete Ce.providerPriority;try{S(de.id),f(null);const je=await o(U,"update_mesh_node",{meshId:t,nodeId:de.id,policy:Ce,providerPriority:Ae}),qe=l(je);if((qe==null?void 0:qe.success)===!1){f(qe.error||"Node policy update failed");return}await m()}catch(je){f((je==null?void 0:je.message)||"Node policy update failed")}finally{S(null)}}const[W,Z]=u.useState(null);async function oe(de,U){if(!t)return;const ie=(e==null?void 0:e.__sourceDaemonId)||s,Y={};Object.prototype.hasOwnProperty.call(U,"schedulingPriority")&&(Y.schedulingPriority=Number.isFinite(U.schedulingPriority)?U.schedulingPriority:0);const Ae={meshId:t,nodeId:de.id,policy:Y};Object.prototype.hasOwnProperty.call(U,"providerRoles")&&(Ae.providerRoles=U.providerRoles);try{Z(de.id),f(null);const Ce=await o(ie,"update_mesh_node",Ae),je=l(Ce);if((je==null?void 0:je.success)===!1){f(je.error||"Node scheduling update failed");return}await m()}catch(Ce){f((Ce==null?void 0:Ce.message)||"Node scheduling update failed")}finally{Z(null)}}async function ue(){if(!s||!t)return;const U={...(e==null?void 0:e.coordinator)||{}};z.override.trim()?U.systemPromptOverride=z.override:delete U.systemPromptOverride,z.append.trim()?U.systemPromptAppend=z.append:delete U.systemPromptAppend,delete U.systemPromptSuffix;try{he(!0),f(null);const ie=await o(s,"update_mesh",{meshId:t,coordinator:U}),Y=l(ie);if((Y==null?void 0:Y.success)===!1){f(Y.error||"Coordinator prompt save failed");return}await m()}catch(ie){f((ie==null?void 0:ie.message)||"Coordinator prompt save failed")}finally{he(!1)}}async function ce(de){if(!s||!t)return;const U=(ke[de.id]||"").trim();try{me(de.id),f(null);const ie=await o(s,"update_mesh_node",{meshId:t,nodeId:de.id,systemPrompt:U}),Y=l(ie);if((Y==null?void 0:Y.success)===!1){f(Y.error||"Node instruction save failed");return}await m()}catch(ie){f((ie==null?void 0:ie.message)||"Node instruction save failed")}finally{me(null)}}async function L(){if(e){f(null),O(null);try{$(!0);const de=c?await c(n,e.id,e):null,U=d(n,e.id,e,e.nodes||[],de);if("error"in U)throw new Error(U.error);const ie=await p(U.targetDaemonId,{meshId:e.id,inlineMesh:U.inlineMesh,coordinatorNodeId:U.coordinatorNodeId,cliType:R.trim()||void 0});O(ie.message)}catch(de){f((de==null?void 0:de.message)||"Coordinator launch failed")}finally{$(!1)}}}return{nodeProviderPriorityDrafts:v,setNodeProviderPriorityDrafts:w,savingNodePolicyId:x,selectedNodeId:k,setSelectedNodeId:j,showAddNode:y,setShowAddNode:N,nodeWorkspace:_,setNodeWorkspace:C,nodeProviderPriority:D,setNodeProviderPriority:T,nodeDaemonId:A,setNodeDaemonId:P,nodeCustomPath:F,setNodeCustomPath:J,nodePickerWorkspaces:ye,nodePickerProviders:Te,coordinatorCliType:R,setCoordinatorCliType:I,launchingCoordinator:E,launchResult:M,savingPolicy:H,coordinatorPromptDraft:z,setCoordinatorPromptDraft:X,savingCoordinatorPrompt:te,nodeSystemPromptDrafts:ke,setNodeSystemPromptDrafts:Q,savingNodeSystemPromptId:q,savingNodeSchedulingId:W,handleAddNode:le,handleRemoveNode:Se,handleUpdatePolicy:ge,handleUpdateNodeProviderPriority:G,handleUpdateNodeScheduling:oe,handleSaveCoordinatorPrompt:ue,handleSaveNodeSystemPrompt:ce,handleLaunchCoordinator:L}}function h3(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],s=new Set;return t.map(i=>typeof i=="string"?i.trim():"").filter(Boolean).filter(i=>s.has(i)?!1:(s.add(i),!0))}function m3(e){const t=e.filter(n=>n.status==="pending"||n.status==="assigned"),s=e.filter(n=>n.status==="completed"||n.status==="failed"||n.status==="cancelled");return{active:t.length,historical:s.length,activeCounts:{pending:t.filter(n=>n.status==="pending").length,assigned:t.filter(n=>n.status==="assigned").length},historicalCounts:{completed:s.filter(n=>n.status==="completed").length,failed:s.filter(n=>n.status==="failed").length},counts:{pending:e.filter(n=>n.status==="pending").length,assigned:e.filter(n=>n.status==="assigned").length,completed:e.filter(n=>n.status==="completed").length,failed:e.filter(n=>n.status==="failed").length},staleAssignedCount:e.filter(n=>n.staleAssigned).length,recent:e.slice(0,20)}}function f3({primaryDaemonId:e,activeDaemonId:t,sendCommand:s,unwrapResult:n,loadLiveMesh:i,resolveCommandTarget:a}){const[o,l]=u.useState([]),[c,d]=u.useState(null),[p,h]=u.useState(!1),[m,g]=u.useState(null),b=u.useCallback(async v=>{if(!e||!v){l([]);return}try{const w=await s(e,"get_mesh_queue",{meshId:v});l(w!=null&&w.success?Array.isArray(w.queue)?w.queue:[]:[])}catch{l([])}},[e,s]);async function f(v){var w,x;if(v){h(!0),g(null);try{const S=i?await i(t,v.id,v):null,k=a(t,v.id,v,v.nodes||[],S);if("error"in k)throw new Error(k.error);const j=await s(k.targetDaemonId,"get_mesh_queue",{meshId:v.id}),y=n(j);if((y==null?void 0:y.success)===!1)throw new Error(y.error||"Queue load failed");const N=Array.isArray(((w=y==null?void 0:y.result)==null?void 0:w.rows)??(y==null?void 0:y.rows)??(y==null?void 0:y.queue))?((x=y==null?void 0:y.result)==null?void 0:x.rows)??(y==null?void 0:y.rows)??(y==null?void 0:y.queue):[];d(m3(N))}catch(S){g((S==null?void 0:S.message)||"Queue load failed")}finally{h(!1)}}}return{meshQueue:o,setMeshQueue:l,queueSummary:c,queueLoading:p,queueError:m,loadQueue:b,handleLoadQueue:f}}function g3(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}function x3({selectedMeshId:e,loadMeshStatus:t,extractStatus:s,normalizeNode:n,gateIncompleteGraph:i}){const[a,o]=u.useState(null),[l,c]=u.useState(!1),[d,p]=u.useState(null),[h,m]=u.useState("idle"),[g,b]=u.useState(!1),f=u.useRef(!1);async function v(w,x=e,S=!1){if(!(!w||!x))try{c(!S&&a===null),m(S?"settling":"first_paint"),p(null);const k=await t(w,x,{refresh:S,retryProfile:S?"settled":"interactive"});b(g3(k));const j=s(k),y=n&&j?{...j,nodes:(j.nodes??[]).map(N=>n(N,j.meshId??x,""))}:j;if(y){if(i&&!S&&a!==null&&!nT(cb(y))){m("settling"),f.current||(f.current=!0,Promise.resolve().then(()=>v(w,x,!0)).finally(()=>{f.current=!1}));return}o(y),m("settled")}else o(null),p("mesh_status returned an unexpected payload."),m("idle")}catch(k){a||o(null),p((k==null?void 0:k.message)||"Failed to load mesh graph"),m("idle")}finally{c(!1)}}return{meshGraphStatus:a,setMeshGraphStatus:o,graphLoading:l,graphError:d,setGraphError:p,graphProvenance:h,graphBootstrapFallback:g,loadGraph:v}}function b3({primaryDaemonId:e,sendCommand:t}){const[s,n]=u.useState([]),[i,a]=u.useState(!1),[o,l]=u.useState(null),[c,d]=u.useState(!1),[p,h]=u.useState(new Set),m=u.useCallback(async f=>{if(!e||!f){n([]);return}a(!0),l(null);try{const v=await t(e,"get_mesh_review_inbox",{meshId:f});v!=null&&v.success?(n(Array.isArray(v.inbox)?v.inbox:[]),d(v.remoteNodesExcluded===!0)):(l((v==null?void 0:v.error)||"Failed to load review inbox"),n([]))}catch(v){l((v==null?void 0:v.message)||"Failed to load review inbox"),n([])}finally{a(!1)}},[e,t]),g=u.useCallback(f=>{h(v=>new Set([...v,f]))},[]);return{items:s.filter(f=>!p.has(f.nodeId)),allItems:s,loading:i,error:o,remoteNodesExcluded:c,dismissedNodeIds:p,loadInbox:m,dismissItem:g}}function y3(){const e=W2(),{sendCommand:t,sendData:s,daemons:n,userName:i,loadMeshStatus:a,launchCoordinator:o,loadLiveMesh:l,extractStatus:c,unwrapResult:d,normalizeMesh:p,normalizeNode:h,resolveCommandTarget:m,features:g,gateIncompleteGraph:b}=e,f=n[0],v=(f==null?void 0:f.id)||"",w=u.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(ut=>ut.category==="cli").map(ut=>({id:ut.type||ut.id,name:ut.displayName||ut.name||ut.type,meshCoordinator:ut.meshCoordinator})),[f]),x=u.useMemo(()=>Sn((f==null?void 0:f.availableProviders)||[]),[f]),{meshes:S,selectedMeshId:k,setSelectedMeshId:j,loading:y,error:N,setError:_,showCreate:C,setShowCreate:D,createName:T,setCreateName:A,createRepoIdentity:P,setCreateRepoIdentity:F,createRepoRemoteUrl:J,setCreateRepoRemoteUrl:R,newMeshDaemonId:I,setNewMeshDaemonId:E,newMeshWorkspace:$,setNewMeshWorkspace:M,createPickerWorkspaces:O,loadMeshes:H,handleCreate:ae,handleDelete:z,cancelCreate:X}=u3({daemons:n,primaryDaemonId:v,sendCommand:t,unwrapResult:d,normalizeMesh:p,features:g}),te=S.find(Ue=>Ue.id===k)||null,{meshGraphStatus:he,setMeshGraphStatus:ke,graphLoading:Q,graphError:q,setGraphError:me,graphProvenance:we,graphBootstrapFallback:ye,loadGraph:Te}=x3({selectedMeshId:k,loadMeshStatus:a,extractStatus:c,normalizeNode:h,gateIncompleteGraph:b}),[le,Se]=u.useState(""),ge=g.meshHostDaemonSection&&le||v,{meshQueue:G,queueSummary:W,queueLoading:Z,queueError:oe,loadQueue:ue,handleLoadQueue:ce}=f3({primaryDaemonId:v,activeDaemonId:ge,sendCommand:t,unwrapResult:d,loadLiveMesh:l,resolveCommandTarget:m}),{items:L,loading:de,error:U,remoteNodesExcluded:ie,loadInbox:Y,dismissItem:Ae}=b3({primaryDaemonId:v,sendCommand:t}),{nodeProviderPriorityDrafts:Ce,setNodeProviderPriorityDrafts:je,savingNodePolicyId:qe,selectedNodeId:it,setSelectedNodeId:lt,showAddNode:ft,setShowAddNode:ct,nodeWorkspace:_t,setNodeWorkspace:Mt,nodeProviderPriority:Et,setNodeProviderPriority:De,nodeDaemonId:He,setNodeDaemonId:pt,nodeCustomPath:Ze,setNodeCustomPath:Lt,nodePickerWorkspaces:B,nodePickerProviders:V,coordinatorCliType:ne,setCoordinatorCliType:xe,launchingCoordinator:ve,launchResult:Ne,savingPolicy:ee,coordinatorPromptDraft:se,setCoordinatorPromptDraft:be,savingCoordinatorPrompt:Me,nodeSystemPromptDrafts:$e,setNodeSystemPromptDrafts:Re,savingNodeSystemPromptId:Oe,savingNodeSchedulingId:ze,handleAddNode:Le,handleRemoveNode:Ye,handleUpdatePolicy:rt,handleUpdateNodeProviderPriority:Ct,handleUpdateNodeScheduling:Ut,handleSaveCoordinatorPrompt:Rt,handleSaveNodeSystemPrompt:It,handleLaunchCoordinator:Ge}=p3({selectedMesh:te,selectedMeshId:k,primaryDaemonId:v,activeDaemonId:ge,daemons:n,availableCliProviders:x,sendCommand:t,unwrapResult:d,loadLiveMesh:l,resolveCommandTarget:m,launchCoordinator:o,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:H,loadQueue:ue,queueSection:g.queueSection,setError:_}),gs=u.useMemo(()=>n.find(Ue=>Ue.id===ge)||f,[n,ge,f]),pe=u.useMemo(()=>new Set(((te==null?void 0:te.nodes)||[]).map(Ue=>String(Ue.daemon_id||Ue.daemonId||""))),[te]),Be=u.useMemo(()=>n.filter(Ue=>Ue.id&&!pe.has(Ue.id)),[n,pe]),fe=(te==null?void 0:te.nodes)||[],Fe=u.useMemo(()=>fe.find(Ue=>String(Ue.daemon_id||Ue.daemonId||"")===le),[fe,le]),Gt=g.meshHostDaemonSection?!!Fe:!0,es=u.useMemo(()=>he?[...new Set((he.nodes??[]).map(Ue=>String(Ue.daemonId||Ue.daemon_id||"")).filter(Boolean))]:[],[he]),Qs=Mb({status:he,daemonId:ge||null,extraDaemonIds:es,meshId:k,sendData:s});return u.useEffect(()=>{je(Object.fromEntries(((te==null?void 0:te.nodes)||[]).map(Ue=>[Ue.id,v3(Ue)])))},[te]),u.useEffect(()=>{const Ue=(te==null?void 0:te.coordinator)||{};be({override:typeof Ue.systemPromptOverride=="string"?Ue.systemPromptOverride:"",append:typeof Ue.systemPromptAppend=="string"?Ue.systemPromptAppend:typeof Ue.systemPromptSuffix=="string"?Ue.systemPromptSuffix:""}),Re(Object.fromEntries(((te==null?void 0:te.nodes)||[]).map(ut=>[ut.id,typeof ut.systemPrompt=="string"?ut.systemPrompt:""])))},[te]),u.useEffect(()=>{const Ue=g.addNodeDaemonPicker?Ci(V):Ci(x);ft&&Et.length===0&&Ue.length>0&&De(Ue)},[ft,x,V,Et.length,g.addNodeDaemonPicker]),u.useEffect(()=>{const Ue=new Set(((te==null?void 0:te.nodes)||[]).map(ut=>ut.id));it&&!Ue.has(it)&<(null)},[te,it]),u.useEffect(()=>{if(g.meshHostDaemonSection){if(!n.length){Se("");return}(!le||!n.some(Ue=>Ue.id===le))&&Se(n[0].id)}},[n,le,g.meshHostDaemonSection]),u.useEffect(()=>{if(g.createDaemonPicker){if(!n.length){E("");return}(!I||!n.some(Ue=>Ue.id===I))&&E(n[0].id)}},[n,I,g.createDaemonPicker]),u.useEffect(()=>{var Ue;if(!g.createDaemonPicker||!I){M("");return}if(!O.length){M("");return}O.some(ut=>ut.path===$)||M(((Ue=O[0])==null?void 0:Ue.path)||"")},[I,$,O,g.createDaemonPicker]),u.useEffect(()=>{k&&(ke(null),me(null),Te(ge,k))},[k,ge]),u.useEffect(()=>{g.queueSection||ue(k)},[k,g.queueSection]),u.useEffect(()=>{!g.reviewInbox||!k||Y(k)},[k,g.reviewInbox]),u.useEffect(()=>{H()},[H]),v?te?r.jsx(d3,{selectedMesh:te,error:N,onDismissError:()=>_(null),onBack:()=>{j(null),ke(null)},onDelete:z,displayedMeshStatus:Qs,graphLoading:Q,graphError:q,graphProvenance:we,graphBootstrapFallback:ye,onRefreshGraph:()=>Te(ge,k,!0),queueSummary:W,queueLoading:Z,queueError:oe,onLoadQueue:()=>ce(te),savingPolicy:ee,onUpdatePolicy:rt,coordinatorPromptDraft:se,onCoordinatorPromptDraftChange:be,savingCoordinatorPrompt:Me,onSaveCoordinatorPrompt:Rt,daemons:n,coordinatorDaemonId:le,onCoordinatorDaemonIdChange:Ue=>{Se(Ue),ke(null)},coordinatorCliType:ne,onCoordinatorCliTypeChange:xe,launchingCoordinator:ve,launchResult:Ne,attachedDaemonIds:pe,isHostNodeAttached:Gt,selectedHostNode:Fe,onLaunchCoordinator:Ge,activeDaemon:gs,activeDaemonId:ge,meshQueue:G,userName:i,nodeProviderPriorityDrafts:Ce,onNodeProviderPriorityDraftChange:(Ue,ut)=>je(Js=>({...Js,[Ue]:ut})),availableCliProviders:x,savingNodePolicyId:qe,onUpdateNodeProviderPriority:Ct,savingNodeSchedulingId:ze,onUpdateNodeScheduling:Ut,schedulingStrategy:Jo(te).schedulingStrategy,nodeSystemPromptDrafts:$e,onNodeSystemPromptDraftChange:(Ue,ut)=>Re(Js=>({...Js,[Ue]:ut})),savingNodeSystemPromptId:Oe,onSaveNodeSystemPrompt:It,selectedNodeId:it,onSelectNode:lt,showAddNode:ft,onShowAddNode:()=>ct(!0),onCancelAddNode:()=>ct(!1),nodeWorkspace:_t,onNodeWorkspaceChange:Mt,nodeProviderPriority:Et,onNodeProviderPriorityChange:De,nodeDaemonId:He,onNodeDaemonIdChange:pt,nodeCustomPath:Ze,onNodeCustomPathChange:Lt,nodePickerWorkspaces:B,nodePickerProviders:V,attachableDaemons:Be,onAddNode:Le,onRemoveNode:Ye,availableCliAgents:w,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,queueSection:g.queueSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction,reviewInbox:g.reviewInbox??!1},reviewInboxItems:L,reviewInboxLoading:de,reviewInboxError:U,reviewInboxRemoteNodesExcluded:ie,onLoadReviewInbox:()=>k&&void Y(k),onDismissReviewInboxItem:Ae,onRefineNode:async Ue=>{k&&(await t(ge,"refine_mesh_node",{meshId:k,nodeId:Ue,inlineMesh:te}),Y(k))},onRequeueLast:async Ue=>{k&&(await t(ge,"requeue_mesh_queue_task",{meshId:k,nodeId:Ue}),Y(k))},sendCommand:t}):r.jsx(K2,{meshes:S,loading:y,error:N,onDismissError:()=>_(null),daemons:n,features:{createDaemonPicker:g.createDaemonPicker},showCreate:C,onToggleCreate:()=>D(!C),createName:T,onCreateNameChange:A,createRepoIdentity:P,onCreateRepoIdentityChange:F,createRepoRemoteUrl:J,onCreateRepoRemoteUrlChange:R,newMeshDaemonId:I,onNewMeshDaemonIdChange:E,newMeshWorkspace:$,onNewMeshWorkspaceChange:M,createPickerWorkspaces:O,onSelectMesh:j,onCreate:ae,onCancelCreate:X}):r.jsx(Zi,{icon:r.jsx(qs,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:r.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})})}function v3(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],s=new Set;return t.map(i=>typeof i=="string"?i.trim():"").filter(Boolean).filter(i=>s.has(i)?!1:(s.add(i),!0))}function w3({children:e}){const{sendCommand:t,sendData:s}=jt(),{ides:n}=Fs(),i=u.useMemo(()=>n.filter(o=>o.daemonMode||o.type==="adhdev-daemon").map(o=>o),[n]),a=u.useMemo(()=>({sendCommand:t,sendData:s,daemons:i,userName:void 0,loadMeshStatus:async(o,l)=>t(o,"mesh_status",{meshId:l}),launchCoordinator:async(o,l)=>{var m;const c={meshId:l.meshId};l.cliType&&(c.cliType=l.cliType);const d=await t(o,"launch_mesh_coordinator",c),p=(d==null?void 0:d.result)??d;if((p==null?void 0:p.success)===!1)throw new Error(p.error||"Coordinator launch failed");const h=(p==null?void 0:p.sessionId)||((m=p==null?void 0:p.session)==null?void 0:m.id)||(p==null?void 0:p.targetSessionId);return{sessionId:h,message:h?`Coordinator launched (${h})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:au,unwrapResult:o=>o,normalizeMesh:(o,l)=>o,normalizeNode:(o,l,c)=>o,resolveCommandTarget:o=>({targetDaemonId:o}),features:B2}),[t,s,i]);return r.jsx($b.Provider,{value:a,children:e})}function Pp(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function S3(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),s=Pp();return s&&!t.searchParams.has("token")&&t.searchParams.set("token",s),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Rs(e,t){return await fetch(S3(e),{credentials:"same-origin",...t})}function Hv(){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 k3{constructor(){re(this,"adapters",new Map);re(this,"states",new Map);re(this,"runtimeListeners",new Map);re(this,"screenshotCallbacks",new Map);re(this,"statusCallbacks",new Set);re(this,"stateChangeCallbacks",new Set);re(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const s of this.adapters.keys())if(s.startsWith("standalone"))return s}return null}register(t,s){this.adapters.set(t,s),this.states.set(t,s.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,s){this.states.set(t,s);const n=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(i=>i(n,s))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const s=this.resolveDaemonId(t);return s?this.adapters.get(s):void 0}getState(t){const s=this.resolveDaemonId(t);return s&&this.states.get(s)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,s){return!1}sendPtyInput(t,s,n){return this.ptyInputSender?this.ptyInputSender(t,s,n):!1}onScreenshot(t,s){return this.screenshotCallbacks.set(t,s),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,s){this.screenshotCallbacks.forEach(n=>n(t,s))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,s){this.statusCallbacks.forEach(n=>n(t,s))}emitRuntimeSnapshot(t,s,n=0,i=!1,a,o){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:s,truncated:i,cols:a,rows:o})}emitSessionOutput(t,s,n){!t||typeof s!="string"||!s||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:s})}onRuntimeEvent(t,s){const n=this.runtimeListeners.get(t)||new Set;return n.add(s),this.runtimeListeners.set(t,n),()=>{const i=this.runtimeListeners.get(t);i&&(i.delete(s),i.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,s,n){if(!s)return{success:!1,error:"sessionId is required"};const i=new URL(`/api/v1/runtime/${encodeURIComponent(s)}/snapshot`,window.location.origin);typeof(n==null?void 0:n.sinceSeq)=="number"&&i.searchParams.set("sinceSeq",String(n.sinceSeq));const a=await Rs(`${i.pathname}${i.search}`);if(!a.ok){let l=`Runtime snapshot unavailable (${a.status})`;try{const c=await a.json();c!=null&&c.error&&(l=c.error)}catch{}return{success:!1,error:l}}const o=await a.json();return this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,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,s){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(i=>i(s))}}const Es=new k3;function j3(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,s=Pp();return s?`${t}?token=${encodeURIComponent(s)}`:t}const Xa=j3(),If=3e3,N3=3e4;let vs=null,_3=0;const Zo=new Map;let wr=null,vi=null;function Af(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Yn(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function C3(e){return e==="connected"?"connected":e}async function wi(e,t,s){const n=ax(e,s||{}),i=vs;if(i&&i.readyState===WebSocket.OPEN){const a=`req_${++_3}_${Date.now()}`;return new Promise((o,l)=>{const c=setTimeout(()=>{Zo.delete(a),l(new Error(`WS command timeout: ${t}`))},3e4);Zo.set(a,{resolve:d=>{clearTimeout(c),o(d)},reject:d=>{clearTimeout(c),l(d)}}),i.send(JSON.stringify({type:"command",requestId:a,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Fd(e,t){const s=vs;if(!s||s.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return s.send(JSON.stringify(t)),!0}catch{return!1}}function zv(e,t,s){const n=vs;if(!n||n.readyState!==WebSocket.OPEN)return!1;const i=ax(e,{sessionId:t,targetSessionId:t,data:s});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:i.payload}})),!0}catch{return!1}}Es.registerPtyInputSender(zv);class I3{constructor(t){re(this,"daemonId");re(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(vs==null?void 0:vs.readyState)===WebSocket.OPEN}get connectionState(){return(vs==null?void 0:vs.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,s){return wi(this.daemonId,t,s)}async sendInput(t,s){return wi(this.daemonId,"cdp_remote_action",{action:t,params:s,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,wr&&(clearInterval(wr),wr=null);const s=async()=>{if(this.hasCommandChannel)try{const n=await wi(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const i=await fetch(`data:image/jpeg;base64,${n.base64}`).then(a=>a.blob());Es.emitScreenshot(this.daemonId,i)}}catch{}};s(),wr=setInterval(s,2e3)}stopScreenshots(t){wr&&(clearInterval(wr),wr=null)}}let ds=null;function A3(e){return(!ds||ds.daemonId!==e)&&(ds=new I3(e)),ds}function T3({children:e}){const t=u.useRef(ji()),s=ji();t.current=s;const{setUserName:n}=Fs(),i=u.useRef(n);i.current=n;const a=u.useRef(null),o=u.useRef(null),[,l]=u.useState("disconnected"),c=u.useCallback((f,v)=>{l(f),vi==null||vi(f,v)},[]),d=u.useRef(null),p=u.useRef(),h=u.useRef(If),m=u.useRef(!0),g=u.useRef(!1),b=u.useRef("initial_connect");return u.useEffect(()=>{m.current=!0,g.current=!1;function f(){var x,S;if(!m.current||((x=d.current)==null?void 0:x.readyState)===WebSocket.OPEN||((S=d.current)==null?void 0:S.readyState)===WebSocket.CONNECTING)return;c("connecting"),console.log(`[Standalone WS] Connecting to ${Xa}...`),Yn("connect_attempt",{url:Xa,reason:b.current,delayMs:h.current});let w;try{w=new WebSocket(Xa)}catch(k){console.error("[Standalone WS] Failed to create WebSocket:",k),v();return}d.current=w,w.onopen=()=>{if(!m.current){w.close();return}c("connected"),h.current=If,Yn("open",{url:Xa,reason:b.current}),Os.resubscribeAll({sendData:Fd}),console.log("[Standalone WS] Connected")},vs=w,w.onmessage=k=>{var j,y;try{const N=JSON.parse(k.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const _=Zo.get(N.requestId);_&&(Zo.delete(N.requestId),N.type==="error"?_.reject(new Error(((j=N.data)==null?void 0:j.message)||"Command failed")):_.resolve(N.data));return}if(N.type==="session_output"){const _=N.sessionId||N.cliId||N.cliType;_&&Es.emitSessionOutput(_,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){Es.emitRuntimeSnapshot(N.sessionId,typeof N.text=="string"?N.text:"",typeof N.seq=="number"?N.seq:0,!!N.truncated,typeof N.cols=="number"?N.cols:void 0,typeof N.rows=="number"?N.rows:void 0);return}if(N.type==="topic_update"){const _=N.update;_&&Os.publish(_);return}if(N.type==="status"||N.type==="initial_state"){const _=N.data;if(!_)return;const{injectEntries:C,markLoaded:D,getIdes:T}=t.current,A=_.instanceId||"standalone",P=T().find(R=>R.id===A),F=A3(A);Es.register(A,F),Es.setState(A,"connected"),c("connected",A),Es.emitStatus(A,_);const J=ko(_,{daemonId:A,existingDaemon:P,existingEntries:T()});Af("ws_status",{type:N.type,daemonId:A,sessions:(_.sessions||[]).map(R=>({id:R.id,parentId:R.parentId,providerType:R.providerType,kind:R.kind,transport:R.transport,unread:R.unread,inboxBucket:R.inboxBucket,lastSeenAt:R.lastSeenAt,lastUpdated:R.lastUpdated,title:R.title})),recentLaunches:(_.recentLaunches||[]).map(R=>({id:R.id,providerType:R.providerType,kind:R.kind,workspace:R.workspace,lastLaunchedAt:R.lastLaunchedAt}))}),Af("entries",{daemonId:A,entries:J.filter(R=>R.type!=="adhdev-daemon").map(R=>({id:R.id,type:R.type,unread:R.unread,inboxBucket:R.inboxBucket,lastSeenAt:R.lastSeenAt,lastUpdated:R.lastUpdated,sessionId:R.sessionId}))}),J.length>0&&C(J,{authoritativeDaemonIds:[A]}),D(),o.current!==A&&((y=a.current)==null||y.call(a),o.current=A,a.current=Os.subscribe({sendData:Fd},A,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${A}`,params:{includeSessions:!0}},R=>{if(R.topic!=="daemon.metadata")return;const I=t.current.getIdes(),E=I.find(M=>M.id===A),$=ko(R.status,{daemonId:A,existingDaemon:E,existingEntries:I,timestamp:R.timestamp});$.length>0&&t.current.injectEntries($,{authoritativeDaemonIds:[A]}),R.userName&&i.current&&i.current(R.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},w.onclose=k=>{m.current&&(ds==null||ds.stopScreenshots(),ds&&Es.setState(ds.daemonId,"disconnected"),c("disconnected"),d.current=null,b.current=`close:${k.code}${k.wasClean?":clean":":unclean"}`,Yn("close",{code:k.code,reason:k.reason||"",wasClean:k.wasClean}),v())},w.onerror=k=>{g.current||!m.current||(b.current="error",Yn("error",{message:k instanceof Event?"event":String(k),readyState:w.readyState}),console.warn("[Standalone WS] Error, will reconnect:",k))}}function v(){if(!m.current)return;clearTimeout(p.current);const w=h.current;console.log(`[Standalone WS] Reconnecting in ${w}ms...`),Yn("schedule_reconnect",{reason:b.current,delayMs:w}),p.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,N3),f()},w)}return f(),()=>{var w;m.current=!1,g.current=!0,(w=a.current)==null||w.call(a),a.current=null,o.current=null,clearTimeout(p.current),d.current&&(d.current.onerror=null,d.current.onclose=null,d.current.close(),d.current=null,vs=null),ds&&(ds.stopScreenshots(),Es.unregister(ds.daemonId))}},[]),r.jsx(r.Fragment,{children:e})}function M3({children:e}){const[t,s]=u.useState("disconnected"),[n,i]=u.useState(null);u.useEffect(()=>(vi=(o,l)=>{s(o),l&&i(l)},()=>{vi=null}),[]);const a=u.useMemo(()=>{const o=t==="connected",l=C3(t),c={};return n&&(c[n]=l),c.standalone=l,{wsStatus:t,isConnected:o,connectionStates:c}},[t,n]);return r.jsx(fS,{connectionOverrides:a,children:r.jsx(T3,{children:e})})}const Kv="adhdev_standalone_font_preferences",Dr={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Dl=[{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"}],Hi=[{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"}],E3=new Set(Dl.map(e=>e.id)),R3=new Set(Hi.map(e=>e.id));function Ds(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:mo("chat",t.chat),code:mo("code",t.code),terminal:mo("terminal",t.terminal)}}function mo(e,t){const s=Dr[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},i=typeof n.preset=="string"?n.preset.trim():"",a=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?E3:R3).has(i)?i==="custom"?a?{preset:"custom",customFamily:a}:s:{preset:i}:s}function fo(e,t){var i;const s=mo(e,t);if(s.preset==="custom"&&s.customFamily)return s.customFamily;const n=e==="chat"?Dl:Hi;return((i=n.find(a=>a.id===s.preset))==null?void 0:i.family)||n[0].family}function P3(e){const t=Ds(e),s=fo("chat",t.chat),n=fo("code",t.code),i=fo("terminal",t.terminal);return{"--chat-font-family":s,"--chat-code-font-family":n,"--chat-terminal-font-family":i,"--chat-tool-font-family":i}}function jr(e,t=document.documentElement){const s=Ds(e),n=P3(s);t.setAttribute("data-standalone-fonts","custom");for(const[i,a]of Object.entries(n))t.style.setProperty(i,a);return s}function Bd(e){const t=Ds(e);try{localStorage.setItem(Kv,JSON.stringify(t))}catch{}return t}function D3(){try{const e=localStorage.getItem(Kv);if(e)return Ds(JSON.parse(e))}catch{}return Dr}function L3(){return jr(D3())}function Qn(e,t){var n;const s=e==="chat"?Dl:Hi;return((n=s.find(i=>i.id===t))==null?void 0:n.label)||s[0].label}const $3=[{id:"dashboard",path:"/dashboard",icon:r.jsx(Kf,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:r.jsx(cr,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:r.jsx(vn,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:r.jsx(nl,{}),label:"Settings"}];function O3({children:e}){const t=zi(),s=Ud(),n=u.useMemo(()=>$3.map(a=>({...a,active:s.pathname.startsWith(a.path),onSelect:()=>t(a.path)})),[s.pathname,t]),i=u.useMemo(()=>[{id:"docs",label:r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"Docs"}),r.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:r.jsx(qf,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:r.jsx(Vf,{}),active:s.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[s.pathname,t]);return r.jsx(A_,{brand:({collapsed:a})=>r.jsxs(r.Fragment,{children:[r.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!a&&r.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:i,footerInfo:({collapsed:a})=>a?null:r.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.82"]}),footerActions:({collapsed:a,toggleCollapsed:o})=>r.jsxs("div",{className:`nav-item cursor-pointer ${a?"justify-center py-2.5 px-0":"mt-1"}`,onClick:o,title:a?"Expand sidebar":"Collapse sidebar",children:[r.jsx("span",{className:"nav-icon text-base",children:a?"›":"‹"}),!a&&r.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const F3=[{icon:r.jsx(cr,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:r.jsx(zr,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:r.jsx(Xf,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:r.jsx(_s,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:r.jsx(vn,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:r.jsx(qf,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],B3=[{icon:r.jsx(DS,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:r.jsx(Kf,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:r.jsx(Gi,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:r.jsx(IS,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:r.jsx(Gf,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:r.jsx(MS,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],W3=[{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 U3(){return r.jsxs(Zi,{icon:r.jsx(Vf,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:r.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.82"]}),children:[r.jsx(wt,{children:r.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[r.jsxs("div",{className:"max-w-2xl",children:[r.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),r.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."}),r.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."})]}),r.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[r.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 ↗"}),r.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 ↗"}),r.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 ↗"})]})]})}),r.jsx(wt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:r.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:F3.map(e=>r.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[r.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]}),r.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),r.jsx(wt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:r.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:ox.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:cx.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:lx.map(e=>`${e.icon} ${e.name}`)}].map(e=>r.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[r.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),r.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>r.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))})}),r.jsx(wt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:r.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:B3.map(e=>r.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[r.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[r.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]}),r.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),r.jsx(wt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:r.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:r.jsxs("table",{className:"w-full text-[13px]",children:[r.jsx("thead",{children:r.jsxs("tr",{className:"bg-bg-secondary",children:[r.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),r.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),r.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),r.jsx("tbody",{children:W3.map((e,t)=>r.jsxs("tr",{className:t%2===0?"bg-bg-glass":"bg-transparent",children:[r.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),r.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?r.jsx("span",{className:"text-emerald-500",children:"✓"}):r.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),r.jsx("td",{className:"px-4 py-2.5 text-center",children:r.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),r.jsx(ul,{icon:r.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:r.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[r.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),r.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[r.jsx(zS,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Wc(e,t,s){return{...e,[t]:s}}function Uc({surface:e,title:t,description:s,value:n,options:i,onChange:a}){return r.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),r.jsx("div",{className:"text-xs text-text-muted mt-1",children:s})]}),r.jsxs("div",{className:"flex flex-col gap-2",children:[r.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;a(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:i.map(o=>r.jsx("option",{value:o.id,children:o.label},o.id))}),n.preset==="custom"&&r.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=>a({preset:"custom",customFamily:o.target.value})}),r.jsxs("div",{className:"text-[11px] text-text-muted",children:[r.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",r.jsx("span",{className:"font-mono break-all",children:fo(e,n)})]})]})]})}function H3({value:e,savedValue:t,saving:s=!1,error:n,notice:i,onChange:a,onSave:o,onResetToSaved:l,onResetToDefaults:c}){const d=JSON.stringify(e)!==JSON.stringify(t);return r.jsxs("div",{className:"flex flex-col gap-4",children:[r.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&&r.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}),i&&r.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:i}),r.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[r.jsx(Uc,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Dl,onChange:p=>a(Wc(e,"chat",p))}),r.jsx(Uc,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Hi,onChange:p=>a(Wc(e,"code",p))}),r.jsx(Uc,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Hi,onChange:p=>a(Wc(e,"terminal",p))})]}),r.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[r.jsxs("div",{className:"flex items-center justify-between gap-3",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),r.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",Qn("chat",e.chat.preset)," · Code: ",Qn("code",e.code.preset)," · Terminal: ",Qn("terminal",e.terminal.preset)]})]}),r.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Qn("chat",Dr.chat.preset)," / ",Qn("code",Dr.code.preset)]})]}),r.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:r.jsxs("div",{className:"chat-container-content",children:[r.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:r.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[r.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[r.jsx("span",{className:"chat-sender",children:"Hermes"}),r.jsx("span",{className:"chat-time",children:"now"})]}),r.jsxs("div",{className:"chat-markdown",children:[r.jsxs("p",{children:["Readable prose, ",r.jsx("strong",{children:"bold text"}),", and ",r.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),r.jsx("pre",{children:r.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),r.jsxs("div",{className:"chat-msg-tool",children:[r.jsx("span",{className:"tool-icon",children:"▸"}),r.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),r.jsxs("div",{className:"chat-msg-terminal",children:[r.jsx("div",{className:"chat-msg-header",children:"Terminal"}),r.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),r.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[r.jsx("button",{type:"button",onClick:o,disabled:s||!d,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:s?"Saving…":"Save font settings"}),r.jsx("button",{type:"button",onClick:l,disabled:s||!d,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"}),r.jsx("button",{type:"button",onClick:c,disabled:s,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 z3(){const{ides:e}=Fs(),t=e.find(Q=>Q.type==="adhdev-daemon"),s=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=jt(),{userName:i}=Fs(),[a,o]=u.useState(i||""),[l,c]=u.useState(null),[d,p]=u.useState(null),[h,m]=u.useState(Dr),[g,b]=u.useState(!1),[f,v]=u.useState(""),[w,x]=u.useState(""),[S,k]=u.useState("127.0.0.1"),[j,y]=u.useState(""),[N,_]=u.useState(""),[C,D]=u.useState(""),[T,A]=u.useState(""),[P,F]=u.useState(""),[J,R]=u.useState(!1),I=async()=>{const q=await(await Rs("/auth/session")).json();c(q)},E=async()=>{const q=await(await Rs("/api/v1/standalone/preferences")).json();p(q),k(q.standaloneBindHost);const me=Ds(q.standaloneFontPreferences);m(me),jr(me),Bd(me)};u.useEffect(()=>{i!==void 0&&o(i)},[i]),u.useEffect(()=>{Promise.all([I(),E()]).catch(Q=>{A(Q instanceof Error?Q.message:String(Q))})},[]),u.useEffect(()=>{jr(h)},[h]);const $=Q=>{const q=Q.target.value.trim();t!=null&&t.id&&q!==i&&n(t.id,"set_user_name",{userName:q}).catch(console.error)},[M,O]=u.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),H=Q=>{O(Q);try{localStorage.setItem("adhdev_sound",Q?"1":"0")}catch{}},ae=async()=>{v(""),x(""),b(!0);try{const Q=Ds(h),q=await Rs("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:Q})}),me=await q.json();if(!q.ok)throw new Error((me==null?void 0:me.error)||"Failed to save standalone font preferences");const we=Ds(me.standaloneFontPreferences);p(me),m(we),jr(we),Bd(we),x("Standalone chat fonts saved for this self-hosted dashboard.")}catch(Q){v(Q instanceof Error?Q.message:String(Q))}finally{b(!1)}},z=()=>{const Q=Ds(d==null?void 0:d.standaloneFontPreferences);v(""),x(""),m(Q),jr(Q)},X=()=>{v(""),x(""),m(Dr),jr(Dr)},te=async()=>{A(""),F(""),R(!0);try{const Q=await Rs("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:S})}),q=await Q.json();if(!Q.ok)throw new Error((q==null?void 0:q.error)||"Failed to save standalone network preference");p(q),k(q.standaloneBindHost),F(q.standaloneBindHost==="0.0.0.0"?"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.":"Default standalone network mode set to localhost only. Restart standalone to apply it.")}catch(Q){A(Q instanceof Error?Q.message:String(Q))}finally{R(!1)}},he=async()=>{if(A(""),F(""),N.trim().length<4){A("Password must be at least 4 characters.");return}if(N!==C){A("New password and confirmation do not match.");return}R(!0);try{const Q=await Rs("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:j,newPassword:N})}),q=await Q.json();if(!Q.ok)throw new Error((q==null?void 0:q.error)||"Failed to save password");c(q),await E(),y(""),_(""),D(""),F(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Hv()}catch(Q){A(Q instanceof Error?Q.message:String(Q))}finally{R(!1)}},ke=async()=>{A(""),F(""),R(!0);try{const Q=await Rs("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:j,clear:!0})}),q=await Q.json();if(!Q.ok)throw new Error((q==null?void 0:q.error)||"Failed to clear password");c(q),await E(),y(""),_(""),D(""),F("Standalone password disabled.")}catch(Q){A(Q instanceof Error?Q.message:String(Q))}finally{R(!1)}};return r.jsxs(Zi,{icon:r.jsx(nl,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[r.jsx(or,{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)&&r.jsx(or,{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."}),r.jsx(wt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:r.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[r.jsx("span",{className:"text-text-muted",children:"Version"}),r.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.82"]}),r.jsx("span",{className:"text-text-muted",children:"Status"}),r.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),r.jsx("span",{className:"text-text-muted",children:"Current bind"}),r.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),r.jsx("span",{className:"text-text-muted",children:"Default bind"}),r.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.standaloneBindHost)||"127.0.0.1"}),r.jsx("span",{className:"text-text-muted",children:"Auth"}),r.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),r.jsx(wt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:r.jsxs("div",{className:"flex flex-col gap-3",children:[r.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."}),r.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[r.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:[r.jsx("input",{type:"radio",name:"standalone-bind-host",checked:S==="127.0.0.1",onChange:()=>k("127.0.0.1")}),r.jsxs("span",{children:[r.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),r.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."})]})]}),r.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:[r.jsx("input",{type:"radio",name:"standalone-bind-host",checked:S==="0.0.0.0",onChange:()=>k("0.0.0.0")}),r.jsxs("span",{children:[r.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),r.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."})]})]})]}),r.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[r.jsx("button",{type:"button",onClick:()=>{te()},disabled:J,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:J?"Saving…":"Save default network mode"}),r.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(d==null?void 0:d.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),r.jsx(wt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:r.jsxs("div",{className:"flex flex-col gap-3",children:[r.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."}),T&&r.jsx(or,{variant:"error",children:T}),P&&r.jsx(or,{variant:"success",children:P}),r.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[r.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:j,onChange:Q=>y(Q.target.value)}),r.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:N,onChange:Q=>_(Q.target.value)}),r.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:C,onChange:Q=>D(Q.target.value)})]}),r.jsxs("div",{className:"flex flex-wrap gap-2",children:[r.jsx("button",{type:"button",onClick:()=>{he()},disabled:J,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:J?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&r.jsx("button",{type:"button",onClick:()=>{ke()},disabled:J,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"})]})]})}),r.jsx(wt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:s.length===0?r.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):r.jsx("div",{className:"flex flex-col gap-1.5",children:s.map(Q=>r.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[r.jsxs("div",{className:"flex items-center gap-2.5",children:[r.jsx("span",{className:`w-2 h-2 rounded-full ${Q.running?"bg-green-400":"bg-text-muted/30"}`}),r.jsx("span",{className:"text-sm font-medium",children:Q.name})]}),r.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:Q.type})]},Q.type))})}),r.jsx(wt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:r.jsx(O_,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),r.jsx(wt,{title:"Coordinator prompts",description:"User-level overrides for the mesh coordinator system prompt. Per-mesh overrides live in the Repo Mesh page.",children:r.jsx(U_,{daemonId:t==null?void 0:t.id})}),r.jsx(wt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:r.jsxs("div",{className:"flex flex-col gap-4",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),r.jsx(z_,{})]}),r.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[r.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),r.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."}),r.jsx(J_,{})]}),r.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[r.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),r.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),r.jsx(H3,{value:h,savedValue:Ds(d==null?void 0:d.standaloneFontPreferences),saving:g,error:f,notice:w,onChange:m,onSave:()=>{ae()},onResetToSaved:z,onResetToDefaults:X})]}),r.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[r.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),r.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."}),r.jsx(tC,{})]})]})}),r.jsx(wt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:r.jsxs("div",{className:"flex flex-col gap-3",children:[r.jsx(D_,{}),r.jsx(kr,{label:r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(HS,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:M,onChange:H})]})}),r.jsx(wt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:r.jsx("div",{className:"flex flex-col gap-3",children:r.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:[r.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[r.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[r.jsx(CS,{size:16,className:"text-text-secondary"})," Display Name"]}),r.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),r.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:a,onChange:Q=>o(Q.target.value),onBlur:$,onKeyDown:Q=>{Q.key==="Enter"&&Q.currentTarget.blur()}})]})})})]})}const K3=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],ii="adhdev_onboarding_done",G3=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],q3={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function V3({onDone:e}){const[t,s]=u.useState([]),[n,i]=u.useState(new Set(K3)),[a,o]=u.useState(!0),[l,c]=u.useState(null),[d,p]=u.useState(!1),[h,m]=u.useState(null),[g,b]=u.useState("all");u.useEffect(()=>{let j=!1;const y=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${y}/providers?sort=popular&limit=100`).then(N=>{if(!N.ok)throw new Error(`HTTP ${N.status}`);return N.json()}).then(N=>{j||s(N.providers??[])}).catch(N=>{j||c(N instanceof Error?N.message:String(N))}).finally(()=>{j||o(!1)}),()=>{j=!0}},[]);const f=t.filter(j=>g==="all"||j.category===g),v=["cli","ide","extension","acp"].map(j=>({category:j,items:f.filter(y=>y.category===j)})).filter(j=>j.items.length>0),w=u.useCallback(j=>{i(y=>{const N=new Set(y);return N.has(j)?N.delete(j):N.add(j),N})},[]),x=u.useCallback(async()=>{if(n.size===0){localStorage.setItem(ii,"1"),e();return}p(!0);const j=[];for(const y of n)try{const _=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:y})})).json().catch(()=>({}));j.push({type:y,ok:!!_.success,error:_.error})}catch(N){j.push({type:y,ok:!1,error:N instanceof Error?N.message:String(N)})}m(j),p(!1),j.every(y=>y.ok)&&localStorage.setItem(ii,"1")},[n,e]),S=u.useCallback(()=>{localStorage.setItem(ii,"1"),e()},[e]),k=u.useCallback(()=>{h&&h.every(j=>j.ok)?e():d||S()},[h,d,e,S]);return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60",onClick:k,children:r.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-2xl max-w-2xl w-full p-6 flex flex-col gap-5 max-h-[85vh] overflow-y-auto",onClick:j=>j.stopPropagation(),children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Welcome to ADHDev"}),r.jsxs("div",{className:"text-[12px] text-text-muted mt-1",children:["Pick the providers you want to use. Defaults to the four officially supported CLI providers; you can install IDE, ACP, or extension providers from the tabs below or later from ",r.jsx("span",{className:"text-text-secondary",children:"Burrow → Providers → Add provider"}),"."]})]}),!a&&!l&&t.length>0&&r.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:G3.map(j=>{const y=j.key==="all"?t.length:t.filter(N=>N.category===j.key).length;return y===0&&j.key!=="all"?null:r.jsxs("button",{onClick:()=>b(j.key),className:`machine-btn text-[10px] px-2 py-0.5 ${g===j.key?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:[j.label," ",r.jsxs("span",{className:"opacity-60",children:["(",y,")"]})]},j.key)})}),a&&r.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"Loading registry…"}),!a&&l&&r.jsxs("div",{className:"rounded-xl border border-red-500/30 bg-red-500/5 px-3 py-2 text-[12px] text-red-400",children:["Failed to load registry: ",l]}),!a&&!l&&f.length===0&&r.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"No providers in this category."}),!a&&!l&&f.length>0&&r.jsx("div",{className:"flex flex-col gap-4",children:v.map(j=>r.jsxs("div",{children:[r.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:q3[j.category]??j.category}),r.jsx("div",{className:"grid gap-1.5",children:j.items.map(y=>{var T,A;const N=n.has(y.type),_=h==null?void 0:h.find(P=>P.type===y.type),C=((T=y.manifest)==null?void 0:T.icon)??"📦",D=((A=y.manifest)==null?void 0:A.details)??"";return r.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${N?"bg-violet-500/[0.06] border-violet-500/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[r.jsx("input",{type:"checkbox",checked:N,onChange:()=>w(y.type),disabled:d,className:"shrink-0"}),r.jsx("span",{className:"text-base shrink-0",children:C}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:y.displayName}),D&&r.jsx("div",{className:"text-[10px] text-text-muted truncate",children:D})]}),_&&r.jsx("span",{className:`text-[10px] font-semibold ${_.ok?"text-green-400":"text-red-400"}`,children:_.ok?"✓ installed":`✗ ${_.error??"failed"}`})]},y.type)})})]},j.category))}),r.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-border-subtle",children:[r.jsxs("div",{className:"text-[11px] text-text-muted",children:[n.size," provider",n.size!==1?"s":""," selected"]}),r.jsxs("div",{className:"ml-auto flex gap-2",children:[r.jsx("button",{onClick:S,disabled:d,className:"machine-btn text-[11px] px-3 py-1",children:"Skip"}),r.jsx("button",{onClick:()=>{h?(localStorage.setItem(ii,"1"),e()):x()},disabled:d||!h&&n.size===0,className:"machine-btn text-[11px] px-3 py-1 bg-violet-500/15 border-violet-500/40 text-violet-400 hover:bg-violet-500/25",children:d?"Installing…":h?"Done":`Install ${n.size}`})]})]})]})})}function X3(){try{return localStorage.getItem(ii)==="1"}catch{return!1}}C_();Y_();L3();const Y3=Bf({baseUrl:"",getToken:Pp});function Q3({children:e}){const[t,s]=u.useState(null),[n,i]=u.useState(!0),[a,o]=u.useState(""),[l,c]=u.useState(""),[d,p]=u.useState(!1),h=async()=>{i(!0),c("");try{const b=await(await Rs("/auth/session")).json();s(b)}catch(g){c(g instanceof Error?g.message:String(g))}finally{i(!1)}};u.useEffect(()=>{h()},[]),u.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let g=!1;return(async()=>{try{const b=await Rs("/api/v1/standalone/preferences");if(!b.ok)return;const f=await b.json();if(g)return;const v=Ds(f.standaloneFontPreferences);jr(v),Bd(v)}catch{}})(),()=>{g=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const m=async g=>{g.preventDefault(),p(!0),c("");try{const b=await Rs("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:a})}),f=await b.json();if(!b.ok)throw new Error((f==null?void 0:f.error)||"Login failed");s(f),o(""),Hv()}catch(b){c(b instanceof Error?b.message:String(b))}finally{p(!1)}};return n?r.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?r.jsx(r.Fragment,{children:e}):r.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:r.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:[r.jsxs("div",{children:[r.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),r.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?r.jsxs("form",{className:"flex flex-col gap-3",onSubmit:m,children:[r.jsx("input",{type:"password",value:a,onChange:g=>o(g.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}),r.jsx("button",{type:"submit",disabled:d||!a,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:d?"Signing in…":"Unlock dashboard"})]}):r.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&&r.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})]})}):r.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 Tf(){const{ides:e,initialLoaded:t}=Fs();if(!t)return r.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const s=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return s?r.jsx(Kc,{to:`/machines/${s.id}`,replace:!0}):r.jsx(Kc,{to:"/dashboard",replace:!0})}function J3(){const[e,t]=u.useState(!1);return u.useEffect(()=>{let s=!1;if(!X3())return fetch("/api/v1/providers/installed").then(n=>n.ok?n.json():{providers:[]}).then(n=>{s||(n.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{s=!0}},[]),e?r.jsx(V3,{onDone:()=>t(!1)}):null}function Z3(){const{ides:e}=Fs(),t=u.useMemo(()=>{for(const d of e)if(d.activeInteractivePrompt)return d.instanceId??d.id;return null},[e]),{promptSession:s,hasActivePrompt:n,responseError:i,isSubmitting:a,submit:o,cancel:l,reopen:c}=yx(t);return n?r.jsxs("div",{className:"relative",children:[!s&&r.jsx("button",{type:"button",onClick:c,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:"Awaiting your input ↑"}),r.jsx(dg,{promptSession:s,isSubmitting:a,error:i,onSubmit:o,onCancel:l})]}):null}function e4(){const e=u.useMemo(()=>({sendCommand:wi,sendData:Fd,sendPtyInput:zv}),[]);return r.jsx(Fw,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:r.jsx(bS,{client:Y3,children:r.jsx(Q3,{children:r.jsx(M3,{children:r.jsx(vS,{value:e,children:r.jsxs(jS,{sendDaemonCommand:wi,children:[r.jsx(Z3,{}),r.jsxs(O3,{children:[r.jsx(J3,{}),r.jsxs(Bw,{children:[r.jsx(er,{path:"/dashboard",element:r.jsx(TE,{})}),r.jsx(er,{path:"/machine",element:r.jsx(Tf,{})}),r.jsx(er,{path:"/machines/:id",element:r.jsx(F2,{})}),r.jsx(er,{path:"/machines",element:r.jsx(Tf,{})}),r.jsx(er,{path:"/about",element:r.jsx(U3,{})}),r.jsx(er,{path:"/settings",element:r.jsx(z3,{})}),r.jsx(er,{path:"/mesh",element:r.jsx(w3,{children:r.jsx(y3,{})})}),r.jsx(er,{path:"*",element:r.jsx(Kc,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}_1({connectionManager:Es});Ww(document.getElementById("root")).render(r.jsx(e4,{}));
|