@adhdev/daemon-standalone 0.9.82-rc.304 → 0.9.82-rc.306

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,113 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-DsCRNxW_.js","assets/vendor-BHUMCOj6.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
+ var Em=Object.defineProperty;var Bm=(e,t,r)=>t in e?Em(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ke=(e,t,r)=>Bm(e,typeof t!="symbol"?t+"":t,r);import{r as l,j as s,M as ei,a as Fm,b as Om,c as zm,R as jt,d as Pr,t as Hm,e as Wm,u as zr,D as Km,f as So,g as Co,E as Um,i as Gm,C as Vm,h as qm,B as Ym,k as Jm,l as Xm,m as Qm,H as ln,P as os,n as Zm,o as eh,p as th,q as sh,s as rh,v as nh,w as ti,x as ah,y as oh,z as ih,A as lh,F as is,N as Io,G as ch}from"./vendor-BHUMCOj6.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&n(i)}).observe(document,{childList:!0,subtree:!0});function r(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(a){if(a.ep)return;a.ep=!0;const o=r(a);fetch(a.href,o)}})();function dh(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),r=[];return{record(n){const a={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...n,payload:n.payload?{...n.payload}:{}};return r.push(a),r.length>t&&r.splice(0,r.length-t),a},list(n={}){const a=Math.max(1,Math.floor(n.limit||100));return r.filter(o=>!n.interactionId||o.interactionId===n.interactionId).filter(o=>!n.topic||o.topic===n.topic).filter(o=>!n.kind||o.kind===n.kind).slice(-a).map(o=>({...o,payload:o.payload?{...o.payload}:{}}))},clear(){r.splice(0,r.length)}}}const Us=dh();function rl(e){const t={};for(const r of e)r.transport&&(t[r.transport]=(t[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:t}}function uh(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function nl(e){return Array.isArray(e)?[...e]:[]}function id(e,t){if(!e)return t??null;const r=Object.prototype.hasOwnProperty.call(e,"messages"),n=Object.prototype.hasOwnProperty.call(e,"activeModal"),a=typeof e.id=="string"?e.id.trim():"",o=typeof(t==null?void 0:t.id)=="string"?t.id.trim():"",i=!!a&&!!o&&a!==o;return t?{...t,...e,messages:r?nl(e.messages):i?[]:t.messages,activeModal:n?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...r?{messages:nl(e.messages)}:{},...n?{activeModal:e.activeModal??null}:{}}}function vr(e,t){const r=uh(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(t==null?void 0:t.parentSessionId)??null,providerSessionId:e.providerSessionId??(t==null?void 0:t.providerSessionId),providerName:r??(t==null?void 0:t.providerName)??(t==null?void 0:t.cliName)??(t==null?void 0:t.type)??e.providerName??e.providerType,title:e.title??(t==null?void 0:t.title)??r??(t==null?void 0:t.providerName)??e.providerName??e.providerType,workspace:e.workspace??(t==null?void 0:t.workspace)??null,mode:e.mode??(t==null?void 0:t.mode),capabilities:e.capabilities??(t==null?void 0:t.sessionCapabilities)??(t==null?void 0:t.capabilities)??[],cdpConnected:e.cdpConnected??(t==null?void 0:t.cdpConnected),activeChat:id(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 ld(e,t,r){if(!(t!=null&&t.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const n=t.map(a=>{const o=e.find(i=>i.id===a.id);return o?vr(a,o):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(t.map(o=>o.id));for(const o of e)a.has(o.id)||n.push(o)}return n}function al(e){return!!e&&typeof e=="object"&&"text"in e}function si(e,t){const r=(t==null?void 0:t.joiner)??" ",n=(t==null?void 0:t.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(o=>typeof o=="string"?o:al(o)?String(o.text||""):"").join(r):al(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Gs(e){return si(e,{normalizeWhitespace:!0})}const cd=l.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}),dd=l.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function ol(e){var r,n;let t=0;return e.activeChat!==void 0&&(t+=4),e.activeInteractivePrompt!==void 0&&(t+=2),(r=e.childSessions)!=null&&r.length&&(t+=2),e.workspace&&(t+=1),e.machine&&(t+=1),(n=e.agents)!=null&&n.length&&(t+=1),t}function ud(e,t,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=t.version??r.version??e.version,o=t.serverVersion??e.serverVersion??r.serverVersion,i=t.versionMismatch===!0||e.versionMismatch===!0,c=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,d=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),o&&(n.serverVersion=o),d&&(n.versionUpdateReason=d),a&&o&&a===o?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||i&&a&&o&&a!==o)&&(n.versionMismatch=!0),c&&(n.versionUpdateRequired=!0),n)}function ph(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function Aa(e){if(!e||typeof e!="object")return"";const t=e,r=ph(Gs(t.content).slice(0,512));return[String(t.id||""),String(t._localId||""),String(t._turnKey||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),r].join(":")}function mh(e,t){if(!Array.isArray(e))return e;if(t!=null&&t.has(e))return{count:e.length,sharedRef:!0};let r=2166136261;for(const n of e){const a=Aa(n);for(let o=0;o<a.length;o+=1)r^=a.charCodeAt(o),r=Math.imul(r,16777619)>>>0}return{count:e.length,hash:r.toString(16).padStart(8,"0"),first:Aa(e[0]),last:Aa(e[e.length-1])}}function Mo(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function Ao(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(Mo(e)&&Mo(t)){const i=e.messages;Array.isArray(i)&&i===t.messages&&r.add(i)}if(Array.isArray(e)&&Array.isArray(t)){const i=Math.min(e.length,t.length);for(let c=0;c<i;c+=1)Ao(e[c],t[c],r);return}const n=e,a=t,o=new Set([...Object.keys(n),...Object.keys(a)]);for(const i of o)i!=="messages"&&Ao(n[i],a[i],r)}function Nr(e,t){return Array.isArray(e)?e.map(r=>Nr(r,t)):!e||typeof e!="object"?e:Mo(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?mh(a,t):Nr(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,Nr(n,t)]))}function hh(e,t){try{const r=new WeakSet;return Ao(e,t,r),JSON.stringify(Nr(e,r))===JSON.stringify(Nr(t,r))}catch{return!1}}function To(e,t,r){return hh(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function pd(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function fh(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function il(e,t,r,n){var c;const a=(c=t.chats)!=null&&c.length?t.chats:e.chats,o=ld(e.childSessions,t.childSessions,{preserveMissing:n}),i=id(t.activeChat,e.activeChat);return ud(e,t,{...e,...t,chats:a,childSessions:o,activeChat:i,_lastUpdate:r})}function xh(e,t,r){var a,o;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=ld(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(n.chats=t.chats);for(const i 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"])fh(n,t,i);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function bh(e,t,r,n){const a=xh(e,t,n),o=Object.keys(a).length>0?ud(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return To(e,o,r)}function gh(e){const t=new Set(e.map(o=>o.id)),r=new Set,n=new Set,a=new Set;for(const o of e){const i=pd(o);i&&r.add(i),i&&o.type!=="adhdev-daemon"&&n.add(i),i&&o.type==="adhdev-daemon"&&o._sessionListAuthoritative&&a.add(i)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function yh(e,t,r,n,a,o){return!a.has(t)||!o.has(t)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function vh(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function wh(e,t,r){var u,m;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(h=>({...h,_lastUpdate:n}));const o=new Map;for(const h of t)o.set(h.id,h);const{incomingIds:i,incomingDaemonIds:c,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:p}=gh(e);for(const h of e){const b=o.get(h.id);if(!b){o.set(h.id,{...h,_lastUpdate:n});continue}const g=ol(h),f=ol(b),j=pd(h),N=!a.has(j);if(g>f){const k=il(b,h,n,N);o.set(h.id,To(b,k,n));continue}if(g<f){o.set(h.id,bh(b,h,n,N));continue}const y=h.timestamp||n,v=b._lastUpdate||b.timestamp||0;if(y>=v){const k=il(b,h,n,N);o.set(h.id,To(b,k,n));continue}(u=h.chats)!=null&&u.length&&!((m=b.chats)!=null&&m.length)&&o.set(h.id,{...b,chats:h.chats})}for(const[h,b]of o){const g=b.daemonId||h.split(":")[0];if(!c.has(g))continue;if(a.has(g)&&p.has(g)&&!i.has(h)){o.delete(h);continue}const f=n-(b._lastUpdate||b.timestamp||0);yh(b,g,f,i,a,d)&&o.delete(h)}for(const[h,b]of o){const g=b.daemonId||h.split(":")[0];if(vh(b,g,c,d,o))continue;n-(b._lastUpdate||b.timestamp||0)>3e5&&b.status!=="online"&&o.delete(h)}return Array.from(o.values())}function jh(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function kh({children:e,connectionOverrides:t}){const[r,n]=l.useState([]),[a,o]=l.useState(!1),[i,c]=l.useState([]),[d,p]=l.useState(void 0),u=l.useRef(r);l.useEffect(()=>{u.current=r},[r]);const m=l.useCallback((N,y)=>{n(v=>{let k=!1;const w=v.map(x=>x.id!==N||x.chats===y?x:(k=!0,{...x,chats:y}));return k?w:v})},[]),h=l.useCallback((N,y)=>{n(v=>{const k=v.length===0?N:wh(N,v,y),w=!jh(v,k);return w&&Us.record({kind:"dashboard.entries_applied",payload:{incoming:rl(N),next:rl(k)}}),w?k:v})},[]),b=l.useCallback(()=>o(!0),[]),g=l.useMemo(()=>({injectEntries:h,markLoaded:b,getIdes:()=>u.current}),[h,b]),f=t,j=l.useMemo(()=>({ides:r,updateRouteChats:m,initialLoaded:a,toasts:i,setToasts:c,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:d,setUserName:p}),[r,m,a,i,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,d]);return s.jsx(dd.Provider,{value:g,children:s.jsx(cd.Provider,{value:j,children:e})})}function es(){return l.useContext(cd)}function Rr(){return l.useContext(dd)}function md(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(c){return c.startsWith("http")?c:`${t}${c.startsWith("/")?"":"/"}${c}`}function o(c){const d=r==null?void 0:r(),p=a(c),u=c.startsWith("http")?new URL(p):new URL(p,typeof window<"u"?window.location.origin:"http://localhost");return d&&u.searchParams.set("token",d),!c.startsWith("http")&&!t?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function i(c,d={}){const p={"Content-Type":"application/json",...d.headers||{}},u=r==null?void 0:r();u&&(p.Authorization=`Bearer ${u}`);const m=a(c),h=new AbortController,b=setTimeout(()=>h.abort(),15e3);try{const g=await fetch(m,{...d,headers:p,signal:h.signal});if(g.status===401)throw n==null||n(),new Error("Unauthorized");if(!g.ok){const f=await g.json().catch(()=>({error:g.statusText}));throw new Error(f.error||`API Error: ${g.status}`)}return g.json()}finally{clearTimeout(b)}}return{getDaemons:()=>i("/api/v1/daemons"),getDaemonStatus:c=>i(`/api/v1/daemons/${c}/status`),sendCommand:(c,d,p={})=>i(`/api/v1/daemons/${c}/command`,{method:"POST",body:JSON.stringify({type:d,payload:p})}),execTerminal:(c,d,p)=>i(`/api/v1/daemons/${c}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:p})}),sendAgentMessage:(c,d,p)=>i(`/api/v1/shortcuts/${c}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:p})}),getAgentStatus:c=>i(`/api/v1/shortcuts/${c}/status`),approveAgent:(c,d,p)=>i(`/api/v1/shortcuts/${c}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:p?"approve":"reject"})}),getMuxState:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/state`),getMuxSocketInfo:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/socket-info`),controlMux:(c,d,p={})=>i(`/api/v1/mux/${encodeURIComponent(c)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:p})}),getMuxEventsUrl:c=>o(`/api/v1/mux/${encodeURIComponent(c)}/events`),getRuntimeEventsUrl:c=>o(`/api/v1/runtime/${encodeURIComponent(c)}/events`),request:i}}const Nh=md({baseUrl:"http://localhost:3847"}),Sh=l.createContext(Nh);function Ch({client:e,children:t}){return s.jsx(Sh.Provider,{value:e,children:t})}const Ih={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},hd=l.createContext(Ih);function Mh({value:e,children:t}){return s.jsx(hd.Provider,{value:e,children:t})}function lt(){return l.useContext(hd)}function fd(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function Ah(e){const t=fd(e);if(!t||t.error!=="untrusted_external_provider")return null;const r=t.provider&&typeof t.provider=="object"?t.provider:null;return{providerType:typeof(r==null?void 0:r.type)=="string"?r.type:null,sourceName:typeof(r==null?void 0:r.sourceName)=="string"?r.sourceName:null,description:typeof t.hint=="string"?t.hint:void 0}}function Th(e){const[t,r]=l.useState(null),n=l.useCallback(async(i,c)=>{const d=m=>e(i,"launch_cli",{...c,...m}),p=await d({}),u=Ah(p);return u?new Promise(m=>{r({providerType:u.providerType||String(c.cliType??"?"),sourceName:u.sourceName,description:u.description,retry:()=>d({confirmExternalUntrusted:!0}),resolve:h=>{h.cancelled?m({success:!1,error:"user_cancelled_untrusted_launch"}):m(h.response)}})}):p},[e]),a=l.useCallback(async()=>{const i=t;if(i){r(null);try{const c=await i.retry(),d=fd(c);d!=null&&d.success?i.resolve({ok:!0,response:c}):i.resolve({ok:!1,error:(d==null?void 0:d.error)||"launch failed after confirm",response:c})}catch(c){i.resolve({ok:!1,error:(c==null?void 0:c.message)||String(c)})}}},[t]),o=l.useCallback(()=>{const i=t;i&&(r(null),i.resolve({ok:!1,cancelled:!0}))},[t]);return{launchCli:n,pending:t,confirm:a,cancel:o}}function _h({providerType:e,sourceName:t,description:r,onConfirm:n,onCancel:a}){const o=l.useRef(null);return l.useEffect(()=>{var i;(i=o.current)==null||i.focus()},[]),l.useEffect(()=>{const i=c=>{c.key==="Escape"&&a()};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[a]),s.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:a,style:{pointerEvents:"auto"},children:s.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:i=>i.stopPropagation(),children:[s.jsxs("div",{className:"px-4 py-3 border-b border-border-subtle flex items-center gap-2",children:[s.jsx("span",{"aria-hidden":!0,className:"text-amber-400 text-base",children:"⚠"}),s.jsx("h2",{className:"text-sm font-semibold",children:"Activate untrusted external provider?"})]}),s.jsxs("div",{className:"px-4 py-3 text-[12px] flex flex-col gap-3",children:[s.jsxs("p",{children:["You're about to activate ",s.jsx("span",{className:"font-mono",children:e}),t?s.jsxs(s.Fragment,{children:[" from ",s.jsx("span",{className:"font-mono",children:t})]}):null,"."]}),s.jsx("p",{className:"text-text-secondary",children:r??"This manifest ships JavaScript that the daemon will execute. Treat as untrusted code — review the source before enabling."}),s.jsx("p",{className:"text-text-secondary",children:"Only proceed if you trust the source URL you added and have reviewed the manifest."})]}),s.jsxs("div",{className:"px-4 py-2 border-t border-border-subtle flex justify-end gap-2",children:[s.jsx("button",{ref:o,type:"button",onClick:a,className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:"Cancel"}),s.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 xd=l.createContext(null);function Lh({sendDaemonCommand:e,children:t}){const r=Th(e),n=l.useMemo(()=>({launchCli:r.launchCli}),[r.launchCli]);return s.jsxs(xd.Provider,{value:n,children:[t,r.pending&&s.jsx(_h,{providerType:r.pending.providerType,sourceName:r.pending.sourceName,description:r.pending.description,onConfirm:r.confirm,onCancel:r.cancel})]})}function pa(){const e=l.useContext(xd);return e||{launchCli:async()=>{throw new Error("useLaunchCli must be used inside <LaunchCliProvider>")}}}function Ph(e){let t=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)t^=n.charCodeAt(a),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function Rh(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function bd(e){return e?Ph([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Rh(e.content)]):""}const Fe={size:18};function gd({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function ri({size:e=Fe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function ps({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),s.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),s.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),s.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function yd({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"9",cy:"7",r:"4"}),s.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),s.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Dh({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function $h({size:e=Fe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function vd({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),s.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),s.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),s.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function Eh({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),s.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),s.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),s.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),s.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function ma({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function wd({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),s.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Bh({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Fh({size:e=Fe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Ls({size:e=Fe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Gt({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function ni({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("polyline",{points:"14 2 14 8 20 8"}),s.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),s.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Vs({size:e=Fe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function ha({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function qs({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),s.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Ys({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M12 22v-5"}),s.jsx("path",{d:"M9 8V2"}),s.jsx("path",{d:"M15 8V2"}),s.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function rs({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"5",r:"2"}),s.jsx("circle",{cx:"5",cy:"19",r:"2"}),s.jsx("circle",{cx:"19",cy:"19",r:"2"}),s.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),s.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),s.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function Oh({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"12 2 2 7 12 12 22 7 12 2"}),s.jsx("polyline",{points:"2 12 12 17 22 12"}),s.jsx("polyline",{points:"2 17 12 22 22 17"})]})}function jd({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function ai({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),s.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),s.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function kd({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function zh({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),s.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),s.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function oi({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"4 17 10 11 4 5"}),s.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Hh({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Nd({size:e=Fe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Sd({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function yt({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Wh({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),s.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),s.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),s.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function Kh({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),s.jsx("path",{d:"M12 2v6"}),s.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Uh({size:e=Fe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function Gh({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),s.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function Hr({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function Vh({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"5"}),s.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),s.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),s.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),s.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),s.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),s.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),s.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),s.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function qh({size:e=Fe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function Yh({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Cd({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),s.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Jh({size:e=Fe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function Xh({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),s.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function Qh({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function Zh({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),s.jsx("path",{d:"M13 2h9v9"}),s.jsx("path",{d:"M22 2L13 11"})]})}function ef({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function tf({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),s.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),s.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),s.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),s.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),s.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),s.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),s.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),s.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),s.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function sf({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function rf({size:e=Fe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const Id="adhdev_chat_activity_visible",ll=new Set(["hidden","debug","internal"]),cl=new Set(["visible","user","chat"]),nf=new Set(["debug","trace","internal"]),af=new Set(["tool_call","terminal_command","runtime_activity"]),of=new Set(["runtime_status","provider_chrome","control"]),lf=new Set(["thought","tool","terminal"]);function Md(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Bs(e){return typeof e=="string"?e.trim().toLowerCase():""}function Ta(e,t,r){return e[r]??(t==null?void 0:t[r])}function dl(e,t,r){const n=e;return r.some(a=>n[a]===!0||(t==null?void 0:t[a])===!0)}function cf(e,t){const r=Bs(e.kind);return r||(t==="tool"?"tool":"standard")}function _a(e,t,r){const n=Md(e),a=typeof(n==null?void 0:n.label)=="string"?n.label.trim():"";return a||(t==="terminal"||r==="terminal_command"?"Terminal":t==="tool"||r==="tool_call"?"Tool":t==="thought"?"Thought":r==="runtime_activity"?"Runtime":"Activity")}function df(e){const t=e.content;return Array.isArray(t)&&t.some(r=>!!r&&typeof r=="object"&&r.type!=="text")}function ii(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=Md(e),r=Bs(e.role),n=cf(e,r),a=Bs(Ta(e,t,"visibility")),o=Bs(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),i=Bs(Ta(e,t,"audience")),c=Bs(Ta(e,t,"source")),d=ll.has(a)||ll.has(o)||nf.has(i)||dl(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),p=cl.has(a)||cl.has(o)||i==="chat"||dl(e,t,["userFacing"]),u=lf.has(n)||af.has(c);if(d)return{surface:u?"activity":"internal",isUserFacing:!1,isActivityFacing:u,isInternal:!u,role:r,kind:n,label:_a(e,n,c)};if(p)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:_a(e,n,c)};if((r==="system"||n==="system")&&df(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:"Chat"};if(of.has(c)||r==="system"||n==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:r,kind:n,label:"Internal"};if(u)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:r,kind:n,label:_a(e,n,c)};const m=(r==="user"||r==="human"||r==="assistant")&&(n==="standard"||n==="");return{surface:m?"chat":"internal",isUserFacing:m,isActivityFacing:!1,isInternal:!m,role:r,kind:n,label:m?"Chat":"Internal"}}function uf(e){return(Array.isArray(e)?e:[]).filter(t=>ii(t).isUserFacing)}function Ad(e){return(Array.isArray(e)?e:[]).filter(t=>ii(t).isActivityFacing)}function pf(e,t,r){return!r||t.length===0?e:[...e,...t].sort((n,a)=>{const o=Number(n.receivedAt??n.timestamp??0)||0,i=Number(a.receivedAt??a.timestamp??0)||0;if(o!==i)return o-i;const c=Number(n.index??0)||0,d=Number(a.index??0)||0;return c-d})}function ul(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(Id))==="1"}catch{return!1}}const Td=[Fm,{singleTilde:!1}],_d=[Td,Om,zm],mf=[Td],li=200,hf=80,pl=650,nr=new Map;function Un(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function ff(e,t){if(!Array.isArray(e)||e.length===0)return"0:empty";const r=String(t||"").trim();if(r)return`${e.length}:${r}`;const n=e[e.length-1];return`${e.length}:${bd(n)}`}function xf(e,t,r,n){return e||!t?!1:Un(r,n)}function bf({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=hf,bottomThresholdPx:a=li}){const o=Math.max(0,Number(e)||0),i=Math.max(0,Number(t)||0),c=Math.max(0,Number(r)||0);return Math.max(0,i-c)<=0?{showTop:!1,showBottom:!1}:{showTop:o>n,showBottom:Math.max(0,i-o-c)>a}}function gf(e){return bf({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function wr(e,t=li){return!!e&&e.fromBottom>=t}function yf(e,t){return Un(e,t)?!wr(e):!0}function vf({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function wf({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function La(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function Ld(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function jf(e,t,r){return Number(e.receivedAt||r[Gn(e,t)]||0)||0}function Pd(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function kf(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function ar(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 Pa(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 cn(e,t,r){return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2 text-sm",role:"note",children:[s.jsx("span",{className:"font-medium",children:e}),t?s.jsx("span",{className:"ml-1 break-all",children:t}):null,r?s.jsx("div",{className:"mt-1 opacity-80",style:{whiteSpace:"pre-wrap"},children:r}):null]})}function ml(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Pd(e)?s.jsx(ei,{remarkPlugins:_d,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}const Nf=l.memo(function({content:t,renderAsPreformatted:r,renderAsMarkdown:n}){return r?s.jsx("pre",{className:"chat-preformatted",children:t}):n?s.jsx(ei,{remarkPlugins:_d,children:t}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:t})});function or({parts:e,renderAsPreformatted:t}){return s.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return s.jsx("div",{children:ml(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=Pa(r),o=r.alt||r.description||ar(r.uri,"image");return a?s.jsx("img",{src:a,alt:o,className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):s.jsx("div",{children:cn("Image",o,r.mimeType)},`image-fallback-${n}`)}if(r.type==="audio"){const a=Pa(r);return a?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("audio",{controls:!0,src:a,className:"max-w-full"}),r.transcript?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:r.transcript}):null]},`audio-${n}`):s.jsx("div",{children:cn("Audio",ar(r.uri,"audio"),r.transcript||r.mimeType)},`audio-fallback-${n}`)}if(r.type==="video"){const a=Pa(r),o=r.title||r.name||r.alt||ar(r.uri,"video"),i=[r.transcript,r.description,r.mimeType].filter(Boolean).join(`
3
+ `);return s.jsxs("div",{className:"flex flex-col gap-1",children:[a?s.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):cn("Video",o,i),a&&i?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:i}):null]},`video-${n}`)}if(r.type==="resource_link"){const a=r.title||r.name||ar(r.uri,"resource"),o=[r.description,r.mimeType].filter(Boolean).join(`
4
+ `);return s.jsxs("div",{className:"flex flex-col gap-1",children:[r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",download:!0,className:"underline break-all",children:a}):cn("Resource",a,o),r.uri&&o?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:o}):null]},`resource-link-${n}`)}if(r.type==="resource"&&r.resource){const a=ar(r.resource.uri,"resource");if(r.resource.text)return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[s.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),ml(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return s.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${n}`)}return null})})}function Gn(e,t){const r=e,n=si(e.content,{joiner:`
5
+ `});return[e.id?`id:${e.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",e.role?`role:${e.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${t}`].filter(Boolean).join("|")}const Sf=l.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(ei,{remarkPlugins:mf,children:t.text}),s.jsx("span",{className:"action-time",children:Ld(t.timestamp)})]})},(e,t)=>e.log===t.log);function hl(e){const t=e.meta;return[bd(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 Cf=l.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:i,onToggleTextExpanded:c}){var S,I,$;const d=(t.role||"").toLowerCase(),p=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),m=ii(t),h=kf(t.content)?t.content:null,b=!!(h!=null&&h.some(R=>R.type!=="text")),g=si(t.content,{joiner:`
6
+ `});if(m.isActivityFacing&&u!=="thought"&&u!=="tool"&&u!=="terminal"){const R=m.label||"Activity";return s.jsxs("div",{className:"self-start chat-msg-activity","data-chat-activity-row":"true",children:[s.jsxs("div",{className:"chat-msg-activity-meta","aria-label":"Activity message",children:[s.jsx("span",{className:"activity-dot"}),s.jsx("span",{children:R})]}),b&&h?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(or,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:g})]})}if(u==="thought"){const R=typeof((S=t.meta)==null?void 0:S.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(Uh,{size:13}),s.jsx("span",{children:R})]}),s.jsx("div",{className:"chat-msg-body",children:g})]})}if(u==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-tool-meta","aria-label":"Tool message",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),s.jsx("span",{className:"tool-label",children:"Tool"})]}),b&&h?s.jsx("div",{className:"tool-text w-full",children:s.jsx(or,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:g})]});if(u==="terminal"){const R=(I=t.meta)!=null&&I.isRunning?"⏳":"✅",_=typeof(($=t.meta)==null?void 0:$.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:R}),s.jsx("span",{children:_})]}),b&&h?s.jsx("div",{className:"chat-msg-body",children:s.jsx(or,{parts:h,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:g})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:b&&h?s.jsx(or,{parts:h,renderAsPreformatted:!1}):g.slice(0,100)});const f=t.meta,N=(typeof(f==null?void 0:f.renderMode)=="string"?f.renderMode.trim():"")==="preformatted",y=g,v=!1,k=y,w=N,x=!p&&!w&&Pd(k),C=["chat-message-row",p?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:C,children:(y||b||p)&&s.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${y||b?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:p?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:Ld(r)})]}),(y||b)&&s.jsx("div",{className:"chat-markdown",children:b&&h?s.jsx(or,{parts:h,renderAsPreformatted:w}):s.jsx(Nf,{content:k,renderAsPreformatted:w,renderAsMarkdown:x})}),v]})})},(e,t)=>(e.message===t.message||hl(e.message)===hl(t.message))&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),If=l.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:o=!1,isWorking:i=!1,contextKey:c="",receivedAtMap:d={},lastMessageHash:p,showActivityMessages:u=!1,emptyState:m,onLoadMore:h,isLoadingMore:b,hasMoreHistory:g,hiddenLiveCount:f=0,loadError:j,scrollToBottomRequestNonce:N,isVisible:y=!0},v){const k=l.useRef(null),w=l.useRef(null),x=l.useRef(null),C=l.useRef(0),S=l.useRef(""),I=l.useRef(""),$=l.useRef(!1),R=l.useRef(null),_=l.useRef(!1),P=l.useRef(null),F=l.useRef(!1),[q,A]=l.useState(new Set),[T,B]=l.useState({showTop:!1,showBottom:!1}),D=l.useRef(!1),M=l.useRef(!1),E=l.useRef(y),z=l.useRef(y),Q=l.useRef(null);z.current=y;const J=()=>{const X=k.current;return X?X.scrollHeight-X.scrollTop-X.clientHeight<li:!0},ae=l.useCallback(()=>{const X=k.current,L=X?gf(X):{showTop:!1,showBottom:!1};B(ue=>ue.showTop===L.showTop&&ue.showBottom===L.showBottom?ue:L)},[]),ne=l.useCallback((X="auto")=>{var ue;const L=k.current;L&&(L.scrollTo({top:L.scrollHeight,behavior:X}),(ue=L.ownerDocument.defaultView)==null||ue.requestAnimationFrame(()=>ae()))},[ae]),ce=l.useCallback((X="auto")=>{var ue;const L=k.current;L&&(L.scrollTo({top:0,behavior:X}),(ue=L.ownerDocument.defaultView)==null||ue.requestAnimationFrame(()=>ae()))},[ae]),be=l.useCallback(()=>{var le;const X=k.current,L=(le=window.getSelection)==null?void 0:le.call(window);if(!X||!L||L.rangeCount===0||L.isCollapsed){F.current=!1;return}const ue=L.anchorNode,H=L.focusNode;F.current=!!(ue&&H&&X.contains(ue)&&X.contains(H))},[]),Z=l.useMemo(()=>{const X=uf(t),L=Ad(t);return pf(X,L,u)},[t,u]),Y=Z.length===t.length?p:void 0,ve=ff(Z,Y),ye=l.useCallback(()=>{const X=k.current;if(!X||!c||!z.current)return;const L={top:X.scrollTop,fromBottom:Math.max(0,X.scrollHeight-X.scrollTop-X.clientHeight),messageFingerprint:ve};Q.current={contextKey:c,snapshot:L},nr.set(c,L)},[c,ve]),xe=l.useCallback((X="auto")=>{R.current!=null&&cancelAnimationFrame(R.current),R.current=requestAnimationFrame(()=>{R.current=null,ne(X)})},[ne]),Se=l.useCallback(()=>{D.current=!1,_.current=!0,M.current=!0,P.current!=null&&window.clearTimeout(P.current),P.current=window.setTimeout(()=>{_.current=!1,P.current=null},pl)},[]);l.useEffect(()=>{const X=!$.current,L=I.current!==c;if(I.current=c,X||L){$.current=!0;const H=c?nr.get(c):null,le=!!H&&Un(H,ve);D.current=le?wr(H):!1,_.current=yf(H,ve),F.current||(le?requestAnimationFrame(()=>{const G=k.current;G&&(La(G,H),D.current=wr(H),ae(),M.current=!0)}):xe("auto")),C.current=Z.length,S.current=ve;return}Z.length>C.current;const ue=ve!==S.current;vf({hasSelection:F.current,userScrolledUp:D.current,hasChatContentChanged:ue})&&xe("auto"),C.current=Z.length,S.current=ve},[ve,c,Z.length,xe,ae]),l.useEffect(()=>{N&&(Se(),F.current||xe("auto"))},[Se,xe,N]),l.useEffect(()=>{const X=E.current;X&&!y&&ye(),z.current=y,E.current=y;const L=c?nr.get(c):null;if(xf(X,y,L,ve)){if(!L)return;D.current=wr(L),_.current=!1,F.current||requestAnimationFrame(()=>{const ue=k.current;ue&&(La(ue,L),ae())});return}},[y,c,ve,Se,ye,xe,ae]),l.useEffect(()=>()=>{const X=Q.current;X&&nr.set(X.contextKey,X.snapshot),R.current!=null&&cancelAnimationFrame(R.current),P.current!=null&&window.clearTimeout(P.current)},[]),l.useEffect(()=>{const X=w.current,L=k.current;if(!X||!L)return;const ue=()=>{P.current!=null&&window.clearTimeout(P.current),P.current=window.setTimeout(()=>{_.current=!1,P.current=null},pl)},H=new ResizeObserver(()=>{ae();const le=_.current;wf({hasSelection:F.current,userScrolledUp:D.current,contextAutoScrollActive:le})&&(xe("auto"),le&&ue())});return H.observe(X),L!==X&&H.observe(L),()=>{H.disconnect(),P.current!=null&&(window.clearTimeout(P.current),P.current=null)}},[xe,c,ae]),l.useImperativeHandle(v,()=>({scrollToBottom:(X="smooth")=>{ne(X)}}),[ne]),l.useEffect(()=>{const X=k.current;if(!X)return;let L;const ue=()=>{ye(),clearTimeout(L),L=setTimeout(()=>{D.current=!J(),ae()},50)};return X.addEventListener("scroll",ue,{passive:!0}),()=>{X.removeEventListener("scroll",ue),clearTimeout(L)}},[ye,ae]),l.useEffect(()=>(document.addEventListener("selectionchange",be),()=>document.removeEventListener("selectionchange",be)),[be]);const ie=l.useRef(0),we=l.useRef(!1);l.useEffect(()=>{const X=k.current;if(!X||!we.current||ie.current===0)return;const L=X.scrollHeight-ie.current;L>0&&(X.scrollTop=L),ae(),ye(),ie.current=0,we.current=!1},[Z.length,ye,ae]),l.useEffect(()=>{if(M.current||!c)return;const X=nr.get(c),L=k.current;if(!(!X||!L)){if(!Un(X,ve)){ne("auto"),M.current=!0;return}La(L,X),D.current=wr(X),ae(),M.current=!0}},[c,ve,Z.length,ne,ae]);const pe=()=>{const X=k.current;X&&(ie.current=X.scrollHeight),we.current=!0,h==null||h()},W=()=>{D.current=!0,ce("smooth"),ye()},O=()=>{Se(),ne("smooth"),ye()},V=l.useMemo(()=>{const X=Z.map((le,G)=>({type:"message",data:le,index:G,ts:jf(le,G,d)}));if(!r||r.length===0)return X;const L=[...r].sort((le,G)=>le.timestamp-G.timestamp).map((le,G)=>({type:"action",data:le,index:G,ts:le.timestamp})),ue=[];let H=0;for(const le of X){for(;H<L.length&&le.ts>0&&L[H].ts<le.ts;)ue.push(L[H++]);ue.push(le)}for(;H<L.length;)ue.push(L[H++]);return ue},[Z,r,d]),oe=f>0||!!g,te=f>0?`↑ Show ${Math.min(f,80)} earlier messages${f>80?` (${f} hidden)`:""}`:j?`↻ ${j}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:k,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:w,className:"chat-container-content",children:[b&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),oe&&!b&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:pe,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${j&&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:te})}),V.length===0&&!oe&&(m||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),V.map(X=>{if(X.type==="action"){const Te=X.data;return s.jsx(Sf,{log:Te},`action-${X.index}`)}const L=X.data,ue=X.index,H=Gn(L,ue),le=L.receivedAt||d[H],G=`${c}-${H}`,Le=q.has(G);return s.jsx(Cf,{message:L,receivedAt:le,agentName:n,userName:a,isCliMode:o,isTextExpanded:Le,onToggleTextExpanded:()=>A(Te=>{const Me=new Set(Te);return Le?Me.delete(G):Me.add(G),Me})},`msg-${H}`)}),i&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),s.jsx("div",{className:"min-h-10",ref:x})]})}),(T.showTop||T.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[T.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:W,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),T.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:O,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Mf=l.memo(If,(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),Af="modulepreload",Tf=function(e){return"/"+e},fl={},_f=function(t,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),c=(i==null?void 0:i.nonce)||(i==null?void 0:i.getAttribute("nonce"));a=Promise.allSettled(r.map(d=>{if(d=Tf(d),d in fl)return;fl[d]=!0;const p=d.endsWith(".css"),u=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const m=document.createElement("link");if(m.rel=p?"stylesheet":Af,p||(m.as="script"),m.crossOrigin="",m.href=d,c&&m.setAttribute("nonce",c),document.head.appendChild(m),p)return new Promise((h,b)=>{m.addEventListener("load",h),m.addEventListener("error",()=>b(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return a.then(i=>{for(const c of i||[])c.status==="rejected"&&o(c.reason);return t().catch(o)})};let xl=!1;const Rd=l.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:o="measured"},i)=>{const c=l.useRef(null),[d,p]=l.useState(null),u=l.useRef([]),m=l.useRef(!1),h=l.useRef(!1),b=l.useRef(!1),g=l.useRef(!1),f=()=>{const j=c.current;if(j){m.current&&(j.clear(),m.current=!1);for(const N of u.current)j.write(N.data,N.onProcessed);u.current=[],h.current&&(j.fit(),h.current=!1),b.current&&(j.bumpResize(),b.current=!1),g.current&&(j.scrollToTop(),g.current=!1)}};return l.useImperativeHandle(i,()=>({write:(j,N)=>{c.current?c.current.write(j,N):u.current.push({data:j,onProcessed:N})},clear:()=>{c.current?c.current.clear():(u.current=[],m.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(u.current=[],m.current=!0)},resize:(j,N)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(j,N)},fit:()=>{c.current?c.current.fit():h.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():b.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():g.current=!0},getSelection:()=>{var j,N;return((N=(j=c.current)==null?void 0:j.getSelection)==null?void 0:N.call(j))||""},getVisibleText:()=>{var j,N;return((N=(j=c.current)==null?void 0:j.getVisibleText)==null?void 0:N.call(j))||""}}),[]),l.useEffect(()=>{d&&f()},[d]),l.useEffect(()=>{let j=!1;return _f(()=>import("./terminal-DsCRNxW_.js"),__vite__mapDeps([0,1,2])).then(N=>{xl||(xl=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),j||p(()=>N.GhosttyTerminalView)}).catch(N=>{console.error("[CliTerminal] failed to load terminal renderer",N)}),()=>{j=!0}},[]),d?s.jsx(d,{ref:c,onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:o,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});Rd.displayName="CliTerminal";function dn({label:e,value:t,sub:r,icon:n}){return s.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsx("span",{className:"text-base flex items-center",children:n}),s.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),s.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:t}),r&&s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function bl({value:e,max:t,label:r,color:n="#8b5cf6",detail:a,compact:o=!1}){const i=t>0?Math.min(Math.round(e/t*100),100):0,c=i>85?"#ef4444":i>60?"var(--status-warning)":n;return o?s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-0.5",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),s.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[i,"%"]})]}),s.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${i}%`,background:c}})})]}):s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-1.5",children:[s.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),s.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[i,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${i}%`,background:`linear-gradient(90deg, ${c}, ${c}cc)`}})}),a&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function Lf({cursorPos:e,viewportRef:t,imgRef:r}){var y;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(y=t.current)==null?void 0:y.getBoundingClientRect();if(!o)return null;const i=n.naturalWidth||a.width,c=n.naturalHeight||a.height,d=i/c,p=a.width/a.height;let u,m,h,b;d>p?(u=a.width,m=a.width/d,h=0,b=(a.height-m)/2):(m=a.height,u=a.height*d,h=(a.width-u)/2,b=0);const g=a.left-o.left+h+u*e.nx,f=a.top-o.top+b+m*e.ny,j=Math.max(8,Math.min(o.width-8,g)),N=Math.max(8,Math.min(o.height-8,f));return s.jsxs("div",{style:{position:"absolute",left:j-8,top:N-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[s.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function Pf({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:i,setImeText:c,handleImeSubmit:d,isConnActive:p,zoom:u,isMobile:m,mobileFillZoom:h,onZoomOut:b,onZoomReset:g,onZoomIn:f,transportType:j,screenshotUsage:N,lastActionStatus:y}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:v=>v.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[s.jsxs("div",{onClick:t,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{n(v=>!v),o(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&s.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:s.jsx("input",{type:"text",placeholder:"Type & Enter...",value:i,autoFocus:!0,onTouchStart:v=>v.stopPropagation(),onChange:v=>c(v.target.value),onKeyDown:v=>{d(v)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{o(v=>!v),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:p?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:p?"#22c55e":"#eab308",boxShadow:p?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:p?"#22c55e":"#eab308"},children:p?"Connected":"WS"})]}),u>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),j==="direct"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),j==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),N&&N.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:N.budgetExhausted?"#ef4444":"#c4b5fd",background:N.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:N.budgetExhausted?"TURN blocked":`TURN ${N.dailyUsedMinutes}/${N.dailyBudgetMinutes}m`}),y&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:y})]})]}),a&&s.jsxs("div",{onTouchStart:v=>v.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",u<=(m?h:1)+.01?m?"FILL":"FIT":`${Math.round(u*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:v=>{v.stopPropagation(),b()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:v=>{v.stopPropagation(),g()},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:m?"FILL":"FIT"}),s.jsx("button",{onClick:v=>{v.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 Rf({waitingLabel:e,waitingHint:t,transportType:r}){return s.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[s.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-white/10 bg-white/[0.04] shadow-[0_10px_30px_rgba(0,0,0,0.35)]",style:{animation:"remote-float 2.8s ease-in-out infinite"},children:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),s.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),s.jsx("div",{className:"text-[11px] text-white/40",children:t}),r==="relay"&&s.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function Df(){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 gl(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 Wr(e,t){const r=l.useRef(null),n=l.useRef(0);l.useEffect(()=>{if(!Df())return;n.current+=1;const a=r.current;if(!a){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([i,c])=>[i,gl(c)]))}),r.current=t;return}const o=Object.keys({...a,...t}).filter(i=>!Object.is(a[i],t[i]));o.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:o,snapshot:Object.fromEntries(o.map(i=>[i,gl(t[i])]))}),r.current=t})}function $f({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:i,panXRef:c,panYRef:d,setPanX:p,setPanY:u,setZoom:m,lastWheelTimeRef:h,onAction:b,setLastActionStatus:g,spawnRippleFromNormalized:f,clampPan:j,isMobile:N,mobileFillZoom:y}){const[v,k]=l.useState(null),w=l.useRef(null),x=l.useRef(null),C=l.useRef(null),S=l.useRef(!1),I=l.useRef(null),$=l.useRef(0),R=l.useRef(null),_=l.useRef(1),P=l.useRef({x:0,y:0}),F=l.useRef(!1),q=l.useRef(n),A=l.useRef(b),T=30,B=550,D=18,M=60,E=400,z=12,Q=()=>{if(w.current)return;const ne={nx:.5,ny:.5};w.current=ne,k(ne)};return l.useEffect(()=>{q.current=n,n==="mouse"&&Q()},[n]),l.useEffect(()=>{A.current=b},[b]),l.useEffect(()=>{const ne=e.current;if(!ne)return;const ce=xe=>{if(!r.current)return null;const Se=r.current.getBoundingClientRect();return!Se.width||!Se.height?null:{nx:Math.max(0,Math.min(1,(xe.clientX-Se.left)/Se.width)),ny:Math.max(0,Math.min(1,(xe.clientY-Se.top)/Se.height))}},be=(xe,Se)=>{if(!r.current)return{dnx:0,dny:0};const ie=r.current,we=ie.getBoundingClientRect(),pe=ie.naturalWidth||we.width,W=ie.naturalHeight||we.height,O=pe/W,V=we.width/we.height;let oe,te;return O>V?(oe=we.width,te=we.width/O):(te=we.height,oe=we.height*O),{dnx:xe/oe,dny:Se/te}},Z=(xe,Se,ie)=>{if(ie<=1.05)return;const we=-(xe-.5)*100,pe=-(Se-.5)*100,W=j(we,pe,ie);(Math.abs(W.x-c.current)>.1||Math.abs(W.y-d.current)>.1)&&(p(W.x),u(W.y),c.current=W.x,d.current=W.y)},Y=xe=>{const Se=t.current;if(Se&&xe.target instanceof Node&&Se.contains(xe.target))xe.preventDefault();else return;if(xe.touches.length===1){const ie=xe.touches[0];x.current={x:ie.clientX,y:ie.clientY,time:Date.now()},C.current={x:ie.clientX,y:ie.clientY},F.current||(S.current=!1),I.current=setTimeout(()=>{if(!S.current&&!F.current)if(S.current=!0,q.current==="mouse"){const we=w.current||{nx:.5,ny:.5};g("Right Click"),f(we.nx,we.ny,"right"),A.current("input_click",{...we,button:"right"}).catch(()=>{})}else{const we=ce(ie);we&&(g("Right Click"),f(we.nx,we.ny,"right"),A.current("input_click",{...we,button:"right"}).catch(()=>{}))}},500);return}if(xe.touches.length===2){I.current&&clearTimeout(I.current),S.current=!0,F.current=!0;const ie=xe.touches[1].clientX-xe.touches[0].clientX,we=xe.touches[1].clientY-xe.touches[0].clientY;R.current=Math.sqrt(ie*ie+we*we),_.current=i.current,P.current={x:(xe.touches[0].clientX+xe.touches[1].clientX)/2,y:(xe.touches[0].clientY+xe.touches[1].clientY)/2}}},ve=xe=>{const Se=t.current;if(Se&&xe.target instanceof Node&&Se.contains(xe.target)&&xe.preventDefault(),xe.touches.length===1&&C.current){const ie=xe.touches[0],we=ie.clientX-C.current.x,pe=ie.clientY-C.current.y;if(!S.current&&x.current){const W=ie.clientX-x.current.x,O=ie.clientY-x.current.y;Math.sqrt(W*W+O*O)>8&&(S.current=!0,I.current&&clearTimeout(I.current))}if(S.current)if(q.current==="mouse"){const W=be(we,pe),O=w.current||{nx:.5,ny:.5},V=Math.max(0,Math.min(1,O.nx+W.dnx)),oe=Math.max(0,Math.min(1,O.ny+W.dny));w.current={nx:V,ny:oe},k({nx:V,ny:oe}),g(`Cursor: ${Math.round(V*100)}%, ${Math.round(oe*100)}%`),Z(V,oe,i.current);const te=Date.now();te-h.current>=30&&(h.current=te,A.current("input_mouseMoved",{nx:V,ny:oe}).catch(()=>{}))}else if(i.current>1){const W=t.current;if(W){const O=W.clientWidth,V=W.clientHeight,oe=c.current+we/O*100,te=d.current+pe/V*100,X=j(oe,te,i.current);p(X.x),u(X.y),c.current=X.x,d.current=X.y}}else{const W=ce(ie);if(W){const O=Date.now();O-h.current>=40&&(h.current=O,g("Scroll"),A.current("input_wheel",{nx:W.nx,ny:W.ny,deltaX:Math.round(-we*2.5),deltaY:Math.round(-pe*2.5)}).catch(()=>{}))}}C.current={x:ie.clientX,y:ie.clientY};return}if(xe.touches.length===2&&R.current!==null){const ie=xe.touches[1].clientX-xe.touches[0].clientX,we=xe.touches[1].clientY-xe.touches[0].clientY,W=Math.sqrt(ie*ie+we*we)/R.current,O=(xe.touches[0].clientX+xe.touches[1].clientX)/2,V=(xe.touches[0].clientY+xe.touches[1].clientY)/2,oe=O-P.current.x,te=V-P.current.y,X=Math.abs(W-1)>.03;if(q.current==="mouse"){if(X){const L=Math.max(o,Math.min(5,_.current*W));m(L),i.current=L}else if(Math.abs(oe)>2||Math.abs(te)>2){const L=w.current||{nx:.5,ny:.5},ue=Date.now();ue-h.current>=30&&(h.current=ue,g("Scroll"),A.current("input_wheel",{nx:L.nx,ny:L.ny,deltaX:Math.round(-oe*3),deltaY:Math.round(-te*3)}).catch(()=>{}))}}else{const L=Math.max(o,Math.min(5,_.current*W));m(L),i.current=L;const ue=t.current;if(ue&&L>1){const H=ue.clientWidth,le=ue.clientHeight,G=c.current+oe/H*100,Le=d.current+te/le*100,Te=j(G,Le,L);p(Te.x),u(Te.y),c.current=Te.x,d.current=Te.y}}P.current={x:O,y:V}}},ye=xe=>{var Se;if(I.current&&clearTimeout(I.current),R.current=null,xe.touches.length===1&&F.current){const ie=xe.touches[0];x.current={x:ie.clientX,y:ie.clientY,time:Date.now()},C.current={x:ie.clientX,y:ie.clientY},S.current=!0;return}if(xe.touches.length===0){if(F.current){F.current=!1,S.current=!1;return}if(xe.changedTouches.length===1){const ie=xe.changedTouches[0],we=Date.now(),pe=we-(((Se=x.current)==null?void 0:Se.time)||0),W=x.current?ie.clientX-x.current.x:0,O=x.current?ie.clientY-x.current.y:0,V=Math.sqrt(W*W+O*O);if(q.current==="mouse"){if(pe<T||pe>B||V>D){S.current=!1;return}const oe=w.current||ce(ie);oe&&(g(`Click: ${Math.round(oe.nx*100)}%, ${Math.round(oe.ny*100)}%`),f(oe.nx,oe.ny,"left"),A.current("input_click",{...oe}).catch(()=>{}))}else{if(S.current){S.current=!1;return}if(pe<M||pe>E||V>z){S.current=!1;return}const oe=ce(ie);if(!oe)return;we-$.current<300?(g("Double tap"),f(oe.nx,oe.ny,"double"),A.current("input_click",{...oe,clickCount:2}).catch(()=>{}),$.current=0):(g(`Tap: ${Math.round(oe.nx*100)}%, ${Math.round(oe.ny*100)}%`),f(oe.nx,oe.ny,"left"),A.current("input_click",{...oe}).catch(()=>{}),$.current=we)}}S.current=!1}};return ne.addEventListener("touchstart",Y,{passive:!1}),ne.addEventListener("touchmove",ve,{passive:!1}),ne.addEventListener("touchend",ye,{passive:!1}),()=>{ne.removeEventListener("touchstart",Y),ne.removeEventListener("touchmove",ve),ne.removeEventListener("touchend",ye),I.current&&clearTimeout(I.current)}},[e,t,r,o,i,c,d,p,u,m,h,g,f,j]),{cursorPos:v,cursorPosRef:w,handleToggleInputMode:()=>{a(ne=>{const ce=ne==="touch"?"mouse":"touch";return ce==="mouse"&&Q(),ce})},handleZoomReset:()=>{const ne=N?y:1;m(ne),i.current=ne,p(0),u(0),c.current=0,d.current=0}}}function Dd({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:o}){const i=l.useRef(null),c=l.useRef(null),d=l.useRef(null),[p,u]=l.useState(null),[m,h]=l.useState(""),[,b]=l.useState(!1),[g,f]=l.useState([]),j=l.useRef(0),[N,y]=l.useState(!1),[v,k]=l.useState(!1),w=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[x,C]=l.useState(w?"mouse":"touch"),[S,I]=l.useState(1),$=l.useRef(!1),[R,_]=l.useState(1),[P,F]=l.useState(0),[q,A]=l.useState(0);Wr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:x,zoom:R,panX:P,panY:q,isMenuOpen:N,isImeOpen:v});const T=l.useRef(0),B=l.useRef(R),D=l.useRef(P),M=l.useRef(q);l.useEffect(()=>{B.current=R},[R]),l.useEffect(()=>{D.current=P},[P]),l.useEffect(()=>{M.current=q},[q]),l.useEffect(()=>{var pe;(pe=i.current)==null||pe.focus()},[]);const E=r==="connected",z=n,Q=E?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",J=E?"The remote stream is warming up":"Waiting for the remote stream to catch up";l.useEffect(()=>{if(!w||$.current||!z)return;const pe=d.current,W=c.current;if(!pe||!W)return;const O=()=>{const V=W.clientWidth,oe=W.clientHeight,te=pe.naturalWidth,X=pe.naturalHeight;if(!te||!X||!V||!oe)return;const L=Math.min(V/te,oe/X),H=Math.max(V/te,oe/X)/L;H>1.01&&(I(H),_(H),B.current=H),$.current=!0};pe.complete&&pe.naturalWidth?O():pe.addEventListener("load",O,{once:!0})},[z,w]);const ae=.5;l.useEffect(()=>{R<=ae&&(F(0),A(0))},[R,ae]);const ne=(pe,W,O)=>{if(O<=ae)return{x:0,y:0};const V=(O-1)/(2*O)*100,oe=(O-1)/(2*O)*100;return{x:Math.max(-V,Math.min(V,pe)),y:Math.max(-oe,Math.min(oe,W))}},ce=(pe,W)=>{if(!d.current)return null;const O=d.current.getBoundingClientRect();return!O.width||!O.height?null:{nx:Math.max(0,Math.min(1,(pe-O.left)/O.width)),ny:Math.max(0,Math.min(1,(W-O.top)/O.height))}},be=(pe,W,O)=>{const V=c.current;if(!V)return;const oe=V.getBoundingClientRect(),te=++j.current;f(X=>[...X,{id:te,x:pe-oe.left,y:W-oe.top,type:O}]),setTimeout(()=>f(X=>X.filter(L=>L.id!==te)),600)},Z=(pe,W,O)=>{const V=d.current,oe=c.current;if(!V||!oe)return;const te=V.getBoundingClientRect(),X=oe.getBoundingClientRect(),L=V.naturalWidth||te.width,ue=V.naturalHeight||te.height,H=L/ue,le=te.width/te.height;let G,Le,Te,Me;H>le?(G=te.width,Le=te.width/H,Te=0,Me=(te.height-Le)/2):(Le=te.height,G=te.height*H,Te=(te.width-G)/2,Me=0);const He=te.left-X.left+Te+G*pe,qe=te.top-X.top+Me+Le*W,Je=++j.current;f(st=>[...st,{id:Je,x:He,y:qe,type:O}]),setTimeout(()=>f(st=>st.filter(Xe=>Xe.id!==Je)),600)},Y=async pe=>{var O;const W=ce(pe.clientX,pe.clientY);if(W){u(`Click: ${Math.round(W.nx*100)}%, ${Math.round(W.ny*100)}%`),be(pe.clientX,pe.clientY,"left"),(O=i.current)==null||O.focus();try{const V=await e("input_click",{nx:W.nx,ny:W.ny});V!=null&&V.success||t(`❌ Click failed: ${V==null?void 0:V.error}`)}catch(V){t(`❌ Click error: ${V.message||V}`)}}},ve=async(pe,W,O,V=0)=>{try{await e("input_key",{type:O?"char":"keyDown",key:pe,code:W,text:O?pe:void 0,unmodifiedText:O?pe:void 0,modifiers:V})}catch(oe){t(`❌ Key error: ${oe.message||oe}`)}},ye=async pe=>{if(pe.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(pe.key)&&pe.preventDefault();let O=0;pe.altKey&&(O|=1),pe.ctrlKey&&(O|=2),pe.metaKey&&(O|=4),pe.shiftKey&&(O|=8),u(`Key: ${pe.key}`),await ve(pe.key,pe.code,pe.key.length===1,O)},xe=async pe=>{if(pe.key==="Enter"){if(pe.nativeEvent.isComposing)return;if(m){const W=m;h(""),u(`IME Sent: ${W}`);try{const O=await e("input_type",{text:W});O!=null&&O.success||t(`❌ IME error: ${O==null?void 0:O.error}`)}catch(O){t(`❌ IME error: ${O.message}`)}}else u("Key: Enter"),await ve("Enter","Enter",!1)}};l.useEffect(()=>{const pe=i.current;if(!pe)return;const W=O=>{var V;if((V=d.current)!=null&&V.contains(O.target)){O.preventDefault();const oe=Date.now();if(oe-T.current<40)return;T.current=oe;const te=ce(O.clientX,O.clientY);if(!te)return;u(`Scroll: ${Math.round(O.deltaY)}`),e("input_wheel",{nx:te.nx,ny:te.ny,deltaX:Math.round(O.deltaX),deltaY:Math.round(O.deltaY)}).catch(()=>{})}};return pe.addEventListener("wheel",W,{passive:!1}),()=>pe.removeEventListener("wheel",W)},[e]);const{cursorPos:Se,handleToggleInputMode:ie,handleZoomReset:we}=$f({containerRef:i,viewportRef:c,imgRef:d,inputMode:x,setInputMode:C,minZoom:ae,zoomRef:B,panXRef:D,panYRef:M,setPanX:F,setPanY:A,setZoom:_,lastWheelTimeRef:T,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:Z,clampPan:ne,isMobile:w,mobileFillZoom:S});return s.jsxs("div",{ref:i,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ye,onContextMenu:pe=>pe.preventDefault(),onFocus:()=>b(!0),onBlur:()=>b(!1),tabIndex:0,children:[s.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[z?s.jsx("img",{ref:d,src:z,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${R}) translate(${P}%, ${q}%)`,transformOrigin:"center center",cursor:x==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:Y,onContextMenu:pe=>pe.preventDefault(),onDragStart:pe=>pe.preventDefault()}):s.jsx(Rf,{waitingLabel:Q,waitingHint:J,transportType:o}),x==="mouse"&&z&&s.jsx(Lf,{cursorPos:Se,viewportRef:c,imgRef:d}),g.map(pe=>{const O={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[pe.type];return s.jsxs("div",{style:{position:"absolute",left:pe.x,top:pe.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${O}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),s.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${O}, 0.9)`,boxShadow:`0 0 12px rgba(${O}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},pe.id)})]}),s.jsx(Pf,{inputMode:x,onToggleInputMode:ie,isImeOpen:v,setIsImeOpen:k,isMenuOpen:N,setIsMenuOpen:y,imeText:m,setImeText:h,handleImeSubmit:xe,isConnActive:E,zoom:R,isMobile:w,mobileFillZoom:S,onZoomOut:()=>_(pe=>Math.max(.5,pe-.25)),onZoomReset:we,onZoomIn:()=>_(pe=>Math.min(5,pe+.25)),transportType:o,screenshotUsage:a,lastActionStatus:p}),s.jsx("style",{children:`
7
+ @keyframes slideUp {
8
+ from { opacity: 0; transform: translateY(6px); }
9
+ to { opacity: 1; transform: translateY(0); }
10
+ }
11
+ @keyframes slideUpSidebar {
12
+ from { opacity: 0; transform: translateY(6px); }
13
+ to { opacity: 1; transform: translateY(0); }
14
+ }
15
+ @keyframes click-ripple-ring {
16
+ 0% { transform: scale(0.3); opacity: 1; }
17
+ 100% { transform: scale(2.2); opacity: 0; }
18
+ }
19
+ @keyframes click-ripple-dot {
20
+ 0% { transform: scale(1); opacity: 0.9; }
21
+ 50% { transform: scale(1.8); opacity: 0.6; }
22
+ 100% { transform: scale(0.5); opacity: 0; }
23
+ }
24
+ @keyframes remote-float {
25
+ 0% { transform: translateY(0px); }
26
+ 50% { transform: translateY(-7px); }
27
+ 100% { transform: translateY(0px); }
28
+ }
29
+ `})]})}function yl(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 Ef(e){var t;return yl(e.activeInteractivePrompt)||yl((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function Bf(e){return e.sessionId||e.instanceId||e.id}function Ff(e,t){const r=typeof t=="string"?t.trim():"";for(const n of e){const a=Ef(n);if(!a)continue;const o=Bf(n);if(r&&r!==o&&r!==n.id)continue;return{daemonId:n.daemonId||n.id.split(":")[0]||n.id,sessionId:o,routeId:n.id,providerType:n.type,title:n.title||n.cliName||n.type,prompt:a}}return null}function $d(e,t){var n;const r={};for(const a of e.questions){const o=t[a.questionId]||{},i=Array.from(new Set((o.selectedLabels||[]).map(d=>d.trim()).filter(Boolean))),c=(n=o.freeformText)==null?void 0:n.trim();r[a.questionId]={selectedLabels:i,...c?{freeformText:c}:{}}}return{promptId:e.promptId,answers:r}}function vl(e){const t={};for(const r of(e==null?void 0:e.prompt.questions)||[])t[r.questionId]={selectedLabels:[],freeformText:""};return t}function wl(e,t){var r,n;return!!((r=t==null?void 0:t.freeformText)!=null&&r.trim())||(((n=t==null?void 0:t.selectedLabels)==null?void 0:n.length)||0)>0||e.options.length===0&&e.allowFreeform}function Of({label:e,description:t,selected:r,multiSelect:n,disabled:a,onClick:o}){return s.jsx("button",{type:"button",disabled:a,role:n?"checkbox":"radio","aria-checked":r,onClick:o,className:`w-full text-left rounded-md border px-3 py-2 transition ${r?"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"} ${a?"cursor-not-allowed opacity-60":""}`,children:s.jsxs("span",{className:"flex items-start gap-2",children:[s.jsx("span",{className:`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center border ${n?"rounded-sm":"rounded-full"} ${r?"border-accent-primary bg-accent-primary text-accent-on-primary":"border-border-secondary"}`,children:r?s.jsx(Cd,{size:12}):null}),s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block text-sm font-semibold leading-5",children:e}),t&&s.jsx("span",{className:"mt-0.5 block text-xs leading-5 text-text-muted",children:t})]})]})})}function Ed({promptSession:e,isSubmitting:t=!1,error:r,onSubmit:n,onCancel:a}){var C;const[o,i]=l.useState(()=>vl(e)),[c,d]=l.useState(0);l.useEffect(()=>{i(vl(e)),d(0)},[e==null?void 0:e.prompt.promptId]);const p=(e==null?void 0:e.prompt.questions)||[],u=p.length,m=c===u-1,h=u===1,b=p[c],g=b?o[b.questionId]:void 0,f=b?wl(b,g):!1,j=l.useMemo(()=>e?e.prompt.questions.every(S=>wl(S,o[S.questionId])):!1,[e,o]);if(!e)return null;const N=(S,I)=>{i($=>{const R=$[S.questionId]||{selectedLabels:[]},_=R.selectedLabels||[],P=S.multiSelect?_.includes(I)?_.filter(F=>F!==I):[..._,I]:[I];return{...$,[S.questionId]:{...R,selectedLabels:P}}})},y=(S,I)=>{i($=>({...$,[S]:{...$[S]||{selectedLabels:[]},freeformText:I}}))},v=()=>{c<u-1&&d(S=>S+1)},k=()=>{c>0&&d(S=>S-1)},w=()=>{!j||t||n(o)},x=$d(e.prompt,o);return s.jsx("div",{className:"fixed inset-0 z-[80] flex items-center justify-center bg-black/50 px-4 py-6",children:s.jsxs("div",{className:"w-full max-w-2xl overflow-hidden rounded-lg border border-border-primary bg-surface-primary shadow-2xl",children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 border-b border-border-primary px-5 py-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-normal text-status-warning",children:[s.jsx(qs,{size:15})," Action Required"]}),s.jsx("h2",{className:"mt-1 text-lg font-bold text-text-primary",children:e.title||e.providerType})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[!h&&s.jsxs("span",{className:"text-xs text-text-muted",children:[c+1," / ",u]}),s.jsx("button",{type:"button",onClick:a,className:"btn btn-ghost btn-sm h-8 w-8 p-0","aria-label":"Cancel interactive prompt",children:s.jsx(yt,{size:16})})]})]}),!h&&s.jsx("div",{className:"flex gap-1.5 px-5 pt-3",children:p.map((S,I)=>s.jsx("div",{className:`h-1.5 flex-1 rounded-full transition-colors ${I<c?"bg-accent-primary":I===c?"bg-accent-primary/60":"bg-border-primary"}`},S.questionId))}),s.jsxs("div",{className:"space-y-4 px-5 py-4",children:[b&&s.jsxs("section",{className:"space-y-3",children:[s.jsxs("div",{children:[b.header&&s.jsx("div",{className:"mb-1 text-xs font-semibold uppercase tracking-normal text-text-muted",children:b.header}),s.jsxs("div",{className:"text-sm font-semibold text-text-primary",children:[h?"":`${c+1}. `,b.question]}),b.multiSelect&&b.options.length>0&&s.jsx("div",{className:"mt-0.5 text-xs text-text-muted",children:"Select all that apply"})]}),s.jsx("div",{className:"grid gap-2",role:b.multiSelect?"group":"radiogroup","aria-label":b.question,children:b.options.map(S=>{var I;return s.jsx(Of,{label:S.label,description:S.description||S.preview,selected:(((I=x.answers[b.questionId])==null?void 0:I.selectedLabels)||[]).includes(S.label),multiSelect:b.multiSelect,disabled:t,onClick:()=>N(b,S.label)},S.label)})}),b.allowFreeform&&s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-semibold text-text-muted",children:"Other"}),s.jsx("textarea",{value:((C=o[b.questionId])==null?void 0:C.freeformText)||"",disabled:t,onChange:S=>y(b.questionId,S.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"})]})]}),r&&s.jsx("div",{className:"rounded-md border border-status-error/30 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:r})]}),s.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-border-primary px-5 py-4",children:[s.jsx("div",{children:!h&&c>0&&s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:k,disabled:t,children:"Back"})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:a,disabled:t,children:"Cancel"}),h||m?s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:w,disabled:!j||t,children:t?"Submitting...":"Submit"}):s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:v,disabled:!f||t,children:"Next"})]})]})]})})}function fa(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,o=Date.now()-e,i=Math.floor(o/1e3);if(i<a)return n;const c=Math.floor(i/60);if(c<60)return`${c}m${r}`;const d=Math.floor(c/60);if(d<24)return`${d}h${r}`;const p=Math.floor(d/24);return p<7?`${p}d${r}`:new Date(e).toLocaleDateString()}const Bd=e=>fa(e);function zf(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 tr(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating"||e.status==="long_generating"||e.status==="streaming",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function Hf(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...zf(a)})};for(const n of e)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const a of n.childSessions||[])r(a.id,a)}return t}function Vn(e,t){if(e.sessionId){const r=t.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,completionMarker:"",seenCompletionMarker:""}}function xa(e,t,r){const n=Vn(e,t),a=tr(e),o=a.isReconnecting,i=a.isConnecting,c=a.isGenerating,d=a.isWaiting,p=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d,u=n.inboxBucket==="working"||c,h=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:h,requiresAction:p,isWorking:u,isReconnecting:o,isConnecting:i,isGenerating:c,isWaiting:d,inboxBucket:p?"needs_attention":u?"working":h?"task_complete":"idle"}}function Wf(e,t,r){return xa(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Fd({activeConv:e,onModalButton:t}){const[r,n]=l.useState(null);if(l.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!tr(e).isWaiting||!e.modalButtons)return null;const o=c=>{r||(n(c),t(c))},i=c=>c.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return s.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&s.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[s.jsx(qs,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((c,d)=>{const p=i(c).toLowerCase(),u=/^(run|approve|accept|yes|allow|always)/.test(p),m=/^(reject|deny|delete|remove|abort)/.test(p),h=r===c,b=r!==null;return s.jsx("button",{onClick:()=>o(c),disabled:b,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${u?"font-extrabold":m?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${b&&!h?"opacity-40":"opacity-100"} ${b?"cursor-not-allowed":"cursor-pointer"}`,style:u?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:m?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:h?"⏳ ...":i(c)},d)})})]})]})}const ci="adhdev_controls_bar_visible",_o="adhdev:controlsbarvisibilitychange";function Ra(e){if(!e)return!1;try{return e.getItem(ci)==="1"}catch{return!1}}function Kf(e,t){if(t)try{t.setItem(ci,e?"1":"0")}catch{}}function Uf(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(_o,{detail:{visible:e}}))}function di(){const[e,t]=l.useState(()=>typeof window>"u"?!1:Ra(window.localStorage)),r=l.useRef(e),n=l.useCallback((i,c=!0)=>{r.current=i,t(i),typeof window<"u"&&Kf(i,window.localStorage),c&&Uf(i)},[]);l.useEffect(()=>{const i=d=>{const p=d.detail,u=typeof(p==null?void 0:p.visible)=="boolean"?p.visible:Ra(window.localStorage);r.current=u,t(u)},c=d=>{if(d.key!==ci)return;const p=Ra(window.localStorage);r.current=p,t(p)};return window.addEventListener(_o,i),window.addEventListener("storage",c),()=>{window.removeEventListener(_o,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{n(i)},[n]),o=l.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:o}}var Gf=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Vf(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function Dt(e,t){if(Vf(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":r==="waiting_choice"?"waiting_choice":Gf.has(r)?"generating":r==="error"?"error":r==="stopped"?"stopped":r==="starting"?"starting":r==="panel_hidden"?"panel_hidden":r==="not_monitored"?"not_monitored":r==="disconnected"?"disconnected":"idle"}function Lo(e){return Dt(e)==="generating"}function jl(e,t){return Dt(e,t)==="waiting_approval"}function Nt(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function qf(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const r=Math.floor(t/60),n=t%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const a=Math.floor(r/24),o=r%24;return`${a}d ${o}h`}function Da(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Od(e,t){const r=typeof t=="string"?t.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const a=n.replace(/[\\/]+$/,""),o=a.split(/[\\/]/).filter(Boolean);return o[o.length-1]||a}function Yf(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const t=e.split("_"),r=t[t.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function Jf(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Xf(e){return Yf(e.trim().replace(/\.local$/i,""))}function Qf(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function zd(e,t={}){var a,o;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(o=e.system)==null?void 0:o.hostname].find(i=>typeof i=="string"&&i.trim().length>0&&!Jf(i));if(r&&r!=="Unknown")return Xf(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function $t(e,t={}){return Qf(e)||zd(e,t)}function Hd(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 Wd(e,t,r={}){const n=String(t).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(o=>String((o==null?void 0:o.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function Ms(e,t){return Hd(e).join(" · ")}function Dr(e){return e.transport==="pty"}function Ws(e){return e.transport==="acp"}function Zf(e,t){var r,n;return(r=t==null?void 0:t.providerLabels)!=null&&r[e]?t.providerLabels[e]:(n=t==null?void 0:t.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:Nt(e)}function kl(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),i=Nt(r||"").trim().toLowerCase();return n===a||n===o||n===i}function ex(e,t=[],r=[]){var d,p,u,m;const n=Dt(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 a=t.find(h=>jl(h.status,{activeModal:h.activeModal})||Lo(h.status));if(a)return Dt(a.status,{activeModal:a.activeModal});const o=r.find(h=>jl(h.status,{activeModal:h.activeModal})||Lo(h.status));if(o)return Dt(o.status,{activeModal:o.activeModal});if(n&&n!=="idle")return n;const i=Dt((d=t[0])==null?void 0:d.status,{activeModal:(p=t[0])==null?void 0:p.activeModal});if(i!=="idle")return i;const c=Dt((u=r[0])==null?void 0:u.status,{activeModal:(m=r[0])==null?void 0:m.activeModal});return c!=="idle"?c:"idle"}function tx(e){return Dt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function sx(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,r=["generating","waiting_approval","waiting_choice","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),o=t.get(a),i=Dt(n.status);if(!o){t.set(a,{...n,status:i});continue}const c=r.indexOf(o.status||"idle"),d=r.indexOf(i||"idle");d>=0&&(c<0||d<c)&&t.set(a,{...n,status:i})}return Array.from(t.values())}function rx(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 nx(e){var r,n;const t=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return t&&rx(t.receivedAt)||0}function ax(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Po(e){return Math.max(ax(e),nx(e.activeChat))}function ox(e,t,r,n,a,o){const i=t-e;if(i!==0)return i;const c=r.localeCompare(n);return c!==0?c:a.localeCompare(o)}function ui(e,t){return ox(Po(e),Po(t),$t(e,{fallbackId:e.id}),$t(t,{fallbackId:t.id}),e.id,t.id)}const Kd="adhdev_notification_prefs",Nl={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function ix(){try{const e=localStorage.getItem(Kd);if(e){const t=JSON.parse(e);return{...Nl,...t}}}catch{}return{...Nl}}function lx(e){try{localStorage.setItem(Kd,JSON.stringify(e))}catch{}}let ts=ix(),Tn=[];function cx(){Tn.forEach(e=>e())}function dx(e){ts={...ts,...e},lx(ts),cx()}function ux(){const[,e]=l.useState(0);l.useEffect(()=>{const r=()=>e(n=>n+1);return Tn.push(r),()=>{Tn=Tn.filter(n=>n!==r)}},[]);const t=l.useCallback(r=>{dx(r)},[]);return[{...ts},t]}function Sr(e){if(!ts.globalEnabled)return!1;switch(e){case"disconnect":return ts.disconnectAlert;case"completion":return ts.completionAlert;case"approval":return ts.approvalAlert;case"browser":return ts.browserNotifications;default:return!0}}const px={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Ud(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Gd(){return"Notification"in window&&Notification.permission==="granted"}let xs=null;function mx(e){return e!==!1}async function hx(){if(xs!==null)return xs;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return xs=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(xs=!!await e.pushManager.getSubscription(),xs):(xs=!1,!1)}catch{return xs=!1,!1}}function Ro(e,t,r){if(Gd())try{const n=new Notification(e,{body:t,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function fx(e,t={}){const r={...px,...t},n=l.useRef(new Map),a=l.useRef(0),[o,i]=l.useState(null);l.useEffect(()=>{let d=!1;return hx().then(p=>{d||i(p)}),()=>{d=!0}},[]);const c=l.useCallback((d,p,u)=>{const m=Date.now();m-a.current<r.throttleMs||(a.current=m,Ro(d,p,u))},[r.throttleMs]);l.useEffect(()=>{var d;if(!(!r.enabled||!Gd())&&Sr("browser")&&!mx(o)){if(document.hasFocus()){for(const p of e)n.current.set(p.id,Dt(p.status,{activeModal:p.activeModal}));return}for(const p of e){const u=n.current.get(p.id),m=Dt(p.status,{activeModal:p.activeModal}),h=p.name||p.id;if(r.onApproval&&Sr("approval")&&m==="waiting_approval"&&u!=="waiting_approval"){const b=((d=p.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${h} — Approval needed`,b.slice(0,120),`approval-${p.id}`)}r.onComplete&&Sr("completion")&&Lo(u)&&m==="idle"&&c(`✅ ${h} — Task complete`,"Agent has finished generating",`complete-${p.id}`),r.onError&&m==="error"&&u!=="error"&&c(`⚠️ ${h} — Error`,"Agent encountered an error",`error-${p.id}`),n.current.set(p.id,m)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,c])}const xx=/^(run|approve|accept|yes|allow|always)/,bx=/^(run|approve|accept|yes|allow|always|proceed|save)/,gx=/^(reject|deny|delete|remove|abort|cancel|no)/;function pi(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function yx(e){const t=pi(e).toLowerCase();return xx.test(t)?"primary":gx.test(t)?"danger":"default"}function vx(e){return bx.test(pi(e).toLowerCase())?"approve":"reject"}function wx(e){return e.map((t,r)=>({label:pi(t),variant:yx(t),action:vx(t),button:t,buttonIndex:r}))}function jx(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function kx(e,t,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,t,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,t,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class Nx{constructor(){Ke(this,"dedupMap",new Map);Ke(this,"DEDUP_WINDOW_MS",5e3);Ke(this,"DEDUP_MAX_SIZE",50);Ke(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ke(this,"toastCallbacks",[]);Ke(this,"statusEventCallbacks",[]);Ke(this,"resolveActionFn",null);Ke(this,"viewRequestRespondFn",null);Ke(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,o]of this.dedupMap)r-o>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(o=>o.id===t.daemonId&&o.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const o=this.ides.find(i=>i.id===a&&i.type==="adhdev-daemon");if(o)return o}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}handleRawEvent(t,r){var g;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),o=n||t.daemonId||"",i=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),c=`${o}:${t.event}:${i}`;if(this.isDuplicate(c))return;for(const f of this.statusEventCallbacks)f(t);const d=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,p=(d==null?void 0:d.type)||"";let u=Nt(p);const m=this.resolveOwningDaemon(t);if(m){const f=$t(m,{fallbackId:m.id});f&&(u=!p||p==="adhdev-daemon"?f:`${f}/${u}`)}let h="",b="info";if(t.event==="agent:generating_completed"){const f=t.duration?` (${t.duration}s)`:"";h=`✅ ${u} agent task completed${f}`,b="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(h=`⚡ ${u} approval needed`,b="warning",(g=t.modalButtons)!=null&&g.length&&this.resolveActionFn){const f=this.resolveActionRouteTarget(t);if(!f)return;const j=this.resolveActionFn,N=wx(t.modalButtons).map(k=>({label:k.label,variant:k.variant,onClick:()=>{j(f,"resolve_action",{action:k.action,button:k.button,buttonIndex:k.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),y=jx(u,t.modalMessage,h),v=Date.now();this.emitToast({id:v,message:y,type:b,timestamp:v,targetKey:n||f,actions:N,duration:15e3}),h=""}}else if(t.event==="monitor:long_generating"){const f=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";h=`⚠️ ${u} agent is taking a long time${f}`,b="warning",Sr("browser")&&!document.hasFocus()&&Ro(`⚠️ ${u} — 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",j=t.requestId,N=t.orgId;if(h=`👁️ ${f} wants to view your session`,b="warning",j&&N&&this.viewRequestRespondFn){const y=Date.now(),v=kx(N,j,this.viewRequestRespondFn,(k,w)=>console.error(`[EventManager] ${k} view request failed:`,w));this.emitToast({id:y,message:h,type:b,timestamp:y,actions:v,duration:3e4}),h=""}Sr("browser")&&!document.hasFocus()&&Ro("👁️ View Request",`${f} wants to view your session`,`view-request-${j}`)}else t.event==="team:view_request_approved"?(h="✅ View request approved",b="success"):t.event==="team:view_request_rejected"&&(h=`❌ ${t.targetName||"Team member"} declined your view request`,b="warning");if(h){const f=Date.now();this.emitToast({id:f,message:h,type:b,timestamp:f,targetKey:n||t.daemonId,duration:5e3})}}}const tt=new Nx,Sl=new Map;function qn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ks(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function ba(e){return qn(e)?qn(e.result)?e.result:e:null}function Sx(e){const t=ba(e);return!t||!qn(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function un(e){const t=ba(e);return!t||!qn(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function ir(e){const t=ba(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function pn(e){const t=ba(e);return!!t&&t.success===!1}function Cx(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";tt.showToast(n.toast.message,a);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const a=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";tt.showToast(n.notification.body,a)}}}function Ix(e,t){return e&&Ks(e.currentValue)?e.currentValue:t}function Mx(e,t){return Ks(t)?Ks(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Ax(e,t){var o,i;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if(Ks(c))return c}const n=(o=t.controlValues)==null?void 0:o[e];if(Ks(n))return n;const a=(i=t.defaultValues)==null?void 0:i[e];return Ks(a)?a:void 0}function _n(e,t){return e.options||t[e.id]||[]}const Tx={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 _x(e,t,r){var n;return((n=Tx[t])==null?void 0:n.has(r.id))===!0}function mi(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!_x(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function $a(e,t){return{value:t}}function Lx(e,t,r){var a;return r?((a=_n(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const Px={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Rx({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:i}){const{sendCommand:c}=lt(),d=`${e}:${t||n}`,p=Px[n]||"#94a3b8",[u,m]=l.useState({}),h=l.useRef({}),b=l.useRef(i);h.current=u,b.current=i;const g=l.useRef(0),f={};for(const T of o||[])T.defaultValue!==void 0&&(f[T.id]=T.defaultValue);const j={...f,...i||{},...Date.now()<g.current?u:{}};l.useEffect(()=>{i&&Date.now()>g.current&&m({})},[i]);const[N,y]=l.useState(Sl.get(d)||{}),[v,k]=l.useState(null),[w,x]=l.useState(null),C=l.useCallback(async(T,B={})=>{const D={...B,...t&&{targetSessionId:t}};return await c(e,T,D)},[e,t,c]),S=l.useCallback(async(T,B={})=>{const D=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await C("invoke_provider_script",{...D,scriptName:T,...B})},[C,n,r,t]),I=l.useCallback((T,B,D)=>{const M=Ix(D,B);m(E=>({...E,[T.id]:M})),Cx(D==null?void 0:D.effects)},[]),$=l.useCallback((T,B)=>{m(D=>{const M={...D};return B===void 0?delete M[T.id]:M[T.id]=B,M}),g.current=0},[]);if(!o||o.length===0)return null;const R=mi(o,{hostIdeType:r,providerType:n});if(R.length===0)return null;const _=async T=>{if(v===T.id){k(null);return}if(_n(T,N).length>0){k(T.id);return}if(T.dynamic&&T.listScript){x(T.id);try{const D=await S(T.listScript,{}),M=Sx(D);if(!M){const Q=ir(D);Q&&tt.showToast(Q,"warning");return}const E=M.options;y(Q=>{const J={...Q,[T.id]:E};return Sl.set(d,J),J});const z=Ax(T.id,{localOverrideUntil:g.current,localValues:h.current,controlValues:b.current,defaultValues:f});if(Mx(z,M.currentValue)){const Q=M.currentValue;m(J=>({...J,[T.id]:Q}))}k(T.id)}catch(D){const M=D instanceof Error?D.message:`Could not load ${T.label}`;tt.showToast(M,"warning")}finally{x(null)}}},P=async(T,B)=>{k(null);const D=(i==null?void 0:i[T.id])??f[T.id];m(M=>({...M,[T.id]:B})),g.current=Date.now()+5e3;try{if(!T.setScript)return;const M=await S(T.setScript,$a(T,B)),E=un(M);if(E&&!E.ok||pn(M))throw new Error((E==null?void 0:E.error)||ir(M)||`Could not update ${T.label}`);I(T,B,E)}catch(M){$(T,D);const E=M instanceof Error?M.message:`Could not update ${T.label}`;tt.showToast(E,"warning")}},F=async T=>{const B=_n(T,N).map(J=>J.value);if(B.length===0)return;const D=String(j[T.id]||""),E=(B.indexOf(D)+1)%B.length,z=B[E];if(typeof z!="string")return;const Q=(i==null?void 0:i[T.id])??f[T.id];m(J=>({...J,[T.id]:z})),g.current=Date.now()+5e3;try{if(!T.setScript)return;const J=await S(T.setScript,$a(T,z)),ae=un(J);if(ae&&!ae.ok||pn(J))throw new Error((ae==null?void 0:ae.error)||ir(J)||`Could not update ${T.label}`);I(T,z,ae)}catch(J){$(T,Q);const ae=J instanceof Error?J.message:`Could not update ${T.label}`;tt.showToast(ae,"warning")}},q=async T=>{const D=!j[T.id],M=(i==null?void 0:i[T.id])??f[T.id];m(E=>({...E,[T.id]:D})),g.current=Date.now()+5e3;try{if(!T.setScript)return;const E=await S(T.setScript,$a(T,D)),z=un(E);if(z&&!z.ok||pn(E))throw new Error((z==null?void 0:z.error)||ir(E)||`Could not update ${T.label}`);I(T,D,z)}catch(E){$(T,M);const z=E instanceof Error?E.message:`Could not update ${T.label}`;tt.showToast(z,"warning")}},A=async T=>{if(!T.invokeScript)return;if(T.confirmMessage){const D=[T.confirmTitle,T.confirmMessage,T.confirmLabel].filter(E=>typeof E=="string"&&E.trim().length>0);if(!window.confirm(D.join(`
30
+
31
+ `)))return}const B=(i==null?void 0:i[T.id])??f[T.id];try{const D=await S(T.invokeScript),M=un(D);if(M&&!M.ok||pn(D))throw new Error((M==null?void 0:M.error)||ir(D)||`Could not run ${T.label}`);M&&I(T,B??!0,M)}catch(D){$(T,B);const M=D instanceof Error?D.message:`Could not run ${T.label}`;tt.showToast(M,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${p}33`,background:`${p}12`,color:p},children:a}),R.map(T=>{const B=String(j[T.id]||""),D=Lx(T,N,B),M=v===T.id,E=w===T.id,z=_n(T,N),Q="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium transition-colors whitespace-nowrap";switch(T.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${Q} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:M?`${p}55`:"var(--border-default)",background:M?`${p}10`:"var(--surface-tertiary)",color:B?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void _(T),title:T.label,children:[T.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:E?"Loading…":D||T.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),M&&z.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>k(null)}),s.jsxs("div",{className:"absolute bottom-full left-0 z-[60] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[s.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:T.label}),z.map(J=>s.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-[12px] transition-colors",style:{background:J.value===B?`${p}14`:"transparent",color:J.value===B?"var(--text-primary)":"var(--text-secondary)",borderLeft:J.value===B?`2px solid ${p}`:"2px solid transparent"},title:J.description||J.label,onMouseEnter:ae=>{ae.currentTarget.style.background=`${p}10`},onMouseLeave:ae=>{ae.currentTarget.style.background=J.value===B?`${p}14`:"transparent"},onClick:()=>void P(T,J.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:J.label}),J.value===B&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:p},children:"✓"})]},J.value))]})]})]},T.id);case"cycle":return s.jsxs("button",{type:"button",className:`${Q} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:B?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void F(T),title:`Click to cycle: ${z.map(J=>J.label).join(" → ")}`,children:[T.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:D||T.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},T.id);case"toggle":return s.jsxs("button",{type:"button",className:`${Q} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:B?`${p}44`:"var(--border-default)",background:B?`${p}14`:"var(--surface-tertiary)",color:B?p:"var(--text-muted)"},onClick:()=>void q(T),"aria-pressed":!!B,children:[T.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),T.label]},T.id);case"action":return s.jsxs("button",{type:"button",className:`${Q} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void A(T),children:[T.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:T.resultDisplay==="inline"&&B?`${T.label}: ${B}`:T.label})]},T.id);case"display":return s.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:B?"var(--text-primary)":"var(--text-muted)"},children:[T.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:B?`${T.label}: ${B}`:T.label})]},T.id);default:return null}})]})})}function Dx({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:c,controlValues:d}){const{isVisible:p}=di(),u=mi(c,{hostIdeType:a,providerType:o});return!e||t||u.length===0||!p?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(Rx,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:u,controlValues:d})})}const lr=5,Vd=10*1024*1024;function $x({hasDraft:e,isBusy:t=!1}){return!e||t}function Ex(e){return new Promise((t,r)=>{const n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(e)})}async function Bx(e){if(e.size>Vd)return null;const t=await Ex(e),r=t.indexOf(",");if(r<0)return null;const n=t.slice(r+1);return{mimeType:e.type||"image/png",data:n,name:e.name,previewUrl:t}}function Fx(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const qd=l.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,onSend:i,onForceSend:c,canForceSend:d=!1,isActive:p=!0,showControlsToggle:u=!1,animateVisibility:m=!0,onControlsToggle:h,messageInput:b}){const g=l.useRef(null),f=l.useRef(null),[j,N]=l.useState(""),[y,v]=l.useState([]),[k,w]=l.useState(null),[x,C]=l.useState(!1),S=l.useRef(!1),{isVisible:I,toggleVisibility:$}=di(),R=Fx(b),_=!!j.trim()||y.length>0;l.useEffect(()=>{N(""),v([]),w(null)},[t]),l.useEffect(()=>{var M;p&&((M=g.current)==null||M.focus({preventScroll:!0}))},[t,p]),l.useEffect(()=>{const M=g.current;M&&(M.style.height="auto",M.style.height=`${Math.min(M.scrollHeight,160)}px`)},[j]);const P=l.useCallback(async M=>{w(null);const E=Array.from(M).filter(ce=>ce.type.startsWith("image/"));if(E.length===0)return;const z=lr-y.length;if(z<=0){w(`Max ${lr} images`);return}const Q=E.slice(0,z);if(Q.filter(ce=>ce.size>Vd).length>0){w("Image too large (max 10 MB)");return}const ne=(await Promise.all(Q.map(Bx))).filter(ce=>ce!==null);v(ce=>[...ce,...ne])},[y.length]),F=l.useCallback(M=>{v(E=>E.filter((z,Q)=>Q!==M))},[]),q=l.useCallback(async()=>{const M=j.trim();if(!M&&y.length===0||a||S.current)return;S.current=!0;const E=y.length>0?[...y]:void 0;try{await i(M,E)!==!1&&(N(""),v([]),w(null))}finally{S.current=!1}},[j,y,a,i]),A=l.useCallback(async()=>{if(!d||!c)return;const M=j.trim();if(!M&&y.length===0||S.current)return;S.current=!0;const E=y.length>0?[...y]:void 0;try{await c(M,E)!==!1&&(N(""),v([]),w(null))}finally{S.current=!1}},[y,d,j,c]),T=l.useCallback(M=>{R&&(M.preventDefault(),C(!0))},[R]),B=l.useCallback(()=>C(!1),[]),D=l.useCallback(M=>{R&&(M.preventDefault(),C(!1),M.dataTransfer.files.length>0&&P(M.dataTransfer.files))},[R,P]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"transition-all duration-200 ease-out":"",x?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:p?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:p?200:0,opacity:p?1:0,transform:p?"translateY(0)":"translateY(10px)",padding:p?"10px 12px":"0 12px",pointerEvents:p?"auto":"none"},"aria-hidden":!p,onDragOver:T,onDragLeave:B,onDrop:D,children:[y.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:y.map((M,E)=>s.jsxs("div",{className:"relative group w-14 h-14 rounded-lg overflow-hidden border border-border-subtle shrink-0",style:{background:"var(--surface-secondary)"},children:[s.jsx("img",{src:M.previewUrl,alt:M.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>F(E),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:"✕"})]},E))}),s.jsxs("div",{className:"flex gap-2 items-center",title:p?`Send message to ${r}`:void 0,children:[u&&s.jsx("button",{type:"button",onClick:()=>{$(),h==null||h()},"aria-label":I?"Hide controls":"Show controls","aria-pressed":I,title:I?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:s.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),R&&s.jsxs(s.Fragment,{children:[s.jsx("input",{ref:f,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:M=>{M.target.files&&P(M.target.files),M.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var M;return(M=f.current)==null?void 0:M.click()},disabled:y.length>=lr,title:y.length>=lr?`Max ${lr} images`:"Attach image",className:"h-10 w-8 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center disabled:opacity-40","aria-label":"Attach image",children:s.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"})})})]}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("textarea",{ref:g,rows:1,placeholder:o||(R&&y.length>0?"Add a message (optional)...":`Send message to ${r}... (Shift+Enter for newline)`),value:j,onChange:M=>N(M.target.value),onPaste:M=>{R&&M.clipboardData.files.length>0&&Array.from(M.clipboardData.files).some(z=>z.type.startsWith("image/"))&&(M.preventDefault(),P(M.clipboardData.files))},onKeyDown:M=>{M.key==="Enter"&&(M.nativeEvent.isComposing||M.shiftKey||(M.preventDefault(),q()))},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"}})}),s.jsx("button",{onClick:()=>{q()},disabled:$x({hasDraft:_,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${_&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:_&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":"Send message",children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:_?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})}),d&&s.jsx("button",{type:"button",onClick:()=>{A()},disabled:!_,className:`h-10 px-3 rounded-full text-[11px] font-medium border border-border-subtle shrink-0 transition-colors ${_?"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||R&&x)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${k?"text-red-400":"text-[var(--accent-primary)]"}`,children:k||"Drop image here"}),o&&!k&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:o})]})});function Cl(e){if(!e||!Number.isFinite(e))return"—";try{return`${new Date(e).toLocaleString()} (${e})`}catch{return String(e)}}function Il(e){if(!e)return"";const t=Date.now()-e;if(t<0)return"";const r=Math.floor(t/1e3);if(r<60)return`${r}s ago`;const n=Math.floor(r/60);if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function Ox({sessionId:e,daemonId:t,onClose:r}){const{sendCommand:n}=lt(),[a,o]=l.useState(!0),[i,c]=l.useState(null),[d,p]=l.useState(null),u=l.useCallback(async()=>{o(!0),p(null);try{const m=await n(t,"get_session_info",{targetSessionId:e}),h=m&&typeof m=="object"?m:{},b=h.result&&typeof h.result=="object"?h.result:h;b!=null&&b.success?c(b):(p((b==null?void 0:b.error)||"Failed to load session info"),c(null))}catch(m){p((m==null?void 0:m.message)||String(m)),c(null)}finally{o(!1)}},[n,t,e]);return l.useEffect(()=>{u()},[u]),l.useEffect(()=>{const m=h=>{h.key==="Escape"&&r()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[r]),s.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:r,style:{pointerEvents:"auto"},children:s.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:m=>m.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-border-subtle px-4 py-3",children:[s.jsx("h2",{className:"text-base font-semibold",children:"Session info"}),s.jsx("button",{type:"button",onClick:r,className:"text-text-secondary hover:text-text-primary px-2 py-1 rounded","aria-label":"Close",children:"×"})]}),s.jsxs("div",{className:"overflow-y-auto px-4 py-3 text-sm space-y-4",children:[a&&s.jsx("div",{className:"text-text-secondary",children:"Loading…"}),d&&s.jsx("div",{className:"text-red-500",children:d}),(i==null?void 0:i.session)&&s.jsxs(Ml,{title:"Session",children:[s.jsx(Ot,{k:"Session ID",v:s.jsx(cr,{children:i.session.sessionId})}),s.jsx(Ot,{k:"Provider",v:`${i.session.providerName||i.session.providerType} (${i.session.providerType})`}),i.session.transport&&s.jsx(Ot,{k:"Transport",v:i.session.transport}),i.session.workspace&&s.jsx(Ot,{k:"Workspace",v:s.jsx(cr,{children:i.session.workspace})}),s.jsx(Ot,{k:"Spawned at",v:s.jsxs(s.Fragment,{children:[Cl(i.session.spawnedAtMs),i.session.spawnedAtMs?s.jsx("span",{className:"text-text-secondary ml-2",children:Il(i.session.spawnedAtMs)}):null]})}),i.session.providerSessionId&&s.jsx(Ot,{k:"Provider session ID",v:s.jsx(cr,{children:i.session.providerSessionId})})]}),(i==null?void 0:i.coordinator)&&s.jsxs(Ml,{title:"Mesh coordinator",children:[s.jsx(Ot,{k:"Mesh ID",v:s.jsx(cr,{children:i.coordinator.meshId})}),i.coordinator.cliType&&s.jsx(Ot,{k:"Coordinator CLI",v:i.coordinator.cliType}),s.jsx(Ot,{k:"Started at",v:s.jsxs(s.Fragment,{children:[Cl(i.coordinator.startedAt),i.coordinator.startedAt?s.jsx("span",{className:"text-text-secondary ml-2",children:Il(i.coordinator.startedAt)}):null]})}),i.coordinator.injection&&s.jsx(Ot,{k:"Prompt injection",v:`${i.coordinator.injection.mode}${i.coordinator.injection.target?` → ${i.coordinator.injection.target}`:""}`}),i.coordinator.mcpConfigPath&&s.jsx(Ot,{k:"MCP config",v:s.jsx(cr,{children:i.coordinator.mcpConfigPath})}),i.coordinator.extraSystemPrompt&&s.jsx(Al,{title:"Per-launch extra prompt",body:i.coordinator.extraSystemPrompt,defaultOpen:!0}),i.coordinator.systemPrompt&&s.jsx(Al,{title:"Final system prompt (click to expand)",body:i.coordinator.systemPrompt})]}),i&&!i.coordinator&&s.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."})]}),s.jsxs("div",{className:"border-t border-border-subtle px-4 py-2 flex justify-end gap-2",children:[s.jsx("button",{type:"button",onClick:()=>void u(),className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:"px-3 py-1 text-sm rounded bg-accent text-white hover:opacity-90",children:"Close"})]})]})})}function Ml({title:e,children:t}){return s.jsxs("div",{children:[s.jsx("h3",{className:"text-xs uppercase tracking-wide text-text-secondary mb-1",children:e}),s.jsx("div",{className:"space-y-1",children:t})]})}function Ot({k:e,v:t}){return s.jsxs("div",{className:"flex gap-3",children:[s.jsx("div",{className:"w-44 shrink-0 text-text-secondary",children:e}),s.jsx("div",{className:"min-w-0 break-all",children:t})]})}function cr({children:e}){return s.jsx("code",{className:"font-mono text-xs",children:e})}function Al({title:e,body:t,defaultOpen:r=!1}){const[n,a]=l.useState(r);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:()=>a(o=>!o),className:"text-xs uppercase tracking-wide text-text-secondary hover:text-text-primary",style:{pointerEvents:"auto"},children:[n?"▾":"▸"," ",e]}),n&&s.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 zx({sessionId:e,daemonId:t}){const[r,n]=l.useState(!1);return!e||!t?null:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:()=>n(!0),title:"Session info — system prompt, MCP config, spawned at, …","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:"ⓘ"}),r&&s.jsx(Ox,{sessionId:e,daemonId:t,onClose:()=>n(!1)})]})}const Ze=e=>e.transport==="pty",sr=(e,t)=>Ze(e)?e.mode||"terminal":"chat",Yd=(e,t)=>Ze(e)&&sr(e)==="terminal",Ye=e=>e.transport==="acp",Hx=180;function ms(e){return e.streamSource!=="agent-stream"}function Ps(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Jd(e){return e.machineName||""}function Kr(e){return Ps(e)}function Qt(e){return e.agentType||""}function Yn(e){return e.hostIdeType||""}function hi(e){return e.displayPrimary||e.agentName||"Agent"}function Xd(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Wx(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Qd(e){const t=Wx(e),r=Gs(t==null?void 0:t.content),n=Gs(e.lastMessagePreview);return r||n||""}function Kx(e,t=Hx){const r=Gs(e);if(!r||t<=0)return"";const n=Array.from(r);return n.length<=t?r:`${n.slice(0,Math.max(0,t-1)).join("").trimEnd()}…`}function Ux(e){return Kx(Qd(e)||e.displaySecondary||"")}function Zd(e){return[e.displaySecondary,Jd(e)].filter(Boolean)}function Js(e){return e.agentName||Nt(Qt(e))}function Gx(e){var t,r;if(!ms(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return Nt(Yn(e)||Qt(e))}function eu(e){return ms(e)?e.sessionId:e.nativeSessionId}function Tl(e){return ms(e)?"native":e.tabKey}function Vx(e){return e.sessionId}function qx(e,t){if(t)return ms(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function Yx(e,t){const r=Qt(e),n=ms(e),a=Ze(e)||Ye(e),o=n?a?Js(e)||(t==null?void 0:t.cliName)||Nt(Yn(e)||r):t!=null&&t.type?Nt(t.type):Nt(Yn(e)||r):Js(e);return{isNativeConversation:n,isCli:Ze(e),isAcp:Ye(e),isCliTerminal:Yd(e),providerType:r,displayLabel:o,targetEntry:qx(e,t)}}function ws(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:Ze(e)||Ye(e)?{agentType:Qt(e)}:e.streamSource==="agent-stream"?{agentType:Qt(e)}:t}function js(e){return e?Kr(e):""}function dr(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function fi(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function _l(e){const t=e instanceof Error?e.message:String(e||""),r=t.toLowerCase();return r.includes("still processing the previous prompt")?"Message queued and will send after the current reply finishes.":r.includes("awaiting confirmation")?"Resolve the pending approval prompt before sending another message.":r.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":r.includes("not running")?"Runtime is not available right now.":t||"Unable to send message right now."}function tu(){return"select_session"}function Jx(){return"open_panel"}function Xx({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function Ll(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function mn(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Cr(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function xi(e){return e instanceof Error?e.message:String(e||"")}function Pl(e){const t=xi(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Rl(e,t){const r=xi(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function Dl(e,t,r,n={}){const a=ws(r);if(!t||t.length===0)return{message:e,...n.force?{force:!0}:{},...a};const o=t.map(i=>({type:"image",mimeType:i.mimeType,data:i.data,alt:i.name}));return e&&o.push({type:"text",text:e}),{message:e,input:{parts:o,textFallback:e},...n.force?{force:!0}:{},...a}}function ga({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,o]=l.useState(!1),[i,c]=l.useState(!1),[d,p]=l.useState(null),u=l.useRef(!1),m=l.useRef(null);l.useEffect(()=>{p(null)},[t==null?void 0:t.tabKey]);const h=l.useCallback(async(N,y)=>{if(!t||u.current)return!1;const v=N.trim(),k=fi(t);if(Xx({hasMessage:!!v,blockedMessage:k,sendInFlight:u.current}))return k&&p(k),!1;const w=Date.now(),x={tabKey:t.tabKey,message:v,timestamp:w};if(Ll(m.current,x))return p(null),!0;u.current=!0,c(!0),p(null),m.current=x;try{const C=js(t);if(!C)return m.current=mn(m.current,x),p("Unable to send message right now."),!1;const S=await e(C,"send_chat",Dl(v,y,t)),I=Cr(S);if(I!=null&&I.deduplicated)return p(null),!0;if((I==null?void 0:I.sent)===!1)throw new Error((I==null?void 0:I.error)||"Send failed");if((I==null?void 0:I.success)===!1)throw new Error((I==null?void 0:I.error)||"Send failed");return p(null),!0}catch(C){const S=xi(C);return S.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",S):console.warn("Send blocked/failed",C),m.current=mn(m.current,x),p(_l(C)),!1}finally{u.current=!1,c(!1)}},[t,e]),b=l.useCallback(async(N,y)=>{if(!t||u.current)return!1;const v=N.trim();if(!v&&(!y||y.length===0))return!1;const k=Date.now(),w={tabKey:t.tabKey,message:`force:${v}`,timestamp:k};if(Ll(m.current,w))return p(null),!0;u.current=!0,c(!0),p(null),m.current=w;try{const x=js(t);if(!x)return m.current=mn(m.current,w),p("Unable to send message right now."),!1;const C=await e(x,"send_chat",Dl(v,y,t,{force:!0})),S=Cr(C);if((S==null?void 0:S.success)===!1||(S==null?void 0:S.sent)===!1)throw new Error((S==null?void 0:S.error)||"Send failed");return p(null),!0}catch(x){return console.warn("Force send blocked/failed",x),m.current=mn(m.current,w),p(_l(x)),!1}finally{u.current=!1,c(!1)}},[t,e]),g=l.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(N){console.error("Relaunch failed",N)}},[t,e]),f=l.useCallback(async N=>{if(t)try{const v=(t.modalButtons||[]).indexOf(N),k=N.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),w=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(k),x=js(t);if(!x)return;const C=await e(x,"resolve_action",{button:N,action:w?"approve":"reject",...v>=0&&{buttonIndex:v},...ws(t)}),S=Cr(C);S.success||r(I=>[...I,{routeId:t.tabKey,text:Rl(N,S==null?void 0:S.error),timestamp:Date.now()}])}catch(y){Pl(y)||console.error("[ModalButton] Error:",y),r(v=>[...v,{routeId:t.tabKey,text:Pl(y)?Rl(N,y):`❌ **${N}** error`,timestamp:Date.now()}])}},[t,e,r]),j=l.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,Jx(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(N){console.error("Focus agent failed",N)}finally{o(!1)}}},[t,a,e]);return{isSendingChat:i,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:h,handleForceSendChat:b,handleRelaunch:g,handleModalButton:f,handleFocusAgent:j}}const Qx=10,Zx=8e3,eb=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function tb(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 Do(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(eb.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=tb(e);return n.length>8e3?`${n.slice(0,8e3)}…[truncated ${n.length-8e3} chars]`:n}if(typeof e!="object")return String(e);if(r>=6)return"[MaxDepth]";if(Array.isArray(e)){const n=e.slice(-20).map(a=>Do(a,t,r+1));return e.length>20?[{truncatedBefore:e.length-20},...n]:n}return Object.fromEntries(Object.entries(e).slice(0,80).map(([n,a])=>[n,Do(a,n,r+1)]))}function ur(e,t){return Array.isArray(e)?e.slice(-t):[]}function sb(e,t=Date.now()){const r=e&&t-e.firstAt<=Zx,n=r?e.count+1:1;return n>=Qx?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function su(e){var n,a;const{activeConv:t}=e,r={version:1,createdAt:new Date(e.now??Date.now()).toISOString(),url:e.locationHref??(typeof window<"u"?window.location.href:void 0),activeConversation:{routeId:t.routeId,tabKey:t.tabKey,sessionId:t.sessionId,providerSessionId:t.providerSessionId,transport:t.transport,agentName:t.agentName,agentType:t.agentType,hostIdeType:t.hostIdeType,status:t.status,connectionState:t.connectionState,title:t.title,workspaceName:t.workspaceName,displayPrimary:t.displayPrimary,displaySecondary:t.displaySecondary,streamSource:t.streamSource,lastMessageHash:t.lastMessageHash},messageCounts:{live:((n=e.chatTailState.liveMessages)==null?void 0:n.length)??t.messages.length,activeConversation:t.messages.length,visible:e.visibleMessages.length,history:((a=e.chatTailState.historyMessages)==null?void 0:a.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:ur(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:ur(t.messages,10),visibleMessagesTail:ur(e.visibleMessages,5),historyMessagesTail:ur(e.chatTailState.historyMessages,5),actionLogsTail:ur(e.actionLogs.filter(o=>o.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 Do(r)}function ru(e,t={}){const r=e&&typeof e=="object"?e:{},n=t.locatorCopyStatus??(t.locatorCopied===!1?"failed":"copied"),a=n==="copied"?"locator copied":n==="manual"?"locator shown for manual copy":"locator copy failed";return r.delivery==="daemon_file"?`Chat debug signal sent${typeof r.bundleId=="string"&&r.bundleId.trim()?` (${r.bundleId})`:""}; saved on daemon, ${a}.`:`Chat debug signal sent; ${a}.`}async function nu(e){var t;if(typeof navigator<"u"&&((t=navigator.clipboard)!=null&&t.writeText)&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(e),"copied"}catch(r){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",r)}if(typeof document<"u"&&document.body){let r=null;try{if(r=document.createElement("textarea"),r.value=e,r.setAttribute("readonly","true"),r.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(r),r.focus(),r.select(),document.execCommand("copy"))return"copied"}catch{}finally{r==null||r.remove()}}if(typeof window<"u"&&typeof window.prompt=="function")try{return window.prompt("Copy ADHDev chat debug locator:",e),"manual"}catch{}return"failed"}function au(e){const t=e&&typeof e=="object"?e:{};if(t.delivery==="daemon_file"){const r=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(t.bundleId||"")}`,`savedPath: ${String(t.savedPath||"")}`,`sizeBytes: ${String(t.sizeBytes||"")}`,`createdAt: ${String(t.createdAt||"")}`];return t.summary&&typeof t.summary=="object"&&r.push("","summary:",JSON.stringify(t.summary,null,2)),Array.isArray(t.warnings)&&t.warnings.length>0&&r.push("","warnings:",...t.warnings.map(n=>`- ${String(n)}`)),r.join(`
32
+ `)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
33
+
34
+ \`\`\`json
35
+ ${JSON.stringify(t.bundle,null,2)}
36
+ \`\`\``:`# ADHDev Chat Debug Bundle
37
+
38
+ \`\`\`json
39
+ ${JSON.stringify(t,null,2)}
40
+ \`\`\``}function Ea(e,t){return`${e}:${t}`}function rb(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function nb(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function $s(e,t){nb()&&console.debug(`[subscription-manager] ${e}`,t)}class ab{constructor(){Ke(this,"active",new Map);Ke(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var u,m;const i=Ea(n.topic,n.key),c=this.active.get(i);let d=!0;if(c)c.handlers.add(a),(!rb(c.request,n)||c.daemonId!==r)&&(c.daemonId=r,c.request=n,d=((u=t.sendData)==null?void 0:u.call(t,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)?this.scheduleRetry(i,t,o.retryIntervalMs):d&&this.clearRetry(i),$s("subscribe_update",{daemonId:r,topic:n.topic,key:n.key,accepted:d})),c.lastUpdate&&a(c.lastUpdate);else{const h={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,h),$s("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((m=t.sendData)==null?void 0:m.call(t,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(i,t,o.retryIntervalMs)}const p=()=>{var g;this.clearRetry(i);const h=this.active.get(i);if(!h||(h.handlers.delete(a),h.handlers.size>0))return;this.active.delete(i);const b={type:"unsubscribe",topic:n.topic,key:n.key};$s("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(g=t.sendData)==null||g.call(t,r,b)};return p.initialSendAccepted=d,p}publish(t){const r=Ea(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Us.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),n.handlers.forEach(a=>{a(t),Us.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,r,n){const a=Ea(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;$s("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=t.sendData)==null||r.call(t,n.daemonId,n.request)}resubscribeForDaemon(t,r){var a;const n=Array.from(this.active.values()).filter(o=>o.daemonId===t);$s("resubscribe_daemon",{daemonId:t,count:n.length,subscriptions:n.map(o=>({topic:o.request.topic,key:o.request.key}))});for(const o of n)(a=r.sendData)==null||a.call(r,o.daemonId,o.request)}scheduleRetry(t,r,n){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var c;this.retryTimers.delete(t);const o=this.active.get(t);if(!o)return;const i=((c=r.sendData)==null?void 0:c.call(r,o.daemonId,o.request))??!1;$s("subscribe_retry",{id:t,accepted:i,topic:o.request.topic,key:o.request.key}),i||this.scheduleRetry(t,r,n)},n);this.retryTimers.set(t,a)}clearRetry(t){const r=this.retryTimers.get(t);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(t))}}const Zt=new ab;function ob(e,t){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===t&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,mode:n.mode,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash,completionMarker:n.completionMarker,seenCompletionMarker:n.seenCompletionMarker,settings:n.settings,activeInteractivePrompt:n.activeInteractivePrompt});for(const o of n.childSessions||[]){if(!(o!=null&&o.id))continue;const i=r.get(o.id)||{};r.set(o.id,{...i,...o})}}return r}function ib(e){const t=[],r=new Map;for(const n of e)if(n.parentId){const a=r.get(n.parentId)||[];a.push(n),r.set(n.parentId,a)}else t.push(n);return{topLevel:t,childrenByParent:r}}function Ba(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function lb(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function cb(e){lb()&&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 Jn(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:i}=t,c=i||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:p,childrenByParent:u}=ib(d),m=ob(o,n),h=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,b=p.filter(j=>j.kind==="workspace"&&j.transport==="cdp-page"),g=p.filter(j=>j.kind==="agent"&&j.transport==="pty"),f=p.filter(j=>j.kind==="agent"&&j.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:c,...e.version&&{version:e.version},...h&&{machine:h,platform:h.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:b.some(j=>!!j.cdpConnected)});for(const j of b){const N=m.get(j.id),y=vr(j,N),v=(u.get(j.id)||[]).map(k=>vr(k,m.get(k.id)));r.push({id:`${n}:ide:${j.id}`,sessionId:j.id,providerSessionId:j.providerSessionId??(N==null?void 0:N.providerSessionId),parentSessionId:y.parentId,sessionKind:y.kind,transport:y.transport,sessionCapabilities:y.capabilities,type:y.providerType,status:y.cdpConnected?"online":"detected",daemonId:n,instanceId:Ba(n,j.id),workspace:y.workspace,terminals:0,childSessions:v,agents:v.map(k=>({id:k.id,name:k.providerName||k.providerType,type:k.providerType,status:k.status})),activeChat:y.activeChat,...y.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:y.activeInteractivePrompt},chats:[],cdpConnected:y.cdpConnected,...y.lastMessagePreview!==void 0&&{lastMessagePreview:y.lastMessagePreview},...y.lastMessageRole!==void 0&&{lastMessageRole:y.lastMessageRole},...y.lastMessageAt!==void 0&&{lastMessageAt:y.lastMessageAt},...y.lastMessageHash!==void 0&&{lastMessageHash:y.lastMessageHash},lastUpdated:y.lastUpdated,unread:y.unread,lastSeenAt:y.lastSeenAt,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,seenCompletionMarker:y.seenCompletionMarker,surfaceHidden:y.surfaceHidden,...y.controlValues!==void 0&&{controlValues:y.controlValues},...y.providerControls!==void 0&&{providerControls:y.providerControls},...y.summaryMetadata!==void 0&&{summaryMetadata:y.summaryMetadata},...y.settings!==void 0&&{settings:y.settings},...y.messageInput!==void 0&&{messageInput:y.messageInput},timestamp:c})}for(const j of g){const N=m.get(j.id),y=vr(j,N);r.push({id:`${n}:cli:${j.id}`,sessionId:j.id,providerSessionId:j.providerSessionId??(N==null?void 0:N.providerSessionId),parentSessionId:y.parentId,sessionKind:y.kind,transport:y.transport,sessionCapabilities:y.capabilities,type:y.providerType,agentType:y.providerType,status:y.status||"running",daemonId:n,instanceId:Ba(n,j.id),cliName:y.providerName||y.providerType,mode:y.mode||(N==null?void 0:N.mode)||"terminal",workspace:y.workspace||"",activeChat:y.activeChat,...y.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:y.activeInteractivePrompt},...y.resume!==void 0&&{resume:y.resume},...y.runtimeKey!==void 0&&{runtimeKey:y.runtimeKey},...y.runtimeDisplayName!==void 0&&{runtimeDisplayName:y.runtimeDisplayName},...y.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:y.runtimeWorkspaceLabel},...y.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:y.runtimeWriteOwner},...y.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:y.runtimeAttachedClients},...y.lastMessagePreview!==void 0&&{lastMessagePreview:y.lastMessagePreview},...y.lastMessageRole!==void 0&&{lastMessageRole:y.lastMessageRole},...y.lastMessageAt!==void 0&&{lastMessageAt:y.lastMessageAt},...y.lastMessageHash!==void 0&&{lastMessageHash:y.lastMessageHash},lastUpdated:y.lastUpdated,unread:y.unread,lastSeenAt:y.lastSeenAt,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,seenCompletionMarker:y.seenCompletionMarker,surfaceHidden:y.surfaceHidden,...y.controlValues!==void 0&&{controlValues:y.controlValues},...y.providerControls!==void 0&&{providerControls:y.providerControls},...y.summaryMetadata!==void 0&&{summaryMetadata:y.summaryMetadata},...y.settings!==void 0&&{settings:y.settings},...y.messageInput!==void 0&&{messageInput:y.messageInput},timestamp:c,_isCli:!0})}for(const j of f){const N=m.get(j.id),y=vr(j,N);r.push({id:`${n}:acp:${j.id}`,sessionId:j.id,providerSessionId:j.providerSessionId??(N==null?void 0:N.providerSessionId),parentSessionId:y.parentId,sessionKind:y.kind,transport:y.transport,sessionCapabilities:y.capabilities,type:y.providerType,agentType:y.providerType,status:y.status||"running",daemonId:n,instanceId:Ba(n,j.id),cliName:y.providerName||y.providerType,mode:"chat",workspace:y.workspace||"",activeChat:y.activeChat,...y.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:y.activeInteractivePrompt},...y.runtimeKey!==void 0&&{runtimeKey:y.runtimeKey},...y.runtimeDisplayName!==void 0&&{runtimeDisplayName:y.runtimeDisplayName},...y.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:y.runtimeWorkspaceLabel},...y.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:y.runtimeWriteOwner},...y.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:y.runtimeAttachedClients},...y.lastMessagePreview!==void 0&&{lastMessagePreview:y.lastMessagePreview},...y.lastMessageRole!==void 0&&{lastMessageRole:y.lastMessageRole},...y.lastMessageAt!==void 0&&{lastMessageAt:y.lastMessageAt},...y.lastMessageHash!==void 0&&{lastMessageHash:y.lastMessageHash},lastUpdated:y.lastUpdated,unread:y.unread,lastSeenAt:y.lastSeenAt,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,seenCompletionMarker:y.seenCompletionMarker,surfaceHidden:y.surfaceHidden,...y.controlValues!==void 0&&{controlValues:y.controlValues},...y.providerControls!==void 0&&{providerControls:y.providerControls},...y.summaryMetadata!==void 0&&{summaryMetadata:y.summaryMetadata},...y.settings!==void 0&&{settings:y.settings},...y.messageInput!==void 0&&{messageInput:y.messageInput},timestamp:c,_isAcp:!0})}return cb(r),r}const db=15e3,ub=15e3,pb=6e4,mb=1200,$l=12,hb=8e3,fb=4e3,Fa=new Map,Oa=new Map,hn=new Set,Ir=new Map;function xb(e){if(!e||typeof e!="object")return null;const t=e,r=t.status;if(r&&typeof r=="object")return r;const n=t.result;if(n&&typeof n=="object"&&"status"in n){const a=n.status;if(a&&typeof a=="object")return a}return t}function El(e,t){const r=Ir.get(e);!r||r.size===0||(Ir.delete(e),r.forEach(n=>n(t)))}function bb(e,t){return new Promise(r=>{const n=Ir.get(e)||new Set;Ir.set(e,n);const a=i=>{clearTimeout(o),n.delete(a),n.size===0&&Ir.delete(e),r(i)},o=setTimeout(()=>a(!1),t);n.add(a)})}function Ur(){const{sendCommand:e,sendData:t}=lt(),{injectEntries:r,getIdes:n}=Rr();return l.useCallback(async(a,o)=>{if(!a)return;const i=(o==null?void 0:o.minFreshMs)??pb,c=Oa.get(a)||0;if(!(o!=null&&o.force)&&hn.has(a)&&c>0||!(o!=null&&o.force)&&c>0&&Date.now()-c<i)return;const d=Fa.get(a);if(d)return d;const p=(async()=>{if(t&&!hn.has(a)){const f=Zt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},j=>{const N=n(),y=N.find(k=>k.id===a),v=Jn(j.status,{daemonId:a,existingDaemon:y,existingEntries:N,timestamp:j.timestamp});v.length>0&&r(v),Oa.set(a,Date.now()),El(a,!0)});if(f.initialSendAccepted?hn.add(a):hn.delete(a),!(o!=null&&o.force)&&f.initialSendAccepted&&await bb(a,mb))return}const u=await e(a,"get_status_metadata"),m=xb(u);if(!m)return;const h=n(),b=h.find(f=>f.id===a),g=Jn(m,{daemonId:a,existingDaemon:b,existingEntries:h,timestamp:m.timestamp||Date.now()});g.length>0&&r(g,{authoritativeDaemonIds:[a]}),Oa.set(a,Date.now()),El(a,!0)})().finally(()=>{Fa.delete(a)});return Fa.set(a,p),p},[n,r,e,t])}function gb(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const yb=60,vb=50;function ou(e={}){return e.isCliLike?vb:yb}function wb(e={}){return ou(e)}function Ct(e){return(typeof e=="string"?e.trim():"")||void 0}function ss(e,t){const r=Ct(t);return r?`${e}:${r}`:void 0}function cs(e,t,r){const n=ss(t,r),a=Ct(r);n&&e.push(n),a&&e.push(a)}function Hs(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function iu(e){return Ct(e.providerSessionId)||Ct(e.sessionId)||Ct(e.tabKey)||Ct(e.routeId)}function ya(e){return Hs([Ct(e.historySessionId),Ct(e.providerSessionId),Ct(e.sessionId)])}function ns(e){const t=[];return cs(t,"provider",e.providerSessionId),cs(t,"session",e.sessionId),cs(t,"tab",e.tabKey),cs(t,"route",e.routeId),Hs(t)}function jb(e){const t=[];return Ct(e.providerSessionId)?(cs(t,"provider",e.providerSessionId),Hs(t)):Ct(e.sessionId)?(cs(t,"session",e.sessionId),Hs(t)):Ct(e.tabKey)?(cs(t,"tab",e.tabKey),Hs(t)):Ct(e.routeId)?(cs(t,"route",e.routeId),Hs(t)):[]}function $r(e){return ss("provider",e.providerSessionId)||ss("session",e.sessionId)||ss("tab",e.tabKey)||ss("route",e.routeId)||"unknown:"}function Gr(e){return ya(e)[0]}function kb(e){const t=Ct(e.providerSessionId),r=Ct(e.sessionId),n=Ct(e.tabKey),a=Ct(e.routeId),o=[ss("provider",t),ss("session",r),ss("tab",n),ss("route",a)].filter(d=>typeof d=="string"),i=ns({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),c=$r({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:c,targetKey:c,targetValue:iu({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:Gr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:i}}function $o(e,t){const r=kb(e);return jb(t).some(n=>r.lookupKeys.includes(n))}const Vr=60,Nb=1e3,Bl=500,bi=12e4,Sb=new Set(["generating","waiting_approval","starting","streaming","working"]),Eo=new Map;function gi(e,t,r){return`${e}::${t}::${r||t}`}function Xn(e=Vr){return{liveMessages:[],hasLiveSnapshot:!1,cursor:Cb([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Cb(e,t=Vr){return{tailLimit:t}}function Fl(e,t){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function Bo(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(Bo).join(`
41
+ `);if(typeof e=="object"){const t=e;return Bo(t.text??t.content??t.value??"")}return String(e)}function Ib(e){return Bo(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function Mb(e){return e.length===0||e.every(Ib)}function Ab(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="generating"||t==="long_generating"||t==="streaming"||t==="working"||t==="starting"}function lu(e,t){return Math.max(Math.max(0,t),Array.isArray(e.liveMessages)?e.liveMessages.length:0)}function Tb(e,t,r,n,a){if(!Ab(n))return!1;const o=lu(e,t);if(o<=0)return!1;if(Mb(r))return!0;if(a&&typeof a=="object"){const i=a.selected,c=a.fallbackReason;if(i==="native-history"||typeof c=="string"&&c!==""&&!c.startsWith("native_history_"))return!1}return r.length<o}function _b(e,t,r,n){if(r.length!==0||lu(e,t)<=0||e.hasLiveSnapshot&&e.liveMessages.length===0||!n||typeof n!="object")return!1;const o=n.selected,i=n.fallbackReason,c=n.nativeSource;return o==="native-history"?!1:c==="native-unavailable"?!0:typeof i=="string"&&i.startsWith("native_history_")}function Lb(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}function Ol(e,t){const r=e[t];return typeof r=="string"?r:""}class Pb{constructor(t){Ke(this,"manager");Ke(this,"sendData");Ke(this,"daemonId");Ke(this,"sessionId");Ke(this,"historySessionId");Ke(this,"subscriptionKey");Ke(this,"fallbackRecentCount");Ke(this,"snapshot");Ke(this,"transportSubscription",null);Ke(this,"listeners",new Set);Ke(this,"retainCount",0);Ke(this,"loadHistoryPromise",null);Ke(this,"pendingDisconnectTimer",null);this.manager=t.manager||Zt,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=Xn(Math.max(0,t.tailLimit??Vr))}updateOptions(t){const r=this.sendData,n=this.daemonId,a=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 o=Math.max(0,t.tailLimit);o!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:o}},this.transportSubscription&&(this.disconnect(),this.connect()))}this.retainCount>0&&(r!==this.sendData||n!==this.daemonId||a!==this.sessionId)&&(this.disconnect(),this.connect())}getSnapshot(){return this.snapshot}clearLiveSnapshot(){this.snapshot={...Xn(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 r=(async()=>{try{const n=this.snapshot.hasLiveSnapshot,a=n?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),o=await t({offset:this.snapshot.historyOffset,excludeRecentCount:a}),i=Array.isArray(o.messages)?o.messages:[],c=!n&&i.length===0&&o.hasMore!==!0&&this.fallbackRecentCount>0,d=[...i,...this.snapshot.historyMessages],p=d.length>Bl?d.slice(d.length-Bl):d;this.snapshot={...this.snapshot,historyMessages:p,historyOffset:this.snapshot.historyOffset+i.length,hasMoreHistory:c?!0:o.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),t=>{this.handleUpdate(t)},{retryIntervalMs:Nb}))}disconnect(){var t;(t=this.transportSubscription)==null||t.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(t=>t(this.snapshot))}handleUpdate(t){if(t.error)return;const r=Ol(t,"sessionId");if(r&&r!==this.sessionId)return;const n=Ol(t,"historySessionId");if(n&&this.historySessionId&&n!==this.historySessionId)return;const a=Lb(t),o=t.messageSource;if(Tb(this.snapshot,this.fallbackRecentCount,a,t.status,o)||_b(this.snapshot,this.fallbackRecentCount,a,o))return;const i={tailLimit:this.snapshot.cursor.tailLimit};Fl(this.snapshot.liveMessages)===Fl(a)&&this.snapshot.cursor.tailLimit===i.tailLimit||(this.snapshot={...this.snapshot,liveMessages:a,hasLiveSnapshot:!0,cursor:i,messageSource:o},this.emit())}}function cu(e){const t=gi(e.daemonId,e.sessionId,e.historySessionId),r=Eo.get(t);if(r)return r.updateOptions(e),r;const n=new Pb(e);return Eo.set(t,n),n}function Rb(e,t,r){if(!e||!t)return;const n=`${e}::${t}::`,a=gi(e,t,r);for(const[o,i]of Eo.entries())(o===a||o.startsWith(n))&&i.clearLiveSnapshot()}function Db(e,t){return{...e,loadHistoryPage:t}}function $b(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Eb(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Sb.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=t.now??Date.now(),a=Math.max(0,Number(t.recentActivityMs??bi)),o=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return o>0?n-o<=a:Array.isArray(e.messages)&&e.messages.length>0}function Bb(e=bi){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Fb(e,t={}){const r=new Set,n=[];for(const a of e){if(!Eb(a,t))continue;const o=Kr(a),i=a.sessionId||"";if(!o||!i)continue;const c=Gr(a),d=gi(o,i,c||i);r.has(d)||(r.add(d),n.push({daemonId:o,sessionId:i,historySessionId:c||i,subscriptionKey:`daemon:${o}:session:${i}`}))}return n.sort($b),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Ob(e,t){const{sendData:r,sendCommand:n}=lt(),a=(t==null?void 0:t.enabled)!==!1,o=Kr(e),i=e.sessionId||"",c=Gr(e)||i,d=`daemon:${o}:session:${i}`,p=Math.max(0,(t==null?void 0:t.tailLimit)??Vr),u=e.messages.length,m=l.useMemo(()=>!a||!o||!i?null:cu({daemonId:o,sessionId:i,historySessionId:c,subscriptionKey:d,sendData:r,tailLimit:p,fallbackRecentCount:u}),[o,a,c,r,i,d,p]);l.useEffect(()=>{m==null||m.updateOptions({fallbackRecentCount:u})},[m,u]);const[h,b]=l.useState(()=>(m==null?void 0:m.getSnapshot())||Xn(p));l.useEffect(()=>{if(!m){b(Xn(p));return}m.retain(),b(m.getSnapshot());const f=m.subscribe(j=>{b(j)});return()=>{f(),m.release()}},[m,p]);const g=l.useCallback(async()=>{!m||!o||!i||await m.loadHistoryPage(async({offset:f,excludeRecentCount:j})=>{const N=e.agentType,y=await n(o,"chat_history",{agentType:N,offset:f,limit:30,targetSessionId:i,historySessionId:c,excludeRecentCount:j}),v=y&&typeof y=="object"&&"result"in y?y.result||{}:y||{};return{messages:Array.isArray(v.messages)?v.messages:[],hasMore:v.hasMore===!0}})},[e.agentType,m,o,c,n,i]);return l.useMemo(()=>Db(h,g),[g,h])}function zb(e,t){const{sendData:r}=lt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??Vr),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??bi)),i=Bb(o),[c,d]=l.useState(0);l.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(m=>m+1)},i);return()=>{clearInterval(u)}},[e.length,n,i]);const p=l.useMemo(()=>Fb(e,{recentActivityMs:o}),[e,o,c]);l.useEffect(()=>{if(!n||!r||p.descriptors.length===0)return;const u=p.descriptors.map(m=>cu({...m,sendData:r,tailLimit:a}));return u.forEach(m=>{m.retain()}),()=>{u.forEach(m=>m.release())}},[p.signature,n,r,a])}function Hb(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function zl(e){const t=String(e.role||"").toLowerCase();if(t!=="user"&&t!=="assistant")return!1;const r=String(e.kind||"standard").toLowerCase();return r===""||r==="standard"}function Wb(e,t){if(e.length===0)return[];if(t.some(zl))return[];const r=[],n=new Set;for(let a=e.length-1;a>=0&&r.length<2;a-=1){const o=e[a];if(!o||!zl(o))continue;const i=String(o.role||"").toLowerCase();n.has(i)||(n.add(i),r.unshift(o))}return r}function Kb(e){const{historyMessages:t,liveMessages:r,visibleLiveCount:n}=e,a=Math.max(0,r.length-n),o=a>0?r.slice(0,a):[],i=a>0?r.slice(-n):r,c=Wb(o,i),d=c.length>0?[...c,...i]:i;return t.length===0?d:[...t,...d]}function Ub(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Gb(e){return Ub(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Ln=new Map,Fo=new Set;function Hl(e,t){!e||Ln.get(e)===t||(t?Ln.set(e,!0):Ln.delete(e),Fo.forEach(n=>n(e,t)))}function Vb(e){return e?Ln.get(e)===!0:!1}function qb(e){return Fo.add(e),()=>{Fo.delete(e)}}function Yb(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function Jb(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function Xb(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function du(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function uu(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 Qb(e){return du(e)?!1:e.inboxBucket==="task_complete"&&uu(e).length>0}function Wl(e){return e.branch||"detached HEAD"}function Zb(e){if(e.error)return`${Wl(e)} · Git error: ${e.error}`;const t=[Wl(e)];return e.changedFiles>0?t.push(Yb(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 eg(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${Zb(t)}`}function tg(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function sg(e,t={}){if(t.enabled===!1)return[];if(!Xb(e))return[];const r=du(e)?"working":Qb(e)?"complete":null;if(!r)return[];const n=r==="complete"?uu(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${Jb(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:eg(r,e.git),timestamp:tg(e,e.git),meta:{source:"git-system-bubble",phase:r,workspace:e.workspacePath,repoRoot:e.git.repoRoot,branch:e.git.branch,changedFiles:e.git.changedFiles,hasConflicts:e.git.hasConflicts}}]}const rg=60;function ng(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 Oo({activeConv:e,ideEntry:t,handleSendChat:r,handleForceSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:d,userName:p,scrollToBottomRequestNonce:u,isInputActive:m=!0,isVisible:h=!0}){var ie,we,pe,W,O,V,oe;const b=l.useRef(new Map),g=l.useRef(void 0),f=Ur(),{sendCommand:j}=lt(),{isVisible:N}=di();Wr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:d.length,isSendingChat:a});const y=jt.useMemo(()=>tr(e),[e.status,e.connectionState]);jt.useEffect(()=>{const te=e.sessionId;if(te)return Hl(te,y.isGenerating),()=>{Hl(te,!1)}},[e.sessionId,y.isGenerating]);const v=l.useMemo(()=>Yx(e,t),[e,t]),k=l.useMemo(()=>{var te;return mi((te=v.targetEntry)==null?void 0:te.providerControls,{hostIdeType:e.hostIdeType,providerType:v.providerType})},[e.hostIdeType,v.providerType,(ie=v.targetEntry)==null?void 0:ie.providerControls]),w=ou({isCliLike:v.isCli||v.isAcp}),x=wb({isCliLike:v.isCli||v.isAcp}),C=Ob(e,{enabled:h&&!!e.sessionId,tailLimit:x}),[S,I]=l.useState(w),[$,R]=l.useState(()=>ul()),_=e.tabKey,P=C.historyMessages,F=C.hasMoreHistory,q=C.historyError,A=Hb(e,C),T=Ad(A).length;l.useEffect(()=>{I(w)},[w,_]);const B=Math.max(0,A.length-S),D=hi(e),M=Kr(e),E=Gb(e),z=fi(e),Q=ng(e),J=o||z||Q,ae=!!z,[ne,ce]=l.useState(!1);l.useEffect(()=>{const te=v.targetEntry;M&&(!te||te.providerControls===void 0||te.controlValues===void 0)&&f(M,{minFreshMs:3e4}).catch(()=>{})},[M,v.isAcp,(we=v.targetEntry)==null?void 0:we.providerControls,(pe=v.targetEntry)==null?void 0:pe.controlValues,f]);const be=l.useCallback(async()=>{if(!ne){if(A.length>S){I(te=>Math.min(A.length,te+rg));return}ce(!0);try{await C.loadHistoryPage()}finally{ce(!1)}}},[C,ne,A.length,S]),{allMessages:Z,receivedAtMap:Y}=l.useMemo(()=>{const te=Kb({historyMessages:P,liveMessages:A,visibleLiveCount:S}),X=sg(e),L=X.length>0?[...te,...X]:te,ue={};return L.forEach((H,le)=>{const G=`${e.tabKey}:${Gn(H,le)}`;let Le=gb(H)||b.current.get(G)||0;Le||(Le=Date.now(),b.current.set(G,Le)),ue[Gn(H,le)]=Le}),{allMessages:L,receivedAtMap:ue}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,B,P,A,S]),ve=l.useMemo(()=>d.filter(te=>te.routeId===e.tabKey).sort((te,X)=>te.timestamp-X.timestamp),[d,e.tabKey]),ye=l.useCallback(async()=>{var le,G;if(!M)return;const te=su({activeConv:e,visibleMessages:Z,actionLogs:d,controls:(le=v.targetEntry)==null?void 0:le.providerControls,controlValues:(G=v.targetEntry)==null?void 0:G.controlValues,visibleBarControlCount:k.length,chatTailState:{liveMessages:C.liveMessages,hasLiveSnapshot:C.hasLiveSnapshot,hasMoreHistory:F,historyError:q,historyMessages:P},ui:{controlsVisible:N,visibleLiveCount:S,activityVisible:$,activityCount:T,hiddenLiveCount:B,isInputActive:m,isVisible:h}}),X=await j(M,"get_chat_debug_bundle",{agentType:v.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:te}),L=Cr(X),ue=au(L),H=await nu(ue);H==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),tt.showToast(ru(L,{locatorCopyStatus:H}),H==="failed"?"warning":"success")},[e,d,T,Z,N,C.hasLiveSnapshot,C.liveMessages,v.providerType,(W=v.targetEntry)==null?void 0:W.controlValues,(O=v.targetEntry)==null?void 0:O.providerControls,M,F,B,P,m,h,q,j,$,k.length,S]);l.useEffect(()=>{const te=X=>{X.key===Id&&R(ul())};return window.addEventListener("storage",te),()=>window.removeEventListener("storage",te)},[]);const xe=l.useCallback(()=>{const te=sb(g.current);g.current=te.state,te.shouldCollect&&ye().catch(X=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",X),tt.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[ye]),Se=l.useMemo(()=>{if(A.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((y.isGenerating||e.status==="streaming")&&ce(!1),e.status==="not_monitored"&&E)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Ys,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Vs,{size:14})," Open ",D," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&E)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(jd,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Vs,{size:14})," Open ",D," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!ne)return!F&&P.length===0?s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"No messages yet"})]}):s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,E,i,F,P.length,c,ne,A.length,D,y.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col relative",children:[s.jsx("div",{className:"chat-activity-toggle-bar",children:s.jsx("div",{className:"ml-auto flex items-center gap-1",children:s.jsx(zx,{sessionId:e.sessionId,daemonId:e.daemonId})})}),s.jsx(Mf,{messages:Z,actionLogs:ve,agentName:Js(e)||D||"Agent",userName:p,isCliMode:v.isCli||v.isAcp,isWorking:y.isGenerating,contextKey:e.tabKey,receivedAtMap:Y,lastMessageHash:e.lastMessageHash,showActivityMessages:$,onLoadMore:be,isLoadingMore:ne,hasMoreHistory:F,hiddenLiveCount:B,loadError:q??void 0,emptyState:Se,scrollToBottomRequestNonce:u,isVisible:h}),s.jsx(Dx,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:v.providerType,displayLabel:v.displayLabel,controls:(V=v.targetEntry)==null?void 0:V.providerControls,controlValues:(oe=v.targetEntry)==null?void 0:oe.controlValues,isActive:m,isCliTerminal:v.isCliTerminal}),!v.isCliTerminal&&s.jsx(qd,{contextKey:e.tabKey,panelLabel:D,isSending:a,isBusy:ae,statusMessage:J,onSend:r,onForceSend:n,canForceSend:!!n&&y.isGenerating&&!ae,isActive:m,showControlsToggle:k.length>0,onControlsToggle:xe,messageInput:e.messageInput})]})}let pu=es;function mu(){return pu()}class ag{constructor(){Ke(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{var n;(n=this.listeners.get(t))==null||n.delete(r)}}emit(t,...r){var n;(n=this.listeners.get(t))==null||n.forEach(a=>a(...r))}}let hu=new ag;class og{sendPtyInput(t,r,n){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,r){return!1}get(t){}onScreenshot(t,r){return()=>{}}onRuntimeEvent(t,r,n){return()=>{}}requestRuntimeSnapshot(t,r,n){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let mt=new og;function ig(e){e.dashboardWS&&(hu=e.dashboardWS),e.connectionManager&&(mt=e.connectionManager),e.useDaemonsHook&&(pu=e.useDaemonsHook)}const lg=.5,cg=1.25;function it(e){return hi(e)}function As(e){return Zd(e).join(" · ")}function dg(e){var a,o,i;const t=[],r=typeof((a=e.settings)==null?void 0:a.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0,n=!!((o=e.coordinator)!=null&&o.meshId)||typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0;return r&&t.push("Mesh node"),n&&t.push("Coordinator"),t}function ug(e){var i,c,d;const t=[],r=typeof((i=e.settings)==null?void 0:i.meshNodeFor)=="string"?e.settings.meshNodeFor.trim():"",n=typeof((c=e.coordinator)==null?void 0:c.meshId)=="string"?e.coordinator.meshId.trim():"",a=typeof((d=e.settings)==null?void 0:d.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor.trim():"",o=n||a;if(r&&t.push(`Mesh node: ${r}`),o&&t.push(`Coordinator: ${o}`),e.meshQueueStats){const{pending:p,assigned:u,completed:m,failed:h}=e.meshQueueStats;t.push(`Queue: ${p} pending, ${u} assigned, ${m} completed, ${h} failed`)}return t.join(" · ")}function fu(e){const t=Qd(e);return t||(e.title?e.title:As(e)||"No messages yet")}function xu(e,t){const{isReconnecting:r,isConnecting:n}=tr(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function pg(e,t){const r=["Chat",...Zd(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function ks(e){return xu(e)||As(e)}function mg(e){return`${it(e)} · ${fu(e)}`}function hg(e){const t=Yn(e),r=t?Nt(t):Js(e);return`${it(e)} — ${r||"Agent"}`}function fg(e){return Js(e)||"CLI"}function bu(e){return Xd(e)}function gu(e){return e?`Remote · ${it(e)||e.workspaceName||"Session"}`:"Remote"}const Kl=[{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:""}})}],xg=[{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 bg(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 yi({cond:e,path:t,sections:r,onChange:n,onRemove:a,onPreview:o,preview:i}){const c=bg(e),d=i[t],p=u=>{const m=Kl.find(h=>h.kind===u);m&&n(m.make(r))};return s.jsxs("div",{className:"border border-zinc-700/60 rounded bg-zinc-800/30 p-1.5 space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("select",{value:c,onChange:u=>p(u.target.value),className:"bg-zinc-900 text-zinc-200 text-[10px] font-mono rounded border border-zinc-700 px-1 py-0.5",children:Kl.map(u=>s.jsx("option",{value:u.kind,children:u.label},u.kind))}),(c==="regex"||c==="stable"||c==="changed"||c==="elapsed")&&s.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:()=>o(t,e),children:"test"}),d&&d!=="loading"&&s.jsx("span",{className:`text-[10px] font-mono px-1.5 py-0.5 rounded ${d.result?"text-green-200 bg-green-600/25":"text-zinc-400 bg-zinc-700/40"}`,children:d.result?"match ✓":"no match"}),d==="loading"&&s.jsx("span",{className:"text-[10px] text-zinc-500",children:"testing…"}),a&&s.jsx("button",{type:"button",className:"ml-auto text-zinc-500 hover:text-red-300 text-xs px-1",onClick:a,children:"×"})]}),c==="regex"&&s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs("select",{value:e.section??"",onChange:u=>n({...e,section:u.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:[s.jsx("option",{value:"",children:"(whole screen)"}),r.map(u=>s.jsx("option",{value:u,children:u},u))]}),s.jsx("input",{value:e.matches??"",onChange:u=>n({...e,matches:u.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"})]}),c==="elapsed"&&s.jsx(ds,{label:"elapsed_ms",value:e.elapsed_ms,onChange:u=>n({elapsed_ms:u})}),c==="stable"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ds,{label:"stable_ms",value:e.stable_ms,onChange:u=>n({...e,stable_ms:u})}),s.jsx(ds,{label:"cursor_above",value:e.cursor_above??0,onChange:u=>n({...e,cursor_above:u||void 0})})]}),c==="changed"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ds,{label:"cursor_above",value:e.cursor_above,onChange:u=>n({...e,cursor_above:u})}),s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-zinc-400",children:[s.jsx("input",{type:"checkbox",checked:!!e.changed,onChange:u=>n({...e,changed:u.target.checked}),className:"accent-sky-500"}),"changed"]})]}),(c==="all"||c==="any")&&s.jsx(gg,{kind:c,cond:e,path:t,sections:r,onChange:n,onPreview:o,preview:i}),c==="not"&&s.jsx("div",{className:"pl-2 border-l border-zinc-700",children:s.jsx(yi,{cond:e.not,path:`${t}.not`,sections:r,onChange:u=>n({not:u}),onPreview:o,preview:i})})]})}function gg({kind:e,cond:t,path:r,sections:n,onChange:a,onPreview:o,preview:i}){const c=(e==="all"?t.all:t.any)??[],d=p=>a(e==="all"?{all:p}:{any:p});return s.jsxs("div",{className:"pl-2 border-l border-zinc-700 space-y-1",children:[c.map((p,u)=>s.jsx(yi,{cond:p,path:`${r}.${e}[${u}]`,sections:n,onChange:m=>d(c.map((h,b)=>b===u?m:h)),onRemove:()=>d(c.filter((m,h)=>h!==u)),onPreview:o,preview:i},u)),s.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[s.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:()=>d([...c,{section:n[0],matches:""}]),children:"+ condition"}),xg.map(p=>s.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:()=>d([...c,JSON.parse(JSON.stringify(p.cond))]),title:"insert verified pattern",children:["+ ",p.label]},p.label))]})]})}function ds({label:e,value:t,onChange:r}){return s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-zinc-400 font-mono",children:[e,s.jsx("input",{type:"number",value:Number.isFinite(t)?t:0,onChange:n=>r(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 yg({sections:e,otherSectionIds:t,onChange:r,onTest:n,testResult:a}){const o=Object.keys(e),i=a&&a!=="loading"&&!("error"in a)?Object.fromEntries(a.sections.map(m=>[m.id,m])):{},c=(m,h)=>{if(!h||h===m||e[h])return;const b={};for(const[g,f]of Object.entries(e))b[g===m?h:g]=f;r(b)},d=(m,h)=>r({...e,[m]:h}),p=m=>{const h={...e};delete h[m],r(h)},u=()=>{let m="section",h=1;for(;e[m];)m=`section${h++}`;r({...e,[m]:{from_top:0}})};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-zinc-400 text-[10px] uppercase tracking-widest font-semibold",children:"Sections"}),s.jsx("span",{className:"text-zinc-600 text-[10px]",children:"— how the screen is split; conditions match against these"}),s.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:a==="loading"?"testing…":"test on live screen"}),s.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:u,children:"+ section"})]}),a&&a!=="loading"&&"error"in a&&s.jsx("div",{className:"text-red-300 bg-red-900/30 border border-red-700/40 rounded p-1.5 text-[10px] mb-1",children:a.error}),s.jsx("div",{className:"space-y-1.5",children:o.map(m=>{var f;const h=e[m],b=h.anchor!=null?"anchor":"positional",g=j=>{j==="anchor"?d(m,{anchor:h.anchor??"^",anchor_last:h.anchor_last,until:h.until}):d(m,{from_top:h.from_top??0,until:h.until})};return s.jsxs("div",{className:"border border-zinc-700/60 rounded bg-zinc-800/30 p-2 space-y-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{value:m,onChange:j=>c(m,j.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"}),s.jsxs("div",{className:"inline-flex rounded border border-zinc-700 overflow-hidden text-[10px]",children:[s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${b==="positional"?"bg-sky-600/30 text-sky-100":"text-zinc-400 hover:bg-zinc-700/40"}`,onClick:()=>g("positional"),children:"positional"}),s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${b==="anchor"?"bg-sky-600/30 text-sky-100":"text-zinc-400 hover:bg-zinc-700/40"}`,onClick:()=>g("anchor"),children:"anchor"})]}),s.jsx("button",{type:"button",className:"ml-auto text-zinc-500 hover:text-red-300 text-sm px-1",onClick:()=>p(m),children:"×"})]}),b==="positional"?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx(ds,{label:"from_top",value:typeof h.from_top=="number"?h.from_top:0,onChange:j=>d(m,{...h,from_top:j,from_bottom:void 0})}),s.jsx(ds,{label:"from_bottom",value:typeof h.from_bottom=="number"?h.from_bottom:0,onChange:j=>d(m,{...h,from_bottom:j||void 0})}),s.jsx(Ul,{def:h,otherIds:t(m),onChange:j=>d(m,j)})]}):s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-[10px] text-zinc-500 w-16",children:"anchor"}),s.jsx("input",{value:h.anchor??"",onChange:j=>d(m,{...h,anchor:j.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"}),s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-zinc-400",children:[s.jsx("input",{type:"checkbox",checked:!!h.anchor_last,onChange:j=>d(m,{...h,anchor_last:j.target.checked||void 0}),className:"accent-sky-500"}),"last"]})]}),s.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s.jsx(Ul,{def:h,otherIds:t(m),onChange:j=>d(m,j)})}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-[10px] text-zinc-500 w-16",children:"ctx next"}),s.jsx("input",{value:((f=h.anchor_context)==null?void 0:f.next)??"",onChange:j=>d(m,{...h,anchor_context:{...h.anchor_context,next:j.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"})]})]}),i[m]&&s.jsxs("div",{className:"border-t border-zinc-700/50 pt-1",children:[s.jsxs("div",{className:"text-[9px] text-zinc-500 mb-0.5",children:["captured lines ",i[m].fromLine,"–",i[m].toLine,i[m].text.trim()===""&&s.jsx("span",{className:"text-amber-400 ml-1",children:"(empty — check bounds)"})]}),s.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:i[m].text||"(empty)"})]})]},m)})})]})}function Ul({def:e,otherIds:t,onChange:r}){const n=e.until??"",a=n.startsWith("^");return s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-zinc-400",children:["until",s.jsxs("select",{value:a?"__regex__":n,onChange:o=>{const i=o.target.value;r(i===""?{...e,until:void 0}:i==="__regex__"?{...e,until:n.startsWith("^")?n:"^"}:{...e,until:i})},className:"bg-zinc-900 text-sky-300 rounded border border-zinc-700 px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(none)"}),t.map(o=>s.jsx("option",{value:o,children:o},o)),s.jsx("option",{value:"__regex__",children:"regex…"})]}),a&&s.jsx("input",{value:n,onChange:o=>r({...e,until:o.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 vg({model:e,onChange:t,onPreview:r,preview:n,onTestSections:a,sectionPreview:o}){const i=e.states.map(m=>m.id),c=Object.keys(e.sections??{}),d=l.useCallback(m=>t({...e,...m}),[e,t]),p=(m,h)=>d({states:e.states.map((b,g)=>g===m?{...b,...h}:b)}),u=(m,h)=>d({transitions:e.transitions.map((b,g)=>g===m?{...b,...h}:b)});return s.jsxs("div",{className:"space-y-3",children:[s.jsx(yg,{sections:e.sections??{},otherSectionIds:m=>c.filter(h=>h!==m),onChange:m=>d({sections:m}),onTest:()=>a(e.sections??{}),testResult:o}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-zinc-400 text-[10px] uppercase tracking-widest font-semibold",children:"States"}),s.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:()=>d({states:[...e.states,{id:`state${e.states.length}`,label:"New"}]}),children:"+ state"})]}),s.jsx("div",{className:"space-y-1.5",children:e.states.map((m,h)=>s.jsxs("div",{className:"border border-zinc-700/60 rounded bg-zinc-800/30 p-2 space-y-1",children:[s.jsxs("div",{className:"flex items-end gap-2 flex-wrap",children:[s.jsxs("label",{className:"flex flex-col gap-0.5",children:[s.jsx("span",{className:"text-[9px] text-zinc-500 uppercase tracking-wide",children:"id (used by transitions)"}),s.jsx("input",{value:m.id,onChange:b=>p(h,{id:b.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"})]}),s.jsxs("label",{className:"flex flex-col gap-0.5 flex-1",children:[s.jsx("span",{className:"text-[9px] text-zinc-500 uppercase tracking-wide",children:"label (shown in dashboard)"}),s.jsx("input",{value:m.label,onChange:b=>p(h,{label:b.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"})]}),s.jsx("button",{type:"button",className:"text-zinc-500 hover:text-red-300 text-sm px-1 pb-0.5",onClick:()=>d({states:e.states.filter((b,g)=>g!==h)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-zinc-400 flex-wrap",children:[s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"radio",name:"initial",checked:!!m.initial,onChange:()=>d({states:e.states.map((b,g)=>({...b,initial:g===h}))}),className:"accent-sky-500"}),"initial"]}),s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"checkbox",checked:!!m.modal,onChange:b=>p(h,{modal:b.target.checked||void 0}),className:"accent-sky-500"}),"modal"]}),s.jsxs("label",{className:"flex items-center gap-1",children:["status",s.jsxs("select",{value:m.status??"",onChange:b=>p(h,{status:b.target.value||void 0}),className:"bg-zinc-900 text-zinc-200 rounded border border-zinc-700 px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(auto)"}),s.jsx("option",{value:"idle",children:"idle"}),s.jsx("option",{value:"generating",children:"generating"}),s.jsx("option",{value:"approval",children:"approval"})]})]})]})]},h))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-zinc-400 text-[10px] uppercase tracking-widest font-semibold",children:"Transitions"}),s.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:()=>d({transitions:[...e.transitions,{from:i[0]??"",to:i[0]??""}]}),children:"+ transition"})]}),s.jsx("div",{className:"space-y-1.5",children:e.transitions.map((m,h)=>s.jsxs("div",{className:"border border-zinc-700/60 rounded bg-zinc-800/30 p-2 space-y-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"text-[10px] text-zinc-500",children:"from"}),s.jsx(wg,{value:m.from,states:i,onChange:b=>u(h,{from:b})}),s.jsx("span",{className:"text-[10px] text-zinc-500",children:"→"}),s.jsx("select",{value:m.to,onChange:b=>u(h,{to:b.target.value}),className:"bg-zinc-900 text-green-200 font-mono text-[10px] rounded border border-zinc-700 px-1 py-0.5",children:i.map(b=>s.jsx("option",{value:b,children:b},b))}),s.jsx("span",{className:"text-[10px] text-zinc-500 ml-1",children:"label"}),s.jsx("input",{value:m.label??"",onChange:b=>u(h,{label:b.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"}),s.jsx("button",{type:"button",className:"text-zinc-500 hover:text-red-300 text-sm px-1",onClick:()=>d({transitions:e.transitions.filter((b,g)=>g!==h)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(ds,{label:"min_hold_ms",value:m.min_hold_ms??0,onChange:b=>u(h,{min_hold_ms:b||void 0})}),s.jsx(ds,{label:"priority",value:m.priority??0,onChange:b=>u(h,{priority:b||void 0})})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-[10px] text-zinc-500",children:"when"}),!m.when&&s.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:()=>u(h,{when:{section:c[0],matches:""}}),children:"+ guard condition"}),m.when&&s.jsx("button",{type:"button",className:"text-[10px] text-zinc-500 hover:text-red-300",onClick:()=>u(h,{when:void 0}),children:"remove guard"})]}),m.when&&s.jsx(yi,{cond:m.when,path:`t${h}`,sections:c,onChange:b=>u(h,{when:b}),onPreview:r,preview:n})]})]},h))})]})]})}function wg({value:e,states:t,onChange:r}){const n=new Set(Array.isArray(e)?e:e==="*"?t:[e]),a=e==="*",o=i=>{const c=new Set(n);c.has(i)?c.delete(i):c.add(i);const d=t.filter(p=>c.has(p));r(d.length===1?d[0]:d)};return s.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.map(i=>s.jsx("button",{type:"button",onClick:()=>o(i),className:`font-mono text-[10px] px-1 py-0.5 rounded border ${a||n.has(i)?"text-sky-200 bg-sky-600/25 border-sky-500/40":"text-zinc-500 border-zinc-700 hover:border-zinc-500"}`,children:i},i))})}function pr(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 r=Math.floor(t/6e4);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}function Gl(e){return e<=0?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}const jg={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"},kg={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 za(e){return kg[e]??"text-zinc-200 bg-zinc-600/20 border border-zinc-500/30"}function fn({children:e}){return s.jsx("div",{className:"text-zinc-400 text-[10px] uppercase tracking-widest font-semibold mb-1.5 mt-0.5",children:e})}function xn(){return s.jsx("div",{className:"border-t border-white/8 my-2"})}function yu({node:e,depth:t=0}){var a;const r=e.result?"text-green-300":"text-zinc-500",n=e.result?"●":"○";return s.jsxs("div",{style:{marginLeft:t*10},className:"font-mono text-[10px] leading-relaxed",children:[s.jsxs("span",{className:r,children:[n," "]}),s.jsx("span",{className:"text-zinc-400",children:e.kind}),s.jsxs("span",{className:"text-zinc-500",children:[" ",e.detail]}),e.remainingMs!=null&&e.remainingMs>0&&s.jsxs("span",{className:"text-amber-300",children:[" (",e.remainingMs,"ms left)"]}),(a=e.children)==null?void 0:a.map((o,i)=>s.jsx(yu,{node:o,depth:t+1},i))]})}function Ng({t:e}){const[t,r]=l.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 s.jsxs("div",{className:"border border-zinc-700/50 rounded bg-zinc-800/30 overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-1 hover:bg-zinc-700/30 text-left",onClick:()=>r(a=>!a),children:[s.jsx("span",{className:"text-[10px] text-zinc-500 w-3",children:e.cond?t?"▾":"▸":" "}),s.jsxs("span",{className:`font-mono text-[11px] px-1.5 py-0.5 rounded border ${n}`,children:["→ ",e.to]}),s.jsx("span",{className:"text-zinc-400 font-mono text-[10px] truncate",children:e.label}),s.jsxs("span",{className:"ml-auto flex items-center gap-1.5 shrink-0",children:[e.fires&&s.jsx("span",{className:"text-green-300 text-[10px] font-mono",children:"FIRES"}),!e.holdSatisfied&&s.jsxs("span",{className:"text-amber-300 text-[10px] font-mono",children:["hold ",e.holdRemainingMs,"ms"]}),s.jsx("span",{className:`text-[10px] font-mono ${e.condResult?"text-green-400":"text-zinc-600"}`,children:e.condResult?"cond✓":"cond✗"})]})]}),t&&e.cond&&s.jsx("div",{className:"px-3 pb-1.5 pt-0.5 bg-black/30 border-t border-zinc-700/50",children:s.jsx(yu,{node:e.cond})})]})}function Sg({activeConv:e,onClose:t}){var xe,Se,ie,we,pe;const{sendCommand:r}=lt(),[n,a]=l.useState(!0),[o,i]=l.useState(null),[c,d]=l.useState(null),[p,u]=l.useState(!1),[m,h]=l.useState(new Set(["footer"])),[b,g]=l.useState("Snapshot"),[f,j]=l.useState(!1),[N,y]=l.useState(null),[v,k]=l.useState(!1),[w,x]=l.useState(""),[C,S]=l.useState(!1),[I,$]=l.useState("idle"),[R,_]=l.useState(null),[P,F]=l.useState([]),[q,A]=l.useState({}),[T,B]=l.useState(null),[D,M]=l.useState(!1),E=e.daemonId||((xe=e.routeId)==null?void 0:xe.split(":")[0])||e.routeId||"",z=e.sessionId||"",Q=l.useCallback(async()=>{a(!0),d(null);try{const W=await r(E,"get_spec_debug",{targetSessionId:z}),O=W&&typeof W=="object"?W:{},V=O.result&&typeof O.result=="object"?O.result:O;V!=null&&V.success?i(V):(d((V==null?void 0:V.error)||"Failed to load spec debug"),i(null))}catch(W){d((W==null?void 0:W.message)||String(W)),i(null)}finally{a(!1)}},[r,E,z]);l.useEffect(()=>{Q()},[Q]),l.useEffect(()=>{if(!D)return;const W=setInterval(()=>{Q()},1e3);return()=>clearInterval(W)},[D,Q]),l.useEffect(()=>{const W=O=>{O.key==="Escape"&&!f&&t()};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[t,f]);const J=l.useCallback(async W=>{try{const O=await r(E,"validate_spec",{content:JSON.stringify(W)}),V=O&&typeof O=="object"?O:{},oe=V.result&&typeof V.result=="object"?V.result:V;F(oe!=null&&oe.valid?[]:(oe==null?void 0:oe.errors)??["validation failed"])}catch(O){F([(O==null?void 0:O.message)||String(O)])}},[r,E]),ae=l.useCallback(async()=>{_(null),$("idle"),A({});try{const W=await r(E,"get_spec_source",{targetSessionId:z}),O=W&&typeof W=="object"?W:{},V=O.result&&typeof O.result=="object"?O.result:O;if(!(V!=null&&V.success)||typeof V.content!="string"){_((V==null?void 0:V.error)||"Failed to load spec source");return}x(V.content);let oe=null;try{oe=JSON.parse(V.content)}catch{}oe&&oe.$schema==="adhdev:cli/spec@4"?(y(oe),k(!1),J(oe)):(y(null),k(!0)),S(!1),j(!0)}catch(W){_((W==null?void 0:W.message)||String(W))}},[r,E,z,J]),ne=l.useCallback(W=>{y(W),x(JSON.stringify(W,null,2)),S(!0),$("idle"),J(W)},[J]),ce=l.useCallback(async(W,O)=>{A(V=>({...V,[W]:"loading"}));try{const V=await r(E,"eval_condition_preview",{targetSessionId:z,condition:O}),oe=V&&typeof V=="object"?V:{},te=oe.result&&typeof oe.result=="object"?oe.result:oe;!(te!=null&&te.success)||!te.result?A(X=>({...X,[W]:{result:!1,detail:te==null?void 0:te.error}})):A(X=>({...X,[W]:{result:te.result.result,detail:te.result.detail}}))}catch(V){A(oe=>({...oe,[W]:{result:!1,detail:V==null?void 0:V.message}}))}},[r,E,z]),be=l.useCallback(async W=>{B("loading");try{const O=await r(E,"resolve_section_preview",{targetSessionId:z,sections:W}),V=O&&typeof O=="object"?O:{},oe=V.result&&typeof V.result=="object"?V.result:V;!(oe!=null&&oe.success)||!Array.isArray(oe.sections)?B({error:(oe==null?void 0:oe.error)||"resolve failed"}):B({sections:oe.sections,screenLineCount:oe.screenLineCount??0})}catch(O){B({error:(O==null?void 0:O.message)||String(O)})}},[r,E,z]),Z=l.useCallback(async()=>{var V,oe;const W=(V=o==null?void 0:o.snapshot)==null?void 0:V.specPath;if(!W){_("No spec path on this session");return}if(!v&&P.length>0){_("Fix validation errors before saving");return}const O=!v&&N?JSON.stringify(N,null,2):w;$("saving"),_(null);try{const te=await r(E,"write_spec_source",{specPath:W,content:O}),X=te&&typeof te=="object"?te:{},L=X.result&&typeof X.result=="object"?X.result:X;if(!(L!=null&&L.success)){$("error"),_(((oe=L==null?void 0:L.validationErrors)==null?void 0:oe.join(`
42
+ `))||(L==null?void 0:L.error)||"Save failed");return}$("saved"),S(!1),setTimeout(()=>{Q()},400),setTimeout(()=>$("idle"),1500)}catch(te){$("error"),_((te==null?void 0:te.message)||String(te))}},[r,E,(Se=o==null?void 0:o.snapshot)==null?void 0:Se.specPath,w,N,v,P,Q]),Y=o==null?void 0:o.snapshot,ve=async()=>{var L,ue,H;let W=o;W||(await Q(),W=o);const O=W==null?void 0:W.snapshot,V=[];if(V.push("# Spec Debug Snapshot"),V.push(`Generated: ${new Date().toISOString()}`),V.push(`Session: ${(W==null?void 0:W.sessionId)??""} (${(W==null?void 0:W.providerType)??""})`),V.push(`Spec: ${(O==null?void 0:O.spec_id)??""} (${(O==null?void 0:O.specPath)??""})`),V.push(`Provider: ${(O==null?void 0:O.name)??""} (${(O==null?void 0:O.cliType)??""})`),V.push(`Working dir: ${(O==null?void 0:O.workingDir)??""}`),V.push(`Spawned: ${O!=null&&O.spawnedAtMs?new Date(O.spawnedAtMs).toISOString():""}`),V.push(""),V.push("## Current State"),V.push(`State: ${((L=O==null?void 0:O.current_state)==null?void 0:L.id)??"none"} (${((ue=O==null?void 0:O.current_state)==null?void 0:ue.label)??""})`),V.push(`Status: ${(O==null?void 0:O.status)??""}`),V.push(`Idle hold pending: ${(O==null?void 0:O.idleHoldPending)??!1}`),V.push(`Exited: ${(O==null?void 0:O.exited)??!1}`),V.push(`Last busy: ${O!=null&&O.lastBusyAt?pr(O.lastBusyAt):""}`),V.push(`Cursor: ${(O==null?void 0:O.cursorPosition)!=null?`(${O.cursorPosition.row},${O.cursorPosition.col})`:"n/a"}`),(H=O==null?void 0:O.completionIdleDebounce)!=null&&H.active){const le=O.completionIdleDebounce;V.push(`completion_idle_after: age=${le.ageMs}ms hold=${le.holdMs}ms force=${le.forceAfterMs}ms remaining=${Math.max(0,le.holdMs-le.ageMs)}ms`)}if(V.push(""),V.push("## Modal"),O!=null&&O.current_modal){const le=O.current_modal.buttons.map(G=>G.label).join(" / ");V.push(`${O.current_modal.title??""} [${le}]`)}else V.push("none");V.push(""),V.push("## State History (last 20)");const oe=O!=null&&O.stateHistory?[...O.stateHistory].reverse().slice(0,20):[];for(const le of oe){const G=le.reason!=null?typeof le.reason=="string"?le.reason:JSON.stringify(le.reason):"",Le=le.debounceKind!=null?typeof le.debounceKind=="string"?le.debounceKind:JSON.stringify(le.debounceKind):"",Te=le.matchedStateId!=null?String(le.matchedStateId):"",Me=(le.matchedRules??[]).map(He=>typeof He=="string"?He:JSON.stringify(He)).join(", ");V.push(`- ${le.stateId} @ ${new Date(le.at).toISOString()} held ${le.durationMs}ms | reason: ${G} | debounce: ${Le} | eval→${Te} | rules: ${Me}`)}if(V.push(""),V.push("## Sections"),O!=null&&O.sections)for(const[le,G]of Object.entries(O.sections)){const Le=G.split(`
43
+ `).slice(0,3).join(`
44
+ `);V.push(`${le}: ${Le}`)}V.push(""),V.push("## Last Assistant Message");const X=[...(O==null?void 0:O.messages)??(O==null?void 0:O.committedMessages)??[]].reverse().find(le=>le.role==="assistant");V.push(X?X.content.slice(0,400):""),V.push(""),V.push("## Screen (first 50 lines)"),V.push(O!=null&&O.screen?O.screen.split(`
45
+ `).slice(0,50).join(`
46
+ `):"");try{await navigator.clipboard.writeText(V.join(`
47
+ `)),g("Copied!"),setTimeout(()=>g("Snapshot"),1500)}catch(le){console.error("[SpecDebugPanel] clipboard write failed",le)}},ye=W=>{h(O=>{const V=new Set(O);return V.has(W)?V.delete(W):V.add(W),V})};return s.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:s.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:W=>W.stopPropagation(),children:[s.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:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 overflow-hidden",children:[s.jsx("span",{className:"text-sm font-semibold text-zinc-100 shrink-0",children:"Spec Debug"}),Y&&s.jsx("span",{className:"text-[11px] text-zinc-400 font-mono bg-zinc-800 px-1.5 py-0.5 rounded truncate",children:Y.spec_id})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(Y==null?void 0:Y.specPath)&&s.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?j(!1):ae()},disabled:n,children:f?"Close Editor":"Edit Spec"}),s.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:()=>{ve()},disabled:n,children:b}),s.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:()=>{Q()},disabled:n,children:n?"Loading…":"Refresh"}),s.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&&s.jsxs("div",{className:"flex-1 flex flex-col min-h-0 px-4 py-3 gap-2",children:[s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsxs("div",{className:"inline-flex rounded border border-zinc-700 overflow-hidden text-[10px]",children:[s.jsx("button",{type:"button",className:`px-2 py-0.5 ${v?"text-zinc-400 hover:bg-zinc-700/40":"bg-sky-600/30 text-sky-100"}`,onClick:()=>{if(v)try{const W=JSON.parse(w);y(W),J(W)}catch{return}k(!1)},disabled:!N&&v,children:"Form"}),s.jsx("button",{type:"button",className:`px-2 py-0.5 ${v?"bg-sky-600/30 text-sky-100":"text-zinc-400 hover:bg-zinc-700/40"}`,onClick:()=>{N&&x(JSON.stringify(N,null,2)),k(!0)},children:"JSON"})]}),s.jsx("span",{className:"text-[10px] text-zinc-500 font-mono truncate flex-1",title:Y==null?void 0:Y.specPath,children:((Y==null?void 0:Y.specPath)??"").split("/").slice(-3).join("/")}),C&&s.jsx("span",{className:"text-amber-300 text-[10px]",children:"unsaved"}),!v&&P.length>0&&s.jsxs("span",{className:"text-red-300 text-[10px]",children:[P.length," error",P.length>1?"s":""]}),s.jsx("button",{type:"button",className:`text-[11px] px-2.5 py-1 rounded border transition-colors ${I==="saving"||!v&&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:()=>{Z()},disabled:I==="saving"||!v&&P.length>0,children:I==="saving"?"Saving…":I==="saved"?"Saved ✓ (reloading)":"Save & Apply"})]}),R&&s.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:R}),!v&&P.length>0&&s.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((W,O)=>s.jsx("div",{className:"font-mono",children:W},O))}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:v||!N?s.jsx("textarea",{value:w,onChange:W=>{x(W.target.value),S(!0),$("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"}):s.jsx(vg,{model:N,onChange:ne,onPreview:ce,preview:q,onTestSections:be,sectionPreview:T})}),s.jsx("div",{className:"text-[10px] text-zinc-500 shrink-0",children:v?"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&&s.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3 space-y-3 text-[12px]",children:[c&&s.jsx("div",{className:"text-red-300 bg-red-900/40 border border-red-700/50 rounded p-2",children:c}),n&&!o&&s.jsx("div",{className:"text-zinc-500 text-center py-6",children:"Loading…"}),o&&!o.isSpecProvider&&s.jsxs("div",{className:"text-zinc-500 text-center py-6",children:["Not a spec-driven provider (",o.providerType||"unknown",")."]}),Y&&s.jsxs(s.Fragment,{children:[s.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:[Y.name&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Provider"}),s.jsxs("span",{className:"font-mono text-zinc-200",children:[Y.name," ",s.jsxs("span",{className:"text-zinc-500",children:["(",Y.cliType,")"]})]})]}),Y.workingDir&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Dir"}),s.jsx("span",{className:"font-mono text-zinc-300 truncate",title:Y.workingDir,children:Y.workingDir})]}),Y.spawnedAtMs?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Spawned"}),s.jsx("span",{className:"text-zinc-400",children:pr(Y.spawnedAtMs)})]}):null,Y.providerSessionId&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Session"}),s.jsx("span",{className:"font-mono text-zinc-500 text-[10px] truncate",title:Y.providerSessionId,children:Y.providerSessionId})]})]}),s.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:[s.jsx("span",{className:`font-semibold font-mono text-[12px] px-2 py-0.5 rounded ${Y.current_state?za(Y.current_state.id):"text-zinc-500"}`,children:Y.current_state?Y.current_state.id:"none"}),((ie=Y.current_state)==null?void 0:ie.label)&&Y.current_state.label!==Y.current_state.id&&s.jsx("span",{className:"text-zinc-400 text-[11px]",children:Y.current_state.label}),Y.status&&Y.status!==((we=Y.current_state)==null?void 0:we.id)&&s.jsxs("span",{className:"text-zinc-500 text-[11px]",children:["engine: ",s.jsx("span",{className:`font-mono ${za(Y.status)} px-1 py-0.5 rounded text-[10px]`,children:Y.status})]}),Y.idleHoldPending&&s.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"}),Y.exited&&s.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"}),Y.cursorPosition!=null&&s.jsxs("span",{className:"text-zinc-500 text-[11px] font-mono",children:["cursor: ",s.jsxs("span",{className:"text-zinc-300",children:[Y.cursorPosition.row,",",Y.cursorPosition.col]})]}),Y.lastBusyAt>0&&s.jsxs("span",{className:"text-zinc-500 text-[11px] ml-auto",children:["last busy: ",s.jsx("span",{className:"text-zinc-400",children:pr(Y.lastBusyAt)})]})]}),((pe=Y.completionIdleDebounce)==null?void 0:pe.active)&&s.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:[s.jsx("span",{className:"text-sky-400",children:"completion_idle_after"}),s.jsxs("span",{className:"text-zinc-400",children:["age: ",s.jsxs("span",{className:"text-sky-200",children:[Y.completionIdleDebounce.ageMs,"ms"]})]}),s.jsx("span",{className:"text-zinc-500",children:"/"}),s.jsxs("span",{className:"text-zinc-400",children:["hold: ",s.jsxs("span",{className:"text-zinc-300",children:[Y.completionIdleDebounce.holdMs,"ms"]})]}),s.jsxs("span",{className:"text-zinc-400",children:["force: ",s.jsxs("span",{className:"text-zinc-300",children:[Y.completionIdleDebounce.forceAfterMs,"ms"]})]}),s.jsx("span",{className:"text-zinc-500 ml-auto",children:Y.completionIdleDebounce.ageMs<Y.completionIdleDebounce.holdMs?s.jsxs("span",{className:"text-amber-300",children:["hold remaining: ",Y.completionIdleDebounce.holdMs-Y.completionIdleDebounce.ageMs,"ms"]}):Y.completionIdleDebounce.ageMs<Y.completionIdleDebounce.forceAfterMs?s.jsxs("span",{className:"text-orange-300",children:["force in: ",Y.completionIdleDebounce.forceAfterMs-Y.completionIdleDebounce.ageMs,"ms"]}):s.jsx("span",{className:"text-red-300",children:"overdue"})})]}),Y.current_modal&&s.jsxs("div",{className:"bg-orange-900/30 border border-orange-600/40 rounded-md p-2.5",children:[s.jsx("span",{className:"text-orange-200 font-semibold",children:"Modal: "}),s.jsx("span",{className:"text-zinc-300",children:Y.current_modal.title||""}),Y.current_modal.buttons.length>0&&s.jsxs("span",{className:"text-zinc-400 ml-2",children:["[",Y.current_modal.buttons.map(W=>W.label).join(" / "),"]"]})]}),Y.fsm&&s.jsxs(s.Fragment,{children:[s.jsx(xn,{}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsxs(fn,{children:["FSM — outgoing from ",s.jsx("span",{className:"text-sky-300 font-mono normal-case",children:Y.fsm.currentState})," (held ",Gl(Y.fsm.stateAgeMs),")"]}),s.jsxs("label",{className:"ml-auto flex items-center gap-1 text-[10px] text-zinc-500 cursor-pointer select-none mb-1.5",children:[s.jsx("input",{type:"checkbox",checked:D,onChange:W=>M(W.target.checked),className:"accent-sky-500"}),"live"]})]}),s.jsxs("div",{className:"space-y-1",children:[Y.fsm.transitions.length===0&&s.jsx("div",{className:"text-zinc-600 text-[11px] italic px-1",children:"no outgoing transitions (terminal state)"}),Y.fsm.transitions.map((W,O)=>s.jsx(Ng,{t:W},O))]})]})]}),s.jsx(xn,{}),Y.sections&&Object.keys(Y.sections).length>0&&s.jsxs("div",{children:[s.jsx(fn,{children:"Sections"}),s.jsx("div",{className:"space-y-1",children:Object.entries(Y.sections).map(([W,O])=>{var X;const V=m.has(W),oe=O.split(`
48
+ `),te=((X=oe[0])==null?void 0:X.slice(0,80))||"(empty)";return s.jsxs("div",{className:"border border-zinc-700 rounded overflow-hidden bg-zinc-800/30",children:[s.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:()=>ye(W),children:[s.jsx("span",{className:"text-[10px] text-zinc-500 w-3",children:V?"▾":"▸"}),s.jsx("span",{className:"font-mono text-sky-300 w-20 shrink-0 text-[11px]",children:W}),!V&&s.jsx("span",{className:"text-zinc-400 truncate font-mono text-[11px]",children:te}),s.jsxs("span",{className:"ml-auto text-zinc-600 text-[10px] shrink-0",children:[oe.length,"L"]})]}),V&&s.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:O||"(empty)"})]},W)})})]}),s.jsx(xn,{}),Y.stateHistory&&Y.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs(fn,{children:["State History (",Y.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...Y.stateHistory].reverse().slice(0,20).map((W,O)=>s.jsxs("div",{className:"rounded px-2 py-1 hover:bg-zinc-800/60 transition-colors",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:`font-mono text-[11px] font-semibold px-1.5 py-0.5 rounded shrink-0 ${za(W.stateId)}`,children:W.stateId}),s.jsx("span",{className:"text-zinc-400 text-[11px] shrink-0 tabular-nums",children:pr(W.at)}),W.durationMs>0&&s.jsxs("span",{className:"text-zinc-500 text-[11px]",children:["held ",s.jsx("span",{className:"text-zinc-400",children:Gl(W.durationMs)})]}),W.reason&&s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${jg[String(W.reason)]??"text-zinc-400 bg-zinc-700/50 border border-zinc-600/30"}`,children:String(W.reason)}),W.debounceKind&&String(W.debounceKind)!=="none"&&s.jsxs("span",{className:"text-zinc-500 text-[10px] font-mono",children:["debounce:",String(W.debounceKind)]}),W.matchedStateId&&String(W.matchedStateId)!==W.stateId&&s.jsxs("span",{className:"text-zinc-500 text-[10px] font-mono",children:["eval→",s.jsx("span",{className:"text-zinc-300",children:String(W.matchedStateId)})]})]}),W.matchedRules&&W.matchedRules.length>0&&s.jsxs("div",{className:"flex items-start gap-1 flex-wrap mt-0.5 ml-1 pl-1 border-l border-zinc-700",children:[W.matchedRules.slice(0,3).map((V,oe)=>s.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 V=="string"?V:JSON.stringify(V)},oe)),W.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-zinc-500",children:["+",W.matchedRules.length-3," more"]})]})]},O))})]}),s.jsx(xn,{}),(()=>{const W=Y.messages??Y.committedMessages??[];if(W.length===0)return null;const O=W.filter(te=>te.role==="user").length,V=W.filter(te=>te.role==="assistant").length,oe=[...W].reverse().find(te=>te.role==="assistant");return s.jsxs("div",{children:[s.jsxs(fn,{children:["Transcript (",W.length," — ",O,"u / ",V,"a)"]}),oe&&s.jsxs("div",{className:"bg-zinc-800/50 border border-zinc-700 rounded-md p-2.5 text-[11px]",children:[s.jsxs("div",{className:"text-zinc-500 mb-1 text-[10px]",children:["Last assistant ",oe.receivedAt?pr(oe.receivedAt):""]}),s.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?"…":""]})]})]})})(),Y.specPath&&s.jsx("div",{className:"text-[10px] text-zinc-600 font-mono truncate border-t border-zinc-800 pt-2 mt-1",title:Y.specPath,children:Y.specPath}),s.jsxs("div",{children:[s.jsxs("button",{type:"button",className:"text-[11px] text-zinc-400 hover:text-zinc-200 transition-colors flex items-center gap-1.5",onClick:()=>u(W=>!W),children:[s.jsx("span",{className:"text-zinc-600",children:p?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",Y.screen?Y.screen.split(`
49
+ `).length:0," lines)"]})]}),p&&s.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:Y.screen||"(empty)"})]})]})]})]})})}function Cg({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var je;es();const{sendPtyInput:d}=lt(),[p,u]=l.useState(!1),m=l.useRef(!1);m.current=p;const[h,b]=l.useState("Runtime terminal unavailable"),[g,f]=l.useState(!1),[j,N]=l.useState(null),[y,v]=l.useState(!1),[k,w]=l.useState(!1),[x,C]=l.useState(1),[S,I]=l.useState(!1),[$,R]=l.useState(!1),[_,P]=l.useState({width:0,height:0}),[F,q]=l.useState({width:0,height:0}),[A,T]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[B,D]=l.useState(null),M=l.useRef(null),E=l.useRef(null),z=l.useRef(!1),Q=l.useRef(!1),J=l.useRef(i),ae=l.useRef(0),ne=l.useRef(!1),ce=l.useRef(""),be=l.useRef(null),Z=l.useRef(!1),Y=l.useRef(!1),ve=l.useRef(null),ye=l.useRef(null),xe=l.useRef(null),Se=32*1024,ie=()=>{var ee,se,fe,Ce;return((se=(ee=M.current)==null?void 0:ee.ownerDocument)==null?void 0:se.defaultView)||((Ce=(fe=E.current)==null?void 0:fe.ownerDocument)==null?void 0:Ce.defaultView)||window},we=ee=>{const se=ie();return{ownerWindow:se,frameId:se.requestAnimationFrame(ee)}},pe=()=>{const ee=ve.current;if(ee){try{ee.ownerWindow.cancelAnimationFrame(ee.frameId)}catch{}ve.current=null}},W=()=>{const ee=ye.current;if(ee){try{ee.ownerWindow.clearTimeout(ee.timeoutId)}catch{}ye.current=null}},O=()=>{const ee=xe.current;if(ee){try{ee.ownerWindow.clearTimeout(ee.timeoutId)}catch{}xe.current=null}},V=()=>{i&&ve.current===null&&(ve.current=we(()=>{at()}))},oe=e.tabKey,te=e.sessionId||"",X=e.daemonId||((je=e.routeId)==null?void 0:je.split(":")[0])||e.routeId||"",L=fi(e),ue=p?o||L:h,H=lg,le=cg,G=.05,Le=()=>{const ee=F.width,se=F.height;if(!Number.isFinite(_.width)||_.width<=0||!Number.isFinite(_.height)||_.height<=0||!Number.isFinite(ee)||ee<=0||!Number.isFinite(se)||se<=0)return 1;const fe=_.width/ee,Ce=_.height/se;return Number(Math.min(le,Math.max(H,Math.min(fe,Ce))).toFixed(2))},Te=Le(),Me=z.current&&x>Te,He=Number.isFinite(F.width)&&F.width>0?Math.max(_.width,Math.round(F.width*x)):_.width,qe=Number.isFinite(F.height)&&F.height>0?Math.max(_.height,Math.round(F.height*x)):_.height,Je=()=>{we(()=>{const ee=E.current;ee&&(ee.scrollLeft=0,ee.scrollTop=ee.scrollHeight-ee.clientHeight)})},st=()=>{var ee,se;ae.current=0,ne.current=!1,ce.current="",be.current=null,Z.current=!1,Y.current=!1,z.current||(Q.current=!1,C(1)),ve.current!==null&&pe(),u(!1),b("Runtime terminal unavailable"),O(),W(),N(null),D(null),I(!1),f(!1),v(!1),w(!1),(se=(ee=r.current)==null?void 0:ee.reset)==null||se.call(ee)},Xe=()=>{var ee,se;ae.current=0,ne.current=!1,ce.current="",be.current=null,Z.current=!1,Y.current=!1,ve.current!==null&&pe(),u(!0),b(""),O(),W(),N(null),D(null),I(!1),f(!1),v(!1),w(!1),(se=(ee=r.current)==null?void 0:ee.reset)==null||se.call(ee)},ct=()=>{Y.current&&(Y.current=!1,we(()=>{var ee,se;(se=(ee=r.current)==null?void 0:ee.scrollToTop)==null||se.call(ee)}))},at=()=>{if(ve.current=null,!i)return;const ee=ce.current;if(!ee)return;const se=ee.slice(0,Se);ce.current=ee.slice(se.length);const fe=r.current;if(!fe){ce.current=se+ce.current,V();return}fe.write(se,()=>{if(ce.current.length>0){V();return}ct()})},ht=ee=>{ee&&(ce.current+=ee,V())},Ae=(ee,se=0,fe,Ce,Pe={})=>{var Re,Be,_e,ze;const Ie=!!Pe.force;!Ie&&se>0&&ae.current>=se||!Ie&&se===0&&ne.current||(ae.current=se,se>0&&v(!0),u(!0),b(""),typeof fe=="number"&&typeof Ce=="number"&&fe>0&&Ce>0&&((Be=(Re=r.current)==null?void 0:Re.resize)==null||Be.call(Re,fe,Ce)),ce.current="",(ze=(_e=r.current)==null?void 0:_e.reset)==null||ze.call(_e),ee?ht(ee):ct())};l.useEffect(()=>{st()},[te]),l.useEffect(()=>{var se;if(!te)return;const ee=((se=mt.onRuntimeEvent)==null?void 0:se.call(mt,te,fe=>{if(!(!fe||fe.sessionId!==te)){if(fe.type==="runtime_snapshot"){if(!i){be.current={text:fe.text||"",seq:fe.seq||0,cols:fe.cols,rows:fe.rows,force:!!fe.force};return}Ae(fe.text||"",fe.seq||0,fe.cols,fe.rows,{force:!!fe.force});return}if(fe.type==="session_output"){ne.current=!0,typeof fe.seq=="number"&&(ae.current=Math.max(ae.current,fe.seq),fe.seq>0&&v(!0)),m.current||u(!0),m.current||b(""),typeof fe.data=="string"&&ht(fe.data);return}if(fe.type==="session_cleared"){if(!i){Z.current=!0,ce.current="",be.current=null;return}Xe();return}if(fe.type==="session_io_error"){const Ce=typeof fe.error=="string"&&fe.error?fe.error:typeof fe.reason=="string"&&fe.reason?fe.reason:"unknown error";u(!1),b(`Runtime input failed: ${Ce}`);return}}},X))||(()=>{});return()=>{ee()}},[X,te,r,i]);const ke=async(ee={})=>{var se;if(!X||!te)return{success:!1,error:"daemonId and sessionId are required"};ee.preserveStatus||b(ee.loadingMessage||"Loading runtime terminal...");try{const fe=await((se=mt.requestRuntimeSnapshot)==null?void 0:se.call(mt,X,te,{sinceSeq:ee.sinceSeq,force:ee.force}));return fe&&fe.success===!1?(ee.preserveStatus||(u(!1),b(`Runtime terminal unavailable: ${fe.error}`)),fe):fe||{success:!0}}catch(fe){const Ce=(fe==null?void 0:fe.message)||String(fe);return ee.preserveStatus||(u(!1),b(`Runtime terminal unavailable: ${Ce}`)),{success:!1,error:Ce}}},Qe=async ee=>{var Ie,Re;const se=((Ie=M.current)==null?void 0:Ie.ownerDocument)||document,fe=se.defaultView||window,Ce=(Re=fe.navigator)==null?void 0:Re.clipboard;if(Ce!=null&&Ce.writeText&&fe.isSecureContext)try{return await Ce.writeText(ee),!0}catch{}let Pe=null;try{return Pe=se.createElement("textarea"),Pe.value=ee,Pe.setAttribute("readonly","true"),Pe.style.position="fixed",Pe.style.left="-9999px",Pe.style.top="0",se.body.appendChild(Pe),Pe.focus(),Pe.select(),se.execCommand("copy")}catch{return!1}finally{Pe==null||Pe.remove()}},Ue=ee=>{W(),D(ee);const se=ie();ye.current={ownerWindow:se,timeoutId:se.setTimeout(()=>{ye.current=null,D(fe=>fe===ee?null:fe)},2200)}},gt=ee=>{O(),N(ee);const se=ie();xe.current={ownerWindow:se,timeoutId:se.setTimeout(()=>{xe.current=null,N(fe=>fe===ee?null:fe)},2200)}},U=async()=>{var Pe,Ie,Re,Be;const ee=((Ie=(Pe=r.current)==null?void 0:Pe.getSelection)==null?void 0:Ie.call(Pe))||"",se=((Be=(Re=r.current)==null?void 0:Re.getVisibleText)==null?void 0:Be.call(Re))||"",fe=ee.trimEnd()||se.trimEnd();if(!fe){Ue("Nothing to copy");return}if(!await Qe(fe)){Ue("Copy failed");return}Ue(ee.trimEnd()?"Copied selection":"Copied visible terminal")},K=ee=>{if(!p||!i)return;((d==null?void 0:d(X,te,ee))??!1)||Ue("Terminal input failed")},re=async()=>{if(g)return;f(!0),N("Loading older terminal output..."),Y.current=!0;const ee=await ke({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:p});if(f(!1),(ee==null?void 0:ee.success)===!1){Y.current=!1,N(`Older terminal output unavailable: ${ee.error}`);return}w(!0),gt("Older terminal output loaded"),we(()=>{var se;(se=r.current)==null||se.bumpResize()})};l.useEffect(()=>{var se,fe;if(!te)return;X&&((se=mt.getState)==null?void 0:se.call(mt,X))==="connected"&&ke();const ee=(fe=mt.onStateChange)==null?void 0:fe.call(mt,(Ce,Pe)=>{Ce!==X||Pe!=="connected"||ke()});return()=>{ee==null||ee()}},[X,te,r]),l.useEffect(()=>{t&&st()},[t,oe,r]),l.useEffect(()=>{var Ce,Pe;const ee=M.current,se=(Pe=(Ce=ee==null?void 0:ee.ownerDocument)==null?void 0:Ce.defaultView)==null?void 0:Pe.ResizeObserver;if(!ee||!se)return;const fe=new se(Ie=>{const Re=Ie[0];if(!Re)return;const{width:Be,height:_e}=Re.contentRect;P(ze=>{const Ve=Math.round(Be),ut=Math.round(_e);return ze.width===Ve&&ze.height===ut?ze:{width:Ve,height:ut}})});return fe.observe(ee),()=>fe.disconnect()},[]),l.useEffect(()=>{if(z.current)return;const ee=Le();!Number.isFinite(ee)||ee<=0||C(se=>Q.current?ee<se-G?ee:se:(Q.current=!0,ee))},[F.height,F.width,_.height,_.width]),l.useEffect(()=>{Me&&Je()},[Me,qe,He]),l.useEffect(()=>{var fe;const ee=J.current;if(J.current=i,!i)return;ee||w(!1),Z.current&&(Z.current=!1,Xe());const se=be.current;se&&(be.current=null,Ae(se.text,se.seq,se.cols,se.rows,{force:!!se.force})),X&&te&&((fe=mt.getState)==null?void 0:fe.call(mt,X))==="connected"&&ke(),ce.current&&ve.current===null&&V(),we(()=>{var Ce;(Ce=r.current)==null||Ce.bumpResize()})},[X,i,te]),l.useEffect(()=>()=>{ve.current!==null&&pe(),W(),O()},[]),l.useEffect(()=>{const ee=Ce=>{var Ie;const Pe=Ce.detail;Pe!=null&&Pe.sessionId&&Pe.sessionId!==te||p&&((Ie=r.current)==null||Ie.bumpResize())},se=ie(),fe=se===window?[window]:[window,se];for(const Ce of fe)Ce.addEventListener("adhdev:fit-cli-terminal",ee);return()=>{for(const Ce of fe)Ce.removeEventListener("adhdev:fit-cli-terminal",ee)}},[p,te,r]);const ge=p&&y&&!k&&(A.atTop||!A.canScroll)||g||!!j;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:M,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[ge&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{re()},disabled:!te||g,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:g?"Loading older...":"Load older terminal output"}),j&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:j})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[B&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:B}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>R(ee=>!ee),title:"Spec debug — inspect current state, sections, and transition history",children:"Debug"}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{U()},disabled:!p,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>I(ee=>!ee),disabled:!p,"aria-label":"Open terminal control keys","aria-expanded":S,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),S&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":"Terminal control keys",className:"absolute right-0 top-10 w-56 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>I(!1),"aria-label":"Close terminal control keys",children:"×"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>K("\x1B"),children:"Esc"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>K(" "),children:"Tab"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>K("\r"),children:"Enter"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>K("\x1B[A"),"aria-label":"Arrow up",children:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>K("\x1B[D"),"aria-label":"Arrow left",children:"←"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>K("\x1B[B"),"aria-label":"Arrow down",children:"↓"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>K("\x1B[C"),"aria-label":"Arrow right",children:"→"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>K(""),children:"Ctrl-C"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>K(""),children:"Ctrl-D"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>K(""),children:"Bksp"})]})]})]}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{z.current=!0,C(ee=>{const se=Math.max(Te,Number((ee-.1).toFixed(2)));return se>Te&&Je(),se})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{z.current=!0,C(ee=>{const se=Math.min(le,Number((ee+.1).toFixed(2)));return se>Te&&Je(),se})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:E,className:Me?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:He>0?`${He}px`:"100%",height:qe>0?`${qe}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.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:x},children:s.jsx(Rd,{ref:r,readOnly:!p||!i,sizingMode:"measured",onViewportMetrics:q,onScrollMetrics:T,onInput:ee=>{!p||(d==null||d(X,te,ee))}})})})}),!p&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:h})]}),s.jsx(qd,{contextKey:e.tabKey,panelLabel:it(e),isSending:a,isBusy:!!L,statusMessage:ue,onSend:async ee=>L?!1:n(ee),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),$&&s.jsx(Sg,{activeConv:e,onClose:()=>R(!1)})]})}const Ig=5e3,Mg=12e3;function Ag(e){return e==="disconnected"||e==="reconnecting"}function Tg({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=Ig,reconnectActionDelayMs:o=Mg}){const i=Ag(e),[c,d]=l.useState(()=>!i||a<=0),[p,u]=l.useState(()=>!i||o<=0),m=l.useRef(!1);l.useEffect(()=>{if(!i){d(!1);return}if(m.current=!1,a<=0){m.current=!0,d(!0);return}d(!1);const w=setTimeout(()=>{m.current=!0,d(!0)},a);return()=>clearTimeout(w)},[a,i]),l.useEffect(()=>{if(!i){u(!1);return}if(o<=0){u(!0);return}u(!1);const w=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(w)},[o,i]);const h=i?c:e==="offline"||e==="auth_failed",b=!!(n&&e!=="auth_failed"&&(!i||p)),g=l.useMemo(()=>!t||e!=="connected"?!1:a<=0||m.current,[a,t,e]),f=e==="auth_failed"?"red":e==="offline"?"orange":"accent",j={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))"},N={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)"},y={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},v="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 s.jsxs(s.Fragment,{children:[h&&s.jsx("div",{className:v,style:k,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:j[f],border:N[f],color:y[f]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&"Network offline",e==="disconnected"&&"Reconnecting",e==="reconnecting"&&"Reconnecting",e==="auth_failed"&&(r?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),b&&s.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>n==null?void 0:n(),disabled:e==="offline",children:"Reconnect now"})]})}),g&&s.jsx("div",{className:v,style:k,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function vu({mode:e,onChange:t,compact:r=!1}){const n=r?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?s.jsx(oi,{size:n}):s.jsx(Ls,{size:n})})}const Jt="New session",wu="A connected machine is ready. Start a new session with any installed provider — CLI, ACP, or IDE.";function _g(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 Lg(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 Pg(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 Qn({git:e,className:t="",compact:r=!1}){const n=_g(e),a=Lg(e);if(!n||!a)return null;const o=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return s.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${Pg(a)} ${t}`.trim(),title:o.join(" · ")||n,"data-git-tone":a,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:n})]})}function Rg({wsStatus:e,isConnected:t,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),o=a.filter(c=>c==="connected").length,i=a.filter(c=>c==="connecting"||c==="new"||c==="checking").length;return r>0&&i>0&&o===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 Vl({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function ql({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const i=fa(e.updatedAt),c=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${c?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",i].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[c?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),o()},children:"Delete"})]})]})}function Dg({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:p,hiddenConversations:u=[],onShowConversation:m,onShowAllHidden:h,onResetPanelsToMain:b,inboxOpen:g,onInboxOpenChange:f,hiddenOpen:j,onHiddenOpenChange:N,onOpenNewSession:y,onOpenDashboardGuide:v,guideNudgeVisible:k=!1,actionShortcuts:w,notifications:x,notificationUnreadCount:C,onOpenNotification:S,onMarkNotificationRead:I,onMarkNotificationUnread:$,onDeleteNotification:R,onOpenGitDialog:_,onOpenMeshGraph:P}){var Se;const{ides:F,p2pStates:q={}}=es(),A=!!e&&Ze(e)&&!Ye(e),T=!!e&&Ye(e),B=!!(e!=null&&e.daemonId)&&!!((Se=e==null?void 0:e.coordinator)!=null&&Se.meshId),D=c||(e?Yd(e)?"terminal":"chat":null),[M,E]=l.useState(!1),z=l.useRef(null),Q=l.useRef(null),J=F.filter(ie=>ie.type==="adhdev-daemon"),ae=Rg({wsStatus:t,isConnected:r,daemonCount:J.length,p2pStates:q}),ne=ae.subtitle,ce=ae.tone==="connected"?"#22c55e":ae.tone==="limited"?"#eab308":"#ef4444",be=ae.tone==="connected"?"0 0 4px #22c55e80":ae.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",Z=l.useMemo(()=>x.filter(ie=>!ie.readAt),[x]),Y=l.useMemo(()=>x.filter(ie=>!!ie.readAt),[x]),ve=l.useMemo(()=>Z.slice(0,9),[Z]),ye=C;l.useEffect(()=>{if(!g)return;const ie=we=>{var pe;(pe=z.current)!=null&&pe.contains(we.target)||f(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[g,f]),l.useEffect(()=>{if(!j)return;const ie=we=>{var pe;(pe=Q.current)!=null&&pe.contains(we.target)||N(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[j,N]),l.useEffect(()=>{if(!j&&!g)return;const ie=we=>{if(!we.altKey)return;const pe=we.code.match(/^Digit([1-9])$/);if(!pe)return;const W=Number(pe[1])-1,O=j?u[W]:void 0,V=g?ve[W]:void 0;if(!(!O&&!V)){if(we.preventDefault(),we.stopPropagation(),O){m==null||m(O),N(!1);return}V&&(S(V),f(!1))}};return window.addEventListener("keydown",ie,!0),()=>window.removeEventListener("keydown",ie,!0)},[u,j,g,ve,N,f,S,m]);const xe=ie=>{if(!ie)return;const we=n.find(pe=>pe.tabKey===ie);we&&(p==null||p(we))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(Ls,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?it(e):"Dashboard"}),s.jsx("span",{title:ae.title,"aria-label":ae.title,className:"header-title-status-dot",style:{background:ce,boxShadow:be}}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:ce,boxShadow:be}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[ne&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ne]}),y&&s.jsx("button",{type:"button",onClick:y,className:"btn btn-secondary btn-sm ml-2",title:`${Jt}${w!=null&&w.openNewSession?` (${w.openNewSession})`:""}`,"aria-label":Jt,children:s.jsx(Sd,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[v&&s.jsxs("button",{type:"button",onClick:v,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:"Dashboard guide","aria-label":"Open dashboard guide",children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),k&&s.jsx("span",{children:"Guide"})]}),e&&(A||T||!Ye(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:As(e)||it(e),children:it(e)}),_&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:()=>_(e.daemonId,e.workspacePath),children:s.jsx(Qn,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Qn,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),B&&P&&s.jsxs("button",{type:"button",onClick:()=>P(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:"Open live repo mesh graph",children:[s.jsx(rs,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:"Mesh graph"})]}),(A||T)&&i&&s.jsxs(s.Fragment,{children:[A&&d&&D&&s.jsx(vu,{mode:D,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:T?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(yt,{size:14})})]}),!Ye(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(ni,{size:14})}),!A&&!Ye(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Gt,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:z,children:[s.jsxs("div",{className:`dashboard-header-hidden${M?" is-drop-target":""}`,ref:Q,onDragEnter:ie=>{ie.dataTransfer.types.includes("text/tab-key")&&(ie.preventDefault(),E(!0))},onDragOver:ie=>{ie.dataTransfer.types.includes("text/tab-key")&&(ie.preventDefault(),ie.dataTransfer.dropEffect="move",E(!0))},onDragLeave:ie=>{ie.currentTarget.contains(ie.relatedTarget)||E(!1)},onDrop:ie=>{const we=ie.dataTransfer.getData("text/tab-key");ie.preventDefault(),E(!1),xe(we)},children:[s.jsxs("button",{type:"button",onClick:()=>N(!j),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${w!=null&&w.toggleHiddenTabs?` (${w.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(ai,{size:16}),u.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),j&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),s.jsx(Vl,{value:w==null?void 0:w.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[b&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:b,children:"Reset panels"}),u.length>0&&h&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{h(),N(!1)},children:"Restore all"})]})]}),e&&p&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>p(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),s.jsx(Vl,{value:w==null?void 0:w.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:it(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(ie=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(ie),N(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:it(ie)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(ie)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(ie)+1]}):null,As(ie)]})]},ie.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>f(!g),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Hr,{size:16}),ye>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ye})]}),g&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[Z.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),Z.map(ie=>s.jsx(ql,{notification:ie,shortcutIndex:ve.indexOf(ie)>=0?ve.indexOf(ie)+1:void 0,onOpen:()=>S(ie),onMarkRead:()=>I(ie.id),onMarkUnread:()=>$(ie.id),onDelete:()=>R(ie.id)},ie.id))]}),Y.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),Y.map(ie=>s.jsx(ql,{notification:ie,onOpen:()=>S(ie),onMarkRead:()=>I(ie.id),onMarkUnread:()=>$(ie.id),onDelete:()=>R(ie.id)},ie.id))]}),x.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function At(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function $g(e,t){return String(e||"")!==String(t||"")}function Eg(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.resumableOnly;return!r&&!n&&!a&&!o?e:e.filter(i=>!(o&&!i.canResume||r&&![i.title,i.preview].map(d=>String(d||"").toLowerCase()).join(`
50
+ `).includes(r)||n&&!String(i.workspace||"").toLowerCase().includes(n)||a&&!Hd(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
51
+ `).includes(a)))}function Bg(e,t="recent"){const r=e.slice();return r.sort((n,a)=>{if(t==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const o=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(o!==0)return o}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function ju(e,t={}){return Bg(Eg(e,t),t.sortMode||"recent")}function Zn(e){return e?"Resume saved history":"Start fresh"}function vi(e){return e?"Resuming saved history…":"Starting fresh…"}function Fg(){return"Start fresh"}function Og(e,t=!1){return e==="cli"?Zn(t):e==="ide"?"Start IDE":"Start ACP session"}function zg(e,t=!1){return e==="cli"?vi(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Hg(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Wg(){return"Open saved history"}function Kg(){return"Saved History"}function wi(){return"Use saved history when you want continuity in the same provider conversation."}function Ug(){return"No saved history found yet."}function Gg(){return"Refresh saved history"}function Vg(){return"Refreshing saved history…"}function ea(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function ta(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 sa(e){return e==="start-fresh"?"Start fresh":"Restart"}function ra(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function ku(e){return`Resume saved history with ${e}?`}function Nu(){return"Review or change the target workspace before resuming saved history."}function qg(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 Su({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:p,onClose:u,onNewChat:m,onSwitchSession:h,onRefreshHistory:b,onResumeSavedSession:g}){var R;const f=t.find(_=>_.id===e.routeId),j=(f==null?void 0:f.chats)||[],N=(R=f==null?void 0:f.activeChat)==null?void 0:R.id,y=Ze(e)&&!Ye(e),[v,k]=l.useState(()=>At()),w=c||v,x=String(d||"").trim(),C=_=>{if(p){p(_);return}k(_)},S=l.useMemo(()=>a.map(_=>{const P=String(_.workspace||"").trim();return _.canResume||P||!x?_:{..._,workspace:x,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[x,a]),I=l.useMemo(()=>ju(S,{textQuery:w.textQuery,workspaceQuery:w.workspaceQuery,modelQuery:w.modelQuery,resumableOnly:w.resumableOnly,sortMode:w.sortMode}),[S,w.modelQuery,w.resumableOnly,w.sortMode,w.textQuery,w.workspaceQuery]),$=s.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:y?Kg():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:hg(e)}),y&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:wi()})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(yt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!y&&s.jsx("button",{onClick:m,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),y?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:w.textQuery,onChange:_=>C({...w,textQuery:_.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:w.workspaceQuery,onChange:_=>C({...w,workspaceQuery:_.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:w.modelQuery,onChange:_=>C({...w,modelQuery:_.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:w.sortMode,onChange:_=>C({...w,sortMode:_.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:w.resumableOnly,onChange:_=>C({...w,resumableOnly:_.target.checked})}),"Resume-ready only"]})]}),I.map(_=>{const P=e.providerSessionId===_.providerSessionId,F=P||!_.canResume||!!i,q=_.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{F||!g||g(_)},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:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${P?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:_.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:_.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:qg(_.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:_.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[_.workspace||"Workspace unknown",q?" · selected workspace":"",Ms(_.summaryMetadata)?` · ${Ms(_.summaryMetadata)}`:"",_.messageCount>0?` · ${_.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:P?"ACTIVE":_.canResume?q?"RESUME IN SELECTED WORKSPACE":i===_.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},_.id)})]}):j.map(_=>s.jsxs("div",{onClick:()=>{h(e.routeId,_.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${N===_.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${N===_.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:_.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[_.id.substring(0,12),"..."]}),N===_.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},_.id)),(y&&!o&&I.length===0||!y&&j.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Gh,{size:32})}),s.jsx("div",{className:"text-[13px]",children:y?a.length>0?"No saved history matches these filters.":Ug():"No recent chat sessions found."})]}),y&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Vg()})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:b,disabled:n||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||o?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ha,{size:13})," ",y?Gg():"Refresh History"]})})})]})]});return typeof document>"u"?$:Pr.createPortal($,document.body)}const Yl={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 Cu({toasts:e,onDismiss:t,onClickToast:r}){return s.jsx("div",{className:"fixed right-4 z-[9999] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const a=Yl[n.type]||Yl.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var o;(o=n.actions)!=null&&o.length||r&&r(n)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:o=>{o.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(yt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((o,i)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${o.variant==="primary"||o.variant==="danger",""}`,style:o.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)"}:o.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:c=>{c.stopPropagation(),o.onClick(),t(n.id)},children:o.label},i))})]})]},n.id)})})}const Yg=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Jg(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Xg(e){return e.sessionId||e.instanceId||e.agentType}function Ha(e,t){return t||e||"unknown"}function Iu(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=$t(r,{fallbackId:r.id}));return t}function Mu(e,t={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=t.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:t.connectionStates?t.connectionStates[r]||t.defaultConnectionState||"new":t.defaultConnectionState}}function ji(e,t={}){return Qg(e,Mu(e,t))}function Qg(e,t={}){var m,h,b,g,f,j,N,y,v;const r=[],n=t.machineName,a=t.connectionState,o=Jg(e),i=e.workspace||"",c=Zf(e.type,{agentName:e.cliName}),d=Ze(e)||Ye(e)?c:Nt(e.type),p=Array.isArray(e.childSessions)?e.childSessions.map(k=>{var w,x,C;return{sessionId:k.id,instanceId:k.id,providerSessionId:k.providerSessionId,activeChatId:(w=k.activeChat)==null?void 0:w.id,transport:k.transport,sessionCapabilities:k.capabilities,agentType:k.providerType,agentName:k.providerName||Nt(k.providerType),status:k.status,title:k.title,lastMessagePreview:k.lastMessagePreview,lastMessageRole:k.lastMessageRole,lastMessageAt:k.lastMessageAt,lastMessageHash:k.lastMessageHash,messages:((x=k.activeChat)==null?void 0:x.messages)||[],activeModal:((C=k.activeChat)==null?void 0:C.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}}):[],u=Yg(e);if(u){const k=e.sessionId||e.instanceId,w=(m=e.settings)==null?void 0:m.meshCoordinatorFor,x=((h=e.settings)==null?void 0:h.meshNodeFor)||!((b=e.settings)!=null&&b.meshCoordinatorFor)&&((g=e.settings)==null?void 0:g.launchedByCoordinator),C=w?" (Coordinator)":x?" (Mesh Node)":"",S=c+C,I=(f=e.activeChat)==null?void 0:f.activeModal,$=I&&Array.isArray(I.buttons)&&I.buttons.length>0,R=ex(e.activeChat,[{status:e.status,activeModal:(j=e.activeChat)==null?void 0:j.activeModal}],e.agents||[]),_=e.activeChat||{title:"",messages:[]};let P=_.title&&String(_.title).trim()?String(_.title).trim():"";const F=(N=e.activeChat)==null?void 0:N.id,q=e.chats;if(F&&Array.isArray(q)&&q.length>0){const Q=q.find(J=>J.id===F||J.id&&String(J.id)===String(F));Q!=null&&Q.title&&String(Q.title).trim()&&(P=String(Q.title).trim())}const A=(Ze(e)||Ye(e),e.type),T=(Ze(e)||Ye(e))&&kl(P,S,A)?"":P,B=_.messages||[],D=typeof F=="string"?F.trim():"",M=(Ze(e)||Ye(e))&&D===String(e.type||"").trim(),E=D&&!M?D:e.providerSessionId,z=e.coordinator||(typeof((y=e.settings)==null?void 0:y.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:k,providerSessionId:e.providerSessionId,historySessionId:E,nativeSessionId:k,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:Ze(e)?e.mode||"terminal":"chat",agentName:S,agentType:A,status:R,title:T,messages:B,resume:e.resume,hostIdeType:!Ze(e)&&!Ye(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:T||o||(Ze(e)?e.mode==="chat"?S:`Terminal${C}`:S),displaySecondary:Ze(e)&&o?S:d,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:$?I.buttons:void 0,modalMessage:$?I.message:void 0,streamSource:"native",tabKey:Ha(k,e.id),machineName:n,connectionState:a,settings:e.settings,coordinator:z,messageInput:e.messageInput})}if(u&&(Ze(e)||Ye(e)))return r;for(const k of p){const w=k.activeModal&&Array.isArray(k.activeModal.buttons)&&k.activeModal.buttons.length>0,x=tx(k),C=Xg(k),S=`${e.id}:${C}`,I=k.title&&String(k.title).trim()||"",$=kl(I,k.agentName,k.agentType)?"":I,R=k.messages||[];if(!(k.transport==="cdp-webview"||!!k.sessionId||!!k.providerSessionId||R.length>0||w||!!$||!["idle","panel_hidden","disconnected","not_monitored"].includes(x)))continue;const P=k.coordinator||(typeof((v=k.settings)==null?void 0:v.meshCoordinatorFor)=="string"&&k.settings.meshCoordinatorFor?{meshId:k.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.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:x,title:$,messages:R,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:k.git||e.git,displayPrimary:$||o||k.agentName||d,displaySecondary:`${d} · ${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:w?k.activeModal.buttons:void 0,modalMessage:w?k.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Ha(k.sessionId||k.instanceId,S),machineName:n,connectionState:a,settings:k.settings,coordinator:P,messageInput:k.messageInput})}return r.length===0&&r.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Ha(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function Au(e){return String(e.type||e.id||"").trim()}function Zg(e){var t;return e.category!=="cli"||!Au(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 Xs(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!Zg(a))continue;const o=Au(a);if(!o||t.has(o))continue;t.add(o);const i=String(a.displayName||a.name||o),c=a.detectedPath||((n=a.lastDetection)==null?void 0:n.path)||null;r.push({type:o,label:i,icon:a.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c})}return r}function qr(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],r=new Set,n=[];for(const a of t){const o=typeof a=="string"?a.trim():"";!o||r.has(o)||(r.add(o),n.push(o))}return n}function Pn(e,t){const r=new Set(t.map(n=>n.type));return qr(e).filter(n=>r.has(n))}function Er(e){return e.map(t=>t.type)}function e0(e,t){const r=qr(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function t0(e,t){return qr(e).filter(r=>r!==t)}function Jl(e,t,r){const n=qr(e),a=n.indexOf(t);if(a<0)return n;const o=n.filter(c=>c!==t);if(r==="top")return[t,...o];if(r==="bottom")return[...o,t];const i=r==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(i,0,t),o}function Xl({direction:e}){return s.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="up"?s.jsx("polyline",{points:"18 15 12 9 6 15"}):s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function Ql({value:e,availableProviders:t,onChange:r,disabled:n=!1,saveButton:a}){const[o,i]=l.useState(""),c=l.useMemo(()=>new Map(t.map(h=>[h.type,h])),[t]),d=l.useMemo(()=>Pn(e,t),[e,t]),p=e.length-d.length,u=t.filter(h=>!d.includes(h.type)),m=()=>{o&&(r(e0(d,o)),i(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:d.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):d.map((h,b)=>{const g=c.get(h);return s.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border-subtle bg-bg-primary px-3 py-2 sm:flex-row sm:items-center sm:justify-between",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",b+1]}),(g==null?void 0:g.icon)&&s.jsx("span",{"aria-hidden":"true",children:g.icon}),s.jsx("span",{className:"font-mono text-[12px] text-text-primary",children:h}),s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:"available"})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:g?`${g.label} · ${g.statusLabel}`:h})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:n||b===0,title:"Move up",onClick:()=>r(Jl(d,h,"up")),children:s.jsx(Xl,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:n||b===d.length-1,title:"Move down",onClick:()=>r(Jl(d,h,"down")),children:s.jsx(Xl,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(t0(d,h)),children:"Remove"})]})]},h)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:"Add available CLI provider"}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:o,onChange:h=>i(h.target.value),disabled:n||u.length===0,children:[s.jsx("option",{value:"",children:u.length?"Select provider…":"No additional detected CLI providers"}),u.map(h=>s.jsxs("option",{value:h.type,children:[h.label," (",h.type,")"]},h.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!o,onClick:m,children:"Add provider"}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Inventory is filtered to CLI providers detected on this machine. New launches use this order; existing running sessions may need restart.",p>0?` ${p} provider${p===1?"":"s"} from the saved policy are not detected now and will be omitted when saved.`:""]})]})}function s0(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 Tu(e,t){const r=s0(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const _u=[{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:"🏄"}],Lu=[{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:"🧩"}],Pu=[{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:"🟠"}],r0=_u,n0=Lu,a0=Pu;function as(...e){return Hm(Wm(e))}function o0({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:as("dashboard-header",o),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function Yr({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:o="max-w-6xl",contentClassName:i,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(o0,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:as("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const zo="adhdev:themechange";function i0(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Fs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Os(e){return e==="system"?i0():e}function Ru(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Rn(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(zo,{detail:{preference:e,theme:t}}))}function l0(){const e=Fs(),t=Os(e);Ru(t),Rn(e,t)}function Rs(){const[e,t]=l.useState(Fs),[r,n]=l.useState(()=>Os(Fs()));l.useEffect(()=>{Ru(r)},[r]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const p=d.matches?"light":"dark";n(p),Rn("system",p)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=d=>{const p=d.detail||{},u=p.preference,m=p.theme;t(u==="dark"||u==="light"||u==="system"?u:Fs()),n(m==="dark"||m==="light"?m:Os(Fs()))},c=d=>{if(d.key!=="theme")return;const p=Fs(),u=Os(p);t(p),n(u)};return window.addEventListener(zo,i),window.addEventListener("storage",c),()=>{window.removeEventListener(zo,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=Os(i);t(i),n(c);try{localStorage.setItem("theme",i)}catch{}Rn(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=Os(c);n(d);try{localStorage.setItem("theme",c)}catch{}return Rn(c,d),c})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const Zl={dark:"Dark",light:"Light",system:"System"};function c0({collapsed:e}){const{preference:t,cycleTheme:r}=Rs(),n=t==="dark"?s.jsx(qh,{size:16}):t==="light"?s.jsx(Vh,{size:16}):s.jsx(Yh,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Zl[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:Zl[t]})]})}function Wa(e,t){return e?typeof e=="function"?e(t):e:null}function d0({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const[p,u]=l.useState(!1),[m,h]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),b=()=>u(!0),g=()=>u(!1),f=()=>{h(v=>{const k=!v;try{localStorage.setItem(d,k?"1":"0")}catch{}return k})},j=l.useMemo(()=>({collapsed:m,mobileMenuOpen:p,openMobileMenu:b,closeMobileMenu:g,toggleCollapsed:f}),[m,p]),N=v=>`nav-item${v.active?" active":""} cursor-pointer ${m?"justify-center py-2.5 px-0":""}${v.className?` ${v.className}`:""}`,y=v=>s.jsxs("div",{className:N(v),id:`nav-${v.id}`,onClick:()=>{v.onSelect(),g()},title:m?v.title??(typeof v.label=="string"?v.label:void 0):v.title,children:[s.jsx("span",{className:"nav-icon",children:v.icon}),!m&&v.label]},v.id);return s.jsxs("div",{className:`app-layout${p?" mobile-menu-open":""}${m?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:b,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),p&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:g,onKeyDown:v=>v.key==="Escape"&&g()}),s.jsxs("aside",{className:`sidebar ${p?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${m?"justify-center gap-0":""}`,children:Wa(t,j)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:g,children:s.jsx(yt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(y)}),n.map(v=>s.jsxs("div",{className:v.className??"border-t border-border-subtle pt-2 mt-2",children:[!m&&v.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:v.title}):null,v.items.map(y)]},v.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(y),Wa(o,j),s.jsx(c0,{collapsed:m}),Wa(i,j)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function dt({title:e,icon:t,description:r,accentColor:n,className:a,children:o}){return s.jsxs("div",{className:as("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&s.jsxs("div",{className:"mb-4",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[t&&s.jsx("span",{className:"mr-1.5",children:t}),e]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),o]})}function va({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:as("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const u0={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"},p0={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function us({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:as("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",u0[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:p0[e]}),s.jsx("span",{children:t})]}),r&&s.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function St({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:as("mb-5",n),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),r,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function Mr(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:as("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 m0={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"},h0={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function f0({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:as("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",m0[e],r),children:[s.jsx("span",{className:as("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",h0[e])}),n]})}function ys({label:e,description:t,checked:r,disabled:n,onChange:a,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o,s.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function x0({onPrefChange:e}){const[t,r]=ux(),[n,a]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const i=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return i(),window.addEventListener("focus",i),document.addEventListener("visibilitychange",i),()=>{window.removeEventListener("focus",i),document.removeEventListener("visibilitychange",i)}},[]);const o=(i,c)=>{r({[i]:c}),e==null||e(i,c)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Hr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:i=>o("globalEnabled",i)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Gt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:i=>o("browserNotifications",i)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{Ud().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Cd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:i=>o("completionAlert",i)}),s.jsx(ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Jh,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:i=>o("approvalAlert",i)}),s.jsx(ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ys,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:i=>o("disconnectAlert",i)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function na(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function b0(e,t){const r=na(e),n=na(t);if(!r||!n)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function ki(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function Ar(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||b0(r,t)>=0)return!1;const n=na(r),a=na(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function g0(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Ka(e,t){return e instanceof Error?e.message:t}function y0({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const o=e.filter(i=>i.type==="adhdev-daemon");return o.length===0?s.jsx(va,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:t||"Install ADHDev on a machine and sign in to connect it here."}):s.jsx("div",{className:"flex flex-col gap-2",children:o.map(i=>s.jsx(w0,{ide:i,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},i.id))})}function ec({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:o}){const i=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return Pr.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:c=>c.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${i}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function v0(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...r0,...n0,...a0].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function w0({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var F,q;const[o,i]=l.useState("idle"),[c,d]=l.useState(""),[p,u]=l.useState(null),[m,h]=l.useState("idle"),[b,g]=l.useState(""),f=e.version||null,j=((F=e.machine)==null?void 0:F.platform)||((q=e.system)==null?void 0:q.platform)||"",N=$t(e,{fallbackId:e.id}),y=j==="win32"?"🪟":j==="darwin"?"🍎":"🐧",v=t.filter(A=>A.daemonId===e.id&&A.transport==="cdp-page"),k=t.filter(A=>A.daemonId===e.id&&A.transport==="pty"),w=t.filter(A=>A.daemonId===e.id&&A.transport==="acp"),x=e.p2p,C=async()=>{if(r){i("upgrading"),d("Starting upgrade...");try{const A=g0(await r(e.id,"daemon_upgrade",{}));A.alreadyLatest?(i("done"),d(`Already on v${A.version||"latest"}.`)):A.upgraded||A.success?(i("done"),d(`Upgrade to v${A.version||"latest"} started. Daemon is restarting...`)):(i("error"),d(A.error||"Upgrade failed"))}catch(A){i("error"),d(Ka(A,"Connection lost during upgrade"))}}},S=async()=>{if(u(null),!!n){h("loading");try{await n(e.id),h("done"),g("Machine disconnected.")}catch(A){h("error"),g(Ka(A,"Failed to disconnect"))}}},I=async()=>{if(u(null),!!a){h("loading");try{await a(e.id),h("done"),g("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(A){h("error"),g(Ka(A,"Failed to revoke token"))}}},$="0.9.82",R=ki(e,$),_=Ar(e,$),P=v.length+k.length+w.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:y}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:N}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),f&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${R?"":"bg-bg-secondary"}`,style:R?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",f,!R&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&R&&s.jsx("button",{onClick:C,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${$}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${_?"↑ Update now":`↑ Update${` to v${$}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:m==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:m==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(f0,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[x&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${x.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${x.state==="connecting"||x.state==="new"?"animate-pulse":""}`,style:x.state==="connecting"||x.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",x.state==="connected"?"connected":x.state==="connecting"||x.state==="new"?"connecting...":x.state||"off"]}),x.peers!==void 0&&x.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",x.peers," peer",x.peers!==1?"s":"",")"]})]}),x&&P>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),P>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[v.map(A=>{const T=v0(A.type),B=A.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:T.icon}),s.jsx("span",{children:T.name}),B!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${B?"bg-green-400":"animate-pulse"}`,style:B?void 0:{background:"var(--status-warning)"},title:B?"CDP connected":"CDP connecting..."})]},A.id)}),k.map(A=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:A.cliName||"CLI"})]},A.id)),w.map(A=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:A.cliName||"ACP"})]},A.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(c||b)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||m==="error"?"text-red-400":o==="done"||m==="done"?"text-green-400":"text-text-muted"}`,children:b||c})]}),p==="disconnect"&&s.jsx(ec,{title:"🔌 Disconnect Machine",message:`Disconnect "${N}" 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:S,onCancel:()=>u(null)}),p==="revoke"&&s.jsx(ec,{title:"⚠️ Remove Machine",message:`Remove "${N}" 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:I,onCancel:()=>u(null)})]})}const j0=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function k0({daemonId:e,knownCliTypes:t=j0}){const{sendCommand:r}=lt(),[n,a]=l.useState({}),[o,i]=l.useState({}),[c,d]=l.useState(!0),[p,u]=l.useState(null),[m,h]=l.useState(null),[b,g]=l.useState(""),f=l.useCallback(async()=>{if(e){d(!0),h(null);try{const y=await r(e,"list_coordinator_prompts",{}),v=y!=null&&y.result&&typeof y.result=="object"?y.result:y;if(!(v!=null&&v.success)){h((v==null?void 0:v.error)||"Failed to load");return}const k=v.entries||{};g(v.dir||"");const w={};for(const x of t)w[x]=k[x]||{override:"",append:""};for(const x of Object.keys(k))w[x]||(w[x]=k[x]);a(w),i(JSON.parse(JSON.stringify(w)))}catch(y){h((y==null?void 0:y.message)||String(y))}finally{d(!1)}}},[r,e,t]);l.useEffect(()=>{f()},[f]);const j=l.useCallback(async(y,v)=>{var k;if(e){u(`${y}:${v}`),h(null);try{const w=((k=n[y])==null?void 0:k[v])||"",x=await r(e,"write_coordinator_prompt",{key:y,kind:v,content:w}),C=x!=null&&x.result&&typeof x.result=="object"?x.result:x;if(!(C!=null&&C.success)){h((C==null?void 0:C.error)||"Save failed");return}i(S=>({...S,[y]:{...S[y]||{override:"",append:""},[v]:w}}))}catch(w){h((w==null?void 0:w.message)||String(w))}finally{u(null)}}},[r,e,n]),N=l.useMemo(()=>(y,v)=>{var k,w;return(((k=n[y])==null?void 0:k[v])||"")!==(((w=o[y])==null?void 0:w[v])||"")},[n,o]);return e?s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",children:[s.jsxs("p",{children:["Customize the coordinator prompt this daemon's mesh coordinator sessions get. ",s.jsx("span",{className:"font-mono text-[11px]",children:b||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx("strong",{children:"Override"})," replaces the daemon's built-in base prompt for that CLI."," ",s.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."]})]}),m&&s.jsx("div",{className:"text-[12px] text-red-400 bg-red-500/10 border border-red-500/20 rounded px-3 py-2",children:m}),c&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(n).map(([y,v])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-2",children:y}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Override"}),s.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:v.override,onChange:k=>a(w=>({...w,[y]:{...w[y],override:k.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:p===`${y}:override`}),s.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void j(y,"override"),disabled:p===`${y}:override`||!N(y,"override"),children:p===`${y}:override`?"Saving…":N(y,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Append"}),s.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:v.append,onChange:k=>a(w=>({...w,[y]:{...w[y],append:k.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:p===`${y}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void j(y,"append"),disabled:p===`${y}:append`||!N(y,"append"),children:p===`${y}:append`?"Saving…":N(y,"append")?"Save append":"Saved"})})]},y))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const N0=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function S0(){const{preference:e,setPreference:t}=Rs();return s.jsx("div",{className:"flex gap-2",children:N0.map(r=>s.jsxs("button",{onClick:()=>t(r.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx("span",{children:r.icon}),r.label]},r.id))})}function C0(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 I0(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Ua(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function tc(e){const{r:t,g:r,b:n}=I0(e);return .2126*Ua(t)+.7152*Ua(r)+.0722*Ua(n)}function sc(e,t){const r=tc(e),n=tc(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function Du(e){const t=C0(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return sc(t,r)>=sc(t,n)?r:n}const Ho={bgPrimary:"#0a0e1a",bgSecondary:"#0f1320",surfacePrimary:"#111726",textPrimary:"#f0f0f5",textSecondary:"#9ca3af",textMuted:"#6b7280",borderSubtle:"#1d2536",borderDefault:"#313c52",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#111726",assistantText:"#f0f0f5",containerBg:"#0f1320",sendButton:"#d97706",inputBorder:"#313c52",bubbleRadius:16},Wo={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},M0=[{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"}}}],$u="adhdev-chat-theme",Eu="adhdev-chat-theme-custom";function Dn(){if(typeof window>"u")return"ember";try{return localStorage.getItem($u)||"ember"}catch{return"ember"}}function Wt(e){try{const t=localStorage.getItem(Eu);if(t){const r=JSON.parse(t);return{...e==="dark"?Ho:Wo,...r[e]}}}catch{}return e==="dark"?Ho:Wo}function bn(e,t){try{localStorage.setItem(Eu,JSON.stringify({dark:e,light:t}))}catch{}}function Pt(e,t){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${t})`}function aa(e,t){const r=Math.min(255,parseInt(e.slice(1,3),16)+t),n=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const A0={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Tr(e,t){var a;const r=(a=A0[e])==null?void 0:a[t];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",aa(r,24)),n.style.setProperty("--accent-on-primary",Du(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${aa(r,18)})`),n.style.setProperty("--border-accent",Pt(r,.35)),n.style.setProperty("--nav-active-bg",Pt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Pt(r,.06)}`)}function Ns(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Pt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Pt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Pt(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",Pt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Pt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",aa(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Du(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${aa(e.accentColor,40)})`),t.style.setProperty("--border-accent",Pt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Pt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Pt(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 ${Pt(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 Ni(){const e=document.documentElement;["--bg-primary","--bg-secondary","--bg-card","--surface-primary","--surface-secondary","--bg-glass","--bg-glass-hover","--text-primary","--text-secondary","--text-muted","--border-subtle","--border-default","--accent-primary","--accent-primary-light","--accent-on-primary","--accent-gradient","--border-accent","--nav-active-bg","--nav-active-shadow","--chat-user-bg","--chat-user-color","--chat-user-radius","--chat-assistant-bg","--chat-assistant-color","--chat-assistant-radius","--chat-assistant-border","--chat-container-bg","--dashboard-pane-bg","--chat-thought-accent","--chat-tool-accent","--chat-action-color","--chat-send-bg","--chat-input-border"].forEach(r=>e.style.removeProperty(r))}function T0(e){try{localStorage.setItem($u,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Ss()?"dark":"light";Ns(Wt(t))}else Ni(),Tr(e,Ss()?"dark":"light")}function _0(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Dn();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Ss()?"dark":"light";Ns(Wt(t))}else Ni(),Tr(e,Ss()?"dark":"light")}function Ss(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function It({label:e,value:t,onChange:r}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function mr({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function L0({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=l.useState(()=>Wt(r));l.useEffect(()=>{a(Wt(r))},[r]);const o=l.useCallback((i,c)=>{a(d=>{const p={...d,[i]:c},m=Wt(r==="dark"?"light":"dark");return r==="dark"?bn(p,m):bn(m,p),Ns(p),t(p),p})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",s.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(mr,{title:"App Background",children:[s.jsx(It,{label:"Background",value:n.bgPrimary,onChange:i=>o("bgPrimary",i)}),s.jsx(It,{label:"Surface",value:n.bgSecondary,onChange:i=>o("bgSecondary",i)}),s.jsx(It,{label:"Card",value:n.surfacePrimary,onChange:i=>o("surfacePrimary",i)})]}),s.jsxs(mr,{title:"App Text",children:[s.jsx(It,{label:"Primary",value:n.textPrimary,onChange:i=>o("textPrimary",i)}),s.jsx(It,{label:"Secondary",value:n.textSecondary,onChange:i=>o("textSecondary",i)}),s.jsx(It,{label:"Muted",value:n.textMuted,onChange:i=>o("textMuted",i)})]}),s.jsxs(mr,{title:"Borders & Accent",children:[s.jsx(It,{label:"Border subtle",value:n.borderSubtle,onChange:i=>o("borderSubtle",i)}),s.jsx(It,{label:"Border default",value:n.borderDefault,onChange:i=>o("borderDefault",i)}),s.jsx(It,{label:"Accent",value:n.accentColor,onChange:i=>o("accentColor",i)})]})]}),s.jsxs("div",{children:[s.jsxs(mr,{title:"Chat Bubbles",children:[s.jsx(It,{label:"User bubble",value:n.userBubble,onChange:i=>o("userBubble",i)}),s.jsx(It,{label:"User text",value:n.userText,onChange:i=>o("userText",i)}),s.jsx(It,{label:"Agent bubble",value:n.assistantBubble,onChange:i=>o("assistantBubble",i)}),s.jsx(It,{label:"Agent text",value:n.assistantText,onChange:i=>o("assistantText",i)})]}),s.jsxs(mr,{title:"Chat Layout",children:[s.jsx(It,{label:"Chat BG",value:n.containerBg,onChange:i=>o("containerBg",i)}),s.jsx(It,{label:"Send button",value:n.sendButton,onChange:i=>o("sendButton",i)}),s.jsx(It,{label:"Input border",value:n.inputBorder,onChange:i=>o("inputBorder",i)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:i=>o("bubbleRadius",Number(i.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const i=e?Ho:Wo,d=Wt(e?"light":"dark");e?bn(i,d):bn(d,i),a(i),Ns(i),t(i)},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 P0(){const[e,t]=l.useState(Dn),[r,n]=l.useState(!0),[a,o]=l.useState(()=>Wt("dark"));l.useEffect(()=>{n(Ss());const d=new MutationObserver(()=>{const m=Ss();n(m);const h=Dn();h==="custom"?Ns(Wt(m?"dark":"light")):Tr(h,m?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const m=Ss();n(m);const h=Dn();h==="custom"?Ns(Wt(m?"dark":"light")):Tr(h,m?"dark":"light")};return p.addEventListener("change",u),()=>{d.disconnect(),p.removeEventListener("change",u)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?Ns(Wt(r?"dark":"light")):(Ni(),Tr(e,r?"dark":"light"))},[e,r]),l.useEffect(()=>{o(Wt(r?"dark":"light"))},[r]);const i=d=>{t(d),T0(d)},c=[...M0,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:c.map(d=>{const p=e===d.id,u=r?d.preview.dark:d.preview.light,m=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>i(d.id),className:"text-left rounded-xl p-3 transition-all",style:{background:p?"var(--bg-glass-hover)":"var(--bg-glass)",border:p?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:p?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:u.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:m},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[p&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:d.id==="custom"?"🎨 Custom":d.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:d.description})]})]})]},d.id)})}),e==="custom"&&s.jsx(L0,{dark:r,onColorsChange:d=>o(d)})]})}const Si="adhdev_mobileDashboardMode_v1",Ko="adhdev:mobile-dashboard-mode-change";function Ci(){try{return localStorage.getItem(Si)==="workspace"?"workspace":"chat"}catch{return"chat"}}function R0(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Ci())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==Si||t()};return window.addEventListener(Ko,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Ko,r),window.removeEventListener("storage",n)}}function D0(e){try{localStorage.setItem(Si,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ko,{detail:e}))}function $0(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(Ci()==="chat")},[]),s.jsx(ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ls,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{t(r),D0(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Ga=new Map,rc=new Map;function E0(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t,n=r.machine;return!n||typeof n!="object"?null:{machine:n,timestamp:typeof r.timestamp=="number"?r.timestamp:void 0}}function B0(e,t,r,n){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n,platform:r.platform,machine:r}}function Bu(){const{sendCommand:e}=lt(),{injectEntries:t,getIdes:r}=Rr();return l.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??ub,i=rc.get(n)||0;if(!(a!=null&&a.force)&&i>0&&Date.now()-i<o)return;const c=Ga.get(n);if(c)return c;const d=(async()=>{const p=await e(n,"get_machine_runtime_stats"),u=E0(p);if(!u)return;const m=r().find(b=>b.id===n),h=B0(m,n,u.machine,u.timestamp||Date.now());t([h]),rc.set(n,Date.now())})().finally(()=>{Ga.delete(n)});return Ga.set(n,d),d},[r,t,e])}function F0(e,t,r){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r.timestamp,platform:r.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...r.machine}}}function O0(e,t){const{sendData:r}=lt(),{injectEntries:n,getIdes:a}=Rr(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(d=>Zt.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const m=a().find(b=>b.id===d),h=F0(m,d,u);n([h])}));return()=>{c.forEach(d=>d())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function z0(e,t){const{sendData:r}=lt(),[n,a]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){a(null),i(!1);return}if(!(t!=null&&t.enabled)||!r){i(!1);return}a(null),i(!0);let c=null;const d=Zt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},p=>{c&&(clearTimeout(c),c=null),a(p.diagnostics),i(!1)});return d.initialSendAccepted?c=setTimeout(()=>{i(!1)},fb):i(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:o,applyDiagnostics:a}}function H0(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Fu(e){const{sendData:t}=lt(),[r,n]=l.useState({});return l.useEffect(()=>{const a=H0(e);if(!a||!e.sessionId||!t){n({});return}const o=Zt.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{n({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),Us.record({interactionId:i.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:i.status,modalButtonCount:Array.isArray(i.modalButtons)?i.modalButtons.length:0}})});return o.initialSendAccepted||n({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const Ou="adhdev_hiddenTabs",zu="adhdev_autoHiddenMeshTabs";function W0(){try{const e=localStorage.getItem(Ou);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function bs(e){try{localStorage.setItem(Ou,JSON.stringify([...e]))}catch{}}function K0(){try{const e=localStorage.getItem(zu);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function nc(e){try{localStorage.setItem(zu,JSON.stringify([...e]))}catch{}}function jr(e){return $r(e)}function wa(e,t){return ns(t).some(r=>e.has(r))}function Hu(e){var t,r,n;return((t=e.settings)==null?void 0:t.launchedByCoordinator)===!0&&typeof((r=e.settings)==null?void 0:r.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0&&((n=e.settings)==null?void 0:n.spawnedSessionVisibility)==="hidden"}function U0(e,t,r=new Set){return e.filter(n=>{if(!Hu(n))return!1;const a=jr(n);return r.has(a)?!1:!wa(t,n)})}function G0(){const[e,t]=l.useState(W0),[r,n]=l.useState(K0),a=l.useCallback(h=>{const b=jr(h);t(g=>{const f=new Set(g);return f.has(b)?f.delete(b):f.add(b),bs(f),f})},[]),o=l.useCallback(h=>{const b=jr(h);t(g=>{if(g.has(b))return g;const f=new Set(g);return f.add(b),bs(f),f})},[]),i=l.useCallback(h=>{const b=jr(h);t(g=>{if(g.has(b))return g;const f=new Set(g);return f.add(b),bs(f),f}),n(g=>{if(g.has(b))return g;const f=new Set(g);return f.add(b),nc(f),f})},[]),c=l.useCallback(h=>{const b=jr(h);t(g=>{if(!g.has(b))return g;const f=new Set(g);return f.delete(b),bs(f),f}),n(g=>{if(g.has(b))return g;const f=new Set(g);return f.add(b),nc(f),f})},[]),d=l.useCallback(()=>{t(h=>{if(h.size===0)return h;const b=new Set;return bs(b),b})},[]),p=l.useCallback((h,b)=>{t(g=>{const f=new Set(g);for(const j of b)f.add(j);return bs(f),f})},[]),u=l.useCallback((h,b)=>{t(g=>{const f=new Set(g);for(const j of b)f.delete(j);return bs(f),f})},[]),m=l.useCallback(h=>wa(e,h),[e]);return{hiddenTabs:e,autoHiddenTabs:r,toggleTarget:a,hideTarget:o,autoHideTarget:i,showTarget:c,showAllTabs:d,hideAllForDaemon:p,showAllForDaemon:u,isHidden:m}}const gn="adhdev_mutedConversations",Va="adhdev_autoMutedMeshConversations";function ac(e){try{const t=localStorage.getItem(e);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function hr(e,t){try{localStorage.setItem(e,JSON.stringify([...t]))}catch{}}function V0(e,t){return ns(t).some(r=>e.has(r))}function q0(){const[e,t]=l.useState(()=>ac(gn)),[r,n]=l.useState(()=>ac(Va)),a=l.useCallback(p=>{const u=$r(p);t(m=>{if(m.has(u))return m;const h=new Set(m);return h.add(u),hr(gn,h),h})},[]),o=l.useCallback(p=>{const u=ns(p);t(m=>{let h=!1;const b=new Set(m);for(const g of u)b.delete(g)&&(h=!0);return h?(hr(gn,b),b):m}),n(m=>{let h=!1;const b=new Set(m);for(const g of u)b.delete(g)&&(h=!0);return h?(hr(Va,b),b):m})},[]),i=l.useCallback(p=>{ns(p).some(h=>e.has(h))?o(p):a(p)},[e,a,o]),c=l.useCallback(p=>{if(!Hu(p))return;const u=$r(p);r.has(u)||(n(m=>{if(m.has(u))return m;const h=new Set(m);return h.add(u),hr(Va,h),h}),t(m=>{if(m.has(u))return m;const h=new Set(m);return h.add(u),hr(gn,h),h}))},[r]),d=l.useCallback(p=>V0(e,p),[e]);return{mutedTargets:e,autoMutedTargets:r,muteTarget:a,unmuteTarget:o,toggleTarget:i,autoMuteIfCoordinator:c,isMuted:d}}function Y0(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function J0(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 X0(e,t,r){const n=await r(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let a=`HTTP ${n.status}`;try{const o=await n.json();typeof(o==null?void 0:o.error)=="string"&&(a=o.error)}catch{}throw new Error(a)}}async function Q0({promptSession:e,response:t,useP2PCommand:r,sendCommand:n,fetchImpl:a=fetch}){if(r){const o=await n(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!Y0(o))throw new Error(J0(o));return}await X0(e.sessionId,t,a)}function Wu(e){const{ides:t,isP2PActive:r,p2pStates:n}=es(),{sendCommand:a}=lt(),[o,i]=l.useState(null),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useMemo(()=>Ff(t,e),[t,e]),h=!!m,b=l.useMemo(()=>m?m.prompt.promptId===o?null:m:null,[o,m]),g=l.useCallback(async N=>{if(!b)return;const y=$d(b.prompt,N);d(!0),u(null);try{const v=(n==null?void 0:n[b.daemonId])==="connected"||r===!0;await Q0({promptSession:b,response:y,useP2PCommand:v,sendCommand:a}),i(b.prompt.promptId)}catch(v){throw u(v instanceof Error?v.message:String(v)),v}finally{d(!1)}},[r,n,b,a]),f=l.useCallback(()=>{b&&i(b.prompt.promptId)},[b]),j=l.useCallback(()=>{i(null),u(null)},[]);return{promptSession:b,hasActivePrompt:h,responseError:p,isSubmitting:c,submit:g,cancel:f,reopen:j}}function Ku(e){return e instanceof Error?e.message:String(e||"")}function Z0(e){const t=Ku(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 ey(e){const t=Ku(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Uu({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!Ze(e)||Ye(e))return;const o=sr(e);if(o===t)return;const i=e.sessionId;i&&a(c=>({...c,[i]:t}));try{await n(Ps(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Qt(e),mode:t})}catch(c){const d=ey(c);i&&!d&&a(p=>{const u={...p};return o===Gu(r,i)?delete u[i]:u[i]=o,u}),Z0(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function oc(e,t){const r=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!r||e.transport!=="pty")return e;const n=t[r];return!n||e.mode===n?e:{...e,mode:n}}function ty(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let r=!1;const n=e.map(a=>{const o=oc(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(d=>oc(d,t)):a.childSessions,c=i!==a.childSessions;return o!==a||c?(r=!0,{...o,...c?{childSessions:i}:{}}):a});return r?n:e}function Gu(e,t){if(!t)return null;for(const r of e){if(r.sessionId===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function sy(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,o]of Object.entries(e))Gu(t,a)===o&&(delete n[a],r=!0);return r?n:e}function ry({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){l.useEffect(()=>{Ud()},[]);const a=l.useMemo(()=>e.map(o=>({id:o.tabKey,name:bu(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return fx(a),l.useEffect(()=>{if(Object.keys(t).length===0)return;const i=setTimeout(()=>{r(c=>{const d=Date.now(),p={};for(const[u,m]of Object.entries(c))d-m<5e3&&(p[u]=m);return Object.keys(p).length===Object.keys(c).length?c:p})},5500);return()=>clearTimeout(i)},[t,r]),l.useEffect(()=>{const o=setInterval(()=>{const i=Date.now()-3e5;n(c=>{const d=c.filter(p=>p.timestamp>i).slice(-100);return d.length===c.length?c:d})},6e4);return()=>clearInterval(o)},[n]),null}function ic(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 Cs(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],r=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,n=ic(t==null?void 0:t.receivedAt)||ic(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function Uo(e,t=0){return Cs(e)||e.lastUpdated||t||0}function Vu(e){return Cs(e)||e.lastUpdated||0}function qu(e,t,r=Vu){const n=r(t)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const o=e.displayPrimary.localeCompare(t.displayPrimary);if(o!==0)return o;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function Go(e){var r;const t=Dt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function ny(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Go(e)&&!e.title.trim()}function ay(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(Go(r))-Number(Go(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:qu(t,r)})[0]||null}function Kt(e,t){const r=e.filter(i=>i.routeId===t);if(r.length===0)return null;const n=r.find(i=>i.streamSource==="native")||null,a=r.filter(i=>i.streamSource==="agent-stream"),o=ay(a);return n?o&&ny(n)?o:n:o||r[0]||null}function oy(e){const t=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return!t||r.startsWith(`${t}:`)?r:`${t}:${r}`}function iy(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=oy(n),o=r.get(a);if(!o){r.set(a,n);continue}const i=(o.workspace?1:0)+(o.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(o.timestamp||0))&&r.set(a,n)}return Array.from(r.values())}function qa(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function ly(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function lc(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?ly(Gs(r.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((r==null?void 0:r.id)||""),String((r==null?void 0:r.index)??""),String((r==null?void 0:r.receivedAt)??(r==null?void 0:r.timestamp)??""),n].join(":")}function cy(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||""),lc(e.activeChat),...t.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastMessageAt||""),r.lastMessagePreview||"",r.lastMessageRole||"",String(r.lastUpdated||""),lc(r.activeChat)].join(":"))].join("|")}function dy(e,t){const r=Date.now();return e.map(n=>{const a=t[n.tabKey];return a&&r-a<5e3?{...n,messages:[],title:""}:n})}function uy(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of ns({routeId:n.routeId}))r.set(o,a);for(const o of ns({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of ns({tabKey:n.tabKey}))r.set(o,n)}return r}function py(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function my(e){const t=py(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const r=String(t.role||""),n=Gs(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function hy({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=l.useMemo(()=>iy(e),[e]),o=l.useMemo(()=>Iu(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),p=l.useRef(new Map),u=l.useRef(new Map),m=l.useMemo(()=>{const k=new Map,w=[];for(const I of a){const{connectionState:$="new",machineName:R}=Mu(I,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),_=cy(I),P=p.current.get(I.id);if(P&&P.ide===I&&P.sourceSignature===_&&P.connectionState===$&&P.machineName===R){k.set(I.id,P),w.push(...P.conversations);continue}const F=ji(I,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),q={ide:I,sourceSignature:_,connectionState:$,machineName:R,conversations:F};k.set(I.id,q),w.push(...F)}p.current=k;const x=new Map,C=I=>{const $=my(I),R=u.current.get(I.tabKey);if(R&&R.signature===$)return x.set(I.tabKey,R),R.timestamp;const _={signature:$,timestamp:Vu(I)||(R==null?void 0:R.timestamp)||0};return x.set(I.tabKey,_),_.timestamp},S=[...w].sort((I,$)=>qu(I,$,C));return u.current=x,S},[a,t,o]),h=l.useMemo(()=>{const k=dy(m,r);return qa(i.current,k)?i.current:(i.current=k,k)},[m,r]),b=l.useMemo(()=>{const k=new Map,w=Array.from(new Set(h.map(x=>x.routeId)));for(const x of w){const C=Kt(h,x);C&&k.set(x,C)}return k},[h]),g=l.useMemo(()=>{const k=new Map;for(const w of h){const x=b.get(w.routeId),C=w.streamSource==="native"&&x?x:w;for(const S of ns({providerSessionId:w.providerSessionId,sessionId:w.sessionId,tabKey:w.tabKey}))k.set(S,C)}return k},[h,b]),f=l.useMemo(()=>uy(h,b),[h,b]),j=l.useCallback(k=>{if(k)return g.get(k)},[g]),N=l.useCallback(k=>{if(k)return f.get(k)},[f]),y=l.useMemo(()=>{const k=h.filter(w=>!wa(n,w));return qa(c.current,k)?c.current:(c.current=k,k)},[h,n]),v=l.useMemo(()=>{const k=y.map(w=>w.tabKey);return qa(d.current,k)?d.current:(d.current=k,k)},[y]);return{chatIdes:a,conversations:h,visibleConversations:y,visibleTabKeys:v,resolveConversationBySessionId:j,resolveConversationByTarget:N}}function fy({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=l.useMemo(()=>{var c;return e||!t?null:((c=r(t))==null?void 0:c.tabKey)??null},[e,r,t]),o=l.useMemo(()=>{var c;return!e||!t?null:((c=r(t))==null?void 0:c.tabKey)??null},[e,r,t]),i=l.useCallback(()=>{t&&n(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function xy({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){l.useEffect(()=>{tt.setIdes(e)},[e]),l.useEffect(()=>{tt.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=tt.onToast(o=>{r(c=>c.some(p=>p.message===o.message&&o.timestamp-p.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>r(c=>c.filter(d=>d.id!==o.id)),i)});return()=>{a()}},[r]),l.useEffect(()=>{const a=hu.on("status_event",o=>{tt.handleRawEvent(o,"ws")});return()=>{a()}},[]),l.useEffect(()=>{var o;const a=i=>{var f;const c=i.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,p=n(d),u=(p==null?void 0:p.routeId)||c.daemonId;if(!u)return;const m=Number(c.buttonIndex),h=c.button||((f=p==null?void 0:p.modalButtons)==null?void 0:f[m])||"Approve",b=String(h).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),g=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(b);t(u,"resolve_action",{action:g?"approve":"reject",button:h,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(j=>console.error("[SW Action] approval failed:",j))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",a)}},[n,t])}const by="adhdev_dashboardLayout_v1",gy="adhdev_dashboardDockview_v1",yy="adhdev_dashboardDockviewHiddenRestore_v1",fr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Ii(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function vy(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Yu(e){return`${by}:${e}`}function wy(e){const t=Yu(e);return Ii(t,null)}function jy(e,t){try{const r=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,n=Yu(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Ju(e){return`${gy}:${e}`}function ky(e){const t=Ju(e);return Ii(t,null)}function Ny(e,t){try{const r=Ju(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Xu(e){return`${yy}:${e}`}function Sy(e){const t=Xu(e);return Ii(t,{})}function Cy(e,t){try{const r=Xu(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Iy(){return{groupAssignments:[...fr.groupAssignments],focusedGroup:fr.focusedGroup,groupActiveTabIds:{...fr.groupActiveTabIds},groupTabOrders:{...fr.groupTabOrders},groupSizes:[...fr.groupSizes]}}function My(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Ay(){const[e]=l.useState(()=>vy(typeof window<"u"?window.innerWidth:1280)),[t,r]=l.useState(()=>new Map),[n,a]=l.useState(0),[o,i]=l.useState({}),[c,d]=l.useState({}),[p,u]=l.useState([]),[m,h]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[b,g]=l.useState(!1),f=l.useCallback(()=>{if(b)return;const I=wy(e)??Iy();r(new Map(I.groupAssignments)),a(I.focusedGroup),i(I.groupActiveTabIds),d(I.groupTabOrders),u(I.groupSizes),g(!0)},[b,e]);l.useEffect(()=>{b&&jy(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[b,e,t,n,o,c,p]),l.useEffect(()=>{const I=window.matchMedia("(max-width: 767px)"),$=R=>h(R.matches);return I.addEventListener("change",$),()=>I.removeEventListener("change",$)},[]);const j=l.useCallback(I=>{r(I)},[]),N=l.useCallback(I=>{a(I)},[]),y=l.useCallback(I=>{i(I)},[]),v=l.useCallback(I=>{d(I)},[]),k=l.useCallback(I=>{u(I)},[]),w=l.useCallback(I=>{N(I)},[N]),x=l.useCallback((I,$)=>{i(R=>(R[I]??null)===($??null)?R:{...R,[I]:$})},[]),C=l.useCallback((I,$)=>{d(R=>{const _=R[I];return My(_,$)?R:{...R,[I]:$}})},[]),S=l.useCallback((I,$)=>{const R=$.get(I)??0;return x(R,I),w(R),R},[w,x]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:j,focusedGroup:n,updateFocusedGroup:N,focusGroup:w,groupActiveTabIds:o,updateGroupActiveTabIds:y,setGroupActiveTab:x,groupTabOrders:c,updateGroupTabOrders:v,setGroupTabOrder:C,groupSizes:p,updateGroupSizes:k,isMobile:m,hasHydratedStoredLayout:b,hydrateStoredLayout:f,focusConversationTab:S}}function Ty(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=ya(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function _y({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:p,isRefreshingHistory:u,ides:m,handleRefreshHistory:h}){const b=l.useRef(!1),g=l.useRef(!1),f=l.useRef(null),j=l.useRef(!1);l.useEffect(()=>{if(!e||b.current||t.length===0)return;if(!a){o();return}const N=r(e);N&&(i(N.tabKey,n),b.current=!0,g.current=!0,f.current!=null&&(window.clearTimeout(f.current),f.current=null),c(y=>{const v=new URLSearchParams(y);return v.delete("activeTab"),v},{replace:!0}))},[e,t,r,n,a,o,i,c]),l.useEffect(()=>{if(!(g.current||a)&&t.length!==0){if(!e){o(),g.current=!0;return}if(b.current){g.current=!0;return}if(f.current==null)return f.current=window.setTimeout(()=>{f.current=null,!(g.current||a)&&(o(),g.current=!0)},1500),()=>{f.current!=null&&(window.clearTimeout(f.current),f.current=null)}}},[e,t.length,a,o]),l.useEffect(()=>{if(!d){j.current=!1;return}if(!p||j.current||u)return;const N=m.find(y=>y.id===p.routeId);N&&(!N.chats||N.chats.length===0||Ty(N.chats,p))&&(j.current=!0,h())},[d,p,u,m,h])}function Ya(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=ya(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Qu({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[i,c]=l.useState(!1),[d,p]=l.useState(!1),u=l.useCallback(async g=>{try{await e("standalone","launch_ide",{ideType:g,enableCdp:!0})}catch(f){console.error("Launch failed",f)}},[e]),m=l.useCallback(async(g,f)=>{try{const j=g||(t==null?void 0:t.daemonId)||"",N=await e(j,"switch_chat",{id:f,sessionId:f,...ws(t)}),y=N==null?void 0:N.result;if((N==null?void 0:N.success)===!0||y==="switched"||y==="switched-by-title")return;y===!1||y==="not_found"?dr(a,"⚠️ Session tab not found — try refreshing history"):typeof y=="string"&&y.startsWith("error:")?dr(a,`⚠️ Switch error: ${y}`):dr(a,"⚠️ Session switch failed")}catch(j){console.error("Switch failed",j),dr(a,`❌ Switch failed: ${j.message||"connection error"}`)}},[t,e,a]),h=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const g=js(t);await e(g,"new_chat",{...ws(t)}),Rb(g,t.sessionId,ya(t)[0]),o(f=>({...f,[t.tabKey]:Date.now()}))}catch(g){console.error("New chat failed",g)}finally{c(!1)}}},[t,i,e,o]),b=l.useCallback(async()=>{var g,f;if(!(!t||d)){p(!0);try{const j=js(t),N=async()=>e(j,"list_chats",{forceExpand:!0,...ws(t)});let y=await N(),v=(y==null?void 0:y.chats)||((g=y==null?void 0:y.result)==null?void 0:g.chats);Ya(v,t)&&(await new Promise(k=>setTimeout(k,450)),y=await N(),v=(y==null?void 0:y.chats)||((f=y==null?void 0:y.result)==null?void 0:f.chats)),y!=null&&y.success&&Array.isArray(v)&&(n(t.routeId,v),Ya(v,t)&&!Ya(r,t)&&dr(a,"⚠️ History dialog did not fully open — try once more"))}catch(j){console.error("Refresh history failed",j)}finally{p(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:m,handleNewChat:h,handleRefreshHistory:b}}function Ly(e,t){if(e.size!==t.size)return!1;for(const[r,n]of e)if(t.get(r)!==n)return!1;return!0}function Py(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function cc(e,t){const r=Object.keys(e),n=Object.keys(t);return r.length!==n.length?!1:r.every(a=>t[Number(a)]===e[Number(a)])}function yn(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[i,c]of e)!r.has(i)||c<=0||n.includes(c)||n.push(c);n.sort((i,c)=>i-c);const a={};n.forEach((i,c)=>{a[i]=c}),n.length===0&&(a[0]=0);const o=new Map;for(const[i,c]of e){if(!r.has(i)||c<=0)continue;const d=a[c];typeof d=="number"&&d>0&&o.set(i,d)}return{assignments:o,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function dc(e,t){const r={};for(const[n,a]of Object.entries(e)){const o=t[Number(n)];typeof o=="number"&&(r[o]=a)}return r}function Ry(e,t,r){if(t.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...t].reverse().find(a=>a<e)??t[0];return r[n]??0}function Dy(e,t,r){if(t.length<=1)return[];const n=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),a=n.length===t.length?n:Array(r).fill(100/r),o=a.reduce((i,c)=>i+c,0);return o>0?a.map(i=>i/o*100):Array(r).fill(100/r)}function uc(e,t){const r={};for(const[n,a]of Object.entries(e)){const o=Number(n);r[o>=t?o+1:o]=a}return r}function pc(e){return Array(e).fill(100/e)}function $y({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:p}){const u=l.useRef(null),m=l.useMemo(()=>yn(e,p),[e,p]),h=m.assignments,b=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),g=b>1,f=l.useCallback((w,x)=>{t(C=>{const S=new Map(yn(C,p).assignments);return x===0?S.delete(w):S.set(w,x),S}),n(C=>({...C,[x]:w})),r(x)},[t,p,n,r]),j=l.useCallback(w=>{t(x=>{const C=yn(x,p).assignments,S=new Map;for(const[I,$]of C)$!==w&&($>w?S.set(I,$-1):S.set(I,$));return S}),i(x=>{if(x.length<=1)return[];const C=[...x];C.splice(w,1);const S=C.reduce((I,$)=>I+$,0);return S>0?C.map(I=>I/S*100):[]}),r(0)},[t,p,i,r]),N=l.useCallback((w,x)=>{x.preventDefault();const C=u.current;if(!C)return;const S=x.clientX,I=C.offsetWidth,$=o.length===b?[...o]:pc(b),R=P=>{const q=(P.clientX-S)/I*100,A=[...$];A[w]=Math.max(15,$[w]+q),A[w+1]=Math.max(15,$[w+1]-q),i(A)},_=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",_),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",R),document.addEventListener("mouseup",_)},[o,b,i]),y=l.useCallback((w,x,C)=>{if(b>=4)return;const S=C==="left"?x:x+1;t(I=>{const $=yn(I,p).assignments,R=new Map;for(const _ of d){const P=$.get(_.tabKey)??0,F=P>=S?P+1:P;F>0&&R.set(_.tabKey,F)}return S>0&&R.set(w,S),R}),i(I=>{const $=I.length===b?[...I]:pc(b),R=$[x]??100/b,_=Math.max(15,R/2),P=Math.max(15,R/2),F=[...$];F[x]=_,F.splice(S,0,P);const q=F.reduce((A,T)=>A+T,0);return F.map(A=>A/q*100)}),n(I=>{const $=uc(I,S);return $[S]=w,$}),a(I=>{const $=uc(I,S);return $[S]=[w],$}),r(S)},[b,t,p,d,i,n,a,r]);l.useEffect(()=>{Ly(e,h)||t(h)},[e,h,t]),l.useEffect(()=>{const{mapping:w,usedGroups:x}=m;n(C=>{const S=dc(C,w);return cc(C,S)?C:S}),a(C=>{const S=dc(C,w);return cc(C,S)?C:S}),r(C=>{const S=c?0:Ry(C,x,w);return C===S?C:S}),i(C=>{const S=c?[]:Dy(C,x,m.groupCount);return Py(C,S)?C:S})},[m,c,n,a,r,i]);const v=l.useMemo(()=>{const w=Array.from({length:b},()=>[]);for(const x of d){const C=h.get(x.tabKey)??0,S=Math.min(C,b-1);w[S].push(x)}return w},[d,h,b]),k=l.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:h,numGroups:b,isSplitMode:g,groupedConvs:v,moveTabToGroup:f,closeGroup:j,handleResizeStart:N,splitTabRelative:y,clearAllSplits:k}}function Ja(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 Ey(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 vn(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Mi(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=Ja(t.channel)||Ja(e.updateChannel)||Ja(e.releaseChannel)||void 0,n=Ey(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=vn(t.targetVersion)||vn(e.serverVersion)||void 0,o=vn(t.minVersion)||void 0,i=vn(t.updateCommand)||(r?`adhdev update --channel ${r}`:void 0);return{...r?{channel:r}:{},...n?{npmTag:n}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...i?{updateCommand:i}:{}}}function zs(e,t=null){return Mi(e).targetVersion||t}function Zu(e){return Mi(e).channel||null}function ep(e){const t=Mi(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 By({ides:e,sendDaemonCommand:t}){const r="0.9.82",n=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:ki(m,zs(m,r))).sort((m,h)=>Number(Ar(h,zs(h,r)))-Number(Ar(m,zs(m,r)))),[r,e]),a=l.useMemo(()=>n.some(m=>Ar(m,zs(m,r))),[r,n]),o=l.useMemo(()=>n.map(m=>zs(m,r)).find(m=>typeof m=="string"&&m.trim().length>0)||r,[r,n]),[i,c]=l.useState(!1),[d,p]=l.useState({}),u=l.useCallback(async m=>{var b,g;const h=e.find(f=>f.id===m);if(h){p(f=>({...f,[m]:"upgrading"}));try{const f=await t(m,"daemon_upgrade",ep(h));(b=f==null?void 0:f.result)!=null&&b.upgraded||(g=f==null?void 0:f.result)!=null&&g.success?p(j=>({...j,[m]:"done"})):p(j=>({...j,[m]:"error"}))}catch{p(f=>({...f,[m]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const tp=80;function $n(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function Fy(e){return{...e,createdAt:$n(e.createdAt),updatedAt:$n(e.updatedAt,e.createdAt),lastEventAt:$n(e.lastEventAt,e.updatedAt||e.createdAt)}}function Oy(e){const t=$r(e);return t==="unknown:"?e.id:t}function zy(e){return[e.type,iu(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Hy(e,t=tp){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Oy(n),o=r.get(a);if(!o){r.set(a,n);continue}(n.updatedAt>o.updatedAt||n.updatedAt===o.updatedAt&&n.createdAt>o.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const o=a.updatedAt-n.updatedAt;return o!==0?o:a.createdAt-n.createdAt}).slice(0,Math.max(0,t))}function Wy(e,t){const r=Date.now(),n=[];for(const a of e){const o=a.sessionId?t.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden)continue;const i=xa(a,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=$n(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),p=zy({type:c,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||a.lastUpdated});n.push(Fy({id:p,dedupKey:p,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Xd(a),preview:Ux(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return Hy(n)}function Ky(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function Uy(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=tp}=e,a=l.useMemo(()=>Wy(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=l.useMemo(()=>Ky(a),[a]);return{notifications:a,unreadCount:o}}function Gy({notifications:e,sendDaemonCommand:t}){const r=l.useCallback(o=>{const i=e.find(d=>d.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),n=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}const Vy=l.createContext(null);function sp(){return l.useContext(Vy)}function Ai(...e){const t=new Set,r=[],n=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),r.push(o))};for(const a of e){if(Array.isArray(a)){for(const o of a)n(o);continue}n(a)}return r}function qy(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const r=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function Ti(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=qy(r);if(n)return n}return"C:\\"}for(const r of t){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function Yy(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const r=t.includes("\\")?"\\":"/",n=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(n[0]||"")?n.length<=2?`${n[0]}\\`:n.slice(0,-1).join("\\"):n.length<=2?r:n.slice(0,-1).join(r)||r}function Jy(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function _i(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=Jy(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const o=typeof(a==null?void 0:a.path)=="string"?a.path:r,i=o.includes("\\")?"\\":"/",c=(p,u)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${u}`:p==="/"||p==="\\"?`${i}${u}`:`${p.replace(/[\\/]+$/,"")}${i}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:c(o,p.name)})).sort((p,u)=>p.name.localeCompare(u.name)):[];return{path:o,directories:d}}function Xy(e,t){const r=t.meshId||"",n={meshId:r,workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp",adhdevMcpArgs:t.adhdevMcpArgs||`mcp --mode ipc --repo-mesh ${r}`};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(a,o)=>n[o]||"")}function rp(e,t={}){const r=e==null?void 0:e.mcpConfig;return(r==null?void 0:r.mode)!=="manual"?null:{serverName:r.serverName||"adhdev-mesh",configFormat:r.format,configPathCommand:r.configPathCommand,requiresRestart:r.requiresRestart===!0,instructions:r.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:Xy(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function Qy(e){if(!e||typeof e!="object")return null;const t=e,r=typeof t.instructions=="string"?t.instructions:"",n=typeof t.template=="string"?t.template:"";return!r&&!n?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:r||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:n}}function Br(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function np(e){return Gr(e)||e.tabKey||e.routeId||null}function ap(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",a=e.conversations.find(o=>{if(n&&o.routeId!==n)return!1;const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||r&&i.includes(r)||n&&o.routeId===n)});if(a!=null&&a.tabKey)return a.tabKey;if(n){const o=Kt(e.conversations,n)||e.conversations.find(i=>i.routeId===n);if(o!=null&&o.tabKey)return o.tabKey}return t||r||n||null}function ls(e){return String(e||"").trim()}function op(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function oa(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Zy(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function ev(e,t){const r=ls(e.providerSessionId),n=ls(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(ls).filter(Boolean);return!!(r&&i.includes(r)||n&&i.includes(n))});return a?a.tabKey:n||r||null}function tv(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=op(t.daemonId);if(n&&n!==e.machineId)return null;const a=ls(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=ls(e.resumeSessionId),i=ls(e.launchedSessionId),c=ls(t.providerSessionId),d=ls(t.targetSessionId);if(o&&o!==c&&o!==d||i&&i!==c&&i!==d)return null;const p=oa(e.workspacePath);if(p){const u=oa(t.workspaceName);if(u&&!Zy(u,p))return null}return ev(t,r)}function mc(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function sv({ides:e,conversations:t,onOpenSession:r}){const[n,a]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,a(null)},[]),c=l.useCallback(d=>{o.current=d,a(d)},[]);return l.useEffect(()=>{if(!n)return;const d=oa(n.workspacePath),p=e.find(m=>{var j,N,y,v;if(!m||m.type==="adhdev-daemon"||op(m.daemonId||m.id)!==n.machineId||(Dr(m)?"cli":Ws(m)?"acp":"ide")!==n.kind)return!1;const g=String(m.agentType||m.type||"");if(n.providerType&&g!==n.providerType)return!1;if(n.resumeSessionId)return String(m.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const k=String(n.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(x=>String(x||"")).filter(Boolean).includes(k)}if(d){const k=oa(m.workspace||m.runtimeWorkspaceLabel);return k?k===d:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((v=(y=(N=(j=m.activeChat)==null?void 0:j.messages)==null?void 0:N.at)==null?void 0:y.call(N,-1))==null?void 0:v.timestamp)||0)>=n.startedAt-5e3});if(!p)return;const u=ap({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});u&&(i(),r(u))},[i,t,e,r,n]),l.useEffect(()=>tt.onStatusEvent(d=>{const p=o.current;if(!p)return;const u=tv(p,d,t);u&&(i(),r(u))}),[i,t,r]),l.useEffect(()=>{if(!n)return;const d=window.setTimeout(()=>{a(p=>!p||p.startedAt!==n.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[n]),{trackPendingLaunch:c}}function rv({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const i=sp(),{launchCli:c}=pa(),d=l.useCallback(async(j,N)=>_i(e,j,N),[e]),p=l.useCallback(async(j,N)=>{if(!N.trim())return{ok:!1,error:"Choose a workspace path first."};try{const y=await e(j,"workspace_add",{path:N.trim()});return y!=null&&y.success?{ok:!0}:{ok:!1,error:(y==null?void 0:y.error)||"Could not save workspace"}}catch(y){return{ok:!1,error:y instanceof Error?y.message:"Could not save workspace"}}},[e]),u=l.useCallback(async(j,N,y)=>{var v;try{const k={ideType:N,enableCdp:!0};(v=y==null?void 0:y.workspacePath)!=null&&v.trim()&&(k.workspace=y.workspacePath.trim());const w=await e(j,"launch_ide",k);return!(w!=null&&w.success)&&(w==null?void 0:w.success)!==void 0?{ok:!1,error:(w==null?void 0:w.error)||"Could not launch IDE"}:(t({machineId:j,kind:"ide",providerType:N,workspacePath:(y==null?void 0:y.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(k){return{ok:!1,error:k instanceof Error?k.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(j,N,y,v)=>{var w,x,C;const k=Date.now();try{const S={cliType:y};(w=v==null?void 0:v.workspacePath)!=null&&w.trim()?S.dir=v.workspacePath.trim():v!=null&&v.workspaceId&&(S.workspaceId=v.workspaceId),(x=v==null?void 0:v.resumeSessionId)!=null&&x.trim()&&(S.resumeSessionId=v.resumeSessionId.trim()),Array.isArray(v==null?void 0:v.cliArgs)&&v.cliArgs.length>0&&(S.cliArgs=v.cliArgs),(C=v==null?void 0:v.initialModel)!=null&&C.trim()&&(S.initialModel=v.initialModel.trim());const I=await c(j,S),$=(I==null?void 0:I.result)||I,R=($==null?void 0:$.sessionId)||($==null?void 0:$.id);return I!=null&&I.success&&R?(t({machineId:j,kind:N,providerType:y,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,launchedSessionId:R,startedAt:k}),{ok:!0}):I!=null&&I.success?(t({machineId:j,kind:N,providerType:y,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:k}),{ok:!0}):{ok:!1,error:(I==null?void 0:I.error)||($==null?void 0:$.error)||`Could not launch ${N.toUpperCase()} session`}}catch(S){return mc(S)?(t({machineId:j,kind:N,providerType:y,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:k}),{ok:!0}):{ok:!1,error:S instanceof Error?S.message:`Could not launch ${N.toUpperCase()} session`}}},[c,e,t]),h=l.useCallback(async j=>{var N;if(i!=null&&i.listMeshes)return i.listMeshes(j);if(!j)return[];try{const y=await e(j,"list_meshes",{}),v=(y==null?void 0:y.result)??y;if((v==null?void 0:v.success)===!1)throw new Error((v==null?void 0:v.error)||"Could not load meshes");return(Array.isArray(v==null?void 0:v.meshes)?v.meshes:Array.isArray((N=v==null?void 0:v.result)==null?void 0:N.meshes)?v.result.meshes:[]).map(w=>{var x;return{id:String((w==null?void 0:w.id)||""),name:String((w==null?void 0:w.name)||(w==null?void 0:w.id)||"Untitled mesh"),repoIdentity:(w==null?void 0:w.repoIdentity)||(w==null?void 0:w.repo_identity)||null,workspace:Array.isArray(w==null?void 0:w.nodes)&&w.nodes.length>0?String(((x=w.nodes[0])==null?void 0:x.workspace)||""):null,nodesCount:Array.isArray(w==null?void 0:w.nodes)?w.nodes.length:void 0,status:(w==null?void 0:w.status)||null}}).filter(w=>w.id)}catch(y){throw console.error("List meshes failed",y),y}},[i,e]),b=l.useCallback(async(j,N,y)=>{if(!N.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(j,N,y);const v=Date.now();try{const k={meshId:N.trim()};y.trim()&&(k.cliType=y.trim());const w=await e(j,"launch_mesh_coordinator",k),x=(w==null?void 0:w.result)??w;if((x==null?void 0:x.success)===!1||(w==null?void 0:w.success)===!1){const S=String((x==null?void 0:x.code)||(w==null?void 0:w.code)||""),I=Qy((x==null?void 0:x.meshCoordinatorSetup)||(x==null?void 0:x.manualSetup)||(w==null?void 0:w.meshCoordinatorSetup)||(w==null?void 0:w.manualSetup));return{ok:!1,error:(x==null?void 0:x.error)||(w==null?void 0:w.error)||"Could not launch mesh coordinator",code:S||void 0,manualSetup:I}}const C=(x==null?void 0:x.sessionId)||(x==null?void 0:x.id);return C?r(C):t({machineId:j,kind:"cli",providerType:(x==null?void 0:x.cliType)||y.trim()||void 0,workspacePath:(x==null?void 0:x.workspace)||null,startedAt:v}),{ok:!0}}catch(k){return mc(k)?(t({machineId:j,kind:"cli",providerType:y.trim()||void 0,startedAt:v}),{ok:!0}):{ok:!1,error:k instanceof Error?k.message:"Could not launch mesh coordinator"}}},[i,r,e,t]),g=l.useCallback(async(j,N)=>{if(!j||!N)return[];try{const y=await e(j,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),v=(y==null?void 0:y.result)??y;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(y){return console.error("List saved sessions failed",y),[]}},[e]),f=l.useCallback(async j=>{await Uu({conversation:n,mode:j,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:p,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineMeshes:h,handleLaunchMeshCoordinator:b,handleListMachineSavedSessions:g,setActiveCliViewMode:f}}function nv(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 av(e,t,r=Date.now()){return!e||!nv(t)?null:{tabKey:e,nonce:r}}function ov({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:i}){const[c,d]=l.useState(null),[p,u]=l.useState(null),m=l.useMemo(()=>{var j,N;if(!e){if(c){const y=t.find(v=>v.tabKey===c);if(y)return y}return r[0]}const f=n[a];if(f){const y=t.find(v=>v.tabKey===f);if(y)return y}return((j=o[a])==null?void 0:j[0])||((N=o[0])==null?void 0:N[0])},[t,c,a,n,o,e,r]),h=l.useCallback(f=>{d(f)},[]),b=l.useCallback(f=>{d(f.tabKey),i(j=>{const N=new URLSearchParams(j),y=Vx(f);return y?N.set("activeTab",y):N.delete("activeTab"),N},{replace:!0})},[i]),g=l.useCallback((f,j)=>{const N=av(f,j);N&&u(N)},[]);return{activeConv:m,openDesktopConversation:b,requestScrollToBottom:g,scrollToBottomRequest:p,setDesktopActiveTab:h}}function iv(e){const t=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:r===e.autoReadKey?r:null}:r===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:r}:{shouldSchedule:!0,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!r,nextPendingKey:null}}function lv(e){const t=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&(!t||t!==r)),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function cv({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),d=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){p(),a.current=null;return}if(!(e!=null&&e.sessionId)){p(),a.current=null;return}const u=Vn(e,r),m=lv({tabKey:e.tabKey,historySessionId:Gr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Cs(e),liveState:u}),h=m.autoReadKey,b=iv({autoReadKey:h,shouldMarkSeen:m.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!m.shouldMarkSeen){b.shouldCancelPending&&p(),a.current=h;return}if(!b.shouldSchedule)return;b.shouldCancelPending&&p();const g=()=>{if(document.visibilityState!=="visible"||a.current===h)return;a.current=h,o.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const j=m.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:j,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=b.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(g,1500);const j=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=j,document.addEventListener("visibilitychange",j);return}const f=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(g,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=f,document.addEventListener("visibilitychange",f)},[e,t,r,n]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function Xa(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const r=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(r)?r:""}function dv({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var B;const{launchCli:p}=pa(),[u,m]=l.useState(!1),[h,b]=l.useState([]),[g,f]=l.useState(()=>At()),[j,N]=l.useState(!1),[y,v]=l.useState(null),k=l.useRef(null),w=l.useMemo(()=>r||t||e,[e,r,t]),x=!!w&&Ze(w)&&!Ye(w),C=l.useMemo(()=>{if(!w||!x)return null;const D=w.daemonId||w.routeId||"",M=Qt(w),E=Xa(w);return`${D}:${M}:${w.providerSessionId||""}:${E}`},[w,x]),S=l.useMemo(()=>!w||!x?"":Xa(w),[w,x]),{isCreatingChat:I,isRefreshingHistory:$,handleSwitchSession:R,handleNewChat:_,handleRefreshHistory:P}=Qu({sendDaemonCommand:a,activeConv:w,chats:(B=n.find(D=>D.id===(w==null?void 0:w.routeId)))==null?void 0:B.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),F=l.useCallback(()=>{m(!0)},[]),q=l.useCallback(()=>{m(!1)},[]),A=l.useCallback(async()=>{if(!(!w||!x||j)){N(!0);try{const D=w.daemonId||w.routeId,M=Qt(w),E=Xa(w),z=await a(D,"list_saved_sessions",{agentType:M,providerType:M,kind:"cli",limit:50,...w.providerSessionId?{providerSessionId:w.providerSessionId}:{},...E?{workspace:E}:{}}),Q=(z==null?void 0:z.result)??z;b(Array.isArray(Q==null?void 0:Q.sessions)?Q.sessions:[])}catch(D){console.error("Refresh saved sessions failed",D),b([])}finally{N(!1)}}},[w,j,x,a]);l.useEffect(()=>{if(!u){k.current=null;return}if(!x){k.current=null,b([]),N(!1);return}!C||j||k.current!==C&&(k.current=C,A())},[A,u,j,x,C]);const T=l.useCallback(async D=>{if(!w||!x||!D.providerSessionId||!D.workspace)return;const M=w.daemonId||w.routeId,E=Qt(w);try{v(D.providerSessionId);const z=await p(M,{cliType:E,dir:D.workspace,resumeSessionId:D.providerSessionId,initialModel:Wd(D.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Q=(z==null?void 0:z.result)??z,J=typeof(Q==null?void 0:Q.sessionId)=="string"?Q.sessionId:typeof(Q==null?void 0:Q.id)=="string"?Q.id:"";J&&d(ae=>{const ne=new URLSearchParams(ae);return ne.set("activeTab",J),ne},{replace:!0}),q()}catch(z){console.error("Resume saved session failed",z)}finally{v(null)}},[q,w,x,a,d]);return{historyModalOpen:u,openHistoryModal:F,closeHistoryModal:q,historyTargetConv:w,isSavedSessionHistoryTarget:x,isHistoryCreatingChat:I,isHistoryRefreshingHistory:$,handleHistorySwitchSession:R,handleHistoryNewChat:_,handleHistoryRefresh:P,savedHistorySessions:h,savedHistoryFilters:g,setSavedHistoryFilters:f,missingWorkspaceResumePath:S,isSavedHistoryLoading:j,resumingSavedHistorySessionId:y,handleRefreshSavedHistory:A,handleResumeSavedHistorySession:T}}function uv({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}){const[d,p]=l.useState(null),[u,m]=l.useState(null),h=l.useMemo(()=>{if(e||!n)return null;const N=c(n);return N&&!Ze(N)&&!Ye(N)?N:null},[e,n,c]),b=l.useMemo(()=>{const N=d==null?void 0:d.routeId;if(!N)return null;const y=d!=null&&d.tabKey?o.find(v=>v.tabKey===d.tabKey):a?o.find(v=>v.tabKey===a):null;return(y==null?void 0:y.routeId)===N?y:Kt(o,N)},[o,d,a]),g=l.useMemo(()=>{if(b)return i.find(N=>N.id===b.routeId)},[i,b]);l.useEffect(()=>{h&&(p({routeId:h.routeId,tabKey:Tl(h)}),m(h),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,h]);const f=l.useCallback(N=>{N&&(p({routeId:N.routeId,tabKey:Tl(N)}),m(N))},[]),j=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:b,remoteDialogIdeEntry:g,remoteDialogActiveConv:u,setRemoteDialogActiveConv:m,openRemoteDialog:f,closeRemoteDialog:j}}function pv({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:p}){const{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:h,setRemoteDialogActiveConv:b,openRemoteDialog:g,closeRemoteDialog:f}=uv({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}),[j,N]=l.useState(!1),[y,v]=l.useState(null),k=l.useCallback(async C=>{const S=C||d;!S||!Ze(S)&&!Ye(S)||(v(S),N(!0))},[d]),w=l.useCallback(()=>{N(!1),v(null)},[]),x=l.useCallback(async C=>{const S=y||d;if(!S||!Ze(S)&&!Ye(S)){w();return}N(!1);try{const I=Qt(S),$=S.routeId||S.daemonId||"";await p($,"stop_cli",{cliType:I,targetSessionId:S.sessionId,mode:C})}catch(I){console.error("Stop CLI failed:",I)}finally{v(null)}},[d,w,y,p]);return{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:h,setRemoteDialogActiveConv:b,openRemoteDialog:g,closeRemoteDialog:f,cliStopDialogOpen:j,cliStopTargetConv:y,requestCliStop:k,cancelCliStop:w,confirmCliStop:x}}function Qa(e,t=!0){return(e??!0)&&t}const Li=l.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m=null,handleFocusAgent:h,isFocusingAgent:b,actionLogs:g,userName:f,scrollToBottomRequestNonce:j,isInputActive:N=!0,isVisible:y=!0}){const v=n,k=!n,w=Qa(y,v),x=Qa(y,k),C=Qa(y),S=Fu(t),I=S.status||S.modalMessage||S.modalButtons?{...t,...S.status?{status:S.status}:{},...S.modalMessage!==void 0?{modalMessage:S.modalMessage}:{},...S.modalButtons!==void 0?{modalButtons:S.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Fd,{activeConv:I,onModalButton:i}),I.transport!=="pty"&&I.transport!=="acp"&&I.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(qs,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:c,children:"Relaunch with CDP"})]})}):null,I.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:v?"visible":"hidden",pointerEvents:v?"auto":"none"},children:s.jsx(Cg,{activeConv:I,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,isVisible:w,isInputActive:N&&w})}),s.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:s.jsx(Oo,{activeConv:I,ideEntry:a,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:b,actionLogs:g,userName:f,scrollToBottomRequestNonce:j,isInputActive:N&&x,isVisible:x})})]}):s.jsx(Oo,{activeConv:I,ideEntry:a,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:b,actionLogs:g,userName:f,scrollToBottomRequestNonce:j,isInputActive:N&&C,isVisible:C})]})},(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 mv({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var v,k,w;const i=zr(),c=Ps(e),d=o?null:Jd(e),p=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!o&&e.streamSource==="agent-stream"&&!!e.agentName,m=!o&&!u&&(e.transport==="pty"||e.transport==="acp"),h=Js(e),b=Gx(e),g=(v=e.settings)==null?void 0:v.meshNodeFor,f=e.meshQueueStats,j=((k=e.coordinator)==null?void 0:k.meshId)||((w=e.settings)==null?void 0:w.meshCoordinatorFor),N=l.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),y=l.useCallback(()=>{if(r){r();return}const x=np(e);x&&i(Br(x))},[e,i,r]);return!p&&!u&&!m&&!d&&!g&&!f?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[p&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:y,title:b,children:[s.jsx(Gt,{size:12}),s.jsx("span",{children:b})]}):s.jsxs("span",{className:"conversation-meta-chip",title:b,children:[s.jsx(Gt,{size:12}),s.jsx("span",{children:b})]})),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(Ys,{size:12}),s.jsx("span",{children:h})]}),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(Ys,{size:12}),s.jsx("span",{children:h})]}),d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:N,title:d,children:[s.jsx(ps,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(ps,{size:12}),s.jsx("span",{children:d})]})),g&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(ps,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),j&&f&&s.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:[s.jsx(Oh,{size:12}),s.jsxs("span",{children:[f.pending," Pending"]})]})]})}function hv({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:p,onOpenNativeConversation:u,onOpenMachine:m,onOpenHistory:h,onOpenRemote:b,onOpenMeshGraph:g,onStopCli:f,cliViewMode:j,onSetCliViewMode:N,handleSendChat:y,handleForceSendChat:v,handleFocusAgent:k,handleModalButton:w,handleRelaunch:x}){var _,P;const C=l.useRef(null),S=Ze(e)&&!t,I=S&&j==="terminal",$=!!e.daemonId&&!!((_=e.coordinator)!=null&&_.meshId||(P=e.settings)!=null&&P.meshCoordinatorFor),R=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${R} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(ri,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:it(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(mv,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S&&j&&s.jsx(vu,{mode:j,onChange:N,compact:!0}),S&&f&&s.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:s.jsx(yt,{size:14})}),$&&g&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(rs,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(e),type:"button",children:s.jsx(ni,{size:14})}),!t&&!S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>b(e),type:"button",children:s.jsx(Gt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(Li,{activeConv:e,clearToken:0,isCliTerminal:I,ideEntry:n,terminalRef:C,handleModalButton:w,handleRelaunch:x,handleSendChat:y,handleForceSendChat:v,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:k,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const Za={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 fv(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function ip(){const[e,t]=l.useState("unix"),[r,n]=l.useState("powershell"),[a,o]=l.useState(!1),i=e==="unix"?"unix":r;l.useEffect(()=>{t(fv())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(Za[i].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[i]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:c,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:Za[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Za[i].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function lp({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Gt},{key:"chats",label:"Chats",icon:Ls}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:a,icon:o})=>{const i=e===n;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${i?"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:i?{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":i,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${i?"text-accent-primary":"bg-transparent text-current"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(o,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function wn({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function Es({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function xr({icon:e,title:t,subtitle:r,children:n}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function xv({conversation:e,onCancel:t,onConfirm:r}){const n=it(e),a=As(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"fade-in relative w-full sm:w-[min(92vw,420px)] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] border border-border-subtle bg-bg-primary shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border-subtle bg-[var(--surface-primary)] px-4 py-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base font-extrabold text-text-primary",children:"Hide this chat from the inbox?"}),s.jsx("div",{className:"mt-1 text-[13px] leading-relaxed text-text-muted",children:"This only collapses the chat locally. You can restore it from Hidden tabs."})]}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary text-text-secondary transition-colors hover:bg-surface-primary hover:text-text-primary",onClick:t,"aria-label":"Cancel hide chat",children:s.jsx(yt,{size:16})})]}),s.jsx("div",{className:"px-4 py-4",children:s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary/60 px-3.5 py-3",children:[s.jsx("div",{className:"truncate text-sm font-bold text-text-primary",children:n}),s.jsx("div",{className:"mt-1 truncate text-xs text-text-muted",children:a})]})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-border-subtle bg-bg-secondary px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))]",children:[s.jsx("button",{type:"button",className:"btn btn-secondary min-h-[40px] px-4 text-sm",onClick:t,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary min-h-[40px] px-4 text-sm",onClick:r,children:"Hide tab"})]})]})]})}function jn({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onOpenMeshGraph:o,onCollectChatDebugBundle:i,isMuted:c,onToggleMute:d}){var _,P;const p=t==="needs_attention"||t==="task_complete",u=t==="working",m=t==="earlier",h=t==="task_complete",{isReconnecting:b,isConnecting:g}=tr(e.conversation),f=it(e.conversation),j=As(e.conversation),N=xu(e.conversation,{requiresAction:t==="needs_attention"}),y=p?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":u?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",v=p?"bg-accent-primary shadow-glow":u?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":m?"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=m?"text-text-secondary":"text-text-primary",w=m?"text-text-muted":"text-text-secondary",x=m?"text-text-secondary opacity-80":"text-text-muted",C=m?"text-text-muted opacity-80":"text-text-muted",S=!u&&!h,I=!!e.conversation.daemonId&&!!((_=e.conversation.coordinator)!=null&&_.meshId||(P=e.conversation.settings)!=null&&P.meshCoordinatorFor),$="text-[color:var(--status-warning)]",R=F=>{if(!i)return;F.preventDefault(),F.stopPropagation();const q=i==null?void 0:i(e.conversation);Promise.resolve(q).catch(A=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",A)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${y}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[p||u?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${v}`,style:p?{color:"var(--accent-on-primary)"}:void 0,children:r(f)}),a&&s.jsxs("button",{type:"button",className:"mobile-inbox-hide-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-border-subtle bg-bg-primary/70 px-2 text-[10px] font-semibold text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:F=>{F.preventDefault(),F.stopPropagation(),a()},"aria-label":`Hide ${f}`,title:"Hide conversation",children:[s.jsx(ai,{size:11}),s.jsx("span",{children:"Hide"})]}),d&&s.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 ${c?"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(),d()},"aria-label":c?`Unmute ${f}`:`Mute ${f}`,title:c?"Unmute (resume notifications)":"Mute notifications",children:[s.jsx(Hr,{size:11}),s.jsx("span",{children:c?"Muted":"Mute"})]}),I&&o&&s.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(),o(e.conversation)},"aria-label":`Open mesh graph for ${f}`,title:"Open live repo mesh graph",children:[s.jsx(rs,{size:11}),s.jsx("span",{children:"Graph"})]})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:R,type:"button",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${k}`,children:f}),S&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${C}`,children:Bd(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${w}`,children:[s.jsx("span",{className:"truncate",children:j}),s.jsx(Qn,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),b?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${$} animate-pulse`,children:"Reconnecting…"})]}):g?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):N==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:$,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${x}`,children:e.preview})]}),p&&!h&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),h&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),u&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]})},e.conversation.tabKey)}function hc({size:e=32}){return s.jsx("div",{className:"flex flex-col items-center gap-2.5",children:s.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}})})}function bv({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:p,onOpenConversation:u,onShowAllHidden:m,onHideConversation:h,onOpenMeshGraph:b,onOpenNewSession:g,onOpenMachine:f,onOpenSettings:j,onSectionChange:N,wsStatus:y="connected",isStandalone:v=!1,onCollectChatDebugBundle:k,isConversationMuted:w,onToggleMuteConversation:x}){const[C,S]=l.useState(null),I=y==="disconnected"||y==="reconnecting"||y==="offline"||y==="auth_failed",$=i.length>0,R=t.length>0||r.length>0||n.length>0||a.length>0,_=e==="machines"?"Machines":"Chats",P=v?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",F=v?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",q=l.useCallback(async B=>{const D=js(B);if(!D)return;const M=Array.isArray(B.messages)?B.messages:[],E=su({activeConv:B,visibleMessages:M,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:M.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),z=await p(D,"get_chat_debug_bundle",{...ws(B),delivery:"daemon_file",frontendSnapshot:E}),Q=Cr(z),J=au(Q),ae=await nu(J);ae==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),tt.showToast(ru(Q,{locatorCopyStatus:ae}),ae==="failed"?"warning":"success")},[d,p]),A=k||q,T=l.useCallback(()=>{C&&(h==null||h(C),S(null))},[C,h]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${P}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:_}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||r.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(Hr,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:j,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(ma,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${F}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:I?s.jsx(xr,{icon:s.jsx(hc,{}),title:y==="offline"?"Network offline":y==="auth_failed"?"Session expired":"Reconnecting",subtitle:y==="offline"?"Waiting for network…":y==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):i.length===0?s.jsx(xr,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:v?"Waiting for your daemon":"Connect your machines",subtitle:v?"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:!v&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(ip,{})})}):s.jsx(Es,{children:i.map((B,D)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${D>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(B.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:c(B.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:B.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:B.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[B.unread," new"]}):B.total>0?`${B.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:B.subtitle}),B.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[B.total," chat",B.total!==1?"s":"",B.unread>0?` · ${B.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},B.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wn,{title:"Needs attention",className:"mb-0"}),s.jsx(Es,{children:t.map((B,D)=>s.jsx("div",{className:D>0?"border-t border-border-subtle/70":"",children:s.jsx(jn,{item:B,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:h?()=>S(B.conversation):void 0,onOpenMeshGraph:b,onCollectChatDebugBundle:A,isMuted:w==null?void 0:w(B.conversation),onToggleMute:x?()=>x(B.conversation):void 0})},B.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wn,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(Es,{children:r.map((B,D)=>s.jsx("div",{className:D>0?"border-t border-border-subtle/70":"",children:s.jsx(jn,{item:B,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:h?()=>S(B.conversation):void 0,onOpenMeshGraph:b,onCollectChatDebugBundle:A,isMuted:w==null?void 0:w(B.conversation),onToggleMute:x?()=>x(B.conversation):void 0})},B.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(wn,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(Es,{children:n.map((B,D)=>s.jsx("div",{className:D>0?"border-t border-border-subtle/70":"",children:s.jsx(jn,{item:B,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:h?()=>S(B.conversation):void 0,onOpenMeshGraph:b,onCollectChatDebugBundle:A,isMuted:w==null?void 0:w(B.conversation),onToggleMute:x?()=>x(B.conversation):void 0})},B.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(wn,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(Es,{children:a.map((B,D)=>s.jsx("div",{className:D>0?"border-t border-border-subtle/70":"",children:s.jsx(jn,{item:B,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:h?()=>S(B.conversation):void 0,onOpenMeshGraph:b,onCollectChatDebugBundle:A,isMuted:w==null?void 0:w(B.conversation),onToggleMute:x?()=>x(B.conversation):void 0})},B.conversation.tabKey))}):R?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):I?s.jsx(xr,{icon:s.jsx(hc,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):$?s.jsx(xr,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(Ls,{size:20})}),title:"No conversations yet",subtitle:wu,children:g&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:g,"aria-label":Jt,title:Jt,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:Jt})]})}):s.jsx(xr,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&o.length>0&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(Es,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[o.length," collapsed ",o.length===1?"conversation":"conversations"]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:m,children:"Restore all"})]})})})]}),e==="chats"&&g&&R&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:g,"aria-label":Jt,title:Jt,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),C&&s.jsx(xv,{conversation:C,onCancel:()=>S(null),onConfirm:T}),s.jsx(lp,{section:e,onSectionChange:N})]})}function gv(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 cp(e){const t=[e.workspace||"Workspace unknown"],r=Ms(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=gv(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Pi({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:d,onConfirm:p}){const[u,m]=l.useState(r);l.useEffect(()=>{m(r)},[r]);const h=Yy(r),b=u.trim();return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:c,"aria-label":"Close folder browser",children:s.jsx(yt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!h||a||d(h)},disabled:!h||a,children:[s.jsx(ri,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:g=>m(g.target.value),onKeyDown:g=>{g.key!=="Enter"||!b||a||(g.preventDefault(),d(b))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!b||a||d(b)},disabled:!b||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):n.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:n.map(g=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(g.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Vs,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:g.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:g.path})]})]},g.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(b||r),disabled:!b&&!r||a,children:i})]})]})})}function dp({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:i="Launch",busyLabel:c="Launching…",busy:d=!1,showArgsInput:p,argsValue:u,onArgsChange:m,showModelInput:h,modelValue:b,onModelChange:g,historyProviderNode:f,onConfirm:j,onCancel:N}){const y=n==null?void 0:n.find(v=>v.key===a);return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:N,"aria-label":"Close launch confirmation",children:s.jsx(yt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:v=>o(v.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:n.map(v=>s.jsx("option",{value:v.key,children:v.label},v.key))}),(y==null?void 0:y.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:y.description})]}),f,r.map(v=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:v.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:v.value})]},`${v.label}:${v.value}`)),h&&g&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:b||"",onChange:v=>g(v.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),p&&m&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:v=>m(v.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:N,disabled:d,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:j,disabled:d,children:[s.jsx(Nd,{size:14}),d?c:i]})]})]})})}function fc(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function up(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,o=[];a&&o.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])o.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${fc(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const i=(r==null?void 0:r.trim())||"",c=i?(t.workspaces||[]).find(d=>d.path===i):null;if(i&&!c&&o.push({key:`custom:${i}`,label:fc(i),description:i,workspaceId:null,workspacePath:i}),n){const d=`saved:${n}`;if(o.some(p=>p.key===d))return{options:o,selectedKey:d}}return c?{options:o,selectedKey:`saved:${c.id}`}:i?{options:o,selectedKey:`custom:${i}`}:{options:o,selectedKey:"__home__"}}function yv(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function vv(e){return[yv(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function wv(e){return e.lastLaunchedAt?fa(e.lastLaunchedAt):""}function pp(e){return{metaText:vv(e),updatedLabel:wv(e)}}function eo(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function jv({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var Xe,ct,at,ht;const i=Ur(),[c,d]=l.useState(!1),p=(((Xe=e.detectedIdes)==null?void 0:Xe.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(Ae=>({id:Ae.id,path:Ae.path,label:Ae.label})),[e]),m=e.defaultWorkspaceId||null,[h,b]=l.useState(m||((ct=u[0])==null?void 0:ct.id)||""),[g,f]=l.useState(""),[j,N]=l.useState(""),[y,v]=l.useState([]),[k,w]=l.useState(!1),[x,C]=l.useState(""),[S,I]=l.useState(!1),[$,R]=l.useState(eo(p,t.length,r.length)),_=l.useRef(null),[P,F]=l.useState(null),q=l.useRef("__home__"),[A,T]=l.useState("__home__"),[B,D]=l.useState(""),[M,E]=l.useState(""),[z,Q]=l.useState(""),[J,ae]=l.useState([]),[ne,ce]=l.useState(()=>At().textQuery),[be,Z]=l.useState(()=>At().workspaceQuery),[Y,ve]=l.useState(()=>At().modelQuery),[ye,xe]=l.useState(()=>At().resumableOnly),[Se,ie]=l.useState(()=>At().sortMode),[we,pe]=l.useState(!1),[W,O]=l.useState(!1),V=l.useRef(null),oe=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const te=h==="__custom__"?g.trim():((at=u.find(Ae=>Ae.id===h))==null?void 0:at.path)||"",X=h==="__custom__"&&!!te&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),L=h!=="__custom__"&&((ht=u.find(Ae=>Ae.id===h))==null?void 0:ht.path)||"",ue=l.useMemo(()=>(e.recentLaunches||[]).map(Ae=>Ae.workspace),[e]),H=l.useCallback(async Ae=>{w(!0),C("");try{const ke=await a(Ae);N(ke.path),f(ke.path),v(ke.directories)}catch(ke){C(ke instanceof Error?ke.message:"Could not load folder")}finally{w(!1)}},[a]),le=l.useCallback(()=>{var ke;b("__custom__"),I(!0);const Ae=Ti(e.platform,Ai(g.trim(),L,ue,e.defaultWorkspacePath,(ke=u.find(Qe=>Qe.id===m))==null?void 0:ke.path,u.map(Qe=>Qe.path)));H(Ae)},[g,m,H,ue,L,e.platform,u]),G=l.useCallback(Ae=>{if(Ae!=null&&Ae.workspaceId){b(Ae.workspaceId),f("");return}if(Ae!=null&&Ae.workspacePath){b("__custom__"),f(Ae.workspacePath);return}b(""),f("")},[]),Le=l.useCallback(Ae=>{if(b(Ae),Ae==="__custom__"){le();return}f("")},[le]),Te=l.useCallback(Ae=>{b("__custom__"),f(Ae)},[]),Me=l.useCallback((Ae,ke)=>{_.current=ke,q.current=Ae.selectedWorkspaceKey||"__home__",T(Ae.selectedWorkspaceKey||"__home__"),D(Ae.initialArgs||""),E(Ae.initialModel||""),Q(""),ae([]);const Qe=Ae.providerType?`${e.id}:${Ae.providerType}`:null;if($g(oe.current,Qe)){const Ue=At();ce(Ue.textQuery),Z(Ue.workspaceQuery),ve(Ue.modelQuery),xe(Ue.resumableOnly),ie(Ue.sortMode)}oe.current=Qe,F(Ae),Ae.providerType&&o&&(pe(!0),o(Ae.providerType).then(Ue=>ae(Ue||[])).catch(Ue=>console.warn("Failed to load saved sessions",Ue)).finally(()=>pe(!1)))},[o,e.id]),He=l.useMemo(()=>ju(J,{textQuery:ne,workspaceQuery:be,modelQuery:Y,resumableOnly:ye,sortMode:Se}),[Y,ye,J,Se,ne,be]);l.useEffect(()=>{z&&(He.some(Ae=>Ae.providerSessionId===z)||Q(""))},[He,z]);const qe=l.useCallback(()=>{_.current&&(O(!0),_.current().finally(()=>{_.current=null,O(!1),F(null)}))},[]),Je=l.useCallback(()=>{_.current=null,F(null)},[]),st=l.useCallback(Ae=>{q.current=Ae,T(Ae)},[]);return l.useEffect(()=>{var Ae;V.current!==e.id&&(V.current=e.id,b(m||((Ae=u[0])==null?void 0:Ae.id)||"__custom__"),f(""),N(""),v([]),C(""),I(!1),ce(At().textQuery),Z(At().workspaceQuery),ve(At().modelQuery),xe(At().resumableOnly),ie(At().sortMode),oe.current=null,R(eo(p,t.length,r.length)))},[r.length,t.length,m,p,e.id,u]),l.useEffect(()=>{var Ae;h!=="__custom__"&&(h&&u.some(ke=>ke.id===h)||b(m||((Ae=u[0])==null?void 0:Ae.id)||"__custom__"))},[m,h,u]),l.useEffect(()=>{$==="ide"&&p||$==="cli"&&t.length>0||$==="acp"&&r.length>0||R(eo(p,t.length,r.length))},[$,r.length,t.length,p]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:p,workspaceRows:u,defaultWorkspaceId:m,workspaceChoice:h,customWorkspacePath:g,browseCurrentPath:j,browseDirectories:y,browseBusy:k,browseError:x,browseDialogOpen:S,activeLauncherKind:$,launchConfirm:P,launchConfirmWorkspaceKeyRef:q,launchConfirmWorkspaceKey:A,launchConfirmArgs:B,launchConfirmModel:M,launchConfirmResumeId:z,launchConfirmSavedSessions:J,launchConfirmTextFilter:ne,launchConfirmWorkspaceFilter:be,launchConfirmModelFilter:Y,launchConfirmResumableOnly:ye,launchConfirmSortMode:Se,filteredLaunchConfirmSavedSessions:He,launchConfirmSessionsLoading:we,launchConfirmBusy:W,resolvedWorkspacePath:te,canCreateMissingWorkspace:X,openBrowseDialog:le,loadBrowsePath:H,handleWorkspaceChoiceChange:Le,chooseCustomWorkspacePath:Te,setCustomWorkspacePath:f,setBrowseDialogOpen:I,setActiveLauncherKind:R,openLaunchConfirm:Me,handleConfirmLaunch:qe,closeLaunchConfirm:Je,setWorkspaceSelectionFromOption:G,setLaunchConfirmWorkspaceKeyAndSync:st,setLaunchConfirmArgs:D,setLaunchConfirmModel:E,setLaunchConfirmResumeId:Q,setLaunchConfirmTextFilter:ce,setLaunchConfirmWorkspaceFilter:Z,setLaunchConfirmModelFilter:ve,setLaunchConfirmResumableOnly:xe,setLaunchConfirmSortMode:ie}}function kv({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:d,section:p,showBottomNav:u,onBack:m,onSectionChange:h,onOpenConversation:b,onOpenRecent:g,onOpenMachineDetails:f,onMachineUpgrade:j,onLaunchDetectedIde:N,onAddWorkspace:y,onBrowseDirectory:v,onLaunchWorkspaceProvider:k,onListSavedSessions:w}){const x=A=>A==="ide"?"Workspace":A==="cli"?"CLI":"ACP",C=r.slice(0,4),S=t.slice(0,3),I=jv({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:c,onBrowseDirectory:v,onListSavedSessions:w}),$=l.useMemo(()=>C.map(A=>{const{metaText:T,updatedLabel:B}=pp(A);return{key:`recent-launch:${A.id}`,primary:A.label,secondary:T,updatedLabel:B,onClick:()=>{const{options:D,selectedKey:M}=up({machine:{workspaces:I.workspaceRows,defaultWorkspaceId:I.defaultWorkspaceId},currentWorkspacePath:A.workspace});I.openLaunchConfirm({title:A.kind==="ide"?ea("restart-ide",A.label):A.providerSessionId?ku(A.label):ea("start-fresh",A.label),description:A.kind==="ide"?ta("restart-ide"):A.providerSessionId?Nu():ta("start-fresh"),confirmLabel:A.kind==="ide"?sa("restart-ide"):A.providerSessionId?Zn(!0):sa("start-fresh"),busyLabel:A.kind==="ide"?ra("restart-ide"):A.providerSessionId?vi(!0):ra("start-fresh"),workspaceOptions:D,selectedWorkspaceKey:M,details:[{label:"Mode",value:x(A.kind)},...A.providerType?[{label:"Provider",value:A.providerType}]:[]]},async()=>{const E=D.find(z=>z.key===I.launchConfirmWorkspaceKeyRef.current);I.setWorkspaceSelectionFromOption(E),await g({...A,workspace:(E==null?void 0:E.workspacePath)??null})})}}}),[I,g,C]),R=l.useMemo(()=>S.map(A=>({key:`recent-chat:${A.conversation.tabKey}`,primary:it(A.conversation),secondary:pg(A.conversation,{timestampLabel:A.timestamp?Bd(A.timestamp):null}),unread:A.unread,onClick:()=>b(A.conversation)})),[b,S]),_=I.showAllRecent?$:$.slice(0,4),P=$.length>0,F=R.length>0,q=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${q} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx(ri,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:$t(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[F&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:R.map(A=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${A.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:A.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:A.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:A.secondary})]},A.key))})]}),P&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:_.map(A=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:A.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:A.primary}),A.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:A.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:A.secondary})]},A.key))}),$.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>I.setShowAllRecent(A=>!A),children:I.showAllRecent?"Show fewer":`Show ${$.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:j,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:f,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),I.browseDialogOpen&&s.jsx(Pi,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:I.browseCurrentPath,directories:I.browseDirectories,busy:I.browseBusy,error:I.browseError,confirmLabel:"Use this folder",onClose:()=>I.setBrowseDialogOpen(!1),onNavigate:A=>{I.loadBrowsePath(A)},onConfirm:A=>{I.chooseCustomWorkspacePath(A),I.setBrowseDialogOpen(!1)}}),I.launchConfirm&&s.jsx(dp,{title:I.launchConfirm.title,description:I.launchConfirm.description,details:I.launchConfirm.details,workspaceOptions:I.launchConfirm.workspaceOptions,selectedWorkspaceKey:I.launchConfirmWorkspaceKey,onWorkspaceChange:I.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:I.launchConfirm.providerType?Zn(!!I.launchConfirmResumeId):I.launchConfirm.confirmLabel,busyLabel:I.launchConfirm.providerType?void 0:I.launchConfirm.busyLabel,busy:I.launchConfirmBusy,showArgsInput:I.launchConfirm.showArgsInput,argsValue:I.launchConfirmArgs,onArgsChange:I.setLaunchConfirmArgs,showModelInput:I.launchConfirm.showModelInput,modelValue:I.launchConfirmModel,onModelChange:I.setLaunchConfirmModel,historyProviderNode:I.launchConfirm.providerType&&(I.launchConfirmSessionsLoading||I.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),I.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:wi()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:I.launchConfirmTextFilter,onChange:A=>I.setLaunchConfirmTextFilter(A.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:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:I.launchConfirmWorkspaceFilter,onChange:A=>I.setLaunchConfirmWorkspaceFilter(A.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:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:I.launchConfirmModelFilter,onChange:A=>I.setLaunchConfirmModelFilter(A.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:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),s.jsxs("select",{value:I.launchConfirmSortMode,onChange:A=>I.setLaunchConfirmSortMode(A.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:I.launchConfirmResumableOnly,onChange:A=>I.setLaunchConfirmResumableOnly(A.target.checked),disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:I.launchConfirmResumeId,onChange:A=>I.setLaunchConfirmResumeId(A.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Fg()}),I.filteredLaunchConfirmSavedSessions.map(A=>s.jsxs("option",{value:A.providerSessionId,disabled:!A.canResume,children:[A.title||A.providerSessionId," ",A.canResume?"":"(workspace missing)"]},A.providerSessionId))]}),!I.launchConfirmSessionsLoading&&I.launchConfirmSavedSessions.length>0&&I.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),I.launchConfirmResumeId&&(()=>{const A=I.filteredLaunchConfirmSavedSessions.find(B=>B.providerSessionId===I.launchConfirmResumeId);if(!A)return null;const T=cp(A);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:T.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:T.providerSessionId}),s.jsx("div",{className:"mt-1",children:T.metaLine}),T.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:T.updatedLabel}),T.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:T.preview})]})})()]}),onConfirm:I.handleConfirmLaunch,onCancel:I.closeLaunchConfirm}),u&&s.jsx(lp,{section:p,onSectionChange:h})]})}function En(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Nv(e,t=[]){const r=new Map(e.map(a=>[a.conversation.tabKey,a])),n=t.map(a=>r.get(a)).filter(a=>!!a);return n.length===e.length?n:En(e)}function Sv(e){var r;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":"Offline"}function Cv(e,t){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:Ms(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 i;const a=Dr(n)?"cli":Ws(n)?"acp":"ide",o=Ms(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||(Dr(n)?n.cliName||n.type:Ws(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ws(n)?o||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:n.lastMessageAt||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Iv(e,t){const r=new Map;for(const n of t){const a=Ps(n.conversation),o=r.get(a);o?o.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],o=[...a].sort((m,h)=>h.timestamp-m.timestamp)[0]||null,i=(o==null?void 0:o.conversation)||null,c=Po(n),d=a.filter(m=>m.unread||m.requiresAction).length,p=Sv(n),u=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:$t(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:i,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:c,preview:i?mg(i):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,a)=>{const o=n.latestTimestamp||n.fallbackActivityAt||0,i=a.latestTimestamp||a.fallbackActivityAt||0;return i!==o?i-o:n.label.localeCompare(a.label)})}function Mv(e){return e==="chat"}function kn(e,t){var r;if(!(typeof window>"u"))try{if(!(!!((r=import.meta.env)!=null&&r.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function Av({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:b,setSelectedTabKey:g,setScreen:f,setSelectedMachineId:j,setSection:N,setMachineBackTarget:y,resetMachineAction:v}){const k=l.useRef(null),w=l.useCallback(x=>{if(!(x!=null&&x.sessionId))return;const C=Vn(x,i),S=Math.max(Date.now(),Cs(x),C.lastUpdated||0);kn("mark_read:start",{tabKey:x.tabKey,sessionId:x.sessionId,displayPrimary:it(x),inboxBucket:C.inboxBucket,unread:C.unread,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,activityAt:Cs(x),readAt:S}),c(Ps(x)||x.routeId,"mark_session_seen",{sessionId:x.sessionId,providerSessionId:x.providerSessionId,seenAt:S,completionMarker:C.completionMarker}).then(I=>{kn("mark_read:result",{tabKey:x.tabKey,sessionId:x.sessionId,result:I})}).catch(I=>{kn("mark_read:error",{tabKey:x.tabKey,sessionId:x.sessionId,error:I instanceof Error?I.message:String(I)})})},[i,c]);return l.useEffect(()=>{var C;if(!n){Mv(o)&&f("inbox"),g(((C=e[0])==null?void 0:C.tabKey)||null),k.current=null;return}if(o!=="chat"){k.current=null;return}const x=`${n.tabKey}:${n.sessionId||""}`;k.current!==x&&(k.current=x,w(n))},[e,w,o,n,f,g]),l.useEffect(()=>{if(!d)return;const x=e.find(C=>C.tabKey===d);x&&(g(x.tabKey),f("chat"),p==null||p())},[e,p,d,f,g]),l.useEffect(()=>{if(!u)return;const x=t.find(C=>C.id===u);x&&(j(x.id),v(),N("machines"),y("inbox"),f("machine"),m==null||m())},[t,m,u,v,y,f,N,j]),l.useEffect(()=>{h&&(N(h),f("inbox"),b==null||b())},[b,h,f,N]),l.useEffect(()=>{const x=r.filter(C=>C.inboxBucket==="task_complete"||C.unread);x.length!==0&&kn("inbox_state",{screen:o,selectedTabKey:a,items:x.map(C=>{const S=Vn(C.conversation,i);return{liveState:S,tabKey:C.conversation.tabKey,sessionId:C.conversation.sessionId,displayPrimary:it(C.conversation),serverBucket:S.inboxBucket,computedBucket:C.inboxBucket,serverUnread:S.unread,computedUnread:C.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:Cs(C.conversation)}})})},[r,i,o,a]),{markConversationRead:w}}function Tv(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function xc(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function _v(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Lv({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const{launchCli:a}=pa(),[o,i]=l.useState("idle"),[c,d]=l.useState(""),[p,u]=l.useState(null),m=l.useCallback(()=>{i("idle"),d(""),u(null)},[]),h=l.useCallback(async(v,k,w)=>{var x;try{i("loading"),d(`Launching ${k}…`);const C={ideType:k,enableCdp:!0};(x=w==null?void 0:w.workspacePath)!=null&&x.trim()&&(C.workspace=w.workspacePath.trim()),await e(v,"launch_ide",C),i("done"),d(`${k} launch requested`)}catch(C){i("error"),d(C instanceof Error?C.message:"Launch IDE failed"),console.error("Launch IDE failed",C)}},[e]),b=l.useCallback(async(v,k,w)=>{if(k.trim())try{i("loading"),d(w!=null&&w.createIfMissing?"Creating folder…":"Saving workspace…");const x=await e(v,"workspace_add",{path:k.trim(),createIfMissing:(w==null?void 0:w.createIfMissing)===!0});if(x!=null&&x.success){i("done"),d(w!=null&&w.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((x==null?void 0:x.error)||"Could not save workspace")}catch(x){i("error"),d(x instanceof Error?x.message:"Could not save workspace")}},[e]),g=l.useCallback(async v=>{var k,w,x,C,S,I;try{i("loading"),d("Starting daemon upgrade…");const $=await e(v,"daemon_upgrade",{});if((k=$==null?void 0:$.result)!=null&&k.alreadyLatest){i("done"),d(`Already on v${((w=$==null?void 0:$.result)==null?void 0:w.version)||"latest"}.`);return}if((x=$==null?void 0:$.result)!=null&&x.upgraded||(C=$==null?void 0:$.result)!=null&&C.success){i("done"),d(`Upgrade to v${((S=$==null?void 0:$.result)==null?void 0:S.version)||"latest"} started. Daemon is restarting…`);return}i("error"),d(((I=$==null?void 0:$.result)==null?void 0:I.error)||"Upgrade failed")}catch($){i("error"),d($ instanceof Error?$.message:"Upgrade failed")}},[e]),f=l.useCallback(async(v,k,w,x)=>{var I,$,R;const C=Date.now(),S={machineId:v,kind:k,providerType:w,workspaceId:(x==null?void 0:x.workspaceId)||null,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,startedAt:C};try{i("loading"),d(`Launching ${w}…`),u(S);const _={cliType:w};(I=x==null?void 0:x.workspacePath)!=null&&I.trim()?_.dir=x.workspacePath.trim():x!=null&&x.workspaceId&&(_.workspaceId=x.workspaceId),x!=null&&x.resumeSessionId&&(_.resumeSessionId=x.resumeSessionId),($=x==null?void 0:x.args)!=null&&$.trim()&&(_.cliArgs=x.args.trim().split(/\s+/).filter(Boolean)),(R=x==null?void 0:x.model)!=null&&R.trim()&&(_.initialModel=x.model.trim());const P=await a(v,_),F=(P==null?void 0:P.result)||P,q=(F==null?void 0:F.sessionId)||(F==null?void 0:F.id);if(P!=null&&P.success&&q){u(null),i("done"),d(`${w} launched`),t(Br(q));return}if(P!=null&&P.success){i("loading"),d(`${w} launch requested — waiting for session…`);return}u(null),i("error"),d((P==null?void 0:P.error)||(F==null?void 0:F.error)||`Could not launch ${k.toUpperCase()} workspace`)}catch(_){if(_v(_)){i("loading"),d(`${w} launch requested — waiting for session…`);return}u(null),i("error"),d(_ instanceof Error?_.message:`Could not launch ${k.toUpperCase()} workspace`)}},[t,e]),j=l.useCallback(async(v,k)=>{try{const w=await e(v,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),x=(w==null?void 0:w.result)??w;return Array.isArray(x==null?void 0:x.sessions)?x.sessions:[]}catch(w){return console.error("Failed to list saved sessions on mobile:",w),[]}},[e]),N=l.useCallback(async(v,k)=>_i(e,v,k),[e]);l.useEffect(()=>{if(!p)return;const v=xc(p.workspacePath),k=r.find(x=>{var _,P,F,q;if(!x||x.type==="adhdev-daemon"||Tv(x.daemonId||x.id)!==p.machineId||(x.transport==="acp"?"acp":x.transport==="pty"?"cli":null)!==p.kind||String(x.agentType||x.type||"")!==p.providerType)return!1;const $=String(x.providerSessionId||"");if(p.resumeSessionId&&$)return $===p.resumeSessionId;if(v){const A=xc(x.workspace||x.runtimeWorkspaceLabel);return A?A===v:!1}return Number(x.lastUpdated||x._lastUpdate||x.timestamp||((q=(F=(P=(_=x.activeChat)==null?void 0:_.messages)==null?void 0:P.at)==null?void 0:F.call(P,-1))==null?void 0:q.timestamp)||0)>=p.startedAt-5e3});if(!k)return;const w=ap({entrySessionId:k.sessionId,entryInstanceId:k.instanceId,entryRouteId:k.id,conversations:n});w&&(u(null),i("done"),d(`${p.providerType} launched`),t(Br(w)))},[n,r,t,p]),l.useEffect(()=>{if(!p)return;const v=window.setTimeout(()=>{u(k=>!k||k.startedAt!==p.startedAt?k:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(v)},[p]);const y=l.useCallback(async(v,k)=>{if(k.kind==="ide"&&k.providerType){await h(v,k.providerType,{workspacePath:k.workspace||null});return}(k.kind==="cli"||k.kind==="acp")&&k.providerType&&await f(v,k.kind,k.providerType,{workspacePath:k.workspace||null,resumeSessionId:k.providerSessionId||null})},[h,f]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:h,handleAddWorkspace:b,handleMachineUpgrade:g,handleLaunchWorkspaceProvider:f,handleListSavedSessions:j,handleBrowseDirectory:N,handleOpenRecent:y}}function Pv({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:p}){const u=l.useCallback(N=>{o(N.tabKey),i("chat"),n(N)},[n,i,o]),m=l.useCallback(N=>{const y=e.find(v=>v.routeId===N.routeId&&v.streamSource==="native");y&&(o(y.tabKey),i("chat"),n(y))},[e,n,i,o]),h=l.useCallback(()=>{n(t),i("inbox")},[n,t,i]),b=l.useCallback((N,y="inbox")=>{c(N),a(),d("machines"),p(y),i("machine")},[a,p,i,d,c]),g=l.useCallback(N=>{const y=Ps(N);y&&b(y,"chat")},[b]),f=l.useCallback(()=>{a(),i(r)},[r,a,i]),j=l.useCallback(N=>{d(N),i("inbox")},[i,d]);return{openConversation:u,openNativeConversation:m,backFromConversation:h,openMachine:b,openConversationMachine:g,backFromMachine:f,changeMachineSection:j}}function Qs(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function Rv(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Dv({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:b,onOpenHistory:g,onOpenRemote:f,onStopCli:j,wsStatus:N,isConnected:y,onShowAllHiddenConversations:v,onHideConversation:k,onOpenMeshGraph:w,onOpenNewSession:x,liveSessionInboxState:C,setCliViewModeOverrides:S}){const[I,$]=l.useState(()=>{var G;return((G=e[0])==null?void 0:G.tabKey)||null}),[R,_]=l.useState(()=>e[0]?"chat":"inbox"),[P,F]=l.useState("chats"),[q,A]=l.useState(null),[T,B]=l.useState("inbox"),D=l.useRef([]),M=zr(),E="0.9.82",z=l.useMemo(()=>e.find(G=>G.tabKey===I)||e[0]||null,[e,I]),Q=l.useMemo(()=>z?r.find(G=>G.id===z.routeId):void 0,[r,z]),J=l.useMemo(()=>!z||Ye(z)||!Ze(z)?null:sr(z),[z]),ae=l.useMemo(()=>r.filter(G=>G.type==="adhdev-daemon").sort(ui),[r]),ne=l.useMemo(()=>ae.find(G=>G.id===q)||null,[ae,q]),ce=ga({sendDaemonCommand:a,activeConv:z||void 0,setActionLogs:o,isStandalone:i}),be=Lv({sendDaemonCommand:a,navigate:M,ides:r,conversations:e}),Z=l.useMemo(()=>e.map(G=>{const Le=R==="chat"&&(z==null?void 0:z.tabKey)===G.tabKey,Te=xa(G,C,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Le}),Me=Cs(G),He=fu(G);return{conversation:G,timestamp:Me,preview:He,unread:Te.unread,requiresAction:Te.requiresAction,isWorking:Te.isWorking,inboxBucket:Te.inboxBucket}}),[e,C,R,z]),{markConversationRead:Y}=Av({conversations:e,machineEntries:ae,items:Z,selectedConversation:z,selectedTabKey:I,screen:R,liveSessionInboxState:C,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:b,setSelectedTabKey:$,setScreen:_,setSelectedMachineId:A,setSection:F,setMachineBackTarget:B,resetMachineAction:be.resetMachineAction}),ve=Pv({conversations:e,selectedConversation:z,machineBackTarget:T,markConversationRead:Y,resetMachineAction:be.resetMachineAction,setSelectedTabKey:$,setScreen:_,setSelectedMachineId:A,setSection:F,setMachineBackTarget:B}),{isMuted:ye,autoMuteIfCoordinator:xe,toggleTarget:Se}=q0();l.useEffect(()=>{if(i)for(const G of Z)xe(G.conversation)},[Z,i,xe]);const ie=l.useMemo(()=>En(Z.filter(G=>G.requiresAction&&!ye(G.conversation))),[Z,ye]),we=l.useMemo(()=>En(Z.filter(G=>G.unread&&!G.requiresAction&&!ye(G.conversation))),[Z,ye]),pe=l.useMemo(()=>Nv(Z.filter(G=>!G.unread&&!G.requiresAction&&G.isWorking),D.current),[Z]);l.useEffect(()=>{D.current=pe.map(G=>G.conversation.tabKey)},[pe]);const W=l.useMemo(()=>En(Z.filter(G=>!G.unread&&!G.requiresAction&&!G.isWorking)),[Z]),O=l.useMemo(()=>ne?Z.filter(G=>Ps(G.conversation)===ne.id):[],[Z,ne]),V=l.useMemo(()=>Cv(ne,r),[r,ne]),oe=(ne==null?void 0:ne.version)||null,te=!!ne&&!!oe&&!0&&oe!==E,X=l.useMemo(()=>(ne==null?void 0:ne.availableProviders)||[],[ne]),L=l.useMemo(()=>X.filter(G=>Qs(G,"cli")).map(G=>({type:G.type,displayName:G.displayName||G.type,icon:G.icon})),[X]),ue=l.useMemo(()=>X.filter(G=>Qs(G,"acp")).map(G=>({type:G.type,displayName:G.displayName||G.type,icon:G.icon})),[X]),H=l.useMemo(()=>Iv(ae,Z),[Z,ae]),le=l.useCallback(async G=>{ne&&await be.handleOpenRecent(ne.id,G)},[be,ne]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:R==="chat"&&z?s.jsx(hv,{selectedConversation:z,isAcp:Ye(z),isStandalone:i,selectedIdeEntry:Q,actionLogs:n,userName:c,isSendingChat:ce.isSendingChat,sendFeedbackMessage:ce.sendFeedbackMessage,isFocusingAgent:ce.isFocusingAgent,handleModalButton:ce.handleModalButton,handleRelaunch:ce.handleRelaunch,onBack:ve.backFromConversation,onOpenNativeConversation:ve.openNativeConversation,onOpenMachine:ve.openConversationMachine,onOpenHistory:g,onOpenRemote:f,onOpenMeshGraph:w,onStopCli:j,cliViewMode:J,onSetCliViewMode:async G=>{await Uu({conversation:z,mode:G,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:S})},handleSendChat:ce.handleSendChat,handleForceSendChat:ce.handleForceSendChat,handleFocusAgent:ce.handleFocusAgent}):R==="machine"&&ne?s.jsx(kv,{selectedMachineEntry:ne,selectedMachineConversations:O,selectedMachineRecentLaunches:V,cliProviders:L,acpProviders:ue,selectedMachineNeedsUpgrade:te,appVersion:E,machineAction:be.machineAction,isStandalone:i,section:P,showBottomNav:T==="inbox",onBack:ve.backFromMachine,onSectionChange:ve.changeMachineSection,onOpenConversation:ve.openConversation,onOpenRecent:le,onOpenMachineDetails:()=>M(`/machines/${ne.id}`),onMachineUpgrade:()=>be.handleMachineUpgrade(ne.id),onLaunchDetectedIde:(G,Le)=>be.handleLaunchDetectedIde(ne.id,G,Le),onAddWorkspace:(G,Le)=>be.handleAddWorkspace(ne.id,G,Le),onBrowseDirectory:G=>be.handleBrowseDirectory(ne.id,G),onLaunchWorkspaceProvider:(G,Le,Te)=>be.handleLaunchWorkspaceProvider(ne.id,G,Le,Te),onListSavedSessions:G=>be.handleListSavedSessions(ne.id,G)}):s.jsx(bv,{section:P,attentionItems:ie,unreadItems:we,workingItems:pe,completedItems:W,hiddenConversations:t,machineCards:H,getAvatarText:Rv,actionLogs:n,sendDaemonCommand:a,onOpenConversation:ve.openConversation,onShowAllHidden:v,onHideConversation:k,onOpenMeshGraph:w,onOpenNewSession:x,onOpenMachine:ve.openMachine,onOpenSettings:()=>M("/settings"),onSectionChange:F,wsStatus:N,isConnected:y,isStandalone:i,isConversationMuted:i?ye:void 0,onToggleMuteConversation:i?Se:void 0})})}function to(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function $v({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const i=l.useRef(0),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useCallback(()=>{i.current=0,d(!1),u(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const h=l.useCallback(j=>{j.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),b=l.useCallback(j=>{if(!j.dataTransfer.types.includes("text/tab-key"))return;if(j.preventDefault(),!to(t,r)){u("merge");return}const N=j.currentTarget.getBoundingClientRect(),y=j.clientX-N.left,v=N.width/3;y<v?u("split-left"):y>v*2?u("split-right"):u("merge")},[t,r]),g=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),u(null))},[]),f=l.useCallback(j=>{i.current=0,d(!1);const N=j.dataTransfer.getData("text/tab-key"),y=N?e.some(k=>k.tabKey===N):!1,v=p;if(u(null),o(),!!N){if(j.preventDefault(),v==="split-left"&&to(t,r)){r==null||r(N,"split-left");return}if(v==="split-right"&&to(t,r)){r==null||r(N,"split-right");return}if(y){a(N);return}n==null||n(N)}},[e,p,t,r,n,a,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:h,handleDragOver:b,handleDragLeave:g,handleDrop:f}}function Ev(e,t){const r=new Set(t.map(o=>o.tabKey)),n=e.filter(o=>r.has(o)),a=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...n,...a]}function Bv({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,i]=l.useState(t??null),[c,d]=l.useState(r??[]),[p,u]=l.useState(null),m=l.useRef(null),h=l.useRef(null),b=l.useRef(n),g=l.useRef(a);l.useEffect(()=>{b.current=n},[n]),l.useEffect(()=>{g.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(C=>{const S=Ev(C,e);return S.length===C.length&&S.every((I,$)=>I===C[$])?C:S})},[e]);const f=l.useMemo(()=>{const C=p??c;if(C.length===0)return e;const S=new Map(C.map((I,$)=>[I,$]));return[...e].sort((I,$)=>{const R=S.get(I.tabKey)??999,_=S.get($.tabKey)??999;return R-_})},[e,p,c]);l.useEffect(()=>{var S,I;if(f.length===0){o!==null&&(i(null),(S=b.current)==null||S.call(b,null));return}if(o&&f.some($=>$.tabKey===o))return;const C=f[0].tabKey;C!==o&&(i(C),(I=b.current)==null||I.call(b,C))},[f,o]);const j=l.useMemo(()=>f.find(C=>C.tabKey===o),[f,o]),N=l.useCallback(C=>{var S;i(C),(S=b.current)==null||S.call(b,C)},[]),y=l.useCallback((C,S,I)=>{d($=>{var F;const R=$.filter(q=>q!==C),_=R.indexOf(S);if(_<0)return $;const P=I==="left"?_:_+1;return R.splice(P,0,C),(F=g.current)==null||F.call(g,R),R}),u(null)},[]),v=l.useCallback((C,S,I)=>{const R=(c.length>0?c:e.map(F=>F.tabKey)).filter(F=>F!==C),_=R.indexOf(S);if(_<0)return;const P=I==="left"?_:_+1;R.splice(P,0,C),m.current=R,u(R)},[c,e]),k=l.useCallback(()=>{var S;const C=m.current;C&&(d(C),(S=g.current)==null||S.call(g,C))},[]),w=l.useCallback(()=>{m.current=null,u(null)},[]),x=l.useCallback(C=>{d(S=>{var $;const I=S.filter(R=>R!==C);return I.push(C),($=g.current)==null||$.call(g,I),I})},[]);return{activeTabId:o,activeConv:j,sortedConversations:f,previewOrderRef:m,draggingTabRef:h,selectTab:N,handleTabReorder:y,updatePreviewOrder:v,commitPreviewOrder:k,clearPreviewOrder:w,moveTabToEnd:x,setDraggingTabKey:C=>{h.current=C}}}function Fv({dropAction:e,canSplit:t}){return s.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),s.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function Ri({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:o}){if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const i=!r&&!n,c=n&&!!o,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",p=n?wu:r?"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?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:p}),c&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Jt,"aria-label":Jt,children:[s.jsx(Sd,{size:14}),s.jsx("span",{children:Jt})]})}),i&&s.jsx(ip,{}),i&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const mp="adhdev-tab-shortcuts";function hp(){try{return JSON.parse(localStorage.getItem(mp)||"{}")}catch{return{}}}function fp({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>hp()),[c,d]=l.useState(null),p=l.useCallback(m=>{const h=[];return m.metaKey&&h.push(a?"⌘":"Meta"),m.ctrlKey&&h.push("Ctrl"),m.altKey&&h.push(a?"⌥":"Alt"),m.shiftKey&&h.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(h.push(m.key.length===1?m.key.toUpperCase():m.key),h.join("+"))},[a]),u=l.useCallback(m=>{i(m);try{localStorage.setItem(mp,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=h=>{if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){d(null);return}const b=p(h);if(!b)return;const g={...o};for(const[f,j]of Object.entries(g))j===b&&delete g[f];g[c]=b,u(g),d(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,u,p]),l.useEffect(()=>{if(!e)return;const m=h=>{if(!(!h.ctrlKey&&!h.metaKey&&!h.altKey)){for(const[b,g]of Object.entries(o))if(t.includes(b)&&p(h)===g){h.preventDefault(),r(),n(b);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,r,n,p]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const so=e=>{e.preventDefault()},Ov=l.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:p,onConversationActivated:u,onPreviewReorder:m,onReorderTab:h,onCommitPreviewOrder:b,onClearPreviewOrder:g,onDragStateReset:f,onDragTabKeyChange:j,onReceiveTab:N,onOpenContextMenu:y,longPressTimer:v,isGroupActive:k}){const w=tr(t),x=w.isGenerating?"agent-tab-generating":w.isWaiting?"agent-tab-waiting":"",C=w.isReconnecting,S=dg(t),I=ug(t),$=l.useCallback(D=>{c.current=t.tabKey,j(t.tabKey),D.dataTransfer.setData("text/tab-key",t.tabKey),D.dataTransfer.effectAllowed="move"},[t.tabKey,c,j]),R=l.useCallback(()=>{c.current=null,j(null),b(),g(),f()},[c,j,b,g,f]),_=l.useCallback(D=>{const M=c.current;if(!(!M||M===t.tabKey)&&D.dataTransfer.types.includes("text/tab-key")){D.preventDefault(),D.stopPropagation();const E=D.currentTarget.getBoundingClientRect(),z=D.clientX<E.left+E.width/2?"left":"right";m(M,t.tabKey,z)}},[t.tabKey,c,m]),P=l.useCallback(D=>{D.preventDefault(),D.stopPropagation();const M=D.dataTransfer.getData("text/tab-key");if(M&&M!==t.tabKey){const E=D.currentTarget.getBoundingClientRect(),z=D.clientX<E.left+E.width/2?"left":"right";i.includes(M)?h(M,t.tabKey,z):N&&N(M)}g()},[t.tabKey,i,h,N,g]),F=l.useCallback(D=>{D.stopPropagation(),d(),p(t.tabKey),u(t)},[t,u,d,p]),q=l.useCallback(D=>{D.preventDefault(),y(D.clientX,D.clientY,t.tabKey)},[t.tabKey,y]),A=l.useCallback(D=>{const M=D.touches[0];v.current=setTimeout(()=>{y(M.clientX,M.clientY,t.tabKey)},600)},[t.tabKey,v,y]),T=l.useCallback(()=>{v.current&&clearTimeout(v.current)},[v]),B=["adhdev-dockview-tab",x,r&&"is-active",k&&"is-group-active",C&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:B,draggable:!0,onDragStart:$,onDragEnd:R,onDragOver:_,onDrop:P,onClick:F,onContextMenu:q,onTouchStart:A,onTouchEnd:T,onTouchMove:T,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:w.isGenerating?s.jsx("div",{className:"tab-spinner"}):w.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):C?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):w.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),S.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:I,"aria-label":I||S.join(" · "),children:S.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:it(t),children:it(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[C?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:ks(t)}):w.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[ks(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:ks(t)}),s.jsx(Qn,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),o&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${o}`,children:o})]})},(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 zv({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:b,onReceiveTab:g,onHideTab:f,isGroupActive:j,allowTabShortcuts:N=!0}){const[y,v]=l.useState(null),k=l.useRef(null),w=l.useRef(null),x=l.useMemo(()=>e.map(P=>P.tabKey),[e]);Wr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(y==null?void 0:y.tabKey)||null});const{isMac:C,tabShortcuts:S,shortcutListening:I,setShortcutListening:$,saveShortcuts:R}=fp({enabled:N,sortedTabKeys:e.map(P=>P.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!y)return;const P=F=>{const q=document.querySelector("[data-pane-context-menu]");q&&q.contains(F.target)||v(null)};return window.addEventListener("mousedown",P,!0),()=>window.removeEventListener("mousedown",P,!0)},[y]),l.useEffect(()=>{const P=w.current;if(!P)return;const F=q=>{Math.abs(q.deltaY)<=Math.abs(q.deltaX)||(q.preventDefault(),P.scrollLeft+=q.deltaY)};return P.addEventListener("wheel",F,{passive:!1}),()=>P.removeEventListener("wheel",F)},[]);const _=l.useCallback((P,F,q)=>{v({x:P,y:F,tabKey:q})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:w,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(P=>s.jsx(Ov,{conv:P,isActive:t===P.tabKey,isDraggedTab:a.current===P.tabKey,isTaskCompleteUnread:n.has(P.tabKey),shortcut:N?S[P.tabKey]:void 0,conversationKeys:x,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:b,onReceiveTab:g,onOpenContextMenu:_,longPressTimer:k,isGroupActive:j},P.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),y&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:y.x,top:y.y},children:[N&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:so,onClick:P=>{P.stopPropagation(),$(y.tabKey),v(null)},children:["⌨ ",S[y.tabKey]?`Change shortcut (${S[y.tabKey]})`:"Set shortcut"]}),S[y.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:so,onClick:()=>{const P={...S};delete P[y.tabKey],R(P),v(null)},children:"✕ Remove shortcut"})]}),f&&s.jsxs(s.Fragment,{children:[N&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:so,onClick:()=>{f(y.tabKey),v(null)},children:"🚫 Hide from Dashboard"})]})]}),N&&I&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>$(null),children:s.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:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",C?"⌘+1":"Ctrl+1",", ",C?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Hv({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,userName:d,groupIndex:p,onFocus:u,isSplitMode:m,numGroups:h,onMoveTab:b,onReceiveTab:g,style:f,onActiveTabChange:j,initialActiveTabId:N,initialTabOrder:y,onTabOrderChange:v,onHideTab:k,isFocused:w,allowTabShortcuts:x=!0,onOpenNewSession:C,liveSessionInboxState:S}){const{sendCommand:I}=lt(),$=l.useRef(null),{activeTabId:R,activeConv:_,sortedConversations:P,draggingTabRef:F,selectTab:q,handleTabReorder:A,updatePreviewOrder:T,commitPreviewOrder:B,clearPreviewOrder:D,moveTabToEnd:M,setDraggingTabKey:E}=Bv({conversations:e,initialActiveTabId:N,initialTabOrder:y,onActiveTabChange:j,onTabOrderChange:v}),z=ga({sendDaemonCommand:a,activeConv:_,setActionLogs:o,isStandalone:i}),{dragOver:Q,dropAction:J,resetDragState:ae,handleDragEnter:ne,handleDragOver:ce,handleDragLeave:be,handleDrop:Z}=$v({conversations:e,numGroups:h,onMoveTab:b,onReceiveTab:g,onOwnTabDrop:M,onClearPreviewOrder:D}),Y=_&&!Ye(_)&&sr(_)==="terminal",ve=l.useMemo(()=>_?t.find(ie=>ie.id===_.routeId):void 0,[t,_]),ye=l.useMemo(()=>_?n.filter(ie=>ie.routeId===_.tabKey):[],[n,_]),xe=l.useMemo(()=>new Set(P.filter(ie=>Wf(ie,S,{isOpenConversation:ie.tabKey===R})).map(ie=>ie.tabKey)),[R,S,P]);Wr("PaneGroup",{groupIndex:p,conversationCount:e.length,activeTabId:R,dragOver:Q});const Se=l.useCallback(ie=>{ie.streamSource==="agent-stream"&&ie.agentType&&I(ie.routeId,tu(),{agentType:ie.agentType,...ie.sessionId&&{targetSessionId:ie.sessionId}}).catch(()=>{})},[I]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...f,outline:Q?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(zv,{conversations:P,activeTabId:R,groupIndex:p,numGroups:h,unreadTabKeys:xe,draggingTabRef:F,onFocus:u,onSelectTab:q,onConversationActivated:Se,onPreviewReorder:T,onReorderTab:A,onCommitPreviewOrder:B,onClearPreviewOrder:D,onDragStateReset:ae,onDragTabKeyChange:E,onMoveTab:b,onReceiveTab:g,onHideTab:k,isGroupActive:w??!1,allowTabShortcuts:x}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ne,onDragOver:ce,onDragLeave:be,onDrop:Z,children:[Q&&s.jsx(Fv,{dropAction:J,canSplit:!!(h<4&&b)}),_?s.jsx(Li,{activeConv:_,clearToken:r[_.tabKey]||0,isCliTerminal:!!Y,ideEntry:ve,terminalRef:$,handleModalButton:z.handleModalButton,handleRelaunch:z.handleRelaunch,handleSendChat:z.handleSendChat,handleForceSendChat:z.handleForceSendChat,isSendingChat:z.isSendingChat,sendFeedbackMessage:z.sendFeedbackMessage,handleFocusAgent:z.handleFocusAgent,isFocusingAgent:z.isFocusingAgent,actionLogs:ye,userName:d,isInputActive:!m||!!w}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Ri,{conversationsCount:e.length,isSplitMode:m,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:C})})]})]})}function Wv({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,userName:h,focusedGroup:b,focusGroup:g,moveTabToGroup:f,splitTabRelative:j,closeGroup:N,handleResizeStart:y,groupActiveTabIds:v,setGroupActiveTab:k,groupTabOrders:w,setGroupTabOrder:x,toggleHiddenTab:C,onOpenNewSession:S,allowTabShortcuts:I=!0,liveSessionInboxState:$}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((R,_)=>{const P=t&&n.length===r?`${n[_]}%`:void 0;return s.jsxs(jt.Fragment,{children:[t&&_>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:F=>y(_-1,F),onDoubleClick:()=>N(_),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(Hv,{style:t?{flexBasis:P??`${100/r}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:R,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,userName:h,groupIndex:_,isFocused:t&&b===_,onFocus:()=>g(_),isSplitMode:t,numGroups:r,onMoveTab:(F,q)=>{q==="left"&&_>0?f(F,_-1):q==="right"&&_<r-1?f(F,_+1):q==="split-left"&&r<4?j(F,_,"left"):q==="split-right"&&r<4&&j(F,_,"right")},onReceiveTab:F=>f(F,_),onActiveTabChange:F=>k(_,F),initialActiveTabId:v[_],initialTabOrder:w[_],onTabOrderChange:F=>x(_,F),onHideTab:C,onOpenNewSession:S,allowTabShortcuts:I,liveSessionInboxState:$})]},_)})})}function xp({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?mt.onScreenshot("ide-page",(u,m)=>{if(u!==e)return;const h=new FileReader;h.onload=()=>o(h.result),h.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{r!=="connected"&&o(null)},[r]),l.useEffect(()=>{var u;return e?((u=mt.onStatus)==null?void 0:u.call(mt,(m,h)=>{m===e&&h!=null&&h.screenshotUsage&&c(h.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?mt.get(e):null;if(!(!p||r!=="connected"))return n!=="chat"&&t?p.startScreenshots(t):p.stopScreenshots(t),()=>{p.stopScreenshots(t)}},[n,r,t,e]);const d=l.useCallback(async(p,u)=>{const m=e?mt.get(e):null;return!m||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(p,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:i,handleRemoteAction:d}}const bp="adhdev-dashboard-action-shortcuts",Kv=1200,Uv=[["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 Gv(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function rt(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 gp(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:rt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:rt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:rt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:rt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:rt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:rt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:rt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:rt("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:rt("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:rt("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:rt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:rt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:rt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:rt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:rt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:rt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:rt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:rt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:rt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:rt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:rt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:rt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:rt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:rt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:rt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:rt("toggleCliView",e)}]}function Vo(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function ia(e){const t=Object.fromEntries(gp(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(bp)||"{}"),n={...t,...r};for(const[a,o]of Uv)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function yp(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Vv({enabled:e=!0,onTrigger:t}){const r=Gv(),[n,a]=l.useState(()=>ia(r)),[o,i]=l.useState(null),[c,d]=l.useState([]),p=l.useRef({parts:[],timer:null}),u=l.useCallback(f=>{const j=[];return f.metaKey&&j.push(r?"⌘":"Meta"),f.ctrlKey&&j.push("Ctrl"),f.altKey&&j.push(r?"⌥":"Alt"),f.shiftKey&&f.key.length!==1&&j.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(j.push(yp(f.key)),j.join("+"))},[r]),m=l.useCallback(f=>{a(f);try{localStorage.setItem(bp,JSON.stringify(f))}catch{}},[]);l.useEffect(()=>{const f=ia(r),j=Object.entries(n),N=Object.entries(f);j.length===N.length&&j.every(([y,v])=>f[y]===v)||m(f)},[n,r,m]);const h=l.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),b=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},Kv))},[]);l.useEffect(()=>{if(!o)return;const f=j=>{if(j.preventDefault(),j.stopPropagation(),j.key==="Escape"){i(null),d([]);return}const N=u(j);if(!N)return;const v=!(j.metaKey||j.ctrlKey||j.altKey)&&/^[A-Z0-9]$/.test(N);if(c.length===0&&v){d([N]);return}const w=[...c,N].slice(0,2).join(" "),x={...n};for(const[C,S]of Object.entries(x))S===w&&delete x[C];x[o]=w,m(x),i(null),d([])};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[n,u,m,o,c]),l.useEffect(()=>{if(!e||o)return;const f=j=>{if(j.defaultPrevented)return;const N=u(j);if(!N)return;const y=j.metaKey||j.ctrlKey||j.altKey;if(Vo(j.target))return;const v=p.current.parts,k=y?[N]:[...v.slice(-1),N].slice(-2),w=k.join(" "),x=k[k.length-1],C=Object.entries(n).filter(([,_])=>!!_),S=C.find(([,_])=>_===w);if(S){j.preventDefault(),h(),t(S[0]);return}if(C.some(([,_])=>_.startsWith(`${w} `))){j.preventDefault(),p.current.parts=k,b();return}const $=C.find(([,_])=>_===x);if($){j.preventDefault(),h(),t($[0]);return}if(C.some(([,_])=>_.startsWith(`${x} `))){j.preventDefault(),p.current.parts=[x],b();return}h()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[n,b,e,u,t,h,o]),l.useEffect(()=>()=>h(),[h]);const g=l.useMemo(()=>gp(r),[r]);return{isMac:r,actionDefinitions:g,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:m}}function qv({isTabInPopout:e,isTabFloating:t,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(t&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):t?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:r?`Change shortcut (${r})`:"Set shortcut",shortcut:n.setActiveTabShortcut}),r&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:n.hideCurrentTab,tone:"muted"}),a}function vp(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function bc({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!vp(n):!0}function Yv({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:vp(r)}const wp=1e3,Jv=4;function gc(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function yc(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function Xv({detachDelayMs:e=wp,stillnessThresholdPx:t=Jv,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,d=null,p=null,u=!1;const m=()=>{p!=null&&(a(p),p=null)},h=()=>{m(),c=null},b=()=>{m(),o=null,i=null,c=null,d=null,u=!1},g=()=>{!o||!c||!d||u||p!=null||(p=n(()=>{p=null,!(!o||!c||!d||u)&&gc(d,i)&&(yc(c,d,t)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},f=N=>{if(!(!o||u)){if(!gc(N,i)){d={clientX:N.clientX,clientY:N.clientY},h();return}(!c||yc(c,N,t))&&(m(),c={clientX:N.clientX,clientY:N.clientY}),d={clientX:N.clientX,clientY:N.clientY},g()}},j=N=>{!o||u||(N&&(d={clientX:N.clientX,clientY:N.clientY}),h())};return{startDrag:N=>{m(),o=N.panelId,i=N.selfPanelBounds??null,c=null,d={clientX:N.clientX,clientY:N.clientY},u=!1},markSelfPanel:f,markNonSelfPanel:j,markNoDropTarget:j,markDockTarget:j,endDrag:b,isDragging:()=>o!=null,hasDetached:()=>u,dispose:b}}function Qv(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Nn(e){return e.isActive}function vc(e){return e.isVisible}const jp=l.createContext(null);function ja(){const e=l.useContext(jp);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Bn(e){return it(e)||e.tabKey}function Zv(e){return`remote:${e}`}function zt(e){return e.startsWith("remote:")}function wc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ew(e){e.preventDefault()}function ro(e){var n;const t=e==null?void 0:e.defaultView;if(!t)return;const r=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),r(e==null?void 0:e.body),r(e==null?void 0:e.documentElement),(n=t.requestAnimationFrame)==null||n.call(t,()=>{try{t.focus(),r(e==null?void 0:e.body)}catch{}})}catch{}}function no(e,t){e.classList.remove(So.className,Co.className),e.classList.add(t==="light"?So.className:Co.className)}function jc(e){return e?Array.from(new Set(e.groups.map(t=>{var r,n;return(n=(r=t.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(t=>!!t&&t!==window))):[]}function tw(e){const[,t]=l.useState(0);l.useEffect(()=>{const r=()=>t(a=>a+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const a of n)a.dispose()}},[e.api,e.containerApi])}function sw(e,t,r){var i;const n=[t];let a;for(const c of n){let d;for(const p of c){const u=e.addPanel({id:p.tabKey,component:"conversation",title:Bn(p),params:{kind:"conversation",tabKey:p.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=u.id)}a=d??a}return r??((i=t[0])==null?void 0:i.tabKey)??null}function kc(e,t){const r=new Set(t.map(a=>a.tabKey)),n=new Map;for(const a of t)n.set(a.tabKey,(n.get(a.tabKey)||0)+1);for(const a of[...e.panels])zt(a.id)||r.has(a.id)||e.removePanel(a);for(const a of t){const o=e.getPanel(a.tabKey);if(o){(n.get(a.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:a.tabKey,daemonId:a.daemonId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,panelId:o.id}),o.update({params:{tabKey:a.tabKey}}),o.title!==Bn(a)&&o.api.setTitle(Bn(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:Bn(a),params:{kind:"conversation",tabKey:a.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function Nc(e,t,r){var d,p;const n=r?Zv(r):null;for(const u of[...e.panels])zt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Kt(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),i=gu(a);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((p=e.panels.find(u=>!zt(u.id)))==null?void 0:p.id);e.addPanel({id:n,component:"remote",title:i,params:{kind:"remote",routeId:r},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function rw({params:e,api:t}){var b;const r=ja(),n=l.useRef(null),[a,o]=l.useState(()=>Nn(t)),[i,c]=l.useState(()=>vc(t)),d=r.conversationsByTabKey.get(e.tabKey),p=ga({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});l.useEffect(()=>{o(Nn(t)),c(vc(t));const g=[t.onDidActiveChange(f=>o(f.isActive)),t.onDidActiveGroupChange(f=>{if(!Nn(t)&&!f.isActive){o(!1);return}o(Nn(t))}),t.onDidVisibilityChange(f=>c(f.isVisible))];return()=>{for(const f of g)f.dispose()}},[t]);const u=l.useMemo(()=>d?r.ides.find(g=>g.id===d.routeId):void 0,[r.ides,d]),m=l.useMemo(()=>d?r.actionLogs.filter(g=>g.routeId===d.tabKey):[],[r.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(Ri,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const h=!Ye(d)&&sr(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(Li,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:h,ideEntry:u,terminalRef:n,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:m,userName:r.userName,scrollToBottomRequestNonce:((b=r.scrollToBottomRequest)==null?void 0:b.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:i})})}function nw({params:e}){var d;const t=ja(),r=l.useMemo(()=>Kt([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=l.useMemo(()=>t.ides.find(p=>p.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((d=r==null?void 0:r.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=xp({doId:a,targetSessionId:r?eu(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(Dd,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:o,screenshotUsage:i,transportType:r.transport,onAction:c})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function aw(){const e=ja();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Ri,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function ow(e){var y,v;tw(e);const t=ja(),r=l.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),a=n==null?void 0:n.sessionId,o=l.useCallback(k=>qb(k),[]),i=l.useCallback(()=>Vb(a),[a]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const k=Kt([...t.conversationsByTabKey.values()],e.params.routeId),w=((y=e.api.group.activePanel)==null?void 0:y.id)===e.api.id,x=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${w?" is-active":""}${x?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(k==null?void 0:k.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:k!=null&&k.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:k.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const d=t.conversationsByTabKey.get(e.params.tabKey);if(!d)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const p=((v=e.api.group.activePanel)==null?void 0:v.id)===e.api.id,u=e.api.isGroupActive,m=xa(d,t.liveSessionInboxState,{isOpenConversation:p}),h=m.isReconnecting,b=m.isConnecting,g=m.isGenerating||c,f=m.isWaiting,j=m.unread,N=t.tabShortcuts[d.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${u?" is-group-active":""}${h?" is-reconnecting":""}`,title:it(d),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:k=>{var w;k.preventDefault(),r(k),t.openTabContextMenu({x:k.clientX,y:k.clientY,tabKey:d.tabKey,sourceDocument:((w=k.target)==null?void 0:w.ownerDocument)??document})},children:[j&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:g?s.jsx("div",{className:"tab-spinner"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):b?s.jsx("div",{className:"tab-connecting-spinner"}):d.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:it(d)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:h?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ks(d)}):b?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ks(d)}):s.jsx("span",{children:ks(d)})})]}),N&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:N,children:N})]})}function iw({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:p,toggleHiddenTab:u,actionShortcuts:m,registerActionHandlers:h,onActiveTabChange:b,onOpenNewSession:g,onRequestScrollToBottom:f,requestedActiveTabKey:j,requestedRemoteIdeId:N,onRequestedActiveTabConsumed:y,scrollToBottomRequest:v,liveSessionInboxState:k,layoutProfile:w}){var Qe,Ue,gt;const{theme:x}=Rs(),{sendCommand:C}=lt(),S=l.useRef(null),I=l.useRef(null),$=l.useRef(null),R=l.useRef(!1),_=l.useRef(!1),P=l.useRef(!1),F=l.useRef(null),q=l.useRef([]),[A,T]=l.useState(null),[B,D]=l.useState(0),M=l.useRef(typeof window>"u"?{}:Sy(w)),E=l.useMemo(()=>new Map(e.map(U=>[U.tabKey,U])),[e]),z=l.useMemo(()=>{const U=S.current;return U?U.groups.some(K=>{try{const re=K.model.location.type;return re!=="floating"&&re!=="popout"?!1:K.panels.some(he=>E.has(he.id))}catch{return!1}}):!1},[E,B,e]),Q=l.useCallback(()=>{var U;(U=S.current)==null||U.focus()},[]),J=l.useCallback((U,K)=>{f==null||f(U,K)},[f]),ae=l.useCallback(U=>{const K=document,re=U.document;for(const se of K.querySelectorAll('link[rel="stylesheet"]')){const fe=re.createElement("link");fe.rel="stylesheet",fe.href=se.href,se.crossOrigin&&(fe.crossOrigin=se.crossOrigin),re.head.appendChild(fe)}for(const se of K.querySelectorAll("style")){const fe=re.createElement("style");fe.textContent=se.textContent,re.head.appendChild(fe)}const he=[];for(const se of K.styleSheets)try{for(const fe of se.cssRules)fe instanceof CSSStyleRule&&(fe.selectorText===":root"||fe.selectorText==="html")&&he.push(fe.cssText)}catch{}if(he.length>0){const se=re.createElement("style");se.textContent=he.join(`
63
+ `),re.head.appendChild(se)}const ge=K.documentElement.getAttribute("data-theme");ge&&re.documentElement.setAttribute("data-theme",ge),re.documentElement.style.colorScheme=ge==="light"?"light":"dark",re.body.className=K.body.className;const je=K.documentElement.getAttribute("style");je&&re.documentElement.setAttribute("style",je);const ee=re.getElementById("dv-popout-window");ee instanceof HTMLElement&&(ee.classList.add("adhdev-dockview"),no(ee,x))},[x]),ne=l.useCallback(()=>{var K;const U=S.current;if(U)for(const re of U.groups)try{const he=(K=re.element)==null?void 0:K.ownerDocument;if(!he||he===document)continue;const ge=he.getElementById("dv-popout-window");ge instanceof HTMLElement&&(ge.classList.add("adhdev-dockview"),no(ge,x));const je=document.documentElement.getAttribute("data-theme");je&&he.documentElement.setAttribute("data-theme",je),he.documentElement.style.colorScheme=je==="light"?"light":"dark",he.body.className=document.body.className;const ee=document.documentElement.getAttribute("style");ee?he.documentElement.setAttribute("style",ee):he.documentElement.removeAttribute("style")}catch{}},[x]),ce=l.useCallback(U=>{const K=S.current;if(!K)return;const re=K.getPanel(U);re&&K.addPopoutGroup(re,{popoutUrl:"/popout.html",onDidOpen:({window:he})=>{ae(he),we();const ge=E.get(U);he.document.title=ge?`${it(ge)} — ADHDev`:"ADHDev — Popout"}})},[E,ae]),be=l.useCallback(U=>{const K=S.current,re=K==null?void 0:K.getPanel(U);if(!K||!re)return;const he=K.groups.filter(ge=>{var je;try{return((je=ge.element)==null?void 0:je.ownerDocument)===document}catch{return!0}});he.length>0?re.api.moveTo({group:he[0],position:"center"}):re.api.moveTo({position:"center"}),re.api.setActive()},[]),Z=l.useCallback(U=>{var he;const K=S.current;if(!K)return!1;const re=K.getPanel(U);if(!re)return!1;try{return((he=re.group.element)==null?void 0:he.ownerDocument)!==document}catch{return!1}},[]),Y=l.useCallback(U=>{Z(U)&&be(U),u(U)},[Z,be,u]),ve=l.useCallback(U=>{const K=S.current,re=K==null?void 0:K.getPanel(U);!K||!re||K.addFloatingGroup(re,{width:600,height:500})},[]),ye=l.useCallback(U=>{var re;const K=(re=S.current)==null?void 0:re.getPanel(U);if(!K)return!1;try{return K.group.model.location.type==="floating"}catch{return!1}},[]),xe=l.useCallback(()=>{var K,re;const U=(re=(K=S.current)==null?void 0:K.activePanel)==null?void 0:re.id;return!U||zt(U)?null:E.has(U)?U:null},[E]),Se=l.useCallback(U=>{const K=S.current,re=K==null?void 0:K.getPanel(U);if(!K||!re)return;const he=K.groups.filter(ge=>{try{return ge.model.location.type==="grid"}catch{return!0}});he.length>0?re.api.moveTo({group:he[0],position:"center"}):re.api.moveTo({position:"center"}),re.api.setActive()},[]),ie=l.useCallback(()=>{var je;const U=S.current;if(!U)return;const re=U.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,he=[...U.panels];for(const ee of he){const se=(je=ee.group.element)==null?void 0:je.ownerDocument,fe=ee.group.model.location.type;se===document&&fe==="grid"||(re&&re.id!==ee.group.id?ee.api.moveTo({group:re,position:"center"}):ee.api.moveTo({position:"center"}))}const ge=U.activePanel;ge&&(ge.group.model.openPanel(ge),ge.api.setActive()),ro(document)},[]),we=l.useCallback(()=>{var K,re;const U=S.current;if(U)for(const he of U.groups){const ge=(K=he.element)==null?void 0:K.ownerDocument;if(!ge||ge===document)continue;const je=ge.getElementById("dv-popout-window");if(!(je instanceof HTMLElement))continue;let ee=null,se=ge.title||"ADHDev",fe="Popout workspace";const Ce=he.activePanel;if(Ce)if(ee=Ce.id,zt(Ce.id)){const _e=((re=Ce.params)==null?void 0:re.routeId)||Ce.id.slice(7),ze=Kt([...E.values()],_e);se=gu(ze),fe=ze!=null&&ze.machineName?`Remote view · ${ze.machineName}`:"Remote view"}else{const _e=E.get(Ce.id);se=_e?it(_e):Ce.title||Ce.id,fe=_e?ks(_e):"Dockview panel"}ge.title=`${se} — ADHDev`;const Pe=Array.from(ge.querySelectorAll("#adhdev-popout-header"));for(const _e of Pe)_e.remove();const Ie=ge.createElement("div");Ie.id="adhdev-popout-header",ge.body.appendChild(Ie),Ie.setAttribute("style",["position:absolute","top:0","left:0","right:0","height:52px","display:flex","align-items:center","justify-content:space-between","gap:12px","padding:0 14px","box-sizing:border-box","background:var(--surface-secondary)","border-bottom:1px solid var(--border-subtle)","z-index:5","backdrop-filter:blur(14px)"].join(";")),Ie.innerHTML=`
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;">${wc(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;">${wc(fe)}</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
+ `,je.style.top="52px",je.style.height="calc(100% - 52px)";const Re=Ie.querySelector("[data-adhdev-popout-focus]");Re&&(Re.onclick=()=>{window.focus()});const Be=Ie.querySelector("[data-adhdev-popout-dock]");Be&&(Be.disabled=!ee,Be.style.opacity=ee?"1":"0.5",Be.style.cursor=ee?"pointer":"default",Be.onclick=()=>{var _e;ee&&be(ee),(_e=ge.defaultView)==null||_e.focus()})}},[E,be]),pe=l.useCallback(U=>{var he;const K=S.current,re=K==null?void 0:K.getPanel(U);if(!(!K||!re)){re.group.model.openPanel(re),re.api.setActive(),J(U,"dockview-shortcut");try{const ge=re.group.model.location;ge.type==="popout"?ge.getWindow().focus():ro((he=re.group.element)==null?void 0:he.ownerDocument)}catch{}}},[J]),W=l.useCallback(U=>{const K=S.current,re=K==null?void 0:K.activePanel,he=(K==null?void 0:K.activeGroup)||(re==null?void 0:re.group);if(!K||!re||!he)return;const ge=he.panels||[];if(ge.length<=1)return;const je=ge.findIndex(fe=>fe.id===re.id);if(je<0)return;const ee=(je+U+ge.length)%ge.length,se=ge[ee];se&&(se.group.model.openPanel(se),se.api.setActive(),zt(se.id)||J(se.id,"dockview-shortcut"))},[J]),O=l.useCallback(U=>{var Re;const K=S.current,re=(K==null?void 0:K.activeGroup)||((Re=K==null?void 0:K.activePanel)==null?void 0:Re.group);if(!K||!re)return;const he=K.groups||[],ge=he.find(Be=>Be.id===re.id);if(!ge)return;const je=ge.element.getBoundingClientRect(),ee=je.left+je.width/2,se=je.top+je.height/2,fe=(Be,_e,ze,Ve)=>Math.max(0,Math.min(_e,Ve)-Math.max(Be,ze)),Ce=Be=>{const _e=Be.element.getBoundingClientRect(),ze=_e.left+_e.width/2,Ve=_e.top+_e.height/2;let ut=0,vt=0,ft=0,pt=!1;if(U==="left"?(pt=ze<ee,ut=Math.max(0,je.left-_e.right),vt=Math.abs(Ve-se),ft=fe(je.top,je.bottom,_e.top,_e.bottom)):U==="right"?(pt=ze>ee,ut=Math.max(0,_e.left-je.right),vt=Math.abs(Ve-se),ft=fe(je.top,je.bottom,_e.top,_e.bottom)):U==="above"?(pt=Ve<se,ut=Math.max(0,je.top-_e.bottom),vt=Math.abs(ze-ee),ft=fe(je.left,je.right,_e.left,_e.right)):(pt=Ve>se,ut=Math.max(0,_e.top-je.bottom),vt=Math.abs(ze-ee),ft=fe(je.left,je.right,_e.left,_e.right)),!pt)return Number.POSITIVE_INFINITY;const Oe=ft>0?0:120;return ut*3+vt+Oe};let Pe=null,Ie=Number.POSITIVE_INFINITY;for(const Be of he){if(Be.id===ge.id)continue;const _e=Ce(Be);Number.isFinite(_e)&&(_e>=Ie||(Ie=_e,Pe=Be))}return Pe||void 0},[]),V=l.useCallback(U=>{var he;const K=O(U);if(!K)return;const re=K.activePanel||K.panels[0];re&&(K.model.openPanel(re),re.api.setActive(),zt(re.id)||J(re.id,"dockview-focus"),ro((he=K.element)==null?void 0:he.ownerDocument))},[O,J]),oe=l.useCallback((U,K)=>{const re=S.current,he=re==null?void 0:re.activePanel,ge=(re==null?void 0:re.activeGroup)||(he==null?void 0:he.group);if(!re||!he||!ge)return;let je=O(U);!je&&(K!=null&&K.createGroupIfMissing)&&(je=re.addGroup({referenceGroup:ge,direction:U})),je&&(he.api.moveTo({group:je,position:"center"}),he.group.model.openPanel(he),he.api.setActive(),zt(he.id)||J(he.id,K!=null&&K.createGroupIfMissing?"dockview-split":"dockview-move"))},[O,J]),{isMac:te,tabShortcuts:X,shortcutListening:L,setShortcutListening:ue,saveShortcuts:H}=fp({sortedTabKeys:e.map(U=>U.tabKey),onFocus:Q,onSelectTab:pe}),le=l.useCallback(()=>{var re;const U=S.current;if(!U)return;const K=U.activePanel;if(K){if(zt(K.id)){const he=((re=K.params)==null?void 0:re.routeId)||K.id.slice(7),ge=Kt(e,he);ge!=null&&ge.tabKey&&ue(ge.tabKey);return}E.has(K.id)&&ue(K.id)}},[E,pe,ue,e]),G=l.useCallback(U=>{const K=[];return U.metaKey&&K.push(te?"⌘":"Meta"),U.ctrlKey&&K.push("Ctrl"),U.altKey&&K.push(te?"⌥":"Alt"),U.shiftKey&&U.key.length!==1&&K.push(te?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(U.key)?null:(K.push(yp(U.key)),K.join("+"))},[te]),Le=l.useCallback(U=>{var K,re;switch(U){case"splitActiveTabRight":oe("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":oe("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const he=xe();he&&ve(he);return}case"popoutActiveTab":{const he=xe();he&&ce(he);return}case"dockActiveTab":{const he=xe();if(!he)return;Z(he)?be(he):ye(he)&&Se(he);return}case"focusLeftPane":V("left");return;case"focusRightPane":V("right");return;case"focusUpPane":V("above");return;case"focusDownPane":V("below");return;case"moveActiveTabToLeftPane":oe("left");return;case"moveActiveTabToRightPane":oe("right");return;case"moveActiveTabToUpPane":oe("above");return;case"moveActiveTabToDownPane":oe("below");return;case"selectPreviousGroupTab":W(-1);return;case"selectNextGroupTab":W(1);return;case"setActiveTabShortcut":le();return;case"hideCurrentTab":{const he=(re=(K=S.current)==null?void 0:K.activePanel)==null?void 0:re.id;he&&!zt(he)&&Y(he);return}default:return}},[W,Se,V,ve,xe,Y,ye,Z,be,oe,ce,le]);l.useEffect(()=>{if(!A)return;const U=A.sourceDocument,K=U.defaultView??window,re=he=>{const ge=U.querySelector("[data-dockview-tab-context-menu]");ge&&ge.contains(he.target)||T(null)};return K.addEventListener("mousedown",re,!0),K!==window&&window.addEventListener("mousedown",()=>T(null),!0),()=>{K.removeEventListener("mousedown",re,!0),K!==window&&window.removeEventListener("mousedown",()=>T(null),!0)}},[A]);const Te=l.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:E,hasDetachedConversationPanels:z,ides:r,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:g,liveSessionInboxState:k,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:Y,userName:p,scrollToBottomRequest:v,tabShortcuts:X,openTabContextMenu:({x:U,y:K,tabKey:re,sourceDocument:he})=>T({x:U,y:K,tabKey:re,sourceDocument:he??document}),popoutTab:ce,moveTabBackToMain:be,isTabInPopout:Z,floatTab:ve,isTabFloating:ye}),[n,t,E,z,r,i,c,g,k,a,o,Y,p,v,X,ce,be,Z,ve,ye]),Me=A?qv({isTabInPopout:Z(A.tabKey),isTabFloating:ye(A.tabKey),tabShortcut:X[A.tabKey],actionShortcuts:m}):[],He=l.useCallback(U=>{var he;const K=S.current;if((((he=K==null?void 0:K.activePanel)==null?void 0:he.id)??null)===U.id){U.group.model.openPanel(U);return}U.group.model.openPanel(U),U.api.setActive()},[]),qe=l.useCallback((U,K="requested-tab")=>{if(!U)return!1;const re=S.current;if(!re)return!1;const he=re.getPanel(U);return he?(He(he),J(U,K),y==null||y(),!0):!1},[He,y,J]),Je=l.useCallback(()=>{if(P.current)return!1;const U=qe(F.current,"stored-layout-restore");return U&&(P.current=!0),U},[qe]),st=l.useCallback(()=>{var K;const U=S.current;U&&Ny(w,{activeTabId:((K=U.activePanel)==null?void 0:K.id)??null,layout:U.toJSON()})},[w]),Xe=l.useCallback(()=>{Cy(w,M.current)},[w]),ct=l.useCallback(U=>{var he,ge,je,ee;const K=S.current;if(!K)return{kind:"grid"};const re=K.toJSON();for(const se of re.floatingGroups||[])if((ge=(he=se.data)==null?void 0:he.views)!=null&&ge.includes(U)&&se.position)return{kind:"floating",position:se.position};for(const se of re.popoutGroups||[])if((ee=(je=se.data)==null?void 0:je.views)!=null&&ee.includes(U))return{kind:"popout",position:se.position,popoutUrl:se.url};return{kind:"grid"}},[]),at=l.useCallback(U=>{const K=S.current;if(!K)return;const re=K.getPanel(U),he=M.current[U];if(!re||!he||he.kind==="grid")return;if(re.group.model.location.type===he.kind){delete M.current[U],Xe();return}if(he.kind==="floating"){K.addFloatingGroup(re,{x:he.position.left??24,y:he.position.top??24,width:he.position.width,height:he.position.height}),delete M.current[U],Xe();return}delete M.current[U],Xe()},[Xe]);l.useEffect(()=>(h==null||h({setShortcutForActiveTab:le,restoreHiddenTabToSavedLocation:at,activateConversationTab:pe,resetAllPanelsToMain:ie,activatePreviousTabInGroup:()=>W(-1),activateNextTabInGroup:()=>W(1),floatActiveTab:()=>{const U=xe();U&&ve(U)},popoutActiveTab:()=>{const U=xe();U&&ce(U)},dockActiveTab:()=>{const U=xe();U&&(Z(U)?be(U):ye(U)&&Se(U))},splitActiveTabRight:()=>oe("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>oe("below",{createGroupIfMissing:!0}),focusLeftPane:()=>V("left"),focusRightPane:()=>V("right"),focusUpPane:()=>V("above"),focusDownPane:()=>V("below"),moveActiveTabToLeftPane:()=>oe("left"),moveActiveTabToRightPane:()=>oe("right"),moveActiveTabToUpPane:()=>oe("above"),moveActiveTabToDownPane:()=>oe("below")}),()=>h==null?void 0:h(null)),[W,Se,ve,V,xe,ye,Z,oe,be,ce,h,ie,at,pe,le]),l.useEffect(()=>()=>{var U;(U=$.current)==null||U.call($),$.current=null},[]);const ht=l.useCallback(U=>{var re,he;S.current=U.api,(re=$.current)==null||re.call($),$.current=null;const K=ky(w);if(F.current=(K==null?void 0:K.activeTabId)??null,K!=null&&K.layout&&U.api.fromJSON(K.layout,{reuseExistingPanels:!1}),_.current=bc({hasStoredLayout:!!(K!=null&&K.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),_.current||(kc(U.api,e),Nc(U.api,e,N)),U.api.totalPanels===0&&e.length>0){const ge=sw(U.api,e,j);if(ge){const je=U.api.getPanel(ge);je&&He(je)}}else!_.current&&!qe(j)&&Je();if(R.current=!0,U.api.onDidActivePanelChange(ge=>{var ee;if(F.current=(ge==null?void 0:ge.id)??null,P.current=!0,we(),ge&&zt(ge.id)){const se=((ee=ge.params)==null?void 0:ee.routeId)||ge.id.slice(7),fe=Kt(e,se);b((fe==null?void 0:fe.tabKey)??null),st();return}if(b((ge==null?void 0:ge.id)??null),st(),!ge)return;const je=E.get(ge.id);(je==null?void 0:je.streamSource)==="agent-stream"&&je.agentType&&C(je.routeId,tu(),{agentType:je.agentType,...je.sessionId&&{targetSessionId:je.sessionId}}).catch(()=>{})}),U.api.onDidLayoutChange(()=>{st(),we(),D(ge=>ge+1)}),Qv()){const ge=Ie=>({clientX:Ie.clientX,clientY:Ie.clientY}),je=Ie=>{const Re=Ie==null?void 0:Ie.getBoundingClientRect();return Re?{left:Re.left,right:Re.right,top:Re.top,bottom:Re.bottom}:null},ee=Ie=>{var Be;const Re=(Be=I.current)==null?void 0:Be.getBoundingClientRect();return Re?Ie.clientX<Re.left||Ie.clientX>Re.right||Ie.clientY<Re.top||Ie.clientY>Re.bottom:!1},se=Xv({detachDelayMs:wp,onDetach:({panelId:Ie,clientX:Re,clientY:Be})=>{var ft,pt;const _e=U.api.getPanel(Ie);if(!_e)return;try{if(_e.group.model.location.type!=="grid")return}catch{return}const ze=(ft=I.current)==null?void 0:ft.getBoundingClientRect(),Ve=(pt=_e.group.element)==null?void 0:pt.getBoundingClientRect(),ut=Math.round(Math.min(Math.max((Ve==null?void 0:Ve.width)??600,360),720)),vt=Math.round(Math.min(Math.max((Ve==null?void 0:Ve.height)??500,260),640));U.api.addFloatingGroup(_e,{x:ze?Math.max(0,Re-ze.left-32):void 0,y:ze?Math.max(0,Be-ze.top-18):void 0,width:ut,height:vt}),_e.api.setActive(),st(),we(),D(Oe=>Oe+1)}}),fe=[U.api.onWillDragPanel(Ie=>{if(!(Ie.nativeEvent.defaultPrevented||Ie.nativeEvent.shiftKey)){try{if(Ie.panel.group.model.location.type!=="grid")return}catch{return}se.startDrag({panelId:Ie.panel.id,selfPanelBounds:je(Ie.panel.group.element),...ge(Ie.nativeEvent)})}}),U.api.onWillShowOverlay(Ie=>{if(se.hasDetached()){Ie.preventDefault();return}se.markDockTarget(ge(Ie.nativeEvent))}),U.api.onWillDrop(Ie=>{if(se.hasDetached()){Ie.preventDefault(),se.endDrag();return}se.markDockTarget(ge(Ie.nativeEvent))}),U.api.onDidDrop(()=>se.endDrag()),U.api.onUnhandledDragOverEvent(Ie=>{se.isDragging()&&se.markSelfPanel(ge(Ie.nativeEvent))})],Ce=Ie=>{if(!se.isDragging())return;const Re=ge(Ie);ee(Re)&&se.markNonSelfPanel(Re)},Pe=()=>se.endDrag();window.addEventListener("dragover",Ce,!0),window.addEventListener("drop",Pe,!0),window.addEventListener("dragend",Pe,!0),$.current=()=>{se.dispose();for(const Ie of fe)Ie.dispose();window.removeEventListener("dragover",Ce,!0),window.removeEventListener("drop",Pe,!0),window.removeEventListener("dragend",Pe,!0)}}U.api.onDidAddGroup(ge=>{requestAnimationFrame(()=>{var je,ee;try{const se=(je=ge.element)==null?void 0:je.ownerDocument;if(!se||se===document)return;(ee=se.getElementById("dv-popout-window"))==null||ee.classList.add("adhdev-dockview");const fe=document.documentElement.getAttribute("data-theme");fe&&se.documentElement.setAttribute("data-theme",fe),se.body.className=document.body.className;const Ce=document.documentElement.getAttribute("style");Ce&&se.documentElement.setAttribute("style",Ce)}catch{}we(),D(se=>se+1)})}),b(((he=U.api.activePanel)==null?void 0:he.id)??null)},[He,qe,E,r,d,w,b,st,j,N,C,we,e]);l.useLayoutEffect(()=>{const U=S.current;if(!U||!R.current||_.current&&bc({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;_.current&&(_.current=!1);const K=q.current,re=new Set(K),he=e.map(Pe=>Pe.tabKey),ge=new Set(he),je=Yv({previousVisibleConversationCount:K.length,visibleConversationCount:e.length,ides:r});let ee=!1;for(const Pe of K)ge.has(Pe)||je||(M.current[Pe]=ct(Pe),ee=!0);ee&&Xe(),je||(kc(U,e),Nc(U,e,N));const se=he.filter(Pe=>!re.has(Pe));let fe=!1;for(const Pe of se){const Ie=U.getPanel(Pe),Re=M.current[Pe];if(!Ie||!Re||Re.kind==="grid")continue;if(Ie.group.model.location.type===Re.kind){delete M.current[Pe],fe=!0;continue}if(Re.kind==="floating"){U.addFloatingGroup(Ie,{x:Re.position.left??24,y:Re.position.top??24,width:Re.position.width,height:Re.position.height}),delete M.current[Pe],fe=!0;continue}}if(fe&&Xe(),q.current=he,j&&qe(j))return;!U.activePanel&&U.panels[0]&&He(U.panels[0]),!!(U.activePanel&&U.getPanel(U.activePanel.id))||Je()},[He,qe,Je,r,d,Xe,ct,j,N,e]),l.useEffect(()=>{R.current&&qe(j)},[qe,j]),l.useEffect(()=>{const U=re=>{const he=re.target;if(!he)return;const ge=he.querySelector("[data-tab-key]")||he.closest("[data-tab-key]");if(ge){const je=ge.getAttribute("data-tab-key");if(je&&re.dataTransfer){const ee=he.closest(".dv-tab")||ge.closest(".dv-tab")||ge;re.dataTransfer.effectAllowed="move",re.dataTransfer.setData("text/tab-key",je),ee instanceof HTMLElement&&re.dataTransfer.setDragImage(ee,Math.max(12,Math.round(ee.clientWidth/2)),Math.max(10,Math.round(ee.clientHeight/2)))}}};window.addEventListener("dragstart",U);const K=jc(S.current);for(const re of K)re.addEventListener("dragstart",U);return()=>{window.removeEventListener("dragstart",U);for(const re of K)re.removeEventListener("dragstart",U)}},[B]),l.useEffect(()=>{var K;const U=(K=I.current)==null?void 0:K.querySelector(".adhdev-dockview");U instanceof HTMLElement&&no(U,x),ne(),we()},[we,ne,x]),l.useEffect(()=>{we()},[we]),l.useEffect(()=>{const U=K=>{if(K.defaultPrevented||L)return;const re=G(K);if(!re)return;const he=K.metaKey||K.ctrlKey||K.altKey;Vo(K.target)&&!he||ia(te).setActiveTabShortcut!==re||(K.preventDefault(),K.stopPropagation(),le())};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[G,te,L,le]),l.useEffect(()=>{const U=I.current;if(!U)return;const K=re=>{var se,fe;if(!re.isTrusted)return;const he=(fe=(se=re.target)==null?void 0:se.closest)==null?void 0:fe.call(se,".dv-scrollable");if(!he)return;re.preventDefault(),re.stopPropagation();const ge=Math.abs(re.deltaX),je=Math.abs(re.deltaY),ee=ge>je?re.deltaX:re.deltaY;he.dispatchEvent(new WheelEvent("wheel",{deltaY:ee,deltaMode:re.deltaMode,bubbles:!1,cancelable:!0}))};return U.addEventListener("wheel",K,{passive:!1,capture:!0}),()=>U.removeEventListener("wheel",K,{capture:!0})},[]),l.useEffect(()=>{const U=jc(S.current);if(U.length===0)return;const K=U.map(re=>{let he=[],ge=null;const je=()=>{ge!=null&&re.clearTimeout(ge),ge=null,he=[]},ee=()=>{ge!=null&&re.clearTimeout(ge),ge=re.setTimeout(()=>{ge=null,he=[]},1200)},se=Ce=>{if(!Ce.ctrlKey&&!Ce.metaKey&&!Ce.altKey)return;const Pe=G(Ce);if(!Pe)return;const Ie=hp();for(const[Re,Be]of Object.entries(Ie))if(e.some(_e=>_e.tabKey===Re)&&Be===Pe){Ce.preventDefault(),pe(Re);return}},fe=Ce=>{if(Ce.defaultPrevented||L)return;const Pe=G(Ce);if(!Pe)return;const Ie=Ce.metaKey||Ce.ctrlKey||Ce.altKey;if(Vo(Ce.target))return;const Re=ia(te),Be=Object.entries(Re).filter(([Oe,Et])=>!!Et&&(Oe==="splitActiveTabRight"||Oe==="splitActiveTabDown"||Oe==="floatActiveTab"||Oe==="popoutActiveTab"||Oe==="dockActiveTab"||Oe==="focusLeftPane"||Oe==="focusRightPane"||Oe==="focusUpPane"||Oe==="focusDownPane"||Oe==="moveActiveTabToLeftPane"||Oe==="moveActiveTabToRightPane"||Oe==="moveActiveTabToUpPane"||Oe==="moveActiveTabToDownPane"||Oe==="selectPreviousGroupTab"||Oe==="selectNextGroupTab"||Oe==="setActiveTabShortcut"||Oe==="hideCurrentTab")),_e=Ie?[Pe]:[...he.slice(-1),Pe].slice(-2),ze=_e.join(" "),Ve=_e[_e.length-1],ut=Be.find(([,Oe])=>Oe===ze);if(ut){Ce.preventDefault(),je(),Le(ut[0]);return}if(Be.some(([,Oe])=>Oe.startsWith(`${ze} `))){Ce.preventDefault(),he=_e,ee();return}const ft=Be.find(([,Oe])=>Oe===Ve);if(ft){Ce.preventDefault(),je(),Le(ft[0]);return}if(Be.some(([,Oe])=>Oe.startsWith(`${Ve} `))){Ce.preventDefault(),he=[Ve],ee();return}je()};return re.addEventListener("keydown",se),re.addEventListener("keydown",fe),()=>{je(),re.removeEventListener("keydown",se),re.removeEventListener("keydown",fe)}});return()=>{for(const re of K)re()}},[G,te,B,pe,L,Le,e]);const Ae=x==="light"?So:Co,ke=((gt=(Ue=(Qe=S.current)==null?void 0:Qe.activePanel)==null?void 0:Ue.group.element)==null?void 0:gt.ownerDocument)??document;return s.jsxs(jp.Provider,{value:Te,children:[s.jsx("div",{ref:I,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(Km,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:rw,remote:nw},defaultTabComponent:ow,watermarkComponent:aw,onReady:ht,singleTabMode:"default",tabAnimation:"smooth",theme:Ae,popoutUrl:"/popout.html"})}),A&&Pr.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:A.x,top:A.y},children:Me.map(U=>{if(U.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},U.id);let K=s.jsx(tf,{size:13,className:"shrink-0 opacity-70"}),re=()=>{};switch(U.id){case"dockInWindow":case"dockBackToGrid":K=s.jsx(rf,{size:13,className:"shrink-0 opacity-70"}),re=()=>{Se(A.tabKey),T(null)};break;case"moveBackToMain":K=s.jsx(ef,{size:13,className:"shrink-0 opacity-70"}),re=()=>{be(A.tabKey),T(null)};break;case"floatAsPanel":K=s.jsx(sf,{size:13,className:"shrink-0 opacity-70"}),re=()=>{ve(A.tabKey),T(null)};break;case"openInNewWindow":K=s.jsx(Zh,{size:13,className:"shrink-0 opacity-70"}),re=()=>{ce(A.tabKey),T(null)};break;case"setShortcut":re=he=>{he.stopPropagation(),ue(A.tabKey),T(null)};break;case"removeShortcut":K=s.jsx(yt,{size:13,className:"shrink-0 opacity-70"}),re=()=>{const he={...X};delete he[A.tabKey],H(he),T(null)};break;case"hideTab":K=s.jsx(ai,{size:13,className:"shrink-0 opacity-70"}),re=()=>{Y(A.tabKey),T(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${U.tone==="muted"?"text-text-muted":""}`,onMouseDown:ew,onClick:re,children:[K,s.jsx("span",{className:"flex-1 min-w-0",children:U.label}),U.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:U.shortcut}):null]},U.id)})}),A.sourceDocument.body),L&&Pr.createPortal(s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>ue(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:U=>U.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",te?"⌘+1":"Ctrl+1",", ",te?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),ke.body)]})}const kp="adhdev-recent-launch-args-v1",lw=8;function cw(e){return String(e||"").trim().replace(/\s+/g," ")}function Np(e,t){return`${e.trim()}::${t.trim()}`}function Sp(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(kp)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function dw(e){if(!(typeof window>"u"))try{window.localStorage.setItem(kp,JSON.stringify(e))}catch{}}function uw(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=Sp().byKey[Np(r,n)])==null?void 0:o.items)||[]}function pw(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=cw(r);if(!n||!a||!o)return;const i=Sp(),c=Np(n,a),d=((u=i.byKey[c])==null?void 0:u.items)||[],p=[o,...d.filter(m=>m!==o)].slice(0,lw);i.byKey[c]={items:p},dw(i)}function mw(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Fn({title:e,description:t,action:r,children:n,className:a="",contentClassName:o=""}){return s.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),t&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:t})]}),r?s.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?s.jsx("div",{className:t||r?`mt-3 ${o}`.trim():o,children:n}):null]})}function hw({savedSessionsLoading:e,savedSessionsLoaded:t,savedSessionsCount:r=0}){return e?"Refreshing saved history…":t?r>0?`${r} saved ${r===1?"history":"histories"} loaded. Open saved history to choose one.`:"No saved history found yet. New Hermes CLI conversations will appear here after ADHDev captures provider history.":"Start fresh, or open saved history when you want continuity."}function fw({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:i,onOpenHistory:c,onClearSelection:d}){const p=o?cp(o):null,u=hw({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Fn,{title:"Saved history",description:wi(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:i,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:c,children:Wg()})]}),children:[p?s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),s.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:p.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:p.providerSessionId}),s.jsx("div",{className:"mt-1",children:p.metaLine}),p.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:p.updatedLabel}),p.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:p.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:d,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:u}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function Cp({setup:e,providerName:t,className:r=""}){return e?s.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${r}`,children:[s.jsxs("div",{className:"font-semibold",children:["Manual MCP setup required",t?` for ${t}`:""]}),e.instructions&&s.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-text-muted",children:[e.serverName&&s.jsxs("span",{children:["Server: ",s.jsx("code",{children:e.serverName})]}),e.configFormat&&s.jsxs("span",{children:["Format: ",s.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&s.jsxs("span",{children:["Config path: ",s.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&s.jsx("span",{children:"Start a fresh CLI session after editing config."})]}),e.template&&s.jsx("pre",{className:"mt-3 max-h-72 overflow-auto rounded-lg border border-border-subtle bg-bg-primary p-3 text-xs font-mono leading-relaxed text-text-primary select-all whitespace-pre-wrap",children:e.template})]}):null}function xw({workspaceMode:e,activeKind:t,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:o,onSelect:i}){return e==="mesh"?null:s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:r},{id:"ide",label:"Workspace",enabled:n},{id:"acp",label:"ACP",enabled:a}].map(c=>s.jsx("button",{type:"button",className:`btn btn-sm ${t===c.id?"btn-primary":"btn-secondary"}`,onClick:()=>i(c.id),disabled:!c.enabled||o,children:c.label},c.id))})]})}function ao(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>Qs(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>Qs(a,"acp"))?"acp":null}function Sn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function bw({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:p}){var Oe,Et;const u=Ur(),m=l.useMemo(()=>[...e].sort(ui),[e]),[h,b]=l.useState(((Oe=m[0])==null?void 0:Oe.id)||""),g=l.useMemo(()=>m.find(de=>de.id===h)||m[0],[h,m]),f=l.useMemo(()=>((g==null?void 0:g.workspaces)||[]).map(de=>({id:de.id,path:de.path,label:de.label})),[g]),j=(g==null?void 0:g.defaultWorkspaceId)||null,[N,y]=l.useState("workspace"),[v,k]=l.useState(""),[w,x]=l.useState(""),[C,S]=l.useState([]),[I,$]=l.useState(""),[R,_]=l.useState(!1),[P,F]=l.useState(null),[q,A]=l.useState(""),[T,B]=l.useState(ao(m[0])),[D,M]=l.useState(""),[E,z]=l.useState(""),[Q,J]=l.useState([]),[ae,ne]=l.useState(""),[ce,be]=l.useState([]),[Z,Y]=l.useState(!1),[ve,ye]=l.useState(!1),[xe,Se]=l.useState(""),[ie,we]=l.useState(!1),[pe,W]=l.useState(()=>At()),[O,V]=l.useState(null),[oe,te]=l.useState(!1),[X,L]=l.useState(""),[ue,H]=l.useState(null),[le,G]=l.useState(!1),[Le,Te]=l.useState(""),[Me,He]=l.useState([]),[qe,Je]=l.useState(!1),[st,Xe]=l.useState(""),[ct,at]=l.useState(!1),ht=l.useRef(null),Ae=l.useRef(0);l.useEffect(()=>{var de;!h&&((de=m[0])!=null&&de.id)&&b(m[0].id)},[h,m]),l.useEffect(()=>{!g||!(!g.workspaces||!g.availableProviders||!g.detectedIdes||!g.recentLaunches)||u(g.id,{minFreshMs:3e4}).catch(()=>{})},[u,g]);const ke=l.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(de=>Qs(de,"cli")),[g]),Qe=l.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(de=>Qs(de,"acp")),[g]),Ue=l.useMemo(()=>((g==null?void 0:g.detectedIdes)||[]).map(de=>({id:de.type,label:de.name||de.type,meta:de.running?"Detected locally":"Available to open"})),[g]),gt=l.useMemo(()=>T==="cli"?ke.map(de=>({id:de.type,label:de.displayName||de.type,meta:"CLI provider"})):T==="acp"?Qe.map(de=>({id:de.type,label:de.displayName||de.type,meta:"ACP provider"})):Ue,[Qe,T,ke,Ue]),U=l.useMemo(()=>C.find(de=>de.id===I)||null,[C,I]),K=l.useMemo(()=>ke.find(de=>de.type===D)||null,[ke,D]),re=l.useMemo(()=>rp(K==null?void 0:K.meshCoordinator,{meshId:(U==null?void 0:U.id)||"",workspace:(U==null?void 0:U.workspace)||""}),[K,U]),he=ue||re,ge=l.useCallback(async de=>{_(!0),A("");try{const $e=await c(de);S($e),$(me=>{var Ee;return $e.some(kt=>kt.id===me)?me:((Ee=$e[0])==null?void 0:Ee.id)||""}),F(de)}catch($e){S([]),$(""),F(de),A($e instanceof Error?$e.message:"Could not load meshes")}finally{_(!1)}},[c]);l.useEffect(()=>{var $e;if(!g)return;if(ht.current!==g.id){ht.current=g.id,y("workspace"),k(j||(($e=f[0])==null?void 0:$e.id)||"__home__"),x(""),S([]),$(""),F(null),A(""),B(ao(g)),M(""),z(""),ne(""),be([]),ye(!1),Se(""),W(At()),L(""),H(null);return}k(me=>{var Ee;return me==="__custom__"||me==="__home__"||f.some(kt=>kt.id===me)?me:j||((Ee=f[0])==null?void 0:Ee.id)||"__home__"}),B(me=>me==="ide"&&Ue.length>0||me==="cli"&&ke.length>0||me==="acp"&&Qe.length>0?me:ao(g))},[Qe.length,ke.length,j,Ue.length,g,f]),l.useEffect(()=>{!g||N!=="mesh"||P===g.id||R||ge(g.id)},[ge,P,R,g,N]),l.useEffect(()=>{N==="mesh"&&T!=="cli"&&ke.length>0&&B("cli")},[T,ke.length,N]),l.useEffect(()=>{var de;T&&(gt.some($e=>$e.id===D)||M(((de=gt[0])==null?void 0:de.id)||""))},[T,gt,D]),l.useEffect(()=>{H(null)},[g==null?void 0:g.id,I,D,N]);const je=l.useCallback(async(de,$e)=>{const me=Ae.current+1;return Ae.current=me,Y(!0),Se(""),p(de,$e).then(Ee=>{Ae.current===me&&be(Ee)}).catch(Ee=>{Ae.current===me&&(be([]),Se(Ee instanceof Error?Ee.message:"Could not load saved sessions"))}).finally(()=>{Ae.current===me&&(Y(!1),ye(!0))})},[p]),ee=l.useCallback((de,$e)=>{J(uw(de,$e))},[]);l.useEffect(()=>{Ae.current+=1,ne(""),W(At()),!g||!D||T==="ide"?J([]):ee(g.id,D),ye(!1),be([]),Se(""),Y(!1)},[T,ee,je,g,D]),l.useEffect(()=>{if(!ae)return;const de=ce.find($e=>$e.providerSessionId===ae);de!=null&&de.canResume||ne("")},[ce,ae]);const se=v==="__custom__"?w.trim():v==="__home__"?"":((Et=f.find(de=>de.id===v))==null?void 0:Et.path)||"",fe=l.useMemo(()=>g?t.filter(de=>de.id!==g.id&&de.daemonId===g.id).map(de=>de.workspace):[],[t,g]),Ce=l.useMemo(()=>((g==null?void 0:g.recentLaunches)||[]).map(de=>de.workspace),[g]),Pe=l.useCallback(de=>{const $e=String(de.workspace||"").trim();if(!$e)return;const me=f.find(Ee=>Sn(Ee.path)===Sn($e));if(me){k(me.id),x("");return}k("__custom__"),x($e)},[f]),Ie=l.useCallback(de=>{const $e=String(de.workspace||"").trim();if(!$e)return{workspaceId:null,workspacePath:null};const me=f.find(Ee=>Sn(Ee.path)===Sn($e));return me?{workspaceId:me.id,workspacePath:null}:{workspaceId:null,workspacePath:$e}},[f]),Re=l.useMemo(()=>ce.find(de=>de.providerSessionId===ae)||null,[ce,ae]),Be=l.useMemo(()=>{var $e;if(T!=="cli"||!g||!D)return null;const de=(($e=ke.find(me=>me.type===D))==null?void 0:$e.displayName)||D;return{routeId:g.id,daemonId:g.id,providerSessionId:ae||void 0,transport:"pty",mode:"chat",agentName:de,agentType:D,status:"idle",title:de,messages:[],ideType:D,workspaceName:se,workspacePath:se,displayPrimary:de,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${g.id}:${D}`,machineName:$t(g,{fallbackId:g.id})}},[T,ke,se,g,ae,D]),_e=l.useCallback(()=>{var $e;if(!g)return;k("__custom__"),G(!0),Xe("");const de=Ti(g.platform,Ai(w.trim(),se,fe,Ce,g.defaultWorkspacePath,($e=f.find(me=>me.id===j))==null?void 0:$e.path,f.map(me=>me.path)));Je(!0),n(g.id,de).then(me=>{Te(me.path),x(me.path),He(me.directories)}).catch(me=>{Xe(me instanceof Error?me.message:"Could not load folder")}).finally(()=>Je(!1))},[w,j,Ce,fe,n,se,g,f]),ze=l.useCallback(de=>{g&&(Je(!0),Xe(""),n(g.id,de).then($e=>{Te($e.path),x($e.path),He($e.directories)}).catch($e=>{Xe($e instanceof Error?$e.message:"Could not load folder")}).finally(()=>Je(!1)))},[n,g]),Ve=l.useCallback(async()=>{if(!g||!se)return;at(!0),L("");const de=await a(g.id,se);if(at(!1),!de.ok){L(de.error||"Could not save workspace");return}L("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,se,g]),ut=l.useCallback(async()=>{if(!g)return;if(N==="mesh"){if(!I||!D)return;te(!0),L(""),H(null);const me=await d(g.id,I,D);if(te(!1),!me.ok){if(me.code==="mesh_coordinator_manual_mcp_setup_required"&&me.manualSetup){H(me.manualSetup),L("Manual MCP setup required before this provider can act as mesh coordinator.");return}L(me.error||"Could not start mesh coordinator");return}r();return}if(!T||!D)return;te(!0),L("");const de=E.trim()?E.trim().split(/\s+/).filter(Boolean):[],$e=T==="ide"?await o(g.id,D,{workspacePath:se||null}):await i(g.id,T,D,{workspaceId:v!=="__home__"&&v!=="__custom__"?v:null,workspacePath:v==="__custom__"&&se||null,resumeSessionId:T==="cli"&&ae?ae:null,cliArgs:de});if(te(!1),!$e.ok){L($e.error||"Could not start session");return}T!=="ide"&&E.trim()&&(pw(g.id,D,E),ee(g.id,D)),r()},[T,E,ee,r,o,d,i,se,g,I,ae,D,v,N]),vt=N==="mesh"?"Start mesh coordinator":T?Og(T,T==="cli"&&!!ae):"Start",ft=N==="mesh"?"Starting coordinator…":T?zg(T,T==="cli"&&!!ae):"Starting…",pt=m.length>5;return g?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(yt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[m.length>1&&s.jsx(Fn,{title:"Machine",children:pt?s.jsx("select",{"aria-label":"Machine",value:g.id,onChange:de=>b(de.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:m.map(de=>s.jsx("option",{value:de.id,children:$t(de,{fallbackId:de.id})},de.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:m.map(de=>{const $e=$t(de,{fallbackId:de.id}),me=g.id===de.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${$e}`,"aria-pressed":me,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${me?"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:()=>b(de.id),disabled:oe,title:$e,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${de.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:$e})]},de.id)})})}),s.jsxs(Fn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:N==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:_e,disabled:oe,children:"Browse…"}):void 0,children:[s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":"Launch target type",children:[{id:"workspace",label:"Workspace",desc:"Normal session"},{id:"mesh",label:"Mesh",desc:"Coordinator session"}].map(de=>s.jsxs("button",{type:"button",role:"radio","aria-checked":N===de.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${N===de.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:()=>{y(de.id),L(""),de.id==="mesh"&&g&&P!==g.id&&!R&&ge(g.id)},disabled:oe,children:[s.jsx("div",{className:"text-sm font-semibold",children:de.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:de.desc})]},de.id))}),N==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:v,onChange:de=>{const $e=de.target.value;k($e),$e==="__custom__"?_e():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:[s.jsx("option",{value:"__home__",children:"Home directory"}),f.map(de=>s.jsxs("option",{value:de.id,children:[de.id===j?"⭐ ":"",Od(de.path,de.label)||de.path]},de.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v==="__home__"?"Launch without a workspace.":se||"Select a workspace folder."}),v==="__custom__"&&se&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:_e,disabled:oe,children:[s.jsx(Vs,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ve,disabled:oe||ct,children:ct?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[R&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!R&&q&&s.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:q}),!R&&!q&&C.length===0&&s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker."}),C.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:C.map(de=>s.jsxs("button",{type:"button",role:"radio","aria-checked":I===de.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${I===de.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(de.id),disabled:oe,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:de.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[de.repoIdentity||"Repo mesh",typeof de.nodesCount=="number"?` · ${de.nodesCount} node${de.nodesCount===1?"":"s"}`:""]}),de.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",de.workspace]})]},de.id))}),U&&s.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),s.jsx(xw,{workspaceMode:N,activeKind:T,cliEnabled:ke.length>0,ideEnabled:Ue.length>0,acpEnabled:Qe.length>0,busy:oe,onSelect:B}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:T==="ide"?"Choose IDE":T==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[gt.map(de=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${D===de.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>M(de.id),disabled:oe,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:de.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:de.meta})]},de.id)),gt.length===0&&s.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),N==="mesh"&&he&&s.jsx(Cp,{setup:he,providerName:(K==null?void 0:K.displayName)||(K==null?void 0:K.name)||D}),N!=="mesh"&&T!=="ide"&&s.jsxs(Fn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:E,onChange:de=>z(de.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}),Q.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:Q.map(de=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>z(de),disabled:oe,title:de,children:de},de))})]}),N!=="mesh"&&T==="cli"&&s.jsx(fw,{busy:oe,savedSessionsLoading:Z,savedSessionsError:xe,selectedSession:Re,onRefresh:()=>{!g||!D||je(g.id,D)},onOpenHistory:()=>{!g||!D||(we(!0),mw({hasLoadedInitialResults:ve,isLoading:Z})&&je(g.id,D))},onClearSelection:()=>ne("")}),X&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${X.includes("saved")||X.includes("requested")||X.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:X})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:r,disabled:oe,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:ut,disabled:oe||(N==="mesh"?!I||!D||T!=="cli"||R:!T||!D||v==="__custom__"&&!se),children:[s.jsx(Nd,{size:14}),oe?ft:vt]})]})]})}),le&&s.jsx(Pi,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:Le,directories:Me,busy:qe,error:st,onClose:()=>G(!1),onNavigate:ze,onConfirm:de=>{x(de),Te(de),k("__custom__"),G(!1)}}),ie&&Be&&s.jsx(Su,{activeConv:Be,ides:[],isCreatingChat:!1,isRefreshingHistory:Z,savedSessions:ce,isSavedSessionsLoading:Z,isResumingSavedSessionId:O,savedHistoryFilters:pe,missingWorkspaceResumePath:se||null,onSavedHistoryFiltersChange:W,onClose:()=>we(!1),onNewChat:()=>{ne(""),we(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!g||!D||je(g.id,D)},onResumeSavedSession:de=>{if(!g||!D||O||!de.canResume)return;const $e=Ie(de);ne(de.providerSessionId),Pe(de),V(de.providerSessionId),we(!1),te(!0),L(""),i(g.id,"cli",D,{workspaceId:$e.workspaceId,workspacePath:$e.workspacePath,resumeSessionId:de.providerSessionId}).then(me=>{if(!me.ok){L(me.error||"Could not resume session");return}r()}).finally(()=>{te(!1),V(me=>me===de.providerSessionId?null:me)})}})]}):null}function Ip(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 Di(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 r=Ip(e);return r?{label:r,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 $i(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function Mp(e){var t;return!$i(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 Cn(e){return[...new Set(e.filter(t=>!!t))]}function gw(e){const t=e.nodes.find(i=>i.type==="defaultBranchNode")??null,r=(t==null?void 0:t.branch)??null,n=e.nodes.filter(i=>i.type!=="defaultBranchNode"&&i.type!=="submoduleNode"&&!i.isOrphan&&!!r&&i.branch===r),a=e.nodes.filter(i=>i.type!=="submoduleNode"&&!i.isOrphan),o=e.nodes.filter(i=>i.type!=="submoduleNode");return t||n.length>0?Cn([t==null?void 0:t.id,...n.map(i=>i.id)]):a.length>0?Cn(a.map(i=>i.id)):o.length>0?Cn(o.map(i=>i.id)):Cn(e.nodes.map(i=>i.id))}function Ap(e){const t=[...e.nodes].sort((n,a)=>n.id.localeCompare(a.id)).map(n=>[n.id,n.type,n.branch??"",n.parentNodeId??"",n.submodulePath??""].join(":")).join("|"),r=[...e.edges].sort((n,a)=>n.id.localeCompare(a.id)).map(n=>[n.id,n.source,n.target,n.type].join(":")).join("|");return`${e.meshId}::${t}::${r}`}function yw(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${Ap(e)}::${n}x${a}`}const vw={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"},ww={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"},jw={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"},kw={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 Ds(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=>ww[t],actionButton:t=>kw[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=>vw[t],actionButton:t=>jw[t]}}const Zs={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,layerGap:220,nodeGap:82,edgeLabelBuffer:180,placeholderTopOffset:0},Jr={worktreeCardWidth:188,submoduleCardWidth:188,minWorktreeCardHeight:88,minSubmoduleCardHeight:88,maxEstimatedCardHeight:178,layerGap:160,nodeGap:52,edgeLabelBuffer:120},Nw={maxWidth:180};function Sw(e){return e==="TB"?"DOWN":"RIGHT"}function Ei(e,t){return{"elk.algorithm":"layered","elk.direction":Sw(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 Cw=Ei(Zs,"LR");Ei(Jr,"LR");function Iw(e){const t=e.nodes.length;if(t<8)return"LR";const r=new Map;for(const a of e.edges)r.set(a.source,(r.get(a.source)??0)+1);let n=0;for(const a of r.values())a>n&&(n=a);return n>=Math.max(6,Math.floor(t/2))?"TB":"LR"}const Mw=new Um;function Fr(e,t=!1){const r=t?Jr:Zs;return e.type==="submoduleNode"?r.submoduleCardWidth:r.worktreeCardWidth}function On(e){var r;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=Ip(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?(r=e.branchConvergence)!=null&&r.needsConvergence?"Needs follow-up":"Clean and even with upstream":t.join(" · ")}function Tp(e,t=!1){const r=t?Jr:Zs,n=Fr(e,t),a=t?e.type==="submoduleNode"?20:22:e.type==="submoduleNode"?24:30,o=t?(e.type==="submoduleNode",2):e.type==="submoduleNode"?2:3,i=Math.ceil(Aw(e)/o),c=In(e.label,a,2),d=In(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,a,2),p=In(On(e),a+(t?1:4),t?2:3),u=Di(e),m=Mp(e)?$i(e):null,h=t?0:In(m,Math.max(24,Math.floor(n/8)),4),b=t?40+c*16+d*12+(u?22:0)+Math.max(0,i-1)*18+Math.max(18,p*16):52+c*18+d*14+(u?30:0)+i*24+Math.max(22,p*18)+(h>0?22+h*16:0),g=e.type==="submoduleNode"?r.minSubmoduleCardHeight:r.minWorktreeCardHeight;return Math.min(r.maxEstimatedCardHeight,Math.max(g,Math.ceil(b)))}function In(e,t,r){const n=(e||"").trim();return n?Math.max(1,Math.min(r,Math.ceil(n.length/t))):0}function Aw(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 Tw(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 _w(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function Lw(e,t,r,n=!0){return{id:e.id,type:"meshNode",position:{x:t,y:r},graphNode:e,selected:!1,draggable:!1,selectable:n}}function Pw(e,t,r){return{id:e.id,x:t,y:r,width:Fr(e),height:Tp(e)}}function Rw(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",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 _p(e){const t=[...e.nodes].sort(Tw),r=t.find(a=>a.type==="defaultBranchNode")??null,n=t.some(a=>a.id!==(r==null?void 0:r.id)&&a.type!=="submoduleNode");return!r||n?t:[...t,Rw(r,e)]}function Dw(e,t=Cw,r=!1,n="LR"){const a=_p(e),o=new Set(a.map(d=>d.id)),i=a.map(d=>({id:d.id,width:Fr(d,r),height:Tp(d,r)})),c=e.edges.filter(d=>o.has(d.source)&&o.has(d.target)).sort(_w).map(d=>({id:d.id,sources:[d.source],targets:[d.target]}));return{id:`${e.meshId||"mesh"}__elk_root`,layoutOptions:{...t},children:i,edges:c}}function $w(e,t=!1){const r=[...new Set(e.map(a=>Math.round(a.x)))].sort((a,o)=>a-o),n=t?Jr.layerGap:Zs.layerGap;return r.length<2?n:Math.min(...r.slice(1).map((a,o)=>a-r[o]))}async function Lp(e,t=!1,r="LR",n){var g,f;const o=Ei(t?Jr:Zs,r),i=_p(e),c=new Map(i.map(j=>[j.id,j])),d=Dw(e,o,t,r);if(n&&n.size>0)for(const j of d.children??[]){const N=n.get(j.id);N&&N>0&&(j.height=N)}const p=await Mw.layout(d),u=(p.children??[]).map(j=>{const N=c.get(j.id);return N?Lw(N,Math.round(j.x??0),Math.round(j.y??Zs.placeholderTopOffset),!j.id.endsWith("__placeholder")):null}).filter(Boolean),m=new Map(i.map((j,N)=>[j.id,N]));u.sort((j,N)=>(m.get(j.id)??0)-(m.get(N.id)??0));const h=u.map(j=>Pw(j.graphNode,j.position.x,j.position.y)),b=new Map;for(const j of p.edges??[]){const N=j.sections;if(!N||N.length===0)continue;const y=N[0],v=(g=j.sources)==null?void 0:g[0],k=(f=j.targets)==null?void 0:f[0];if(!v||!k)continue;const w=[];w.push({x:Math.round(y.startPoint.x),y:Math.round(y.startPoint.y)});for(const x of y.bendPoints??[])w.push({x:Math.round(x.x),y:Math.round(x.y)});w.push({x:Math.round(y.endPoint.x),y:Math.round(y.endPoint.y)}),b.set(j.id,{id:j.id,source:v,target:k,points:w})}return{nodes:u,bounds:h,edgeRoutes:b,columnGap:$w(h,t),layoutOptions:{...o}}}function Ew(e){var t,r;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)??"",(r=e.branchConvergence)!=null&&r.needsConvergence?1:0,e.nextStepHint??"",e.error??"",e.parentNodeId??"",e.submodulePath??"",e.submoduleCommit??""].join("|")}function Pp(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function Bw(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(Ew),...e.edges.map(Pp)].join("::")}function Fw(e){return[e.meshId,e.nodes.length,e.edges.length,...e.nodes.map(t=>{var r,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,((r=t.branchConvergence)==null?void 0:r.status)??"",(n=t.branchConvergence)!=null&&n.needsConvergence?1:0,t.nextStepHint??"",t.parentNodeId??"",t.submodulePath??"",t.submoduleCommit??""].join("|")}),...e.edges.map(Pp)].join("::")}const Ow=7,Bi=l.createContext(Ds("dark")),Rp=l.createContext(!1),Dp=l.createContext("LR"),$p={overflowWrap:"anywhere",wordBreak:"break-word"},zw={...$p,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},Hw={...$p,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function Ep(e){return e.activeSessionCount>0}function Ww(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function Sc(e,t,r){const n=Ep(e),a=Ww(e);let o;t?o="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?o=r?"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)]":a?o=r?"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":o=r?"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 i=Di(e);if((i==null?void 0:i.tone)==="danger")return`${o} ${r?"bg-rose-500/12":"bg-rose-50/95"}`;if((i==null?void 0:i.tone)==="warn")return`${o} ${r?"bg-amber-500/10":"bg-amber-50/95"}`;if((i==null?void 0:i.tone)==="info")return`${o} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;switch(e.health){case"online":return`${o} ${r?n?"bg-emerald-500/10":"bg-emerald-500/8":n?"bg-emerald-50":"bg-emerald-50/95"}`;case"dirty":return`${o} ${r?"bg-amber-500/8":"bg-amber-50/95"}`;case"degraded":return`${o} ${r?"bg-rose-500/10":"bg-rose-50/95"}`;case"wrong_branch":return`${o} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;case"offline":return`${o} ${r?"bg-slate-500/10":"bg-slate-100/90"}`;default:return`${o} ${r?"bg-slate-950/78":"bg-white/96"}`}}function Mt(e,t){switch(e){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 Cc(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 Ic(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 Kw(e){return e.replace(/_/g," ")}function Vt(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const r=t.toLowerCase().replace(/[\s-]+/g,"_");return r.includes("approval")?"awaiting approval":r.includes("generating")||r.includes("running")||r.includes("busy")?"generating":r.includes("failed")||r.includes("stopped")||r.includes("interrupted")?r.replace(/_/g," "):r.includes("idle")||r.includes("ready")||r.includes("waiting_input")?"idle":r.replace(/_/g," ")}function Uw(e){var t;return((t=e.sessionDetails)==null?void 0:t.some(r=>Vt(r)==="generating"))??!1}function oo(e,t){const r=Vt(e);return r.includes("approval")?t?"border-amber-400/30 bg-amber-500/12 text-amber-100":"border-amber-300 bg-amber-50 text-amber-700":r==="generating"?t?"border-cyan-400/30 bg-cyan-500/12 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700":r==="idle"?t?"border-emerald-400/30 bg-emerald-500/12 text-emerald-100":"border-emerald-300 bg-emerald-50 text-emerald-700":r.includes("failed")||r.includes("stopped")||r.includes("interrupted")?t?"border-rose-400/30 bg-rose-500/12 text-rose-100":"border-rose-300 bg-rose-50 text-rose-700":Mt("health",t)}function Gw(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function Mc(e){const t=Gw(e);if(t===null)return"runtime age not reported";const r=Math.max(0,Math.floor((Date.now()-t)/1e3));if(r<60)return`${r}s`;const n=Math.floor(r/60);if(n<60)return`${n}m`;const a=Math.floor(n/60);return a<48?`${a}h ${n%60}m`:`${Math.floor(a/24)}d ${a%24}h`}function io(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function br(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function Vw(e){if(e.sessionDetails.length===0)return null;const t=e.sessionDetails.filter(o=>Vt(o)==="generating").length,r=e.sessionDetails.filter(o=>o.isSelfCoordinator).length,n=e.sessionDetails.length-r,a=[`${e.sessionDetails.length} chat${e.sessionDetails.length===1?"":"s"}`];return t>0&&a.push(`${t} generating`),r>0&&a.push(r===1?"coordinator attached":`${r} coordinators`),n>0&&a.push(`${n} worker${n===1?"":"s"}`),t===0&&r>0&&a.push("sampled status"),a.join(" · ")}function Ac(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function qw(e){return e.locality==="remote"?"meta":"health"}function Yw({data:e,selected:t}){const r=l.useContext(Bi),n=l.useContext(Rp),a=l.useContext(Dp),o=e.graphNode,i=o.type==="defaultBranchNode",c=o.type==="submoduleNode",d=Mp(o),p=i?"default branch anchor":c?o.submodulePath||"submodule checkout":[o.machineLabel,Ac(o.locality)].filter(Boolean).join(" · ")||o.workspace,u=o.submoduleCommit?o.submoduleCommit.slice(0,7):null,m=Di(o),h=$i(o),b=Ep(o),g=o.sessionDetails,f=o.sessionDetails,j=Vw(o),N=o.sessionDetails.map(v=>{const k=Vt(v),w=v.providerType||"provider unknown",x=br(v),C=v.startedAt||v.createdAt||null,S=v.statusNote?` · ${v.statusNote}`:"";return`Session: ${v.sessionId} · ${w} · ${k} · ${x} · ${Mc(C)}${S}`});if(n)return s.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${Sc(o,t,r.isDark)}`,style:{width:Fr(o,!0)},title:[o.label,o.branch?`Branch: ${o.branch}`:null,o.machineLabel?`Machine: ${o.machineLabel}`:null,o.workspace?`Workspace: ${o.workspace}`:null,m?`Status: ${m.label}`:null,On(o),...N].filter(Boolean).join(`
74
+ `),children:[s.jsx(ln,{type:"target",position:a==="TB"?os.Top:os.Left,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-xs font-semibold leading-4 ${r.textPrimary}`,children:o.label}),!i&&s.jsx("div",{className:`truncate text-[10px] leading-3.5 ${r.textMuted}`,children:p})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[b&&s.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${r.isDark?"bg-emerald-400":"bg-emerald-500"} animate-pulse`,"aria-label":"active session"}),s.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full",style:{backgroundColor:Ic(o.health)},"aria-hidden":!0})]})]}),o.health==="unknown"&&!m&&s.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 ${Mt("health",r.isDark)}`,children:s.jsx("span",{className:"truncate",children:"Connecting..."})}),m&&s.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] ${Cc(m.tone,r.isDark)}`,title:m.label,children:s.jsx("span",{className:"truncate",children:m.label})}),!m&&o.branch&&!c&&o.health!=="unknown"&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[10px] ${Mt("meta",r.isDark)} rounded-full border px-2 py-0.5 inline-block`,title:o.branch,children:o.branch}),j&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[9px] ${r.isDark?"text-cyan-100/85":"text-sky-700"}`,title:N.join(`
75
+ `),children:j}),f.length>0&&s.jsx("div",{className:"mt-1.5 flex max-h-28 min-w-0 flex-col gap-1 overflow-y-auto pr-1",children:f.map(v=>s.jsxs("div",{className:`min-w-0 rounded-md border px-1.5 py-1 ${r.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/80"}`,title:[`Session ID: ${v.sessionId}`,v.providerType?`Provider: ${v.providerType}`:null,`Status: ${Vt(v)}`,`Role: ${br(v)}`].filter(Boolean).join(`
76
+ `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-1.5",children:[s.jsx("span",{className:`min-w-0 truncate text-[9px] ${r.textMuted}`,children:v.providerType||"provider unknown"}),s.jsx("span",{className:`shrink-0 rounded-full border px-1 py-0 text-[8px] font-semibold uppercase tracking-[0.1em] ${oo(v,r.isDark)}`,children:Vt(v)})]}),s.jsxs("div",{className:`mt-0.5 flex min-w-0 items-center gap-1.5 text-[8px] ${r.textMuted}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",children:io(v.sessionId)}),s.jsx("span",{className:"shrink-0",children:br(v)})]})]},v.sessionId))}),s.jsx(ln,{type:"source",position:a==="TB"?os.Bottom:os.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]});const y=[o.label,p,m?`Status: ${m.label}`:null,On(o),o.branch?`Branch: ${o.branch}`:null,o.dirty?c?"Local changes":`${o.dirtyFiles} dirty`:null,o.hasConflicts?"Has conflicts":null,o.outOfSync?"Out of sync":null,!c&&o.upstream&&o.upstreamStatus!=="fresh"?"Upstream unverified":null,o.isOrphan?"Needs follow-up":null,d&&h?`Note: ${h}`:null,...N].filter(Boolean).join(`
77
+ `);return s.jsxs("div",{className:`rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all ${Sc(o,t,r.isDark)}${Uw(o)?" mesh-node-generating":""}`,style:{width:Fr(o)},title:y,children:[s.jsx(ln,{type:"target",position:a==="TB"?os.Top:os.Left,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${r.textPrimary}`,children:o.label}),s.jsx("div",{className:`truncate text-[11px] ${r.textMuted}`,children:p})]}),s.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 shrink-0",children:[b&&s.jsx("span",{className:`h-2 w-2 rounded-full ${r.isDark?"bg-emerald-400":"bg-emerald-500"} animate-pulse`,"aria-label":"active session"}),s.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:Ic(o.health)},"aria-hidden":!0})]})]}),m?s.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] ${Cc(m.tone,r.isDark)}`,title:m.label,children:s.jsx("span",{className:"truncate",children:m.label})}):o.branch&&!c?s.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] ${Mt("meta",r.isDark)}`,title:o.branch,children:s.jsx("span",{className:"truncate",children:o.branch})}):null,j&&s.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 ${r.isDark?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}`,title:N.join(`
78
+ `),children:s.jsx("span",{className:"truncate",children:j})}),f.length>0&&s.jsx("div",{className:"mt-2 flex max-h-44 min-w-0 flex-col gap-1.5 overflow-y-auto pr-1",children:f.map(v=>{const k=br(v);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/85"}`,title:[`Session ID: ${v.sessionId}`,v.providerType?`Provider: ${v.providerType}`:null,`Status: ${Vt(v)}`,`Role: ${k}`].filter(Boolean).join(`
79
+ `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate text-[10px] ${r.textMuted}`,children:v.providerType||"provider unknown"}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${oo(v,r.isDark)}`,children:Vt(v)})]}),s.jsxs("div",{className:`mt-0.5 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",children:io(v.sessionId)}),s.jsx("span",{children:k})]})]},v.sessionId)})}),s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"flex min-w-0 flex-wrap gap-1.5 text-[10px]",children:[o.health==="unknown"?s.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${Mt("health",r.isDark)}`,children:"connecting..."}):s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${Mt("health",r.isDark)}`,children:Kw(o.health)}),c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Mt("submodule",r.isDark)}`,children:"submodule"}),!i&&o.health==="unknown"&&!o.locality&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${Mt("health",r.isDark)}`,children:"..."}),!i&&(o.health!=="unknown"||o.locality)&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Mt(qw(o),r.isDark)}`,children:Ac(o.locality)}),u&&c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Mt("meta",r.isDark)}`,children:u}),o.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Mt("dirty",r.isDark)}`,children:c?"local changes":`${o.dirtyFiles} dirty`}),o.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Mt("conflict",r.isDark)}`,children:"out of sync"}),o.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Mt("conflict",r.isDark)}`,children:"conflicts"}),!c&&o.upstream&&o.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Mt("orphan",r.isDark)}`,children:"upstream unverified"}),o.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Mt("orphan",r.isDark)}`,children:"needs follow-up"}),!c&&o.refineJobStatus==="completed"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Mt("refineDone",r.isDark)}`,title:o.refineJobBranch?`refined ${o.refineJobBranch}${o.refineJobInto?` → ${o.refineJobInto}`:""}`:"refine completed",children:"refined"})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,style:zw,children:On(o)}),g.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[9px] font-semibold uppercase tracking-[0.16em] ${r.textMuted}`,children:"Attached Chats"}),s.jsx("div",{className:"flex max-h-56 flex-col gap-1.5 overflow-y-auto pr-1",children:g.map(v=>{const k=v.startedAt||v.createdAt||null,w=br(v);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-white/8 bg-white/[0.035]":"border-slate-200 bg-white/80"}`,title:[`Session ID: ${v.sessionId}`,v.providerType?`Provider: ${v.providerType}`:null,`Status: ${Vt(v)}`,`Role: ${w}`,k?`Started: ${k}`:"Started: not reported",v.statusNote?`Note: ${v.statusNote}`:null].filter(Boolean).join(`
80
+ `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono text-[10px] select-text ${r.textPrimary}`,children:io(v.sessionId)}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${oo(v,r.isDark)}`,children:Vt(v)})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"truncate",children:v.providerType||"provider unknown"}),s.jsx("span",{children:w}),s.jsx("span",{children:Mc(k)})]}),v.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${r.textMuted}`,children:v.statusNote})]},v.sessionId)})})]}),d&&h&&s.jsx("div",{className:`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${r.isDark?"border-cyan-400/15 bg-cyan-500/8 text-cyan-50/90":"border-sky-300 bg-sky-50 text-sky-700"}`,style:Hw,children:h})]}),s.jsx(ln,{type:"source",position:a==="TB"?os.Bottom:os.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const Jw={meshNode:Yw},Xw=8;function Qw(e){if(e.length<2)return null;if(e.length===2){const[p,u]=e;return{d:`M ${p.x},${p.y} L ${u.x},${u.y}`,labelX:(p.x+u.x)/2,labelY:(p.y+u.y)/2}}const t=Xw,r=[`M ${e[0].x},${e[0].y}`];for(let p=1;p<e.length-1;p+=1){const u=e[p-1],m=e[p],h=e[p+1],b=Math.sign(m.x-u.x),g=Math.sign(m.y-u.y),f=Math.sign(h.x-m.x),j=Math.sign(h.y-m.y),N=Math.hypot(m.x-u.x,m.y-u.y),y=Math.hypot(h.x-m.x,h.y-m.y),v=Math.min(t,N/2,y/2);if(v<1||b===f&&g===j){r.push(`L ${m.x},${m.y}`);continue}const k=m.x-b*v,w=m.y-g*v,x=m.x+f*v,C=m.y+j*v;r.push(`L ${k},${w}`),r.push(`Q ${m.x},${m.y} ${x},${C}`)}const n=e[e.length-1];r.push(`L ${n.x},${n.y}`);let a=0;const o=[0];for(let p=1;p<e.length;p+=1)a+=Math.hypot(e[p].x-e[p-1].x,e[p].y-e[p-1].y),o.push(a);const i=a/2;let c=e[0].x,d=e[0].y;for(let p=1;p<e.length;p+=1)if(o[p]>=i){const u=o[p]-o[p-1],m=u===0?0:(i-o[p-1])/u;c=e[p-1].x+(e[p].x-e[p-1].x)*m,d=e[p-1].y+(e[p].y-e[p-1].y)*m;break}return{d:r.join(" "),labelX:c,labelY:d}}function Zw(e){const t=e.data.routePoints;if(t&&t.length>=2){const o=Qw(t);if(o)return[o.d,o.labelX,o.labelY]}const r={sourceX:e.sourceX,sourceY:e.sourceY,sourcePosition:e.sourcePosition,targetX:e.targetX,targetY:e.targetY,targetPosition:e.targetPosition},n=e.data.graphEdge;let a;return n.type==="parentBranch"?a=nh(r):n.type==="worktreeLink"||n.type==="submoduleLink"||n.type==="cloneLink"?a=sh(r):a=rh(r),[a[0],a[1],a[2]]}function ej(e,t){const r="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?`${r} border-orange-400/35 bg-orange-500/14 text-orange-100`:`${r} border-orange-300 bg-orange-50 text-orange-700`;case"submoduleLink":return t?`${r} border-violet-400/30 bg-violet-500/14 text-violet-100`:`${r} border-violet-300 bg-violet-50 text-violet-700`;case"sessionLink":return t?`${r} border-emerald-400/30 bg-emerald-500/14 text-emerald-100`:`${r} border-emerald-300 bg-emerald-50 text-emerald-700`;case"cloneLink":return t?`${r} border-teal-400/30 bg-teal-500/14 text-teal-100`:`${r} border-teal-300 bg-teal-50 text-teal-700`;default:return t?`${r} border-sky-400/25 bg-slate-950/78 text-sky-100`:`${r} border-sky-300 bg-white/95 text-sky-700`}}function tj(e){const t=l.useContext(Bi),r=e.data.graphEdge,[n,a,o]=Zw(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(Xm,{id:e.id,path:n,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(Qm,{children:s.jsx("div",{className:ej(r,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${a}px, ${o}px)`,pointerEvents:"none",maxWidth:Nw.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const sj={meshEdge:tj};async function rj(e,t,r,n,a){const o=await Lp(e,r,n,a);return Bp(e,o,t,r)}async function nj(e,t=Ds("dark"),r=!1,n="LR"){const a=await Lp(e,r,n);return Bp(e,a,t,r)}function Bp(e,t,r,n=!1){const a=new Set(t.nodes.map(p=>p.id)),o=t.nodes.map(p=>({id:p.id,type:p.type,position:p.position,data:{graphNode:p.graphNode,compact:n},selected:p.selected,draggable:p.draggable,selectable:p.selectable})),i=e.edges.filter(p=>a.has(p.source)&&a.has(p.target)),c=ij(i),d=i.map(p=>{var u;return{id:p.id,source:p.source,target:p.target,label:c.has(p.id)?p.label:void 0,type:"meshEdge",data:{graphEdge:p,routePoints:(u=t.edgeRoutes.get(p.id))==null?void 0:u.points},animated:p.type==="orphanLink",markerEnd:p.direction==="directed"?{type:th.ArrowClosed,width:p.type==="submoduleLink"?16:18,height:p.type==="submoduleLink"?16:18,color:_c(p)}:void 0,style:{stroke:_c(p),strokeWidth:p.type==="orphanLink"?2.25:p.type==="submoduleLink"?1.7:p.type==="worktreeLink"?1.8:p.type==="cloneLink"?1.6:2,strokeDasharray:p.type==="orphanLink"?"5 4":p.type==="submoduleLink"?"4 3":p.type==="cloneLink"?"6 3":void 0},labelStyle:{fill:r.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:r.edgeLabelBackgroundColor,fillOpacity:1,stroke:r.edgeLabelBorderColor},labelBgPadding:[6,4],labelBgBorderRadius:7}});return{nodes:o,edges:d}}const aj=3,oj=2;function Tc(e){switch(e.type){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 ij(e){const t=new Set,r=new Map;for(const n of e){if(!n.label)continue;const a=r.get(n.source);a?a.push(n):r.set(n.source,[n])}for(const n of r.values()){if(n.length<aj){for(const o of n)t.add(o.id);continue}const a=[...n].sort((o,i)=>{const c=Tc(i)-Tc(o);return c!==0?c:o.id.localeCompare(i.id)});for(const o of a.slice(0,oj))t.add(o.id)}return t}function _c(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";default:return"#64748b"}}function lj(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 cj(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 dj({data:e,viewportKey:t}){const r=Zm(),n=eh(),a=l.useRef(null),o=l.useMemo(()=>Ap(e),[e]),i=l.useMemo(()=>gw(e),[e]);return l.useEffect(()=>{if(!r||e.nodes.length===0||a.current===t)return;let c=!1;const d=requestAnimationFrame(()=>{if(c)return;const p=i.length>0&&i.length<e.nodes.length;n.fitView({nodes:p?i.map(u=>({id:u})):void 0,padding:p?.24:.2,maxZoom:p?.98:.9,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(d)}},[e.nodes.length,i,o,r,n,t]),null}const uj=12;function pj(e){return e>=16?"min-h-[720px]":e>=10?"min-h-[580px]":"min-h-[460px]"}function mj({data:e,selectedNodeId:t=null,directionPref:r,onNodeClick:n,onEdgeClick:a,onNodeHoverChange:o,onEdgeHoverChange:i}){const{theme:c}=Rs(),d=l.useMemo(()=>Ds(c),[c]),p=l.useMemo(()=>Bw(e),[e]),u=l.useMemo(()=>Fw(e),[e]),m=e.nodes.length>=Ow,[h]=l.useState("LR"),b=r??h,g=l.useMemo(()=>b==="auto"?Iw(e):b,[b,p,e]),f=e.nodes.length>=uj,[j,N]=l.useState({nodes:[],edges:[]}),y=l.useRef(null),[v,k]=l.useState({width:0,height:0}),w=l.useMemo(()=>`${yw(e,v.width,v.height)}::${g}`,[p,e,v.height,v.width,g]);l.useEffect(()=>{let C=!1;return nj(e,d,m,g).then(S=>{if(C)return;N(S);const I=requestAnimationFrame(()=>{if(C)return;const $=y.current;if(!$)return;const R=new Map;for(const _ of S.nodes){const P=$.querySelector(`.react-flow__node[data-id="${CSS.escape(_.id)}"]`);P&&P.offsetHeight>0&&R.set(_.id,P.offsetHeight)}R.size!==0&&rj(e,d,m,g,R).then(_=>{C||N(_)})});return()=>cancelAnimationFrame(I)}),()=>{C=!0}},[e,u,d,m,g]);const x=l.useMemo(()=>j.nodes.map(C=>({...C,selected:C.id===t})),[j.nodes,t]);return l.useEffect(()=>{const C=y.current;if(!C)return;const S=()=>{const $=Math.max(0,Math.round(C.clientWidth)),R=Math.max(0,Math.round(C.clientHeight));k(_=>_.width===$&&_.height===R?_:{width:$,height:R})};S();const I=typeof ResizeObserver=="function"?new ResizeObserver(()=>S()):null;return I==null||I.observe(C),window.addEventListener("resize",S),()=>{I==null||I.disconnect(),window.removeEventListener("resize",S)}},[]),s.jsx(Bi.Provider,{value:d,children:s.jsx(Rp.Provider,{value:m,children:s.jsx(Dp.Provider,{value:g,children:s.jsxs("div",{ref:y,className:`${d.graphShellClass} ${pj(e.nodes.length)}`,style:{height:"100%"},children:[s.jsx("div",{className:`pointer-events-none absolute left-1/2 top-2 z-10 -translate-x-1/2 px-3 py-1 text-[10px] ${d.graphStatChipClass}`,children:"drag or scroll to pan"}),s.jsx("div",{className:"w-full min-w-0 flex-1",style:{height:"100%"},children:s.jsxs(Gm,{nodes:x,edges:j.edges,nodeTypes:Jw,edgeTypes:sj,minZoom:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(C,S)=>n==null?void 0:n(S.data.graphNode),onEdgeClick:(C,S)=>{var $;const I=($=S.data)==null?void 0:$.graphEdge;I&&(a==null||a(I))},onNodeMouseEnter:(C,S)=>o==null?void 0:o(S.data.graphNode),onNodeMouseLeave:()=>o==null?void 0:o(null),onEdgeMouseEnter:(C,S)=>{var I;return i==null?void 0:i(((I=S.data)==null?void 0:I.graphEdge)??null)},onEdgeMouseLeave:()=>i==null?void 0:i(null),className:"h-full w-full",colorMode:d.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(dj,{data:e,viewportKey:w}),s.jsx(Vm,{className:d.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),f&&s.jsx(qm,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:lj,nodeClassName:cj,nodeStrokeWidth:3,className:d.isDark?"overflow-hidden rounded-xl border border-white/10 bg-slate-950/85":"overflow-hidden rounded-xl border border-slate-200 bg-white/95"}),s.jsx(Ym,{variant:Jm.Dots,gap:18,size:1.2,color:d.graphBackgroundDotColor})]})})]})})})})}function nt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ne(...e){for(const t of e){if(typeof t!="string")continue;const r=t.trim();if(r)return r}}function Lt(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function Tt(...e){for(const t of e)if(typeof t=="boolean")return t}function lo(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function hj(e,t){const r=typeof e=="string"?e.trim().replace(/[\\/]+$/,""):"",n=typeof t=="string"?t.trim():"";if(n){if(/^(?:[A-Za-z]:[\\/]|\/)/.test(n))return n;if(r)return`${r}/${n.replace(/^[\\/]+/,"")}`}}function Fi(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 fj(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=nt(n),o=Ne(a.path),i=Ne(a.commit),c=Ne(a.repoPath,a.repo_root)??hj(t,o);if(!o||!i)return null;const d={path:o,commit:i,dirty:Tt(a.dirty)??!1,outOfSync:Tt(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:Lt(a.lastCheckedAt,a.last_checked_at)??Date.now()};c&&(d.repoPath=c);const p=Ne(a.error);return p&&(d.error=p),d}).filter(n=>n!==null);return r.length>0?r:void 0}function xj(e){return Tt(e.isGitRepo)!==void 0||!!Ne(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||!!Ne(e.repoRoot,e.repo_root,e.workspace)||Lt(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 zn(e,t,r){const n=Tt(e.isGitRepo);if(!Object.keys(e).length||!xj(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(v=>typeof v=="string"):[],i=Lt(e.conflicts)??o.length,c=Tt(e.hasConflicts)??i>0,d=Ne(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,p=fj(e.submodules,d),u=Ne(e.upstreamStatus,e.upstream_status),m=Lt(e.upstreamFetchedAt,e.upstream_fetched_at),h=Ne(e.upstreamFetchError,e.upstream_fetch_error),b=Ne(e.error),g=Lt(e.staged)??0,f=Lt(e.modified)??0,j=Lt(e.untracked)??0,N=Lt(e.deleted)??0,y=Lt(e.renamed)??0;return{workspace:Ne(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:a,branch:Ne(e.branch)??null,headCommit:Ne(e.headCommit)??null,headMessage:Ne(e.headMessage)??null,upstream:Ne(e.upstream)??null,upstreamStatus:u??"unchecked",...m!==void 0?{upstreamFetchedAt:m}:{},...h?{upstreamFetchError:h}:{},ahead:Lt(e.ahead)??0,behind:Lt(e.behind)??0,staged:g,modified:f,untracked:j,deleted:N,renamed:y,dirty:Tt(e.dirty,e.isDirty,e.is_dirty)??(g+f+j+N+y>0||c),hasConflicts:c,conflictFiles:o,stashCount:Lt(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??Lt(e.lastCheckedAt,e.last_checked_at)??Date.now(),...p?{submodules:p}:{},...b?{error:b}:{}}}function bj(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+=Fi(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 gj(e,t){const r=nt(e.lastGit??e.last_git),n=nt(r.result),a=nt(r.status),o=nt(n.status),i=nt(e.lastProbe??e.last_probe),c=nt(i.git),d=nt(c.result),p=nt(c.status),u=nt(d.status),m=t==null?void 0:t.lastCheckedAt;let h=null;for(const b of[a,o,p,u]){const g=zn(b,e,{lastCheckedAt:m??Date.now()});if(!g)continue;const f=bj(g);(!h||f>h.score)&&(h={git:g,score:f})}return h==null?void 0:h.git}function yj(e){const t=[Ne(e.workspace),Ne(e.providerType,e.provider),Ne(e.role),Ne(e.state,e.status),Ne(e.title),Ne(e.createdAt,e.created_at),Ne(e.startedAt,e.started_at)].filter(r=>!!r);if(t.length!==0)return`synthetic:${t.join("|")}`}function qo(e){const t=nt(e),r=Ne(t.sessionId,t.session_id,t.id)??yj(t);return r?{sessionId:r,...Ne(t.providerType,t.provider)?{providerType:Ne(t.providerType,t.provider)}:{},...Ne(t.state,t.status)?{state:Ne(t.state,t.status)}:{},...Ne(t.chatStatus,t.chat_status)?{chatStatus:Ne(t.chatStatus,t.chat_status)}:{},...Ne(t.lifecycle)?{lifecycle:Ne(t.lifecycle)}:{},...Ne(t.surfaceKind,t.surface_kind)?{surfaceKind:Ne(t.surfaceKind,t.surface_kind)}:{},...Ne(t.recoveryState,t.recovery_state)?{recoveryState:Ne(t.recoveryState,t.recovery_state)}:{},...Ne(t.workspace)?{workspace:Ne(t.workspace)}:{},...Ne(t.title)?{title:Ne(t.title)}:{},...Ne(t.role)?{role:Ne(t.role)}:{},...Tt(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:Tt(t.isSelfCoordinator,t.is_self_coordinator)}:{},...Ne(t.statusNote,t.status_note)?{statusNote:Ne(t.statusNote,t.status_note)}:{},...Ne(t.createdAt,t.created_at)?{createdAt:Ne(t.createdAt,t.created_at)}:{},...Ne(t.startedAt,t.started_at)?{startedAt:Ne(t.startedAt,t.started_at)}:{},...Ne(t.lastActivityAt,t.last_activity_at)?{lastActivityAt:Ne(t.lastActivityAt,t.last_activity_at)}:{},...Tt(t.isCached,t.is_cached)!==void 0?{isCached:Tt(t.isCached,t.is_cached)}:{}}:null}function vj(e){return gj(e,{lastCheckedAt:Date.now()})}function wj(e){const t=Array.isArray(e==null?void 0:e.submodules)?e.submodules:[];let r=!1,n=!1;for(const a of t)a!=null&&a.outOfSync&&(n=!0),a!=null&&a.dirty&&(r=!0);return{dirty:r,outOfSync:n}}function jj(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 la(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=wj(e);return t.outOfSync?"degraded":t.dirty||jj(e)?"dirty":"online"}function kj(e,t){const r=t?la(t):void 0;return!e||e==="unknown"?r:e}function Nj(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 o=t.map(qo).filter(i=>i!==null);if(o.length>0)return o}const r=nt(e.activeSession??e.active_session),n={...r,sessionId:Ne(r.sessionId,r.id,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id)},a=qo(n);return a?[a]:void 0}function Sj(e){const t=nt(e.connection);return Object.keys(t).length>0?t:void 0}function Cj(e){const t=e==null?void 0:e.source,r=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:r&&r!=="unknown"?r:"direct",reported:!0,reason:"Live peer git snapshot reported by the selected coordinator."}}function Oi(e){var r;const t=e.git;return!!(t&&(t.isGitRepo===!0||t.isGitRepo===!1||t.branch||t.upstream||t.headCommit||typeof t.lastCheckedAt=="number"||(((r=t.submodules)==null?void 0:r.length)??0)>0))}function Lc(e){var n,a,o,i,c,d;let t=0;const r=e.git;return Oi(e)&&(t+=80,(r==null?void 0:r.isGitRepo)===!0&&(t+=20),(r==null?void 0:r.isGitRepo)===!1&&(t+=5),r!=null&&r.branch&&(t+=20),r!=null&&r.upstream&&(t+=12),r!=null&&r.headCommit&&(t+=12),t+=Fi(r==null?void 0:r.upstreamStatus),typeof(r==null?void 0:r.lastCheckedAt)=="number"&&(t+=6),t+=(((n=r==null?void 0:r.submodules)==null?void 0:n.length)??0)*6),(a=e.branchConvergence)!=null&&a.status&&(t+=12),(((o=e.connection)==null?void 0:o.state)==="connected"||((i=e.connection)==null?void 0:i.state)==="self")&&(t+=8),((c=e.connection)==null?void 0:c.transport)==="direct"&&(t+=4),((d=e.connection)==null?void 0:d.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 Ij(e,t){var g,f,j,N;const r=Lc(e),a=Lc(t)>r?t:e,o=a===t?e:t,i=a.git??o.git,c=(((g=a.providers)==null?void 0:g.length)??0)>0?a.providers:o.providers,d=(((f=a.activeSessions)==null?void 0:f.length)??0)>0?a.activeSessions:o.activeSessions,p=(((j=a.activeSessionDetails)==null?void 0:j.length)??0)>0?a.activeSessionDetails:o.activeSessionDetails,u=(((N=a.providerPriority)==null?void 0:N.length)??0)>0?a.providerPriority:o.providerPriority,m=a.connection??o.connection,h={...o,...a,machineLabel:a.machineLabel||o.machineLabel,workspace:a.workspace||o.workspace,...a.repoRoot||o.repoRoot?{repoRoot:a.repoRoot||o.repoRoot}:{},...a.daemonId||o.daemonId?{daemonId:a.daemonId||o.daemonId}:{},...a.machineId||o.machineId?{machineId:a.machineId||o.machineId}:{},...a.machineStatus||o.machineStatus?{machineStatus:a.machineStatus||o.machineStatus}:{},health:i&&(!a.health||a.health==="unknown")?la(i):a.health,providers:c??[],activeSessions:d??[],...p&&p.length>0?{activeSessionDetails:p}:{},...u&&u.length>0?{providerPriority:u}:{},...m?{connection:m}:{},...i?{git:i}:{}},b=nt(a.branchConvergence);return Object.keys(b).length>0?Object.assign(h,{branchConvergence:b}):delete h.branchConvergence,i&&(delete h.gitProbePending,delete h.error),h}function Fp(e){const t=nt(e),r=Ne(t.nodeId,t.id);if(!r)return null;const n=nt(t.cachedStatus),a=vj(t),o=a?void 0:zn(nt(t.git),t)??zn(t,t),i=a??o,c=i?void 0:zn(nt(n.git),t),d=i??c,p=Ne(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),u=Ne(t.health),m=a?la(d):kj(u,i)||(d?la(d):void 0)||Ne(n.health)||p||Ne(t.status)||"unknown",b=(a?void 0:Ne(t.error))??(i?void 0:Ne(n.error)),g=Nj(t),f=lo(t.activeSessions),j=(g==null?void 0:g.map(S=>S.sessionId))??[],N=lo(t.providerPriority),y=Tt(t.gitProbePending,t.git_probe_pending),v=i?void 0:y,k=Sj(t),w=nt(t.branchConvergence??t.branch_convergence),x=k==null?void 0:k.state,C=a&&(!(k!=null&&k.reported)||x==="unknown")?Cj(k):k;return{nodeId:r,machineLabel:Ne(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:Ne(t.workspace,d==null?void 0:d.workspace)||"",...Ne(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:Ne(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},...Ne(t.daemonId,t.daemon_id)?{daemonId:Ne(t.daemonId,t.daemon_id)}:{},...Ne(t.machineId,t.machine_id)?{machineId:Ne(t.machineId,t.machine_id)}:{},...p?{machineStatus:p}:{},...Tt(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Tt(t.isLocalWorktree,t.is_local_worktree)}:{},...Ne(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:Ne(t.worktreeBranch,t.worktree_branch)}:{},...Ne(t.clonedFromNodeId,t.cloned_from_node_id)?{clonedFromNodeId:Ne(t.clonedFromNodeId,t.cloned_from_node_id)}:{},health:m,...d?{git:d}:{},...v!==void 0?{gitProbePending:v}:{},providers:lo(t.providers),activeSessions:f.length>0?f:j,...g&&g.length>0?{activeSessionDetails:g}:{},...N.length>0?{providerPriority:N}:{},...Tt(t.launchReady)!==void 0?{launchReady:Tt(t.launchReady)}:a?{launchReady:!0}:{},...Ne(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:Ne(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},...Ne(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:Ne(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...C?{connection:C}:{},...Object.keys(w).length>0?{branchConvergence:w}:{},...b?{error:b}:{}}}function Pc(e){const t=new Map;for(const r of e){const n=t.get(r.sessionId);t.set(r.sessionId,n?{...n,...r}:r)}return[...t.values()]}function Op(e,t){const r=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],n=r.map(qo).filter(a=>a!==null);return n.length===0?t:t.map(a=>{const o=n.filter(c=>{const d=nt(r.find(h=>{const b=nt(h);return Ne(b.sessionId,b.session_id,b.id)===c.sessionId})),p=Ne(d.nodeId,d.node_id),u=Ne(d.daemonId,d.daemon_id),m=Ne(d.workspace);return p&&p===a.nodeId?!0:u&&a.daemonId&&u===a.daemonId?!m||!a.workspace||m===a.workspace:!!(m&&a.workspace&&m===a.workspace)});if(o.length===0)return a;const i=Pc([...a.activeSessionDetails??[],...o]);return{...a,activeSessionDetails:i,activeSessions:Pc([...a.activeSessionDetails??[],...o,...(a.activeSessions??[]).map(c=>({sessionId:c}))]).map(c=>c.sessionId)}})}function Mj(e){const t=nt(e);return Array.isArray(t.sessions)||Array.isArray(t.active_session_details)||Ne(t.daemon_id,t.machine_id,t.repo_root,t.worktree_branch,t.cloned_from_node_id)!==void 0||Tt(t.is_local_worktree)!==void 0}function zp(e){const t=new Map,r=[];for(const n of e){const a=Mj(n)?Fp(n)??n:n;if(!(a!=null&&a.nodeId))continue;const o=t.get(a.nodeId);if(!o){t.set(a.nodeId,a),r.push(a);continue}const i=Ij(o,a);t.set(a.nodeId,i);const c=r.findIndex(d=>d.nodeId===a.nodeId);c>=0&&(r[c]=i)}return r}function zi(e){const t=zp(e.nodes??[]);return{...e,nodes:Op(e,t)}}function Aj(e){var r;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:Oi(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:((r=t==null?void 0:t.submodules)==null?void 0:r.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 Tj(e){const t=Ne(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(d=>Fp(d)).filter(d=>d!==null):null;if(!t||!n)return null;const a=Op(e,zp(n)),o=Ne(e.meshName,e.mesh_name,e.name),i=Ne(e.repoIdentity,e.repo_identity),c=Ne(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!o||!i||!c?null:{...e,meshId:t,meshName:o,repoIdentity:i,refreshedAt:c,nodes:a}}function _j(e){var o;let t=0;const r=nt(e.sourceOfTruth),n=nt(r.directPeerTruth);Ne(r.currentStatus)==="live_git_and_session_probes"&&(t+=100),r.coordinatorOwnsLiveTruth===!0&&(t+=25),n.satisfied===!0&&(t+=15);for(const i of e.nodes){const c=i.git;if(!c){i.gitProbePending&&(t-=8);continue}t+=10,c.isGitRepo===!0&&(t+=5),c.isGitRepo===!1&&(t+=1),c.branch&&(t+=4),c.upstream&&(t+=3),c.headCommit&&(t+=3),t+=Fi(c.upstreamStatus),typeof c.ahead=="number"&&(t+=1),typeof c.behind=="number"&&(t+=1),typeof c.lastCheckedAt=="number"&&(t+=2),t+=(((o=c.submodules)==null?void 0:o.length)??0)*2}return t}function Lj(e){const t=e.refreshedAt;if(typeof t!="string"||t.length===0)return 0;const r=Date.parse(t);return Number.isFinite(r)?r:0}const Pj=20;function Rc(e){let t=null;for(const r of e){const n=Tj(nt(r));if(!n)continue;const a=_j(n),o=Lj(n);if(!t){t={status:n,score:a,refreshedAt:o};continue}(Math.abs(a-t.score)<=Pj?o>t.refreshedAt||o===t.refreshedAt&&a>t.score:a>t.score)&&(t={status:n,score:a,refreshedAt:o})}return(t==null?void 0:t.status)??null}function Hp(e){const r=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,n=Rc([r==null?void 0:r.status,r]);return n||Rc([e==null?void 0:e.status,e])}const Rj=5,Dj={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function ka(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function Wp(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const r=t.toLowerCase().replace(/[\s-]+/g,"_");return r.includes("approval")?"awaiting approval":r.includes("generating")||r.includes("running")||r.includes("busy")?"generating":r.includes("idle")||r.includes("ready")||r.includes("waiting_input")?"idle":r.replace(/_/g," ")}function Kp(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 $j(e){const t=e.git;if(!t)return e.gitProbePending?"git probe pending":"no git probe";const r=(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}`),r>0&&n.push(`✎${r}`),t.hasConflicts&&n.push("conflicts"),n.join(" · ")||"clean"}function Up(e){switch(e){case"active":return"emerald";case"paused":return"amber";case"completed":return"sky";case"abandoned":return"rose";default:return"muted"}}function Ej(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 Gp(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 Dc(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 Ut(e){if(!e)return null;const t=Date.parse(e);if(!Number.isFinite(t))return null;const r=Math.max(0,Math.floor((Date.now()-t)/1e3));if(r<60)return`${r}s ago`;const n=Math.floor(r/60);if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<48?`${a}h ago`:`${Math.floor(a/24)}d ago`}function $c(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),r=t%60,n=Math.floor(t/60),a=n%60,o=Math.floor(n/60),i=[];return o>0&&i.push(`${o}h`),a>0&&i.push(`${a}m`),(r>0||i.length===0)&&i.push(`${r}s`),i.join(" ")}function Hi(e){return e.replace(/[_-]+/g," ")}function Vp(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 qp(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 Bj({status:e}){var j,N,y,v;const{theme:t}=Rs(),r=l.useMemo(()=>Ds(t),[t]),n=l.useMemo(()=>zi(e),[e]),a=((j=n.queue)==null?void 0:j.summary)??null,o=((N=n.queue)==null?void 0:N.tasks)??[],i=((y=n.ledger)==null?void 0:y.summary)??Dj,c=((v=n.ledger)==null?void 0:v.entries)??[],d=n.missions??[],p=d.filter(k=>k.status==="active"||k.status==="paused"),u=d.filter(k=>k.status==="completed"||k.status==="abandoned"),m=n.asyncRefineJobs??[],[h,b]=l.useState(null),g=l.useCallback(()=>b(null),[]),f=l.useMemo(()=>{const k=[];for(const w of n.nodes){const x=w.activeSessionDetails&&w.activeSessionDetails.length>0?w.activeSessionDetails:(w.activeSessions??[]).map(C=>({sessionId:C,workspace:w.workspace,isCached:!0}));for(const C of x)k.push({node:w,session:C})}return k},[n.nodes]);return s.jsxs("div",{className:"flex flex-col gap-3 pb-2",children:[s.jsx(Uj,{meshTheme:r,liveMissions:p,historyMissions:u,hasMissionField:Array.isArray(n.missions),onSelect:k=>b({kind:"mission",mission:k})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(Gj,{meshTheme:r,ledgerSummary:i,entries:c,onSelect:k=>b({kind:"ledger",entry:k})}),s.jsx(Vj,{meshTheme:r,queueSummary:a,tasks:o,onSelect:k=>b({kind:"queue",task:k})})]}),s.jsx(Yj,{meshTheme:r,nodes:n.nodes}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(Jj,{meshTheme:r,entries:f,onSelect:(k,w)=>b({kind:"session",node:k,session:w})}),s.jsx(Xj,{meshTheme:r,jobs:m})]}),h&&s.jsx(Oj,{meshTheme:r,detail:h,onClose:g})]})}function Ts({meshTheme:e,title:t,count:r,children:n,action:a}){const o=e.isDark;return s.jsxs("div",{className:`flex min-w-0 flex-col overflow-hidden rounded-2xl border p-4 ${o?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,children:[s.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[s.jsx("span",{className:`text-[11px] font-semibold uppercase tracking-[0.14em] ${e.textSecondary}`,children:t}),r!==void 0&&s.jsx("span",{className:`tabular-nums text-[11px] ${e.textMuted}`,children:r}),a&&s.jsx("span",{className:"ml-auto",children:a})]}),n]})}function _t({meshTheme:e,label:t,tone:r}){const n=e.isDark,a=r==="rose"?n?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700":r==="sky"?n?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700":r==="amber"?n?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700":r==="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 s.jsx("span",{className:`shrink-0 rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${a}`,children:t})}function xt({meshTheme:e,label:t,value:r,tone:n}){const a=e.isDark,o=n==="rose"?a?"text-rose-300":"text-rose-600":n==="sky"?a?"text-sky-300":"text-sky-600":n==="amber"?a?"text-amber-300":"text-amber-600":n==="emerald"?a?"text-emerald-300":"text-emerald-600":n==="muted"?e.textMuted:e.textPrimary;return s.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-2 ${a?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[s.jsx("span",{className:`tabular-nums text-base font-semibold leading-none ${o}`,children:r}),s.jsx("span",{className:`mt-1 text-[9px] uppercase tracking-wide ${e.textMuted}`,children:t})]})}function Xr({meshTheme:e,children:t}){return s.jsx("div",{className:`text-xs ${e.textMuted}`,children:t})}function Na({meshTheme:e,onClick:t,children:r}){const n=e.isDark,a=t?n?"hover:bg-white/[0.05]":"hover:bg-slate-100/70":"";return s.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 ${a} ${t?"cursor-pointer":"cursor-default"}`,children:r})}function Sa({meshTheme:e,expanded:t,hiddenCount:r,onToggle:n}){return r<=0?null:s.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":`+${r} more`})}function Ca(e,t=Rj){const[r,n]=l.useState(!1),a=r?e:e.slice(0,t),o=Math.max(0,e.length-t),i=l.useCallback(()=>n(c=>!c),[]);return{visible:a,hiddenCount:o,expanded:r,toggle:i}}function ot({meshTheme:e,label:t,value:r}){return s.jsxs("div",{className:e.rowClass,children:[s.jsx("span",{className:e.rowLabelClass,children:t}),s.jsx("span",{className:e.rowValueClass,children:r})]})}function Fj(e){switch(e.kind){case"mission":return{kicker:"Mission",title:e.mission.title};case"ledger":return{kicker:"Ledger entry",title:Hi(e.entry.kind)};case"queue":return{kicker:"Queue task",title:e.task.id};case"session":return{kicker:"Session",title:ka(e.session.sessionId)}}}function Oj({meshTheme:e,detail:t,onClose:r}){l.useEffect(()=>{const d=p=>{p.key==="Escape"&&r()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[r]);const n=e.isDark,{kicker:a,title:o}=Fj(t),i=n?"bg-[#030617]/[0.92]":"bg-[rgba(15,23,42,0.82)]",c=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 s.jsx("div",{className:`fixed inset-0 z-[1300] flex items-stretch justify-center p-0 md:items-center md:p-4 ${i}`,role:"dialog","aria-modal":"true",onClick:r,children:s.jsxs("div",{className:`flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden border ${c} md:h-auto md:max-h-[88dvh] md:max-w-[min(640px,calc(100vw-32px))] md:rounded-2xl`,onClick:d=>d.stopPropagation(),children:[s.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:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:a}),s.jsx("div",{className:`mt-0.5 break-all text-sm font-semibold ${e.textPrimary}`,children:o})]}),s.jsx("button",{type:"button",onClick:r,"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:"✕"})]}),s.jsxs("div",{className:"min-h-0 min-w-0 flex-1 overflow-y-auto px-4 py-4",children:[t.kind==="mission"&&s.jsx(zj,{meshTheme:e,mission:t.mission}),t.kind==="ledger"&&s.jsx(Hj,{meshTheme:e,entry:t.entry}),t.kind==="queue"&&s.jsx(Wj,{meshTheme:e,task:t.task}),t.kind==="session"&&s.jsx(Kj,{meshTheme:e,node:t.node,session:t.session})]})]})})}function zj({meshTheme:e,mission:t}){var c;const r=t.tasks,n="goal"in t&&typeof t.goal=="string"&&t.goal?t.goal:"goalPreview"in t?t.goalPreview:"",a="goalTruncated"in t?t.goalTruncated===!0:!1,o=t.stats??null,i=((c=o==null?void 0:o.incompleteTaskIds)==null?void 0:c.length)??0;return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(_t,{meshTheme:e,label:t.status,tone:Up(t.status)}),s.jsx(_t,{meshTheme:e,label:`${r.total} tasks`,tone:"muted"})]}),n&&s.jsxs("div",{className:`max-h-64 overflow-y-auto whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:[n,a&&s.jsx("span",{className:e.textMuted,children:" … (truncated)"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5 sm:grid-cols-6",children:[s.jsx(xt,{meshTheme:e,label:"Completed",value:r.completed,tone:"emerald"}),s.jsx(xt,{meshTheme:e,label:"Assigned",value:r.assigned,tone:r.assigned>0?"sky":void 0}),s.jsx(xt,{meshTheme:e,label:"Pending",value:r.pending}),s.jsx(xt,{meshTheme:e,label:"Failed",value:r.failed,tone:r.failed>0?"rose":void 0}),s.jsx(xt,{meshTheme:e,label:"Blocked",value:r.blocked,tone:r.blocked>0?"amber":void 0}),s.jsx(xt,{meshTheme:e,label:"Cancelled",value:r.cancelled,tone:"muted"})]}),o&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(xt,{meshTheme:e,label:"Wall clock",value:$c(o.wallClockMs)??"—"}),s.jsx(xt,{meshTheme:e,label:"Total runtime",value:$c(o.totalDurationMs)??"—"}),s.jsx(xt,{meshTheme:e,label:"Retries",value:o.retries,tone:o.retries>0?"amber":void 0})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ot,{meshTheme:e,label:"Mission id",value:t.id}),s.jsx(ot,{meshTheme:e,label:"Created",value:Ut(t.createdAt)??t.createdAt}),s.jsx(ot,{meshTheme:e,label:"Updated",value:Ut(t.updatedAt)??t.updatedAt}),r.lastActivityAt&&s.jsx(ot,{meshTheme:e,label:"Last task activity",value:Ut(r.lastActivityAt)??r.lastActivityAt}),i>0&&o&&s.jsx(ot,{meshTheme:e,label:"Incomplete evidence",value:s.jsxs("details",{children:[s.jsxs("summary",{className:"cursor-pointer select-none",children:[i," task",i===1?"":"s"]}),s.jsx("div",{className:"mt-1 flex flex-col gap-0.5 break-all",children:o.incompleteTaskIds.map(d=>s.jsx("span",{className:`font-mono text-[10px] ${e.textMuted}`,children:d},d))})]})})]})]})}function Hj({meshTheme:e,entry:t}){const r=qp(t.payload);let n="";try{n=JSON.stringify(t.payload??{},null,2)}catch{n=String(t.payload)}return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:s.jsx(_t,{meshTheme:e,label:Hi(t.kind),tone:Vp(t.kind)})}),r&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:r}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ot,{meshTheme:e,label:"Entry id",value:t.id}),s.jsx(ot,{meshTheme:e,label:"When",value:Ut(t.timestamp)??t.timestamp}),t.nodeId&&s.jsx(ot,{meshTheme:e,label:"Node",value:t.nodeId}),t.sessionId&&s.jsx(ot,{meshTheme:e,label:"Session",value:ka(t.sessionId)}),t.providerType&&s.jsx(ot,{meshTheme:e,label:"Provider",value:t.providerType})]}),n&&n!=="{}"&&s.jsxs("div",{children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:"Payload"}),s.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 Wj({meshTheme:e,task:t}){return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(_t,{meshTheme:e,label:t.status,tone:Gp(t.status)}),(t.requeueCount??0)>0&&s.jsx(_t,{meshTheme:e,label:`requeued ${t.requeueCount}`,tone:"amber"})]}),t.message&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:t.message}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ot,{meshTheme:e,label:"Task id",value:t.id}),s.jsx(ot,{meshTheme:e,label:"Created",value:Ut(t.createdAt)??t.createdAt}),s.jsx(ot,{meshTheme:e,label:"Updated",value:Ut(t.updatedAt)??t.updatedAt}),(t.assignedNodeId||t.targetNodeId)&&s.jsx(ot,{meshTheme:e,label:"Node",value:t.assignedNodeId||t.targetNodeId}),(t.assignedSessionId||t.targetSessionId)&&s.jsx(ot,{meshTheme:e,label:"Session",value:ka(t.assignedSessionId||t.targetSessionId)}),t.cancelReason&&s.jsx(ot,{meshTheme:e,label:"Cancel reason",value:t.cancelReason}),t.requeueReason&&s.jsx(ot,{meshTheme:e,label:"Requeue reason",value:t.requeueReason}),t.autoLaunch&&s.jsx(ot,{meshTheme:e,label:"Auto launch",value:`${t.autoLaunch.status}${t.autoLaunch.reason?` · ${t.autoLaunch.reason}`:""}`})]})]})}function Kj({meshTheme:e,node:t,session:r}){var a,o;const n=Wp(r);return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(_t,{meshTheme:e,label:n,tone:Kp(n)}),s.jsx(_t,{meshTheme:e,label:r.providerType||"provider unknown",tone:"muted"})]}),r.statusNote&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:r.statusNote}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ot,{meshTheme:e,label:"Session id",value:r.sessionId}),s.jsx(ot,{meshTheme:e,label:"Node",value:t.machineLabel}),s.jsx(ot,{meshTheme:e,label:"Workspace",value:r.workspace||t.workspace}),(((a=t.git)==null?void 0:a.branch)??t.worktreeBranch)&&s.jsx(ot,{meshTheme:e,label:"Branch",value:((o=t.git)==null?void 0:o.branch)??t.worktreeBranch}),typeof r.role=="string"&&r.role&&s.jsx(ot,{meshTheme:e,label:"Role",value:r.role}),(r.startedAt||r.createdAt)&&s.jsx(ot,{meshTheme:e,label:"Started",value:Ut(r.startedAt||r.createdAt)??(r.startedAt||r.createdAt)})]})]})}function Ec({meshTheme:e,mission:t,onSelect:r}){const n=t.tasks,a=Ut(n.lastActivityAt);return s.jsxs(Na,{meshTheme:e,onClick:r,children:[s.jsx(_t,{meshTheme:e,label:t.status,tone:Up(t.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate font-medium ${e.textPrimary}`,children:t.title}),s.jsxs("span",{className:`shrink-0 tabular-nums text-[11px] ${e.textMuted}`,children:["✓",n.completed,"/",n.total]}),a&&s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:a})]})}function Uj({meshTheme:e,liveMissions:t,historyMissions:r,hasMissionField:n,onSelect:a}){const[o,i]=l.useState(!1),c=e.isDark,d=Ca(t);return s.jsxs(Ts,{meshTheme:e,title:"Missions",count:t.length||void 0,children:[t.length>0?s.jsxs("div",{className:"flex flex-col gap-0.5",children:[d.visible.map(p=>s.jsx(Ec,{meshTheme:e,mission:p,onSelect:()=>a(p)},p.id)),s.jsx(Sa,{meshTheme:e,expanded:d.expanded,hiddenCount:d.hiddenCount,onToggle:d.toggle})]}):s.jsx(Xr,{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."}),r.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${c?"border-white/8":"border-slate-200"}`,children:[s.jsxs("button",{type:"button",onClick:()=>i(p=>!p),className:`flex w-full items-center gap-1.5 text-[11px] font-medium ${e.textSecondary}`,children:[s.jsx("span",{className:`inline-block transition-transform ${o?"rotate-90":""}`,children:"▸"}),s.jsx("span",{children:"Completed / abandoned history"}),s.jsx("span",{className:`tabular-nums ${e.textMuted}`,children:r.length})]}),o&&s.jsx("div",{className:"mt-2 flex flex-col gap-0.5",children:r.map(p=>s.jsx(Ec,{meshTheme:e,mission:p,onSelect:()=>a(p)},p.id))})]})]})}function Gj({meshTheme:e,ledgerSummary:t,entries:r,onSelect:n}){const a=Ut(t.lastActivityAt),o=l.useMemo(()=>[...r].reverse(),[r]),i=Ca(o);return s.jsxs(Ts,{meshTheme:e,title:"Ledger",children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(xt,{meshTheme:e,label:"Dispatched",value:t.taskDispatched}),s.jsx(xt,{meshTheme:e,label:"Completed",value:t.taskCompleted,tone:"emerald"}),s.jsx(xt,{meshTheme:e,label:"Failed",value:t.taskFailed,tone:t.taskFailed>0?"rose":void 0}),s.jsx(xt,{meshTheme:e,label:"Stalled",value:t.taskStalled,tone:t.taskStalled>0?"amber":void 0}),s.jsx(xt,{meshTheme:e,label:"Sessions",value:t.sessionLaunched}),s.jsx(xt,{meshTheme:e,label:"Checkpoints",value:t.checkpointCreated})]}),o.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:"Recent activity"}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[i.visible.map(c=>{const d=qp(c.payload);return s.jsxs(Na,{meshTheme:e,onClick:()=>n(c),children:[s.jsx(_t,{meshTheme:e,label:Hi(c.kind),tone:Vp(c.kind)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,children:d||c.nodeId||c.sessionId||"—"}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:Ut(c.timestamp)??""})]},c.id)}),s.jsx(Sa,{meshTheme:e,expanded:i.expanded,hiddenCount:i.hiddenCount,onToggle:i.toggle})]})]}),(t.recentFailures>0||a&&o.length===0)&&s.jsxs("div",{className:`mt-2 flex items-center justify-between text-[11px] ${e.textMuted}`,children:[t.recentFailures>0?s.jsxs("span",{className:e.isDark?"text-amber-300":"text-amber-600",children:[t.recentFailures," recent failures"]}):s.jsx("span",{}),a&&o.length===0&&s.jsx("span",{children:a})]})]})}function Vj({meshTheme:e,queueSummary:t,tasks:r,onSelect:n}){const a=l.useMemo(()=>[...r].sort((i,c)=>{const d=Dc(i.status)-Dc(c.status);return d!==0?d:(c.updatedAt||"").localeCompare(i.updatedAt||"")}),[r]),o=Ca(a);return t?s.jsxs(Ts,{meshTheme:e,title:"Queue",count:t.active>0?`${t.active} active`:void 0,children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(xt,{meshTheme:e,label:"Pending",value:t.pending}),s.jsx(xt,{meshTheme:e,label:"Assigned",value:t.assigned,tone:t.assigned>0?"sky":void 0}),s.jsx(xt,{meshTheme:e,label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(xt,{meshTheme:e,label:"Completed",value:t.completed,tone:"emerald"}),s.jsx(xt,{meshTheme:e,label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0}),s.jsx(xt,{meshTheme:e,label:"Cancelled",value:t.cancelled,tone:"muted"})]}),a.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:"Recent tasks"}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.visible.map(i=>s.jsxs(Na,{meshTheme:e,onClick:()=>n(i),children:[s.jsx(_t,{meshTheme:e,label:i.status,tone:Gp(i.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,children:i.message||i.id}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:Ut(i.updatedAt)??""})]},i.id)),s.jsx(Sa,{meshTheme:e,expanded:o.expanded,hiddenCount:o.hiddenCount,onToggle:o.toggle})]})]})]}):s.jsx(Ts,{meshTheme:e,title:"Queue",children:s.jsx(Xr,{meshTheme:e,children:"No queue activity."})})}function qj(e){return e.autoFastForwardEligible||e.suggestedAction==="auto_fast_forward"?{label:"fast-forward",tone:"sky"}:e.launchBlockedReason?{label:"blocked",tone:"rose"}:null}function Yj({meshTheme:e,nodes:t}){const r=e.isDark;return s.jsx(Ts,{meshTheme:e,title:"Nodes",count:t.length,children:t.length===0?s.jsx(Xr,{meshTheme:e,children:"No nodes in this mesh yet."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:t.map(n=>{var c,d,p;const a=(((c=n.activeSessionDetails)==null?void 0:c.length)??0)||(((d=n.activeSessions)==null?void 0:d.length)??0),o=qj(n),i=((p=n.git)==null?void 0:p.branch)??n.worktreeBranch??null;return s.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 ${r?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx(_t,{meshTheme:e,label:n.health,tone:Ej(n.health)}),s.jsx("span",{className:`min-w-0 max-w-full flex-1 truncate text-sm font-medium ${e.textPrimary}`,title:n.workspace,children:n.machineLabel}),i&&s.jsx("span",{className:`max-w-full truncate font-mono text-[11px] ${e.textSecondary}`,title:i,children:i}),s.jsx("span",{className:`max-w-full truncate font-mono text-[10px] ${e.textMuted}`,children:$j(n)}),a>0&&s.jsxs("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:[a," session",a>1?"s":""]}),o&&s.jsx(_t,{meshTheme:e,label:o.label,tone:o.tone})]},n.nodeId)})})})}function Jj({meshTheme:e,entries:t,onSelect:r}){const n=Ca(t);return s.jsx(Ts,{meshTheme:e,title:"Active sessions",count:t.length||void 0,children:t.length===0?s.jsx(Xr,{meshTheme:e,children:"No active sessions."}):s.jsxs("div",{className:"flex flex-col gap-0.5",children:[n.visible.map(({node:a,session:o})=>{const i=Wp(o);return s.jsxs(Na,{meshTheme:e,onClick:()=>r(a,o),children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:ka(o.sessionId)}),s.jsx("span",{className:`shrink-0 ${e.textMuted}`,children:o.providerType||"?"}),s.jsx(_t,{meshTheme:e,label:i,tone:Kp(i)})]},o.sessionId)}),s.jsx(Sa,{meshTheme:e,expanded:n.expanded,hiddenCount:n.hiddenCount,onToggle:n.toggle})]})})}function Xj({meshTheme:e,jobs:t}){const r=e.isDark,n=t.filter(a=>a.status==="failed").length;return s.jsx(Ts,{meshTheme:e,title:"Refine jobs",count:t.length||void 0,action:n>0?s.jsx(_t,{meshTheme:e,label:`${n} failed`,tone:"rose"}):void 0,children:t.length===0?s.jsx(Xr,{meshTheme:e,children:"No refine jobs."}):s.jsx("div",{className:"flex flex-col gap-1",children:t.slice(0,8).map(a=>s.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:[a.branch??a.jobId.slice(0,14),a.into?` → ${a.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[10px] font-semibold ${a.status==="failed"?r?"text-rose-300":"text-rose-600":a.status==="running"||a.status==="accepted"?r?"text-sky-300":"text-sky-600":r?"text-emerald-300":"text-emerald-600"}`,children:a.status})]},a.jobId))})})}const Qj=[{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:"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 Zj({meshTheme:e,open:t,onToggle:r}){const n=e.isDark,a="inline-flex h-7 w-7 items-center justify-center rounded-lg border transition",o=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 s.jsx("button",{type:"button",onClick:r,"aria-label":"Mesh help","aria-expanded":t,title:"Mesh concept help",className:`${a} ${o}`,children:s.jsx(Bh,{size:15})})}function ek({meshTheme:e,onClose:t}){const r=e.isDark;return l.useEffect(()=>{const n=a=>{a.key==="Escape"&&t()};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[t]),s.jsxs("div",{className:`shrink-0 rounded-2xl border p-4 ${r?"border-white/10 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,role:"region","aria-label":"Mesh concept help",children:[s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:"Help"}),s.jsx("div",{className:`mt-0.5 text-sm font-semibold ${e.textPrimary}`,children:"Mesh concepts at a glance"})]}),s.jsx("button",{type:"button",onClick:t,"aria-label":"Close help",className:r?"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:s.jsx(yt,{size:14})})]}),s.jsx("dl",{className:"grid gap-3 sm:grid-cols-2",children:Qj.map(n=>s.jsxs("div",{className:`rounded-xl border p-3 ${r?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx("dt",{className:`text-xs font-semibold ${e.textPrimary}`,children:n.term}),s.jsx("dd",{className:`mt-1 text-[11px] leading-5 ${e.textSecondary}`,children:n.summary}),n.details&&n.details.length>0&&s.jsx("ul",{className:`mt-1.5 flex flex-col gap-1 text-[11px] leading-5 ${e.textMuted}`,children:n.details.map((a,o)=>s.jsxs("li",{className:"flex gap-1.5",children:[s.jsx("span",{"aria-hidden":!0,className:"select-none",children:"·"}),s.jsx("span",{className:"min-w-0",children:a})]},o))})]},n.term))})]})}const tk=5*60*1e3;function Yp(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function Jp(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function sk(e){var t,r,n;return((t=e.connection)==null?void 0:t.state)==="self"||e.isLocalWorktree===!0?"local":((r=e.connection)==null?void 0:r.transport)==="direct"||((n=e.connection)==null?void 0:n.transport)==="relay"||Yp(e)||Jp(e)?"remote":"unknown"}function rk(e){return Oi(e)}function Xp(e){var t;return rk(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function Qp(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function nk(e){return e.activeSessionDetails&&e.activeSessionDetails.length>0?e.activeSessionDetails:(e.activeSessions??[]).map(t=>({sessionId:t,workspace:e.workspace,isCached:!0}))}function Zp(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function em(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function Wi(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function ak(e){return Wi(e)?"degraded":em(e)?"dirty":"online"}function ok(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function Bc(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 co(e){return e.length===0?"unknown":e.reduce((t,r)=>Bc(r)>Bc(t)?r:t)}function ik(e){var o,i,c,d,p;const t=new Map,r=new Map;for(const u of e){const m=(i=(o=u.git)==null?void 0:o.branch)==null?void 0:i.trim();m&&(r.set(m,(r.get(m)??0)+1),(c=u.git)!=null&&c.upstream&&t.set(m,(t.get(m)??0)+1))}const n=[...t.entries()].sort((u,m)=>{if(m[1]!==u[1])return m[1]-u[1];const h=["main","master","develop","dev"],b=h.indexOf(u[0]),g=h.indexOf(m[0]);return b!==-1||g!==-1?b===-1?1:g===-1?-1:b-g:u[0].localeCompare(m[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((p=[...r.entries()].sort((u,m)=>m[1]-u[1])[0])==null?void 0:p[0])??null}function lk(e,t){const r=[],n=e.git;return n?n.isGitRepo?(!n.branch&&n.headCommit&&r.push("Detached HEAD"),n.hasConflicts&&r.push("Merge conflicts need resolution"),n.branch&&t&&n.branch!==t&&!n.upstream&&r.push(`No upstream tracking for ${n.branch}`),n.upstream&&n.upstreamStatus&&n.upstreamStatus!=="fresh"&&r.push(`Upstream freshness unverified for ${n.branch??"workspace"}`),e.error&&r.push(e.error),r):(r.push("Not a git repository"),r):(r.push("No git status available"),r)}function Fc(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 ck(e){return e.reduce((t,r)=>Fc(r.status)>Fc(t.status)?r:t)}function dk(e){const t=e.branchConvergenceSummary;if(Array.isArray(t==null?void 0:t.followUps))return t.followUps;const r=e.followUps;return Array.isArray(r)?r:(t==null?void 0:t.needsFollowUp)===!1||(t==null?void 0:t.unresolvedCount)===0?[]:null}function uk(e){var a,o,i;const t=e.sourceOfTruth,r=[],n=(a=t==null?void 0:t.fallback)==null?void 0:a.warning;return typeof n=="string"&&n.trim()&&r.push(n.trim()),(t==null?void 0:t.currentStatus)==="bootstrap_inventory_fallback"&&((o=t.directPeerTruth)==null?void 0:o.required)===!0&&((i=t.directPeerTruth)==null?void 0:i.satisfied)!==!0&&!r.some(c=>c.includes("direct mesh truth"))&&r.push("Direct mesh truth is not confirmed yet; this graph is drawn from setup inventory only."),r}function pk(e){const t=e.asyncRefineJobs;if(!Array.isArray(t))return[];const r=[];for(const n of t){if(!n||typeof n!="object")continue;const a=n,o=typeof a.jobId=="string"?a.jobId:null,i=a.status;o&&(i!=="accepted"&&i!=="running"&&i!=="completed"&&i!=="failed"||r.push({jobId:o,status:i,nodeId:typeof a.nodeId=="string"?a.nodeId:void 0,targetNodeId:typeof a.targetNodeId=="string"?a.targetNodeId:void 0,workspace:typeof a.workspace=="string"?a.workspace:void 0,branch:typeof a.branch=="string"?a.branch:void 0,into:typeof a.into=="string"?a.into:void 0,lastUpdatedAt:typeof a.lastUpdatedAt=="string"?a.lastUpdatedAt:void 0,startedAt:typeof a.startedAt=="string"?a.startedAt:void 0,completedAt:typeof a.completedAt=="string"?a.completedAt:void 0}))}return r}function Oc(e){switch(e){case"running":case"accepted":return 0;case"failed":return 1;case"completed":default:return 2}}function zc(e){const t=e.lastUpdatedAt||e.completedAt||e.startedAt||"";return Qp(t)??0}function mk(e){return e.length===0?null:e.reduce((t,r)=>{const n=Oc(t.status),a=Oc(r.status);return a!==n?a<n?r:t:zc(r)>zc(t)?r:t})}function hk(e){var r,n;const t=new Map;for(const a of e){const o=((r=a.nodeId)==null?void 0:r.trim())||((n=a.targetNodeId)==null?void 0:n.trim());if(!o)continue;const i=t.get(o)??[];i.push(a),t.set(o,i)}return t}function fk(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 xk(e,t){var r,n;return{status:"merged_to_main",needsConvergence:!1,reason:"clean_default_branch_aggregate",nextStep:null,branch:e,defaultBranch:e,upstream:((r=t.find(a=>a.upstream))==null?void 0:r.upstream)??null,upstreamStatus:((n=t.find(a=>a.upstreamStatus))==null?void 0:n.upstreamStatus)??null,ahead:0,behind:0,dirty:!1,hasConflicts:!1}}function bk(e,t){if(Xp(e))return null;const r=e.branchConvergence;if(!r||typeof r!="object")return null;const n=r.status;if(!n||!["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"].includes(n))return null;const a=e.git,o=Zp(a)||em(a),i=!!(a!=null&&a.hasConflicts)||Wi(a),c=(a==null?void 0:a.ahead)??0,d=(a==null?void 0:a.behind)??0,p=(a==null?void 0:a.branch)??null,u=(a==null?void 0:a.upstream)??null,m=(a==null?void 0:a.upstreamStatus)??null,h=r.defaultBranch??t??null;return{status:n,needsConvergence:r.needsConvergence??n!=="merged_to_main",reason:r.reason??"provided_by_coordinator",nextStep:r.nextStep??null,branch:r.branch??p,defaultBranch:h,upstream:r.upstream??u,upstreamStatus:r.upstreamStatus??m,ahead:r.ahead??c,behind:r.behind??d,dirty:r.dirty??o,hasConflicts:r.hasConflicts??i}}function gk(e,t){const r=bk(e,t);return r?{...r,defaultBranch:r.defaultBranch??t}:null}function yk(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function vk(e){var d,p,u;const{nodeStatus:t,expectedSubmodulePaths:r,refreshedAtMs:n}=e,a=[],o=t.machineLabel||t.nodeId,i=t.git;if(!i){if(Xp(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const m=t.health==="online"||t.machineStatus==="online"||((d=t.connection)==null?void 0:d.state)==="connected"||((p=t.connection)==null?void 0:p.state)==="self";return a.push(m?`${o} is online but no peer git snapshot is visible yet.`:`${o} has no peer git snapshot visible yet.`),{snapshotCompleteness:"missing_git",snapshotWarnings:a}}const c=new Set((i.submodules??[]).map(m=>m.path));if(r.size>0){const m=[...r].filter(h=>!c.has(h));m.length>0&&a.push(`${o} is missing submodule visibility for ${m.join(", ")} even though another peer reported it.`)}return((u=t.connection)==null?void 0:u.state)!=="self"&&n!==null&&typeof i.lastCheckedAt=="number"&&n-i.lastCheckedAt>tk&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(m=>m.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(m=>m.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function tm(e){const t=zi(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??ik(t.nodes),a=Qp(t.refreshedAt),o=new Set(t.nodes.flatMap(A=>{var T;return(((T=A.git)==null?void 0:T.submodules)??[]).map(B=>B.path)})),i=[],c=[],d=uk(t),p=new Map,u=hk(pk(t));for(const A of t.nodes){const T=A.git,B=(T==null?void 0:T.branch)??null,D=ak(T),M=Zp(T)||D==="dirty",E=lk(A,n),z=gk(A,n),Q=vk({nodeStatus:A,expectedSubmodulePaths:o,refreshedAtMs:a}),J=typeof A.clonedFromNodeId=="string"?A.clonedFromNodeId:null,ae=nk(A),ne=mk(u.get(A.nodeId)??[]),ce={id:A.nodeId,type:E.length>0?"orphanNode":"worktreeNode",label:A.machineLabel||A.nodeId.slice(0,8),workspace:A.workspace,branch:B,upstream:(T==null?void 0:T.upstream)??null,upstreamStatus:(T==null?void 0:T.upstreamStatus)??null,daemonId:Yp(A),machineId:Jp(A),machineLabel:A.machineLabel||null,locality:sk(A),health:co([A.health,D]),ahead:(T==null?void 0:T.ahead)??0,behind:(T==null?void 0:T.behind)??0,dirty:M,dirtyFiles:ok(T),hasConflicts:(T==null?void 0:T.hasConflicts)??!1,activeSessionCount:ae.length,activeSessions:ae.map(be=>be.sessionId),sessionDetails:ae,providers:A.providers??[],isOrphan:E.length>0,orphanReasons:E,error:A.error,nextStepHint:Q.snapshotWarnings[0]??E[0]??(z==null?void 0:z.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:J,worktreeBranch:A.worktreeBranch??null,submodulePath:null,submoduleCommit:(T==null?void 0:T.headCommit)??null,outOfSync:Wi(T),snapshotCompleteness:Q.snapshotCompleteness,snapshotWarnings:Q.snapshotWarnings,branchConvergence:z,refineJobStatus:(ne==null?void 0:ne.status)??null,refineJobId:(ne==null?void 0:ne.jobId)??null,refineJobBranch:(ne==null?void 0:ne.branch)??null,refineJobInto:(ne==null?void 0:ne.into)??null,source:A};if(i.push(ce),B){const be=p.get(B)??[];be.push(ce.id),p.set(B,be)}for(const be of(T==null?void 0:T.submodules)??[]){const Z=`${ce.id}::submodule::${be.path}`,Y=be.path.split("/").filter(Boolean).pop()||be.path;i.push({id:Z,type:"submoduleNode",label:Y,workspace:be.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:ce.daemonId,machineId:ce.machineId,machineLabel:ce.machineLabel,locality:ce.locality,health:yk(be),ahead:0,behind:0,dirty:be.dirty,dirtyFiles:be.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],error:be.error,nextStepHint:be.error||(be.outOfSync?`${be.path} is out of sync with the parent checkout`:be.dirty?`${be.path} has local changes`:`${be.path} is in sync with the parent checkout`),parentNodeId:ce.id,submodulePath:be.path,submoduleCommit:be.commit,outOfSync:be.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:ce.id,parentWorkspace:A.workspace,submodule:be}}),c.push({id:`${ce.id}--${Z}`,source:ce.id,target:Z,type:"submoduleLink",label:be.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const m=n?`__branch_${n}`:null;if(m&&n){const T=(p.get(n)??[]).map(J=>i.find(ae=>ae.id===J)).filter(Boolean),B=T.map(J=>J.branchConvergence).filter(Boolean),D=dk(t),M=T.length>0&&T.every(J=>fk(J,n)),E=(D==null?void 0:D.length)===0&&M?xk(n,T):B.length>0?ck(B):null,z=(D==null?void 0:D.length)===0&&M?0:B.filter(J=>J.needsConvergence).length,Q={id:m,type:"defaultBranchNode",label:n,workspace:t.repoIdentity,branch:n,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:"default branch",locality:"unknown",health:co(T.map(J=>J.health)),ahead:0,behind:0,dirty:T.some(J=>J.dirty),dirtyFiles:T.reduce((J,ae)=>J+ae.dirtyFiles,0),hasConflicts:T.some(J=>J.hasConflicts),activeSessionCount:T.reduce((J,ae)=>J+ae.activeSessionCount,0),activeSessions:T.flatMap(J=>J.activeSessions),sessionDetails:T.flatMap(J=>J.sessionDetails),providers:[...new Set(T.flatMap(J=>J.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:z>0?`${z} workspace(s) on ${n} still need follow-up`:T.length>0?`${T.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:E,source:{nodeId:m,machineLabel:n,workspace:t.repoIdentity,health:co(T.map(J=>J.health)),providers:[],activeSessions:[],activeSessionDetails:[]}};i.push(Q);for(const J of i)if(!(J.id===m||J.type==="submoduleNode")){if(J.branch===n){c.push({id:`${m}--${J.id}`,source:m,target:J.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(J.branch){c.push({id:`${m}--${J.id}`,source:m,target:J.id,type:J.isOrphan?"orphanLink":"parentBranch",label:J.branch,direction:"undirected"});continue}J.isOrphan&&c.push({id:`${m}--${J.id}`,source:m,target:J.id,type:"orphanLink",label:"detached",direction:"undirected"})}}const h=new Set(i.map(A=>A.id)),b=new Set;for(const A of i){if(!A.clonedFromNodeId||A.type==="submoduleNode"||!h.has(A.clonedFromNodeId))continue;const T=`clone_${A.clonedFromNodeId}--${A.id}`;if(b.has(T))continue;b.add(T);const B=A.worktreeBranch??A.branch??void 0;c.push({id:T,source:A.clonedFromNodeId,target:A.id,type:"cloneLink",label:B?`cloned · ${B}`:"cloned",direction:"directed"})}const g=i.filter(A=>A.type!=="defaultBranchNode"),f=g.filter(A=>A.isOrphan).length,j=g.filter(A=>A.hasConflicts).length,N=g.filter(A=>A.health==="offline").length,y=g.filter(A=>A.type==="submoduleNode"&&A.outOfSync).length,v=g.filter(A=>{var T;return A.type!=="submoduleNode"&&((T=A.branchConvergence)==null?void 0:T.needsConvergence)}).length,k=g.filter(A=>{var T;return((T=A.branchConvergence)==null?void 0:T.status)==="blocked_review"}).length,w=g.filter(A=>{var T;return((T=A.branchConvergence)==null?void 0:T.status)==="pushed_feature_branch_needs_merge"}).length,x=g.filter(A=>{var T;return((T=A.branchConvergence)==null?void 0:T.status)==="cleanup_candidate"}).length,C=g.filter(A=>{var T;return((T=A.branchConvergence)==null?void 0:T.status)==="not_mergeable"}).length,S=g.filter(A=>A.snapshotWarnings.length>0).length,I=g.filter(A=>A.snapshotCompleteness==="pending_git").length,$=g.filter(A=>A.snapshotCompleteness==="missing_git").length,R=g.filter(A=>A.snapshotCompleteness==="missing_submodule_report").length,_=g.filter(A=>A.snapshotCompleteness==="stale").length,P=g.filter(A=>A.refineJobStatus==="running"||A.refineJobStatus==="accepted").length,F=g.filter(A=>A.refineJobStatus==="failed").length,q=[I>0?`${I} node(s) are still waiting for a live peer git snapshot`:null,$>0?`${$} node(s) have no visible peer git snapshot`:null,R>0?`${R} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,_>0?`${_} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return v>0&&d.push(`${v} workspace(s) still need follow-up before the mesh is converged`),f>0&&d.push(`${f} workspace(s) need attention before safe coordination`),k>0&&d.push(`${k} workspace(s) are blocked on branch convergence or upstream sync`),w>0&&d.push(`${w} clean feature branch workspace(s) still need merge follow-up`),x>0&&d.push(`${x} worktree workspace(s) are ready for refine / cleanup`),C>0&&d.push(`${C} workspace(s) have local changes or conflicts blocking convergence`),j>0&&d.push(`${j} workspace(s) report merge conflicts`),N>0&&d.push(`${N} node(s) are currently offline`),y>0&&d.push(`${y} submodule(s) are out of sync with their parent checkout`),d.push(...q),n||d.push("Could not infer a default branch from live mesh status"),{meshId:t.meshId,meshName:t.meshName,repoIdentity:t.repoIdentity,refreshedAt:t.refreshedAt,nodes:i,edges:c,stats:{totalNodes:g.length,onlineNodes:g.filter(A=>A.health==="online").length,dirtyNodes:g.filter(A=>A.dirty).length,orphanNodes:f,errorNodes:g.filter(A=>!!A.error||A.outOfSync).length,offlineNodes:N,followUpNodes:v,blockedReviewNodes:k,mergeReadyNodes:w,cleanupCandidateNodes:x,notMergeableNodes:C,incompleteSnapshotNodes:S,pendingGitSnapshotNodes:I,missingGitSnapshotNodes:$,missingSubmoduleSnapshotNodes:R,staleGitSnapshotNodes:_,activeRefineNodes:P,failedRefineNodes:F,totalActiveSessions:g.reduce((A,T)=>A+T.activeSessionCount,0)},warnings:d,snapshotWarnings:q}}function wk(e){return!e.nodes.some(t=>t.snapshotCompleteness==="pending_git"||t.snapshotCompleteness==="missing_git"||t.snapshotCompleteness==="missing_submodule_report")}const jk={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0},Ki=l.createContext(Ds("dark"));function Ge({label:e,tone:t="default"}){const r=l.useContext(Ki);return s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${r.badge(t)}`,children:e})}function wt({label:e,value:t}){const r=l.useContext(Ki);return s.jsxs("div",{className:r.rowClass,children:[s.jsx("span",{className:r.rowLabelClass,children:e}),s.jsx("span",{className:r.rowValueClass,children:t})]})}function kk(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 uo(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 Hn(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const r=t.toLowerCase().replace(/[\s-]+/g,"_");return r.includes("approval")?"awaiting approval":r.includes("generating")||r.includes("running")||r.includes("busy")?"generating":r.includes("idle")||r.includes("ready")||r.includes("waiting_input")?"idle":r.replace(/_/g," ")}function Nk(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function Sk(e){return e.startedAt||e.createdAt||null}function Ck(e){const t=Sk(e);if(!t)return"runtime age not reported";const r=Date.parse(t);if(!Number.isFinite(r))return"runtime age not reported";const n=Math.max(0,Math.floor((Date.now()-r)/1e3));if(n<60)return`${n}s`;const a=Math.floor(n/60);if(a<60)return`${a}m`;const o=Math.floor(a/60);return o<48?`${o}h ${a%60}m`:`${Math.floor(o/24)}d ${o%24}h`}function sm(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function Ik(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 Mk(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 Ak(e){var r;const t=[];for(const n of e.nodes){const a=n.activeSessionDetails&&n.activeSessionDetails.length>0?n.activeSessionDetails:(n.activeSessions??[]).map(o=>({sessionId:o,workspace:n.workspace,isCached:!0}));for(const o of a)t.push({nodeId:n.nodeId,machineLabel:n.machineLabel,workspace:n.workspace,branch:((r=n.git)==null?void 0:r.branch)??null,nodeHealth:n.health,session:o})}return t}function Tk(e){return e.assignedNodeId||e.targetNodeId||null}function Hc(e){return e?e.slice(0,7):null}function _k(e,t){var o,i,c;const r=Hc((o=e==null?void 0:e.git)==null?void 0:o.headCommit),n=((c=(i=e==null?void 0:e.git)==null?void 0:i.headMessage)==null?void 0:c.trim())||"";if(r||n)return[r,n].filter(Boolean).join(" · ");const a=t[0];return a?[Hc(a.commit),a.message].filter(Boolean).join(" · "):null}function Lk(e,t){const r=_k(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function Pk(e){const t=(e==null?void 0:e.result)??e,r=(t==null?void 0:t.log)??(e==null?void 0:e.log)??t;return Array.isArray(r==null?void 0:r.entries)?r.entries:[]}function Rk(e){var r,n,a,o,i,c;const t=((r=e.selectedSessionEntry)==null?void 0:r.session.workspace)||((n=e.selectedSessionEntry)==null?void 0:n.workspace)||((o=(a=e.selectedNodeStatus)==null?void 0:a.git)==null?void 0:o.workspace)||((i=e.selectedNodeStatus)==null?void 0:i.workspace)||null;if(t&&e.selectedSessionEntry){const d=((c=e.selectedNodeStatus)==null?void 0:c.daemonId)||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}if(t&&e.selectedNodeStatus){const d=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}return null}function Dk(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":Mk(e.connection)}function $k(e){var r;const t=e.source;return t!=null&&t.kind?t.kind:((r=t==null?void 0:t.connection)==null?void 0:r.source)??"mesh_status"}function Wc(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 Ek(e){return e.direction==="directed"?"directed":"undirected"}function Bk(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function Fk(e){var t,r,n,a;return[e.meshId,e.refreshedAt,e.nodes.length,((r=(t=e.queue)==null?void 0:t.summary)==null?void 0:r.active)??"",((a=(n=e.ledger)==null?void 0:n.summary)==null?void 0:a.recentFailures)??"",...e.nodes.map(o=>{var i,c,d,p,u,m,h,b,g,f,j,N,y,v,k,w,x,C,S,I,$,R;return[o.nodeId,o.daemonId??"",o.machineId??"",o.machineLabel,o.machineStatus??"",((i=o.connection)==null?void 0:i.state)??"",((c=o.connection)==null?void 0:c.transport)??"",((d=o.connection)==null?void 0:d.source)??"",o.health,o.gitProbePending?1:0,((p=o.git)==null?void 0:p.branch)??"",((u=o.git)==null?void 0:u.upstream)??"",((m=o.git)==null?void 0:m.upstreamStatus)??"",((h=o.git)==null?void 0:h.ahead)??"",((b=o.git)==null?void 0:b.behind)??"",((g=o.git)==null?void 0:g.headCommit)??"",((f=o.git)==null?void 0:f.staged)??"",((j=o.git)==null?void 0:j.modified)??"",((N=o.git)==null?void 0:N.untracked)??"",((y=o.git)==null?void 0:y.deleted)??"",((v=o.git)==null?void 0:v.renamed)??"",(k=o.git)!=null&&k.hasConflicts?1:0,((w=o.git)==null?void 0:w.lastCheckedAt)??"",((x=o.activeSessions)==null?void 0:x.join(","))??"",((C=o.activeSessionDetails)==null?void 0:C.length)??"",((S=o.activeSessionDetails)==null?void 0:S.map(_=>[_.sessionId,_.providerType??"",_.state??"",_.chatStatus??"",_.lifecycle??"",_.role??"",_.isSelfCoordinator?1:0,_.statusNote??"",_.startedAt??"",_.createdAt??""].join("/")).join(","))??"",((I=o.providers)==null?void 0:I.join(","))??"",(($=o.providerPriority)==null?void 0:$.join(","))??"",o.error??"",(((R=o.git)==null?void 0:R.submodules)??[]).map(_=>[_.path,_.commit,_.dirty?1:0,_.outOfSync?1:0,_.error??""].join("/")).join(",")].join("|")})].join("::")}function Ok({canonicalStatus:e,queueSummary:t,ledgerSummary:r,isBootstrapMode:n,meshTheme:a,sessionEntries:o,inlineMode:i=!1}){var w;const c=t&&(t.active>0||t.historical>0),d=r.recentFailures>0||r.taskFailed>0,p=(w=e.queue)!=null&&w.tasks?e.queue.tasks.filter(x=>x.status==="failed"||x.status==="cancelled").slice(0,5):[],u=e.asyncRefineJobs,m=(u==null?void 0:u.filter(x=>x.status==="running"||x.status==="accepted"))??[],h=(u==null?void 0:u.filter(x=>x.status==="failed"))??[],b=e.staleDirectWorkSummary,g=b&&b.count>0;if(!c&&!d&&e.nodes.length===0&&!n&&m.length===0&&h.length===0&&!g&&o.length===0)return null;const f=a.isDark,j=`border-t ${f?"border-white/8":"border-slate-200"}`,N=`group w-full rounded-lg border text-xs ${f?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,y=`flex cursor-pointer list-none items-center gap-1.5 px-2.5 py-1.5 [&::-webkit-details-marker]:hidden ${a.textSecondary}`;function v({label:x,value:C,tone:S}){const I=S==="rose"?f?"text-rose-300":"text-rose-600":S==="sky"?f?"text-sky-300":"text-sky-600":S==="amber"?f?"text-amber-300":"text-amber-600":S==="emerald"?f?"text-emerald-300":"text-emerald-600":S==="muted"?a.textMuted:a.textPrimary;return s.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:[s.jsx("span",{className:`tabular-nums text-sm font-semibold leading-none ${I}`,children:C}),s.jsx("span",{className:`mt-0.5 text-[9px] uppercase tracking-wide ${a.textMuted}`,children:x})]})}const k=s.jsxs("div",{className:"flex flex-col gap-3 text-xs",children:[s.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t?s.jsxs(s.Fragment,{children:[s.jsx(v,{label:"Pending",value:t.pending}),s.jsx(v,{label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(v,{label:"Done",value:t.completed,tone:"emerald"}),s.jsx(v,{label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0})]}):s.jsxs(s.Fragment,{children:[s.jsx(v,{label:"Done",value:r.taskCompleted,tone:"emerald"}),s.jsx(v,{label:"Failed",value:r.taskFailed,tone:r.taskFailed>0?"rose":void 0}),s.jsx(v,{label:"Sessions",value:r.sessionLaunched}),s.jsx(v,{label:"Recent↯",value:r.recentFailures,tone:r.recentFailures>0?"amber":"muted"})]})}),t&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(v,{label:"Ledger done",value:r.taskCompleted,tone:"emerald"}),s.jsx(v,{label:"Sessions",value:r.sessionLaunched}),s.jsx(v,{label:"Recent↯",value:r.recentFailures,tone:r.recentFailures>0?"amber":"muted"})]}),r.lastActivityAt&&s.jsxs("div",{className:`flex items-center justify-between ${a.textMuted}`,children:[s.jsx("span",{children:"Last activity"}),s.jsx("span",{className:"font-mono text-[10px]",children:r.lastActivityAt.slice(5,16)})]}),e.nodes.length>0&&s.jsx("div",{className:`pt-2.5 ${j}`,children:s.jsx("div",{className:"flex flex-col gap-1",children:e.nodes.map(x=>{var _;const C=((_=x.connection)==null?void 0:_.state)??"unknown",S=C==="unknown"||C==="connecting",R=S?"bg-amber-400":C==="failed"||C==="closed"||C==="disconnected"?f?"bg-rose-400":"bg-rose-500":C==="connected"||C==="self"?f?"bg-emerald-400":"bg-emerald-500":f?"bg-slate-500":"bg-slate-400";return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`size-1.5 shrink-0 rounded-full ${R}`}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${a.textSecondary}`,title:x.workspace,children:x.machineLabel}),s.jsx("span",{className:`shrink-0 font-mono text-[10px] ${a.textMuted}`,children:S?"…":C})]},x.nodeId)})})}),u&&u.length>0&&s.jsx("div",{className:`pt-2.5 ${j}`,children:s.jsxs("details",{className:N,children:[s.jsxs("summary",{className:y,children:[s.jsx("span",{className:"flex-1",children:"Refine jobs"}),s.jsx("span",{className:`tabular-nums ${f?"text-slate-400":"text-slate-500"}`,children:u.length}),h.length>0&&s.jsxs("span",{className:f?"text-rose-300":"text-rose-600",children:[h.length," failed"]})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:u.slice(0,8).map(x=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${a.textMuted}`,children:[x.branch??x.jobId.slice(0,14),x.into?` → ${x.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${x.status==="failed"?f?"text-rose-300":"text-rose-600":x.status==="running"||x.status==="accepted"?f?"text-sky-300":"text-sky-600":f?"text-emerald-300":"text-emerald-600"}`,children:x.status})]},x.jobId))})]})}),p.length>0&&s.jsx("div",{className:u&&u.length>0?"":`pt-2.5 ${j}`,children:s.jsxs("details",{className:N,children:[s.jsxs("summary",{className:y,children:[s.jsx("span",{className:`flex-1 ${f?"text-rose-300":"text-rose-600"}`,children:"Failed tasks"}),s.jsx("span",{className:`tabular-nums ${f?"text-rose-400":"text-rose-500"}`,children:p.length})]}),s.jsx("div",{className:"flex flex-col gap-1 px-2.5 pb-2",children:p.map(x=>s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`font-mono text-[10px] ${a.textMuted}`,children:x.id.slice(0,10)}),x.message&&s.jsx("span",{className:`flex-1 truncate ${f?"text-slate-300":"text-slate-700"}`,children:x.message.slice(0,55)})]}),x.cancelReason&&s.jsx("div",{className:`truncate text-[10px] ${a.textMuted}`,children:x.cancelReason.slice(0,55)})]},x.id))})]})}),g&&s.jsxs("div",{className:`flex items-center justify-between pt-2.5 ${j}`,children:[s.jsx("span",{className:a.textMuted,children:"Stale work"}),s.jsx("span",{className:`tabular-nums ${f?"text-amber-300":"text-amber-600"}`,children:b.count})]}),o.length>0&&s.jsx("div",{className:`pt-2.5 ${j}`,children:s.jsxs("details",{className:N,children:[s.jsxs("summary",{className:y,children:[s.jsx("span",{className:"flex-1",children:"Sessions"}),s.jsx("span",{className:`tabular-nums ${f?"text-slate-400":"text-slate-500"}`,children:o.length})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:o.map(x=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${a.textMuted}`,title:x.session.sessionId,children:sm(x.session.sessionId)}),s.jsx("span",{className:`shrink-0 ${a.textMuted}`,children:x.session.providerType||"?"}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${a.textMuted}`,children:Hn(x.session)})]},x.session.sessionId))})]})})]});return i?k:s.jsxs("details",{className:`rounded-2xl border text-xs ${a.isDark?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsxs("summary",{className:`flex cursor-pointer list-none items-center gap-2 px-4 py-3 font-medium [&::-webkit-details-marker]:hidden ${a.textSecondary}`,children:[s.jsx("span",{className:"flex-1",children:"Mesh Health Panel"}),m.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700"}`,children:[m.length," refining"]}),h.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[h.length," refine failed"]}),d&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[r.recentFailures," recent failures"]}),n&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.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 zk(e){return e.nodes.length===0?!1:e.nodes.every(t=>t.health==="unknown"&&(!t.connection||t.connection.state==="unknown"))}function rm({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null,bootstrapFallback:a}){var te,X,L,ue;const{theme:o}=Rs(),i=l.useMemo(()=>Ds(o),[o]),c=a??zk(e),d=l.useMemo(()=>zi(e),[e]),p=l.useMemo(()=>Fk(d),[d]),u=l.useMemo(()=>tm(d),[p]),[m,h]=l.useState("overview"),[b,g]=l.useState(!1),[f,j]=l.useState(!1),[N,y]=l.useState(null),[v,k]=l.useState(null),[w,x]=l.useState(null),[C,S]=l.useState({}),[I,$]=l.useState(null),[R,_]=l.useState(null),P=l.useMemo(()=>new Map(d.nodes.map(H=>[H.nodeId,H])),[d.nodes]),F=l.useMemo(()=>new Map(u.nodes.map(H=>[H.id,H])),[u.nodes]),q=((te=d.queue)==null?void 0:te.summary)??null,A=((X=d.ledger)==null?void 0:X.summary)??jk,T=l.useMemo(()=>Ak(d),[d]),B=l.useMemo(()=>{const H=new Map;for(const le of T){const G=Hn(le.session);H.set(G,(H.get(G)??0)+1)}return[...H.entries()].sort((le,G)=>G[1]-le[1])},[T]);l.useEffect(()=>{N&&(F.has(N)||(y(null),x(H=>!H||"nodeId"in H&&H.nodeId===N?null:H)))},[F,N]);const D=N?P.get(N)??null:null,M=Bk(u,N),E=(w==null?void 0:w.kind)==="edge"&&v?u.edges.find(H=>H.id===v)??null:null,z=E?u.nodes.find(H=>H.id===E.source)??null:null,Q=E?u.nodes.find(H=>H.id===E.target)??null:null;l.useEffect(()=>{var H,le,G;if(N)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:d.meshId,selectedNodeId:N,canonicalNode:Aj(D),graphNode:M?{id:M.id,branch:M.branch,upstream:M.upstream,headCommit:M.submoduleCommit,submoduleCount:((le=(H=D==null?void 0:D.git)==null?void 0:H.submodules)==null?void 0:le.length)??0,snapshotCompleteness:M.snapshotCompleteness,snapshotWarnings:M.snapshotWarnings,branchConvergence:((G=M.branchConvergence)==null?void 0:G.status)??null}:null})}catch{}},[d.meshId,M,N,D]);const J=(w==null?void 0:w.kind)==="session"?T.find(H=>H.nodeId===w.nodeId&&H.session.sessionId===w.sessionId)??null:null,ae=l.useMemo(()=>T.filter(H=>H.nodeId===N),[N,T]),ne=Rk({coordinatorDaemonId:r,selectedNodeStatus:D,selectedSessionEntry:J}),ce=(ne==null?void 0:ne.workspace)??null,be=ce?C[ce]??null:null,Z=Lk(D,(be==null?void 0:be.entries)??[]),Y=(M==null?void 0:M.daemonId)??(D==null?void 0:D.daemonId)??r??null,ve=!!(M&&n&&Y&&M.type!=="submoduleNode"&&M.behind>0&&M.ahead===0&&M.dirtyFiles===0&&!M.dirty&&!M.hasConflicts&&M.upstreamStatus==="fresh"),ye=l.useCallback(()=>{y(null),k(null),x(null),$(null)},[]);l.useEffect(()=>{$(null)},[N]);const xe=l.useCallback(async()=>{if(!M||!Y||!n||!ve)return;_(M.id),$(null);const H=(D==null?void 0:D.workspace)??M.workspace??"";try{const le=await n(Y,"fast_forward_mesh_node",{meshId:d.meshId,nodeId:M.id,workspace:H,updateSubmodules:!0,dryRun:!0,execute:!1}),G=(le==null?void 0:le.result)??le;if($({phase:"dry_run",code:typeof(G==null?void 0:G.code)=="string"?G.code:void 0,error:typeof(G==null?void 0:G.operationError)=="string"?G.operationError:null,executed:(G==null?void 0:G.executed)===!0}),!(G!=null&&G.success)||G.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${M.label}?`))return;const Te=await n(Y,"fast_forward_mesh_node",{meshId:d.meshId,nodeId:M.id,workspace:H,updateSubmodules:!0,dryRun:!1,execute:!0}),Me=(Te==null?void 0:Te.result)??Te;$({phase:"execute",code:typeof(Me==null?void 0:Me.code)=="string"?Me.code:void 0,error:typeof(Me==null?void 0:Me.operationError)=="string"?Me.operationError:null,executed:(Me==null?void 0:Me.executed)===!0})}catch(le){$({phase:"dry_run",error:le instanceof Error?le.message:"fast-forward failed"})}finally{_(null)}},[ve,d.meshId,M,Y,n]);l.useEffect(()=>{if(!M&&!E)return;const H=le=>{le.key==="Escape"&&ye()};return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[ye,E,M]),l.useEffect(()=>{if(!ne||!n)return;const{daemonId:H,workspace:le}=ne,G=C[le];if(G!=null&&G.loading||G&&(G.entries.length>0||G.error))return;let Le=!1;return S(Te=>{var Me;return{...Te,[le]:{loading:!0,error:null,entries:((Me=Te[le])==null?void 0:Me.entries)??[]}}}),n(H,"git_log",{workspace:le,limit:5}).then(Te=>{Le||S(Me=>({...Me,[le]:{loading:!1,error:null,entries:Pk(Te)}}))}).catch(Te=>{Le||S(Me=>({...Me,[le]:{loading:!1,error:Te instanceof Error?Te.message:"git_log failed",entries:[]}}))}),()=>{Le=!0}},[C,ne,n]);const Se=[...u.warnings??[],...d.nodes.filter(H=>H.machineStatus&&H.machineStatus!=="online").map(H=>`${H.machineLabel}: ${H.machineStatus}`)],ie=u.stats.incompleteSnapshotNodes>0,we=u.stats.followUpNodes>0?`${u.stats.followUpNodes} need follow-up`:ie?"mesh visibility incomplete":"mesh converged",pe=u.stats.followUpNodes>0?"danger":ie?"warn":"good",[W,O]=l.useState("LR"),V=H=>H?i.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":i.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=H=>H?i.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 ${i.textSecondary} border border-transparent hover:bg-white/[0.04]`;return s.jsx(Ki.Provider,{value:i,children:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[s.jsxs("div",{className:"shrink-0 flex items-center gap-2",children:[s.jsxs("div",{className:`inline-flex w-fit items-center gap-1 rounded-xl border p-1 ${i.isDark?"border-white/10 bg-slate-950/40":"border-slate-200 bg-slate-50"}`,role:"tablist","aria-label":"Mesh view",children:[s.jsx("button",{type:"button",role:"tab","aria-selected":m==="overview",className:oe(m==="overview"),onClick:()=>h("overview"),children:"Overview"}),s.jsx("button",{type:"button",role:"tab","aria-selected":m==="graph",className:oe(m==="graph"),onClick:()=>{j(!0),h("graph")},children:"Graph"})]}),s.jsx("div",{className:"ml-auto",children:s.jsx(Zj,{meshTheme:i,open:b,onToggle:()=>g(H=>!H)})})]}),b&&s.jsx(ek,{meshTheme:i,onClose:()=>g(!1)}),s.jsx("div",{className:`${m==="overview"?"flex":"hidden"} min-h-0 flex-1 flex-col overflow-y-auto`,children:m==="overview"&&s.jsx(Bj,{status:e})}),s.jsx("div",{className:`${m==="graph"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-4`,children:s.jsxs("div",{className:`${i.cardClass} relative flex min-h-0 flex-1 flex-col rounded-[28px]`,style:{minHeight:480},children:[s.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 ${i.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-wrap gap-2 text-xs ${i.textSecondary}`,children:[s.jsx(Ge,{label:we,tone:pe}),u.stats.blockedReviewNodes>0&&s.jsx(Ge,{label:`${u.stats.blockedReviewNodes} blocked review`,tone:"danger"}),u.stats.notMergeableNodes>0&&s.jsx(Ge,{label:`${u.stats.notMergeableNodes} not mergeable`,tone:"danger"}),u.stats.mergeReadyNodes>0&&s.jsx(Ge,{label:`${u.stats.mergeReadyNodes} need merge`,tone:"warn"}),u.stats.cleanupCandidateNodes>0&&s.jsx(Ge,{label:`${u.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),u.stats.offlineNodes>0&&s.jsx(Ge,{label:`${u.stats.offlineNodes} offline`,tone:"danger"}),u.stats.incompleteSnapshotNodes>0&&s.jsx(Ge,{label:`${u.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),u.stats.missingGitSnapshotNodes>0&&s.jsx(Ge,{label:`${u.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),u.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Ge,{label:`${u.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),u.stats.staleGitSnapshotNodes>0&&s.jsx(Ge,{label:`${u.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((q==null?void 0:q.active)??0)>0&&s.jsx(Ge,{label:`${(q==null?void 0:q.active)??0} active queue`,tone:"info"}),s.jsx(Ge,{label:`${u.stats.totalNodes} nodes`,tone:"default"}),u.stats.totalActiveSessions>0&&s.jsx(Ge,{label:`${u.stats.totalActiveSessions} attached chats`,tone:"info"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[s.jsxs("div",{className:i.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:[s.jsx("button",{type:"button",onClick:()=>O("auto"),className:V(W==="auto"),title:"Auto-detect direction",children:"Auto"}),s.jsx("button",{type:"button",onClick:()=>O("LR"),className:V(W==="LR"),title:"Left to right",children:"LR"}),s.jsx("button",{type:"button",onClick:()=>O("TB"),className:V(W==="TB"),title:"Top to bottom",children:"TB"})]}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${i.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${i.textSecondary} [&::-webkit-details-marker]:hidden`,children:(()=>{var G;const H=((G=d.asyncRefineJobs)==null?void 0:G.filter(Le=>Le.status==="failed").length)??0,le=A.recentFailures;return H>0?s.jsxs("span",{className:i.isDark?"text-rose-300":"text-rose-600",children:[H," refine failed"]}):le>0?s.jsxs("span",{className:i.isDark?"text-amber-300":"text-amber-600",children:[le," failures"]}):"Health"})()}),s.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 ${i.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsx(Ok,{canonicalStatus:d,queueSummary:q,ledgerSummary:A,isBootstrapMode:c,meshTheme:i,sessionEntries:T,inlineMode:!0})})]})}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${i.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${i.textSecondary} [&::-webkit-details-marker]:hidden`,children:"Legend"}),s.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 rounded-xl border p-3 shadow-xl backdrop-blur-xl ${i.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ge,{label:`${u.stats.dirtyNodes} dirty`,tone:u.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Ge,{label:`${u.stats.orphanNodes} orphan`,tone:u.stats.orphanNodes>0?"warn":"good"}),s.jsx(Ge,{label:`${A.recentFailures} recent failures`,tone:A.recentFailures>0?"danger":"good"}),B.length===0?s.jsx(Ge,{label:"no session metadata"}):B.slice(0,2).map(([H,le])=>s.jsx(Ge,{label:`${le} ${H}`,tone:uo(H)},H))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ge,{label:"Anchor = default branch",tone:"info"}),s.jsx(Ge,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Ge,{label:"Submodule link = child checkout",tone:"warn"})]}),Se.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:Se.map(H=>s.jsx("span",{className:i.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:H},H))}),s.jsx("div",{className:`text-xs ${i.textMuted}`,children:"Click a node or edge to pin its drill-down details in the side panel. Click it again to close."})]})})]})})]})]}),c&&u.nodes.length>0&&s.jsxs("div",{className:`shrink-0 mx-4 mt-2 flex items-center gap-2 rounded-xl border px-3.5 py-2 text-xs ${i.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full animate-pulse ${i.isDark?"bg-amber-400":"bg-amber-500"}`,"aria-hidden":!0}),s.jsx("span",{children:"Awaiting live data — showing setup inventory until peer mesh_status probes succeed."})]}),s.jsxs("div",{className:"relative flex flex-1 min-w-0",style:{minHeight:360},children:[s.jsx("div",{className:"flex-1 min-w-0",children:f?u.nodes.length>0?s.jsx(mj,{data:u,selectedNodeId:N,directionPref:W,onNodeClick:H=>{if((w==null?void 0:w.kind)==="node"&&N===H.id){ye();return}k(null),y(H.id),x({kind:"node",nodeId:H.id})},onEdgeClick:H=>{if((w==null?void 0:w.kind)==="edge"&&v===H.id){ye();return}y(null),k(H.id),x({kind:"edge",edgeId:H.id})}}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:t}):s.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&&(w==null?void 0:w.kind)==="node"&&s.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 ${i.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${i.textMuted}`,children:"Selected node"}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${i.textPrimary}`,children:M.label}),s.jsx("div",{className:`mt-0.5 font-mono text-[11px] ${i.textMuted}`,children:M.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[M.behind>0&&s.jsx("button",{type:"button",onClick:()=>{xe()},disabled:!ve||R===M.id,className:i.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:R===M.id?"Checking":"Heal"}),s.jsx("button",{type:"button",onClick:ye,"aria-label":"Close detail panel",className:i.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:"✕"})]})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[(()=>{const H=(D==null?void 0:D.health)??M.health;return H==="unknown"?s.jsx(Ge,{label:"connecting...",tone:"default"}):s.jsx(Ge,{label:H,tone:kk(H)})})(),M.branch&&s.jsx(Ge,{label:M.branch,tone:"default"}),M.ahead>0&&s.jsx(Ge,{label:`ahead ${M.ahead}`,tone:"warn"}),M.behind>0&&s.jsx(Ge,{label:`behind ${M.behind}`,tone:"warn"}),M.dirtyFiles>0&&s.jsx(Ge,{label:`${M.dirtyFiles} dirty`,tone:"warn"}),(D==null?void 0:D.connection)&&D.connection.state!=="unknown"&&s.jsx(Ge,{label:Dk(D),tone:Ik(D.connection)}),((L=D==null?void 0:D.connection)==null?void 0:L.state)==="unknown"&&s.jsx(Ge,{label:"mesh connecting...",tone:"warn"}),ae.length>0&&s.jsx(Ge,{label:`${ae.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[M.machineLabel&&s.jsx(wt,{label:"Machine",value:M.machineLabel}),M.locality&&M.locality!=="unknown"&&s.jsx(wt,{label:"Locality",value:M.locality}),s.jsx(wt,{label:"Workspace",value:(D==null?void 0:D.workspace)??M.workspace}),Z&&s.jsx(wt,{label:"HEAD",value:Z}),(M.dirtyFiles>0||M.ahead>0||M.behind>0)&&s.jsx(wt,{label:"Dirty/ahead/behind",value:`${M.dirtyFiles}/${M.ahead}/${M.behind}`}),ae.length>0&&s.jsx(wt,{label:"Sessions",value:String(ae.length)}),M.upstream&&s.jsx(wt,{label:"Upstream",value:M.upstream}),(()=>{var le;const H=((le=D==null?void 0:D.connection)==null?void 0:le.source)??$k(M);return H&&H!=="unknown"?s.jsx(wt,{label:"Source",value:String(H)}):null})(),(()=>{var le;const H=(le=D==null?void 0:D.connection)==null?void 0:le.transport;return H&&H!=="unknown"?s.jsx(wt,{label:"Transport",value:H}):null})(),(()=>{const H=M.machineId??(D==null?void 0:D.machineId);return H?s.jsx(wt,{label:"Machine id",value:H}):null})(),(()=>{const H=M.daemonId??(D==null?void 0:D.daemonId);return H?s.jsx(wt,{label:"Daemon id",value:H}):null})()]}),ae.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${i.textMuted}`,children:"Active Sessions"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:ae.map(H=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${i.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono select-text ${i.textMuted}`,title:H.session.sessionId,children:sm(H.session.sessionId)}),s.jsx(Ge,{label:Hn(H.session),tone:uo(Hn(H.session))})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 ${i.textMuted}`,children:[s.jsx("span",{className:"truncate",children:H.session.providerType||"provider unknown"}),s.jsx("span",{children:Nk(H.session)}),s.jsx("span",{children:Ck(H.session)})]}),H.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${i.textMuted}`,children:H.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${i.textMuted}`,title:H.session.workspace||H.workspace,children:[(H.session.workspace||H.workspace).slice(0,38),H.branch?` · ${H.branch}`:""]})]},H.session.sessionId))})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${i.textMuted}`,children:"Ledger (mesh-wide)"}),s.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[s.jsx(wt,{label:"Completed",value:String(A.taskCompleted)}),s.jsx(wt,{label:"Failed",value:s.jsx("span",{className:A.taskFailed>0?i.isDark?"text-rose-300":"text-rose-600":"",children:A.taskFailed})}),s.jsx(wt,{label:"Launched",value:String(A.sessionLaunched)}),s.jsx(wt,{label:"Recent failures",value:s.jsx("span",{className:A.recentFailures>0?i.isDark?"text-amber-300":"text-amber-600":"",children:A.recentFailures})})]})]}),(()=>{var G,Le;const H=((G=d.queue)==null?void 0:G.tasks)??((Le=d.queue)==null?void 0:Le.items)??null;if(!Array.isArray(H)||H.length===0)return null;const le=H.filter(Te=>Tk(Te)===N).slice(0,3);return le.length===0?null:s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${i.textMuted}`,children:"Queue tasks"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:le.map(Te=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${i.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`font-mono ${i.textMuted}`,children:Te.id.slice(0,12)}),s.jsx(Ge,{label:Te.status??"unknown",tone:uo(Te.status)})]}),Te.message&&s.jsx("div",{className:`mt-0.5 truncate ${i.textMuted}`,children:Te.message.slice(0,48)})]},Te.id))})]})})(),M.snapshotWarnings.length>0&&s.jsxs("div",{className:i.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:[s.jsx("div",{className:"font-medium",children:"Key warning"}),s.jsx("div",{className:"mt-1",children:M.snapshotWarnings[0]})]}),((ue=M.branchConvergence)==null?void 0:ue.nextStep)&&s.jsxs("div",{className:i.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:[s.jsx("div",{className:"font-medium",children:"Follow-up"}),s.jsx("div",{className:"mt-1",children:M.branchConvergence.nextStep})]}),I&&s.jsxs("div",{className:i.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:[s.jsx("div",{className:"font-medium",children:I.phase==="execute"?"Heal result":"Heal preview"}),s.jsx("div",{className:"mt-1",children:I.code??I.error??"No result code returned."})]})]}),E&&(w==null?void 0:w.kind)==="edge"&&s.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 ${i.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${i.textMuted}`,children:"Selected edge"}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${i.textPrimary}`,children:E.label||Wc(E)}),s.jsx("div",{className:`mt-0.5 break-all font-mono text-[11px] ${i.textMuted}`,children:E.id})]}),s.jsx("button",{type:"button",onClick:ye,"aria-label":"Close detail panel",className:i.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:"✕"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[s.jsx(Ge,{label:Wc(E),tone:"default"}),s.jsx(Ge,{label:Ek(E),tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(wt,{label:"From",value:(z==null?void 0:z.label)??E.source}),s.jsx(wt,{label:"To",value:(Q==null?void 0:Q.label)??E.target}),s.jsx(wt,{label:"Label",value:E.label??"none"})]})]})]})]})})]})})}function bt(e){return typeof e=="string"?e.trim():""}function Yo(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ui(...e){const t=new Set;for(const r of e){const n=bt(r);n&&t.add(n)}return[...t]}function Hk(e,t){var m,h;const r=Yo(e==null?void 0:e.settings),n=bt((m=e==null?void 0:e.coordinator)==null?void 0:m.meshId)||bt(r.meshCoordinatorFor),a=bt(r.meshNodeFor),o=!!n||!!a,i=n===t||a===t;if(o&&!i)return null;const c=Yo(e==null?void 0:e.activeChat),d=Ui(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,c.sessionId,c.session_id,c.providerSessionId,c.provider_session_id),p=d[0]||"";if(!p)return null;const u=n===t?bt((h=e==null?void 0:e.coordinator)==null?void 0:h.role)||"coordinator":a===t?bt(r.meshNodeRole)||"worker":bt(e==null?void 0:e.role)||bt(r.meshNodeRole)||void 0;return{sessionId:p,aliases:d,meshId:t,nodeId:i&&bt(r.meshNodeId)||null,providerType:bt(e==null?void 0:e.providerType)||void 0,state:bt(e==null?void 0:e.status)||void 0,chatStatus:bt(c.status)||void 0,lifecycle:bt(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:bt(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:bt(e==null?void 0:e.runtimeRecoveryState)||void 0,...u?{role:u}:{},...i?{isSelfCoordinator:n===t}:{},workspace:bt(e==null?void 0:e.workspace)||null}}function nm(e,t){var n;return t?(Array.isArray((n=e.status)==null?void 0:n.sessions)?e.status.sessions:[]).map(a=>Hk(a,t)).filter(a=>a!==null):[]}function ca(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function Wk(e,t){const r=new Set(ca(t));return ca(e).some(n=>r.has(n))}function Kk(e,t){const r=t.filter(a=>!!a);return r.length===0?e:[...e.filter(a=>!r.some(o=>Wk(a,o))),...r]}function Uk(e,t){if(t.length===0)return e;const r=new Map;for(const i of t)for(const c of ca(i))r.set(c,i);let n=!1;const o=(e.nodes??[]).map((i,c)=>{const d=Array.isArray(i.activeSessionDetails)?i.activeSessionDetails:Array.isArray(i.sessions)?i.sessions:[],p=new Map;for(const h of d){const b=Ui(h==null?void 0:h.sessionId,h==null?void 0:h.session_id,h==null?void 0:h.id,h==null?void 0:h.providerSessionId,h==null?void 0:h.provider_session_id),g=b[0]||"";if(!g)continue;const f=b.map(j=>r.get(j)).find(Boolean);f&&(n=!0),p.set(g,f?{...h,sessionId:g,providerType:f.providerType||h.providerType,state:f.state||h.state,chatStatus:f.chatStatus||h.chatStatus,lifecycle:f.lifecycle||h.lifecycle,surfaceKind:f.surfaceKind||h.surfaceKind,recoveryState:f.recoveryState||h.recoveryState,role:f.role||h.role,isSelfCoordinator:f.isSelfCoordinator??h.isSelfCoordinator,workspace:f.workspace||h.workspace}:{...h,sessionId:g})}for(const h of i.activeSessions??[])p.has(h)||p.set(h,{sessionId:h,workspace:i.workspace,isCached:!0});const u=c===0;for(const h of t){if(ca(h).some(j=>p.has(j)))continue;const g=h.nodeId!=null&&h.nodeId===i.nodeId,f=h.isSelfCoordinator&&!h.nodeId&&u;!g&&!f||(n=!0,p.set(h.sessionId,{sessionId:h.sessionId,providerType:h.providerType,state:h.state,chatStatus:h.chatStatus,lifecycle:h.lifecycle,surfaceKind:h.surfaceKind,recoveryState:h.recoveryState,role:h.role,isSelfCoordinator:h.isSelfCoordinator,workspace:h.workspace||i.workspace}))}const m=[...p.values()];return m.length===0?i:{...i,activeSessionDetails:m,activeSessions:m.map(h=>h.sessionId)}});return n?{...e,nodes:o}:e}function Gk(e,t){const n=nm(e,t).map(a=>{var d;const o=(Array.isArray((d=e.status)==null?void 0:d.sessions)?e.status.sessions:[]).find(p=>bt(p==null?void 0:p.id)===a.sessionId),i=Yo(o==null?void 0:o.activeInteractivePrompt),c=o!=null&&o.meshQueueStats&&typeof o.meshQueueStats=="object"?JSON.stringify(o.meshQueueStats):"";return[a.sessionId,a.providerType??"",a.state??"",a.chatStatus??"",a.lifecycle??"",a.surfaceKind??"",a.recoveryState??"",bt(i.status)||bt(i.kind)||bt(i.type),a.nodeId??"",a.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(a=>!!a).sort();return n.length>0?n.join(`
81
+ `):null}function am({status:e,daemonId:t,extraDaemonIds:r,meshId:n,sendData:a,extraLiveSessions:o=[]}){const[i,c]=l.useState(new Map),d=l.useRef(new Map),p=l.useMemo(()=>{const b=new Set;if(t&&b.add(t),r)for(const g of r)g&&b.add(g);return[...b].sort()},[t,r]),u=p.join(",");l.useEffect(()=>{d.current=new Map,c(new Map)},[t,n]),l.useEffect(()=>{if(!n||!a||p.length===0)return;const b=p.map(g=>Zt.subscribe({sendData:a},g,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${g}`,params:{includeSessions:!0}},f=>{if(f.topic!=="daemon.metadata")return;const j=Gk(f,n);if(j===(d.current.get(g)??null))return;d.current.set(g,j);const N=nm(f,n);c(y=>{const v=new Map(y);return v.set(g,N),v})}));return()=>{for(const g of b)g()}},[u,n,a]);const m=l.useMemo(()=>{const b=[];for(const g of i.values())b.push(...g);return b},[i]),h=l.useMemo(()=>Kk(m,o),[o,m]);return l.useMemo(()=>e?Uk(e,h):null,[h,e])}const Kc=[1500,3e3,5e3,8e3,12e3];function Vk(e){var t,r,n,a,o,i;return!!(((t=e.git)==null?void 0:t.isGitRepo)===!0||(r=e.git)!=null&&r.branch||(n=e.git)!=null&&n.upstream||(a=e.git)!=null&&a.headCommit||(o=e.git)!=null&&o.workspace||(i=e.git)!=null&&i.repoRoot)}function qk(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>{var r;return Vk(t)?!1:t.gitProbePending||((r=t.connection)==null?void 0:r.state)==="connecting"?!0:t.machineStatus==="online"||t.launchReady===!0})}function Yk(e){return!Number.isInteger(e)||e<0?Kc[0]:Kc[e]??null}const po=new Map;function Jk(e,t){return!e||!t?null:`${e}::${t}`}function Xk(e,t){var o,i,c,d;if(!t||!e.sessionId)return null;const r=((o=e.coordinator)==null?void 0:o.meshId)??(typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),n=typeof((c=e.settings)==null?void 0:c.meshNodeFor)=="string"?e.settings.meshNodeFor:null;if(r!==t&&n!==t)return null;const a=typeof((d=e.settings)==null?void 0:d.meshNodeId)=="string"?e.settings.meshNodeId:null;return{sessionId:e.sessionId,aliases:Ui(e.sessionId,e.providerSessionId,e.historySessionId,e.nativeSessionId),meshId:t,nodeId:a,providerType:e.agentType,state:e.status,chatStatus:e.status,role:r===t?"coordinator":"worker",isSelfCoordinator:r===t,workspace:e.workspacePath??null}}function Qk({activeConv:e,sendDaemonCommand:t,onClose:r}){var D,M,E,z,Q,J;const n=((D=e.coordinator)==null?void 0:D.meshId)??(typeof((M=e.settings)==null?void 0:M.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),a=e.daemonId??null,o=Jk(a,n),i=o?po.get(o)??null:null,c=sp(),{sendData:d}=lt(),{theme:p}=Rs(),u=l.useMemo(()=>Ds(p),[p]),m=l.useMemo(()=>Xk(e,n),[e.agentType,(E=e.coordinator)==null?void 0:E.meshId,e.sessionId,(z=e.settings)==null?void 0:z.meshCoordinatorFor,(Q=e.settings)==null?void 0:Q.meshNodeFor,(J=e.settings)==null?void 0:J.meshNodeId,e.status,e.workspacePath,n]),[h,b]=l.useState(i),[g,f]=l.useState(!1),[j,N]=l.useState(!1),[y,v]=l.useState(null),[k,w]=l.useState((i==null?void 0:i.refreshedAt)??null),x=l.useRef(i!==null),C=l.useRef(!1),S=l.useRef(!1),I=l.useRef(!0),$=l.useRef(0),R=l.useRef(null);l.useEffect(()=>{x.current=h!==null},[h]);const _=l.useCallback(()=>{R.current!==null&&(clearTimeout(R.current),R.current=null)},[]);l.useEffect(()=>{_(),$.current=0;const ae=o?po.get(o)??null:null;b(ae),w((ae==null?void 0:ae.refreshedAt)??null),x.current=ae!==null,S.current=!1,N(!1),v(null)},[o,_]);const P=l.useCallback(async(ae=!1,ne=!1)=>{if(!a||!n){v("This coordinator does not expose a live mesh id."),b(null);return}if(C.current){ae&&(S.current=!0);return}ne||(_(),$.current=0),C.current=!0;const ce=!x.current;f(ce),N(ae&&x.current),v(null);try{const be=c!=null&&c.loadMeshStatus?await c.loadMeshStatus(a,n,{refresh:ae,retryProfile:"settled"}):await t(a,"mesh_status",{meshId:n,refresh:ae}),Z=Hp(be);if(!Z){v("mesh_status returned an unexpected payload.");return}if(o&&po.set(o,Z),b(Z),x.current=!0,w(Z.refreshedAt||new Date().toISOString()),qk(Z.nodes)){const Y=Yk($.current);Y!==null&&I.current&&($.current+=1,R.current=setTimeout(()=>{I.current&&P(!0,!0)},Y))}else $.current=0}catch(be){v(be instanceof Error?be.message:"Failed to load live mesh status")}finally{C.current=!1,f(!1),N(!1),S.current&&I.current&&(S.current=!1,window.setTimeout(()=>{I.current&&P(!0)},0))}},[o,_,a,n,c,t]);l.useEffect(()=>(I.current=!0,$.current=0,(async()=>(await P(!1),I.current&&R.current===null&&!C.current&&P(!0)))(),()=>{I.current=!1,_()}),[P,_]),l.useEffect(()=>{const ae=ne=>{ne.key==="Escape"&&r()};return window.addEventListener("keydown",ae),()=>window.removeEventListener("keydown",ae)},[r]);const F=(h==null?void 0:h.meshName)||n||"Repo Mesh",q=l.useMemo(()=>m?[m]:[],[m]),A=am({status:h,daemonId:a,meshId:n,sendData:d,extraLiveSessions:q}),T=k?new Date(k).toLocaleTimeString():null,B=l.useMemo(()=>g?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[g]);return s.jsx("div",{className:u.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:u.dialogShellClass,onClick:ae=>ae.stopPropagation(),children:[s.jsxs("div",{className:u.dialogHeaderClass,children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.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:s.jsx(rs,{size:18})}),s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("h2",{className:u.dialogTitleClass,children:F}),s.jsx("span",{className:u.dialogKickerClass,children:"Mesh observability"})]}),s.jsxs("p",{className:u.dialogSubtitleClass,children:[it(e),e.workspaceName?` · ${e.workspaceName}`:"",h!=null&&h.repoIdentity?` · ${h.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[T&&s.jsx("span",{className:u.dialogRefreshedChipClass,children:j?"Refreshing mesh...":`Refreshed ${T}`}),!j&&h&&s.jsx("span",{className:u.dialogRefreshedChipClass,children:d&&!y?"Live daemon metadata":"Metadata subscription unavailable"}),s.jsx("button",{type:"button",onClick:()=>{P(!0)},disabled:g||j,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:g||j?"Refreshing…":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:u.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:s.jsx(yt,{size:16})})]})]}),y&&s.jsx("div",{className:u.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:y}),s.jsx("div",{className:u.dialogBodyClass,children:A?s.jsx(rm,{status:A,emptyMessage:B,daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:u.dialogEmptyClass,children:B})})]})})}function Zk(e,t){const{sendCommand:r}=lt(),[n,a]=l.useState(null),[o,i]=l.useState(!1);l.useEffect(()=>{if(!e||!t){a(null);return}i(!0),r(e,"git_remote_url",{workspace:t}).then(d=>{const p=(d==null?void 0:d.result)??d;a(typeof(p==null?void 0:p.remoteUrl)=="string"?p.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>i(!1))},[e,t,r]);const c=e1(n);return{remoteUrl:n,githubUrl:c,loading:o}}function e1(e){if(!e)return null;const t=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(t)return`https://github.com/${t[1]}`;const r=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return r?`https://github.com/${r[1]}`:null}const om=5e3;function t1(e){return`git:${e}`}function s1({workspace:e,includeDiffSummary:t=!1,intervalMs:r=om}){return{type:"subscribe",topic:"workspace.git",key:t1(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function Gi(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function _s(e,t){if(e instanceof Error)return e.message;if(e&&typeof e=="object"){const r=e;if(typeof r.error=="string"&&r.error.trim())return r.error;if(typeof r.message=="string"&&r.message.trim())return r.message}return t}function r1(e){const t=Gi(e);return(t==null?void 0:t.success)===!1?{status:null,error:_s(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:_s(t,"Git status response did not include status")}}function n1(e){const t=Gi(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:_s(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:_s(t,"Git diff summary response did not include diffSummary")}}function mo(e){return e===void 0||typeof e=="boolean"}function a1(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&mo(t.binary)&&mo(t.truncated)&&mo(t.staged)}function o1(e){const t=Gi(e);return(t==null?void 0:t.success)===!1?{diff:null,error:_s(t,"Git file diff request failed")}:a1(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:_s(t,"Git file diff response did not include a valid diff object")}}function i1({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=om}){const{sendCommand:o,sendData:i}=lt(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[p,u]=l.useState(null),[m,h]=l.useState(null),[b,g]=l.useState(!1),[f,j]=l.useState(null),N=l.useCallback(async()=>{if(!(!d||!e||!c)){g(!0),j(null);try{const v=r1(await o(e,"git_status",{workspace:c}));if(v.error){u(null),h(null),j(v.error);return}if(u(v.status),!n){h(null);return}const k=n1(await o(e,"git_diff_summary",{workspace:c}));if(k.error){h(null),j(k.error);return}h(k.diffSummary)}catch(v){j(_s(v,"Git status request failed"))}finally{g(!1)}}},[d,e,n,o,c]),y=l.useMemo(()=>c?s1({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return l.useEffect(()=>{if(!d||!e||!c||!y){u(null),h(null),g(!1),j(null);return}const v=i?Zt.subscribe({sendData:i},e,y,k=>{var w,x;k.workspace===c&&(u(k.status),h(k.diffSummary??null),j(((w=k.status)==null?void 0:w.error)||((x=k.diffSummary)==null?void 0:x.error)||null),g(!1))},{retryIntervalMs:1e3}):null;return N(),()=>{v==null||v()}},[d,e,N,y,i,c]),{status:p,diffSummary:m,loading:b,error:f,refresh:N}}const l1={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},c1={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 Uc(e){return e.split("/").pop()??e}function d1(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function u1({files:e,truncated:t,onFileClick:r,selectedPath:n,className:a=""}){return e.length===0?s.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:"No changed files."}):s.jsxs("div",{className:`flex flex-col ${a}`,children:[s.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(o=>{const i=n===o.path,c=l1[o.status]??"?",d=c1[o.status]??"text-zinc-400",p=d1(o.path),u=Uc(o.path),m=o.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${i?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(o),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:o.status,children:c}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[p&&s.jsxs("span",{className:"text-text-secondary",children:[p,"/"]}),s.jsx("span",{className:"text-text-primary",children:u}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",Uc(o.oldPath)]}),m]}),!o.binary&&(o.insertions>0||o.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",o.insertions]}),o.insertions>0&&o.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),o.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",o.deletions]})]}),o.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${o.path}-${o.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function p1(e,t){let r="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?r="bg-emerald-500/10 text-emerald-300":e.startsWith("-")&&!e.startsWith("---")?r="bg-red-500/10 text-red-300":e.startsWith("@@")?r="text-sky-400":(e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ "))&&(r="text-text-secondary"),s.jsx("div",{className:`px-3 ${r}`,children:s.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},t)}function im({diff:e,binary:t,truncated:r,loading:n,error:a,className:o=""}){const i=l.useRef(null);if(l.useEffect(()=>{i.current&&(i.current.scrollTop=0)},[e]),n)return s.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${o}`,children:"Loading diff…"});if(a)return s.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${o}`,children:a});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"No diff available."});const c=e.split(`
82
+ `);return s.jsxs("div",{ref:i,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((d,p)=>p1(d,p))}),r&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary border-t border-border/30",children:["Diff truncated — run ",s.jsx("code",{className:"font-mono",children:"git diff"})," locally for full output."]})]})}function m1(e,t){const r=[`Branch: ${e||"unknown"}`];r.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const n={};for(const a of t.files)n[a.status]||(n[a.status]=[]),n[a.status].push(a.path);for(const[a,o]of Object.entries(n))r.push(`${a}: ${o.slice(0,5).join(", ")}${o.length>5?` (+${o.length-5} more)`:""}`);return r.join(`
83
+ `)}function lm({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=lt(),{status:a,diffSummary:o,loading:i,error:c,refresh:d}=i1({daemonId:e,workspace:t,includeDiffSummary:!0}),[p,u]=l.useState(null),[m,h]=l.useState(null),[b,g]=l.useState(""),[f,j]=l.useState(!1),[N,y]=l.useState(!1),[v,k]=l.useState(null),[w,x]=l.useState(null),{githubUrl:C}=Zk(e,t),S=l.useCallback(async F=>{if(!((p==null?void 0:p.path)===F.path&&!p.loading)){u({path:F.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const q=await n(e,"git_diff_file",{workspace:t,path:F.path,staged:F.staged}),A=o1(q);if(A.error||!A.diff){u({path:F.path,diff:"",binary:!1,truncated:!1,loading:!1,error:A.error??"Failed to load diff"});return}u({path:F.path,diff:A.diff.diff,binary:A.diff.binary??!1,truncated:A.diff.truncated??!1,loading:!1,error:null})}catch(q){const A=q instanceof Error?q.message:"Failed to load diff";u({path:F.path,diff:"",binary:!1,truncated:!1,loading:!1,error:A})}}},[e,n,p,t]),I=l.useCallback(F=>{g(""),j(!1),k(null),x(null),h(F)},[]),$=l.useCallback(()=>{h(null),k(null),y(!1)},[]),R=l.useCallback(async()=>{var F,q,A;if(m){y(!0),k(null);try{let T;m==="checkpoint"?T=await n(e,"git_checkpoint",{workspace:t,message:b,includeUntracked:f}):m==="stash"?T=await n(e,"git_stash_push",{workspace:t,message:b,includeUntracked:f}):m==="stash_pop"?T=await n(e,"git_stash_pop",{workspace:t}):m==="checkout_files"&&p&&(T=await n(e,"git_checkout_files",{workspace:t,paths:[p.path]}));const B=(T==null?void 0:T.result)??T;if((B==null?void 0:B.success)===!1||B!=null&&B.error){k((B==null?void 0:B.error)??"Action failed"),y(!1);return}m==="checkpoint"?x(`Checkpoint created: ${((q=(F=B==null?void 0:B.checkpoint)==null?void 0:F.commit)==null?void 0:q.slice(0,7))??"done"}`):m==="stash"?x(`Stashed as ${((A=B==null?void 0:B.stash)==null?void 0:A.stashRef)??"stash@{0}"}`):m==="stash_pop"?x("Stash restored"):(x("File reverted"),u(null)),h(null),await d()}catch(T){k(T instanceof Error?T.message:"Action failed")}finally{y(!1)}}},[m,n,e,t,b,f,p,d]),_=!!(a!=null&&a.hasConflicts),P=a?a.staged+a.modified+a.untracked+a.deleted+a.renamed:null;return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:F=>{F.target===F.currentTarget&&r()},children:s.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),C&&s.jsx("a",{href:`${C}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-sky-400 underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:d,disabled:i,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),s.jsx("button",{onClick:r,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(yt,{className:"h-4 w-4"})})]}),a&&s.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[a.headCommit&&s.jsxs("span",{title:a.headMessage??void 0,children:[s.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&s.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&s.jsxs("span",{className:"text-orange-400",children:["↑",a.ahead," ahead"]}),a.behind>0&&s.jsxs("span",{className:"text-orange-400",children:["↓",a.behind," behind"]}),a.staged>0&&s.jsxs("span",{className:"text-emerald-400",children:[a.staged," staged"]}),a.modified>0&&s.jsxs("span",{children:[a.modified," modified"]}),a.untracked>0&&s.jsxs("span",{children:[a.untracked," untracked"]}),a.deleted>0&&s.jsxs("span",{className:"text-red-400",children:[a.deleted," deleted"]}),a.stashCount>0&&s.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&s.jsx("span",{className:"font-bold text-red-400",children:"conflicts"}),P===0&&!a.error&&s.jsx("span",{className:"text-emerald-500",children:"clean"}),o&&o.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[o.files.length," file",o.files.length!==1?"s":"",o.totalInsertions>0&&s.jsxs("span",{className:"text-emerald-500",children:[" +",o.totalInsertions]}),o.totalDeletions>0&&s.jsxs("span",{className:"text-red-400",children:[" -",o.totalDeletions]})]})]}),c&&s.jsx("div",{className:"shrink-0 border-b border-border/50 bg-red-500/10 px-4 py-2 text-xs text-red-400",children:c}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[i&&!o&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),o&&s.jsx(u1,{files:o.files,truncated:o.truncated,selectedPath:(p==null?void 0:p.path)??null,onFileClick:S}),!i&&!o&&!c&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:p?s.jsx(im,{diff:p.diff,binary:p.binary,truncated:p.truncated,loading:p.loading,error:p.error,className:"h-full"}):s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),w&&s.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-emerald-500/10 px-4 py-2 text-xs text-emerald-400 flex items-center justify-between",children:[s.jsx("span",{children:w}),s.jsx("button",{onClick:()=>x(null),className:"ml-2 text-emerald-400 hover:text-text-primary",children:"×"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[s.jsx("button",{onClick:()=>I("checkpoint"),disabled:_,title:_?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),s.jsx("button",{onClick:()=>I("stash"),disabled:_,title:_?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),s.jsx("button",{onClick:()=>I("stash_pop"),disabled:_||!(a!=null&&a.stashCount),title:_?"Resolve conflicts before restoring a stash":a!=null&&a.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),s.jsx("button",{onClick:()=>I("checkout_files"),disabled:!p,title:p?`Revert changes to ${p.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"}),o&&o.files.length>0&&s.jsx("button",{onClick:()=>{const F=m1((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(F),x("Copied to clipboard"),setTimeout(()=>x(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),m&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[m==="checkpoint"&&"Create checkpoint commit",m==="stash"&&"Stash changes",m==="stash_pop"&&"Restore latest stash?",m==="checkout_files"&&`Revert changes to ${(p==null?void 0:p.path)??"file"}?`]}),(m==="checkpoint"||m==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:b,onChange:F=>g(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}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:f,onChange:F=>j(F.target.checked)}),"Include untracked files"]})]}),v&&s.jsx("p",{className:"text-xs text-red-400",children:v}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:$,disabled:N,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),s.jsx("button",{onClick:R,disabled:N||(m==="checkpoint"||m==="stash")&&!b.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:N?"Working…":"Confirm"})]})]})})]})})}function h1({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=l.useState(!1),[o,i]=l.useState(!1),[c,d]=l.useState(!1),[p,u]=l.useState(!1),[m,h]=l.useState(!1),[b,g]=l.useState("quickstart"),[f,j]=l.useState("workspace"),N=l.useMemo(()=>!t&&!e,[t,e]),y=l.useCallback(S=>{a(S),S&&i(!1)},[]),v=l.useCallback(S=>{i(S),S&&a(!1)},[]),k=l.useCallback(()=>{g(r===0?"quickstart":"shortcuts"),j("workspace"),d(!0),a(!1),i(!1)},[r]),w=l.useCallback(()=>{d(!1)},[]),x=l.useCallback(()=>{u(!0)},[]),C=l.useCallback(()=>{u(!1)},[]);return l.useEffect(()=>{if(!N){h(!1);return}h(!0);const S=window.setTimeout(()=>{h(!1)},1e4);return()=>window.clearTimeout(S)},[N]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:p,guideNudgeVisible:m,guideTab:b,shortcutSection:f,isDesktopDashboard:N,setGuideTab:g,setShortcutSection:j,handleInboxOpenChange:y,handleHiddenOpenChange:v,handleOpenShortcutHelp:k,closeShortcutHelp:w,openNewSession:x,closeNewSession:C}}function f1(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 x1(e){return e instanceof Error?e.message:String(e||"")}function b1(e){const t=x1(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function g1({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:i,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:p,mobileChatConversations:u,hiddenConversations:m,ides:h,actionLogs:b,sendDaemonCommand:g,setActionLogs:f,setCliViewModeOverrides:j,isStandalone:N,initialDataLoaded:y,userName:v,requestedMobileTabKey:k,onRequestedMobileTabConsumed:w,requestedMachineId:x,onRequestedMachineConsumed:C,requestedMobileSection:S,onRequestedMobileSectionConsumed:I,containerRef:$,isSplitMode:R,numGroups:_,groupSizes:P,groupedConvs:F,clearedTabs:q,focusedGroup:A,focusGroup:T,moveTabToGroup:B,splitTabRelative:D,closeGroup:M,handleResizeStart:E,groupActiveTabIds:z,setGroupActiveTab:Q,groupTabOrders:J,setGroupTabOrder:ae,toggleHiddenTab:ne,visibleConversations:ce,requestedDesktopTabKey:be,onRequestedDesktopTabConsumed:Z,onDesktopActiveTabChange:Y,onRequestScrollToBottom:ve,onHideConversation:ye,onShowHiddenConversation:xe,onShowAllHiddenConversations:Se,scrollToBottomRequest:ie,machineEntries:we,layoutProfile:pe,onBrowseMachineDirectory:W,onSaveMachineWorkspace:O,onLaunchMachineIde:V,onLaunchMachineProvider:oe,onListMachineMeshes:te,onLaunchMeshCoordinator:X,onListMachineSavedSessions:L,notifications:ue,notificationUnreadCount:H,liveSessionInboxState:le,onMarkNotificationRead:G,onMarkNotificationUnread:Le,onDeleteNotification:Te}){const Me=jt.useRef(null),{inboxOpen:He,hiddenOpen:qe,shortcutHelpOpen:Je,newSessionOpen:st,guideNudgeVisible:Xe,guideTab:ct,shortcutSection:at,isDesktopDashboard:ht,setGuideTab:Ae,setShortcutSection:ke,handleInboxOpenChange:Qe,handleHiddenOpenChange:Ue,handleOpenShortcutHelp:gt,closeShortcutHelp:U,openNewSession:K,closeNewSession:re}=h1({isMobile:t,showMobileChatMode:e,visibleConversationCount:ce.length}),[he,ge]=jt.useState(null),[je,ee]=jt.useState(null),se=jt.useCallback((me,Ee)=>{ge({daemonId:me,workspace:Ee})},[]),fe=jt.useCallback(me=>{ee(me)},[]),Ce=jt.useCallback(me=>{var Ee;Pr.flushSync(()=>{xe(me)}),(Ee=Me.current)==null||Ee.restoreHiddenTabToSavedLocation(me.tabKey)},[xe]),Pe=jt.useCallback(me=>{var kt;const Ee=u.find(De=>$o(De,me))||m.find(De=>$o(De,me));Ee&&(m.some(De=>De.tabKey===Ee.tabKey)&&Ce(Ee),Y(Ee.tabKey),(kt=Me.current)==null||kt.activateConversationTab(Ee.tabKey),ve(Ee.tabKey,"notification-open")),G(me.id),Qe(!1)},[Ce,m,u,Y,G,ve]),Ie=jt.useCallback(()=>{var Ee;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Ee=Me.current)==null||Ee.resetAllPanelsToMain(),Ue(!1))},[Ue]),Re=jt.useCallback(async me=>{var Bt;if(!r)return;const Ee=(Bt=r.modalButtons)==null?void 0:Bt[me];if(!Ee)return;const kt=js(r);if(!kt)return;const De=Ee.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),et=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(De);try{await g(kt,"resolve_action",{button:Ee,action:et?"approve":"reject",buttonIndex:me,...ws(r)})}catch(hs){b1(hs)||console.error("[Shortcut approval] Failed:",hs)}},[r,g]),{isMac:Be,actionDefinitions:_e,actionShortcuts:ze,shortcutListening:Ve,shortcutListeningDraft:ut,setShortcutListening:vt,setShortcutListeningDraft:ft,saveShortcuts:pt}=Vv({enabled:ht&&!Je,onTrigger:me=>{var Ee,kt,De,et,Bt,hs,Qr,Zr,en,tn,sn,rn,nn,an,fs,on;if(me==="openShortcutHelp"){gt();return}if(me==="openNewSession"){K();return}if(me==="hideCurrentTab"){r&&ye(r);return}if(me==="toggleHiddenTabs"){Ue(!qe);return}if(me==="openHistoryForActiveTab"){r&&!Ye(r)&&o(r);return}if(me==="openRemoteForActiveTab"){r&&!Ze(r)&&!Ye(r)&&i(r);return}if(me==="splitActiveTabRight"){(Ee=Me.current)==null||Ee.splitActiveTabRight();return}if(me==="splitActiveTabDown"){(kt=Me.current)==null||kt.splitActiveTabDown();return}if(me==="floatActiveTab"){(De=Me.current)==null||De.floatActiveTab();return}if(me==="popoutActiveTab"){(et=Me.current)==null||et.popoutActiveTab();return}if(me==="dockActiveTab"){(Bt=Me.current)==null||Bt.dockActiveTab();return}if(me==="focusLeftPane"){(hs=Me.current)==null||hs.focusLeftPane();return}if(me==="focusRightPane"){(Qr=Me.current)==null||Qr.focusRightPane();return}if(me==="focusUpPane"){(Zr=Me.current)==null||Zr.focusUpPane();return}if(me==="focusDownPane"){(en=Me.current)==null||en.focusDownPane();return}if(me==="moveActiveTabToLeftPane"){(tn=Me.current)==null||tn.moveActiveTabToLeftPane();return}if(me==="moveActiveTabToRightPane"){(sn=Me.current)==null||sn.moveActiveTabToRightPane();return}if(me==="moveActiveTabToUpPane"){(rn=Me.current)==null||rn.moveActiveTabToUpPane();return}if(me==="moveActiveTabToDownPane"){(nn=Me.current)==null||nn.moveActiveTabToDownPane();return}if(me==="triggerPrimaryApprovalAction"){Re(0);return}if(me==="triggerSecondaryApprovalAction"){Re(1);return}if(me==="triggerTertiaryApprovalAction"){Re(2);return}if(me==="setActiveTabShortcut"){(an=Me.current)==null||an.setShortcutForActiveTab();return}if(me==="selectPreviousGroupTab"){(fs=Me.current)==null||fs.activatePreviousTabInGroup();return}if(me==="selectNextGroupTab"){(on=Me.current)==null||on.activateNextTabInGroup();return}!r||!Ze(r)||Ye(r)||me==="toggleCliView"&&p(d==="chat"?"terminal":"chat")}}),Oe=jt.useCallback(()=>{U(),vt(null),ft([])},[U,vt,ft]),Et=jt.useMemo(()=>at==="all"?_e:_e.filter(me=>f1(me)===at),[_e,at]),de=jt.useCallback(()=>{const me=Object.fromEntries(_e.map(Ee=>[Ee.id,""]));pt(me)},[_e,pt]),$e=jt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const me=Object.fromEntries(_e.map(Ee=>[Ee.id,Ee.defaultShortcut]));pt(me)},[_e,pt]);return jt.useEffect(()=>{const me=Ee=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Ee.metaKey&&Ee.key.toLowerCase()==="w":Ee.ctrlKey&&Ee.key.toLowerCase()==="w")&&(Ee.preventDefault(),r&&ye&&ye(r))};return window.addEventListener("keydown",me),()=>window.removeEventListener("keydown",me)},[r,ye]),jt.useEffect(()=>{if(!Je||Ve)return;const me=Ee=>{Ee.key==="Escape"&&(Ee.preventDefault(),Oe())};return window.addEventListener("keydown",me,!0),()=>window.removeEventListener("keydown",me,!0)},[Oe,Je,Ve]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(Dg,{activeConv:r,wsStatus:n,isConnected:a,conversations:ce,hiddenConversations:m,onOpenHistory:o,onHideConversation:ye,onShowConversation:Ce,onShowAllHidden:Se,onResetPanelsToMain:Ie,notifications:ue,notificationUnreadCount:H,onOpenNotification:Pe,onMarkNotificationRead:G,onMarkNotificationUnread:Le,onDeleteNotification:Te,inboxOpen:He,onInboxOpenChange:Qe,hiddenOpen:qe,onHiddenOpenChange:Ue,onOpenNewSession:t?void 0:K,onOpenDashboardGuide:gt,guideNudgeVisible:Xe,actionShortcuts:ze,onOpenRemote:()=>{!r||Ze(r)||Ye(r)||i(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:p,onOpenGitDialog:se,onOpenMeshGraph:fe}),e?s.jsx(Dv,{conversations:u,hiddenConversations:m,ides:h,actionLogs:b,sendDaemonCommand:g,setActionLogs:f,setCliViewModeOverrides:j,isStandalone:N,userName:v,requestedActiveTabKey:k,onRequestedActiveTabConsumed:w,requestedMachineId:x,onRequestedMachineConsumed:C,requestedMobileSection:S,onRequestedMobileSectionConsumed:I,onOpenHistory:o,onOpenRemote:i,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Se,onHideConversation:ye,onOpenMeshGraph:fe,onOpenNewSession:K,liveSessionInboxState:le}):t?s.jsx(Wv,{containerRef:$,isSplitMode:R,numGroups:_,groupSizes:P,groupedConvs:F,clearedTabs:q,ides:h,actionLogs:b,sendDaemonCommand:g,setActionLogs:f,isStandalone:N,hasRegisteredMachines:we.length>0,userName:v,focusedGroup:A,focusGroup:T,moveTabToGroup:B,splitTabRelative:D,closeGroup:M,handleResizeStart:E,groupActiveTabIds:z,setGroupActiveTab:Q,groupTabOrders:J,setGroupTabOrder:ae,toggleHiddenTab:ne,onOpenNewSession:K,allowTabShortcuts:!1,liveSessionInboxState:le}):s.jsx(iw,{visibleConversations:ce,clearedTabs:q,ides:h,actionLogs:b,sendDaemonCommand:g,setActionLogs:f,isStandalone:N,hasRegisteredMachines:we.length>0,initialDataLoaded:y,userName:v,toggleHiddenTab:ne,actionShortcuts:ze,registerActionHandlers:me=>{Me.current=me},onActiveTabChange:Y,requestedActiveTabKey:be,onRequestedActiveTabConsumed:Z,onRequestScrollToBottom:ve,scrollToBottomRequest:ie,onOpenNewSession:K,liveSessionInboxState:le,layoutProfile:pe}),st&&s.jsx(bw,{machines:we,ides:h,onClose:re,onBrowseDirectory:W,onSaveWorkspace:O,onLaunchIde:V,onLaunchProvider:oe,onListMeshes:te,onLaunchMeshCoordinator:X,onListSavedSessions:L}),je&&s.jsx(Qk,{activeConv:je,sendDaemonCommand:g,onClose:()=>ee(null)}),he&&s.jsx(lm,{daemonId:he.daemonId,workspace:he.workspace,onClose:()=>ge(null)}),Je&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:Oe,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",onClick:me=>me.stopPropagation(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:Oe,"aria-label":"Close dashboard guide",children:s.jsx(yt,{size:14})})]}),s.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(me=>s.jsx("button",{type:"button",className:`btn btn-sm ${ct===me.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ae(me.id),children:me.label},me.id))}),ct==="overview"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Be?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),ct==="quickstart"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),ct==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(me=>s.jsx("button",{type:"button",className:`btn btn-sm ${at===me.id?"btn-primary":"btn-secondary"}`,onClick:()=>ke(me.id),children:me.label},me.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:de,children:"Disable all"}),s.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:$e,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Et.map(me=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Ve===me.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:me.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:me.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:me.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:Ve===me.id?ut.length>0?`${ut.join(" ")} ...`:"Listening...":ze[me.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{vt(me.id),ft([])},children:Ve===me.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Ee={...ze};Ee[me.id]="",pt(Ee)},children:"Disable"})]})]})},me.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Be?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",", or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs."]})]})]})})]})}const ho=[{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 y1({onClose:e}){const[t,r]=l.useState(0),n=ho[t],a=t===ho.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:o=>{o.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(yt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:ho.map((o,i)=>s.jsx("div",{style:{width:i===t?24:8,height:8,borderRadius:4,background:i===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},i))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx("span",{children:n.icon})," ",n.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&s.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>a?e():r(o=>o+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
84
+ @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
85
+ @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
86
+ `})]})}function v1({hasExtensions:e,ideName:t,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?s.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[s.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${r==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a("native"),children:t}),n.map(o=>{const i=r===o.tabKey,c=o.status==="waiting_approval",d=o.status==="generating";return s.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${i?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(o.tabKey),children:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:c?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),o.title,c&&s.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},o.tabKey)})]}):null}function w1({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,i]=l.useState(()=>a||"native"),c=l.useMemo(()=>Iu(t),[t]),d=l.useMemo(()=>e?ji(e,{machineNames:c,connectionStates:r,defaultConnectionState:"new"}):[],[e,c,r]),p=l.useMemo(()=>d.find(f=>f.streamSource==="native"),[d]),u=l.useMemo(()=>d.filter(f=>f.streamSource==="agent-stream"),[d]),m=l.useMemo(()=>e?Kt(d,e.id):null,[d,e]);l.useEffect(()=>{a&&i(a)},[a]),l.useEffect(()=>{if(a||!m)return;const f=m.streamSource==="native"?"native":m.tabKey;!f||o===f||o==="native"&&i(f)},[o,m,a]),l.useEffect(()=>{var f;o!=="native"&&(u.some(j=>j.tabKey===o)||i(((f=u[0])==null?void 0:f.tabKey)||"native"))},[o,u]),l.useEffect(()=>{o==="native"&&(p||u[0]&&i(u[0].tabKey))},[o,p,u]);const h=l.useMemo(()=>o==="native"&&p?p:u.find(f=>f.tabKey===o)||m||p||u[0],[o,p,m,u]),b=l.useMemo(()=>u.map(f=>({tabKey:f.tabKey,title:bu(f)||n,status:f.status})),[u,n]),g=l.useCallback(f=>{if(f)return d.find(j=>$o(j,{sessionId:f,routeId:f,tabKey:f,providerSessionId:f}))},[d]);return{activeChatTab:o,setActiveChatTab:i,activeConv:h,conversations:d,extensionTabs:b,hasExtensions:b.length>0,resolveConversationByTarget:g}}function j1({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:i,isStandalone:c,userName:d,onOpenHistory:p,onConversationChange:u,onClose:m}){const[h,b]=l.useState("split"),[g,f]=l.useState(()=>ms(e)?"native":e.tabKey),j=l.useRef(null),N=l.useMemo(()=>t||r.find(T=>T.id===e.routeId),[e.routeId,t,r]),y=l.useMemo(()=>Nt((N==null?void 0:N.type)||""),[N==null?void 0:N.type]),{conversations:v,extensionTabs:k,hasExtensions:w}=w1({ideData:N,allIdes:r,connectionStates:n,ideName:y||"IDE",preferredTabKey:ms(e)?void 0:e.tabKey}),x=l.useMemo(()=>N?Kt(v,N.id):null,[N,v]);l.useEffect(()=>{const T=j.current,B={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(j.current=B,!(T&&T.routeId===B.routeId&&T.tabKey===B.tabKey&&T.streamSource===B.streamSource)){if(ms(e)){f("native");return}f(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),l.useEffect(()=>{if(g==="native"){if(v.some(T=>T.streamSource==="native"))return;(x==null?void 0:x.streamSource)==="agent-stream"&&f(x.tabKey);return}if(!v.some(T=>T.tabKey===g)){if((x==null?void 0:x.streamSource)==="agent-stream"){f(x.tabKey);return}f("native")}},[v,g,x]);const C=l.useMemo(()=>g==="native"?v.find(T=>T.streamSource==="native")||e:v.find(T=>T.tabKey===g)||e,[e,v,g]),S=Fu(C),I=l.useMemo(()=>S.status||S.modalMessage||S.modalButtons?{...C,...S.status?{status:S.status}:{},...S.modalMessage!==void 0?{modalMessage:S.modalMessage}:{},...S.modalButtons!==void 0?{modalButtons:S.modalButtons}:{}}:C,[C,S]),$=Kr(I),R=ga({sendDaemonCommand:o,activeConv:I,setActionLogs:i,isStandalone:c}),{connScreenshot:_,screenshotUsage:P,handleRemoteAction:F}=xp({doId:$,targetSessionId:eu(I),connState:I.connectionState||"new",viewMode:h}),q=l.useMemo(()=>a.filter(T=>T.routeId===I.tabKey),[a,I.tabKey]);l.useEffect(()=>{u==null||u(I)},[I,u]),l.useEffect(()=>{const T=B=>{B.key==="Escape"&&m()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[m]);const A=l.useCallback(T=>{T.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:m,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:A,children:[s.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[s.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Gt,{size:16})}),s.jsx("span",{className:"truncate",children:hi(C)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:m,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(T=>{const B=h===T;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${B?"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:()=>b(T),title:T==="split"?"Split view":"Remote only",children:T==="split"?s.jsx(Hh,{size:15}):s.jsx(Gt,{size:15})},T)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>p(C),title:"Chat History",children:[s.jsx(ni,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:m,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${h==="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:[h!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${h==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(v1,{hasExtensions:w,ideName:y||"IDE",activeChatTab:g,extensionTabs:k,onSelectTab:f}),s.jsx(Fd,{activeConv:I,onModalButton:R.handleModalButton}),s.jsx(Oo,{activeConv:I,ideEntry:N,showMetaChips:!1,handleSendChat:R.handleSendChat,handleForceSendChat:R.handleForceSendChat,isSendingChat:R.isSendingChat,sendFeedbackMessage:R.sendFeedbackMessage,handleFocusAgent:R.handleFocusAgent,isFocusingAgent:R.isFocusingAgent,actionLogs:q,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${h==="split"?"order-1 md:order-2":""}`,children:s.jsx(Dd,{addLog:()=>{},connState:I.connectionState||"new",connScreenshot:_,screenshotUsage:P,transportType:I.transport,onAction:F})})]})]})})}function k1({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=fg(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[s.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",o,"?"]}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:t?"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.":"This provider does not support graceful stop. Force Stop will end the runtime immediately."})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&s.jsx("button",{onClick:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),s.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:"Force Stop"}),s.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function N1({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o,interactivePrompt:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(Tg,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(Su,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,missingWorkspaceResumePath:e.missingWorkspaceResumePath,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),t.conversation&&s.jsx(j1,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose}),r.open&&r.targetConv&&(Ze(r.targetConv)||Ye(r.targetConv))&&s.jsx(k1,{activeConv:r.targetConv,canSaveAndStop:Ze(r.targetConv)&&!Ye(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(Cu,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),s.jsx(Ed,{promptSession:(i==null?void 0:i.promptSession)??null,isSubmitting:(i==null?void 0:i.isSubmitting)??!1,error:(i==null?void 0:i.responseError)??null,onSubmit:(i==null?void 0:i.submit)??(async()=>{}),onCancel:(i==null?void 0:i.cancel)??(()=>{})}),o.open&&s.jsx(y1,{onClose:o.onClose})]})}function S1({daemons:e,targetVersion:t,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:o}){return e.length===0?null:s.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:r?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:r?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[s.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:s.jsx(ha,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[r?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(i=>{const c=$t(i,{fallbackId:i.id}),d=n[i.id],p=i.version||i.daemonVersion||"unknown",u=i.versionUpdateRequired===!0,h=Zu(i)==="preview"?"Update to preview":u?"Update now":"Upgrade";return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:c}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",p]}),u&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),d==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:u?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):d==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(i.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:u?"var(--status-danger)":"var(--status-warning)",background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(i.id),children:h})]},i.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:s.jsx(yt,{size:16})})]})}function C1(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function I1(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 M1(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>I1(t)).map(t=>t.id)}}function A1(){var Zi,el,tl,sl;const{sendCommand:e}=lt(),t=Ur(),r=Bu(),n=ti(),a=zr(),[o,i]=ah(),c=o.get("activeTab"),d=((Zi=n.state)==null?void 0:Zi.openRemoteForTabKey)||null,p=((el=n.state)==null?void 0:el.openMachineId)||null,u=((tl=n.state)==null?void 0:tl.mobileSection)||null,m=mu(),h=m.ides||[],b=m.initialLoaded??!0,{updateRouteChats:g,setToasts:f}=m,[j,N]=l.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),y=m.toasts||[],v=m.wsStatus||"connected",k=m.isConnected??!0,w=m.connectionStates||{},x=m.showReconnected||!1,{layoutProfile:C,groupAssignments:S,updateGroupAssignments:I,focusedGroup:$,updateFocusedGroup:R,focusGroup:_,groupActiveTabIds:P,updateGroupActiveTabIds:F,setGroupActiveTab:q,groupTabOrders:A,updateGroupTabOrders:T,setGroupTabOrder:B,groupSizes:D,updateGroupSizes:M,isMobile:E,hasHydratedStoredLayout:z,hydrateStoredLayout:Q,focusConversationTab:J}=Ay(),[ae,ne]=l.useState(()=>Ci());l.useEffect(()=>R0(ne),[]);const ce=l.useMemo(()=>C1({isMobile:E,mobileViewMode:ae}),[E,ae]),[be,Z]=l.useState([]),[Y,ve]=l.useState({}),[ye,xe]=l.useState({});Wr("Dashboard",{ideCount:h.length,toastCount:y.length,focusedGroup:$,groupCount:Object.keys(S).length,actionLogCount:be.length});const Se=l.useMemo(()=>h.filter(We=>We.type==="adhdev-daemon").sort(ui),[h]),we=!!Se[0];l.useEffect(()=>{const{metadataDaemonIds:We,runtimeDaemonIds:Ft}=M1(Se);for(const rr of We)t(rr,{minFreshMs:3e4}).catch(()=>{});for(const rr of Ft)r(rr,{minFreshMs:3e4}).catch(()=>{})},[t,r,Se]);const pe=l.useMemo(()=>ty(h,Y),[h,Y]),{hiddenTabs:W,autoHiddenTabs:O,autoHideTarget:V,hideTarget:oe,toggleTarget:te,showTarget:X,showAllTabs:L}=G0(),{conversations:ue,visibleConversations:H,visibleTabKeys:le,resolveConversationBySessionId:G,resolveConversationByTarget:Le}=hy({ides:pe,connectionStates:w,clearedTabs:ye,hiddenTabs:W}),Te=l.useMemo(()=>new Map(ue.map(We=>[We.tabKey,We])),[ue]),Me=l.useMemo(()=>U0(ue,W,O),[ue,W,O]);l.useEffect(()=>{for(const We of Me)V(We)},[Me,V]),zb(H,ce),l.useEffect(()=>{Object.keys(Y).length!==0&&ve(We=>sy(We,h))},[h,Y]);const He=l.useMemo(()=>Hf(h),[h]),{notifications:qe,unreadCount:Je}=Uy({conversations:ue,liveSessionInboxState:He}),{handleMarkDashboardNotificationRead:st,handleMarkDashboardNotificationUnread:Xe,handleDeleteDashboardNotification:ct}=Gy({notifications:qe,sendDaemonCommand:e}),{containerRef:at,normalizedGroupAssignments:ht,numGroups:Ae,isSplitMode:ke,groupedConvs:Qe,moveTabToGroup:Ue,closeGroup:gt,handleResizeStart:U,splitTabRelative:K}=$y({groupAssignments:S,updateGroupAssignments:I,updateFocusedGroup:R,updateGroupActiveTabIds:F,updateGroupTabOrders:T,groupSizes:D,updateGroupSizes:M,isMobile:E,visibleConversations:H,visibleTabKeys:le}),{activeConv:re,openDesktopConversation:he,requestScrollToBottom:ge,scrollToBottomRequest:je,setDesktopActiveTab:ee}=ov({isMobile:E,conversations:ue,visibleConversations:H,groupActiveTabIds:P,focusedGroup:$,groupedConvs:Qe,setSearchParams:i});cv({activeConv:re,isMobile:E,liveSessionInboxState:He,sendDaemonCommand:e});const{requestedDesktopTabKey:se,requestedMobileTabKey:fe,consumeRequestedActiveTab:Ce}=fy({isMobile:E,urlActiveTab:c,resolveConversationBySessionId:G,setSearchParams:i}),{remoteDialogConv:Pe,remoteDialogIdeEntry:Ie,remoteDialogActiveConv:Re,setRemoteDialogActiveConv:Be,openRemoteDialog:_e,closeRemoteDialog:ze,cliStopDialogOpen:Ve,cliStopTargetConv:ut,requestCliStop:vt,cancelCliStop:ft,confirmCliStop:pt}=pv({isMobile:E,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:se,conversations:ue,ides:h,resolveConversationByTarget:Le,activeConv:re,sendDaemonCommand:e}),{historyModalOpen:Oe,openHistoryModal:Et,closeHistoryModal:de,historyTargetConv:$e,isSavedSessionHistoryTarget:me,isHistoryCreatingChat:Ee,isHistoryRefreshingHistory:kt,handleHistorySwitchSession:De,handleHistoryNewChat:et,handleHistoryRefresh:Bt,savedHistorySessions:hs,savedHistoryFilters:Qr,setSavedHistoryFilters:Zr,missingWorkspaceResumePath:en,isSavedHistoryLoading:tn,resumingSavedHistorySessionId:sn,handleRefreshSavedHistory:rn,handleResumeSavedHistorySession:nn}=dv({activeConv:re,remoteDialogConv:Pe,remoteDialogActiveConv:Re,ides:h,sendDaemonCommand:e,updateRouteChats:g,setToasts:f,setClearedTabs:xe,setSearchParams:i}),an=l.useMemo(()=>H,[H]),fs=E&&ae==="chat",on=l.useMemo(()=>ue.filter(We=>wa(W,We)),[ue,W]),Ji=l.useCallback(We=>{const Ft=new URLSearchParams(o);Ft.set("activeTab",We),i(Ft,{replace:!0})},[o,i]),{trackPendingLaunch:bm}=sv({ides:h,conversations:ue,onOpenSession:Ji}),{handleBrowseMachineDirectory:gm,handleSaveMachineWorkspace:ym,handleLaunchMachineIde:vm,handleLaunchMachineProvider:wm,handleListMachineMeshes:jm,handleLaunchMeshCoordinator:km,handleListMachineSavedSessions:Nm,setActiveCliViewMode:Sm}=rv({sendDaemonCommand:e,trackPendingLaunch:bm,onOpenSession:Ji,activeConv:re,ides:h,setCliViewModeOverrides:ve});ry({visibleConversations:H,clearedTabs:ye,setClearedTabs:xe,setActionLogs:Z}),xy({ides:h,sendDaemonCommand:e,setToasts:f,resolveConversationByTarget:Le});const Cm=Wu(),{isRefreshingHistory:Im,handleRefreshHistory:Mm}=Qu({sendDaemonCommand:e,activeConv:re,chats:(sl=h.find(We=>We.id===(re==null?void 0:re.routeId)))==null?void 0:sl.chats,updateRouteChats:g,setToasts:f,setClearedTabs:xe});_y({urlActiveTab:E&&!fs?c:null,conversations:ue,resolveConversationBySessionId:G,normalizedGroupAssignments:ht,hasHydratedStoredLayout:E&&!fs?z:!0,hydrateStoredLayout:E&&!fs?Q:()=>{},focusConversationTab:J,setSearchParams:i,historyModalOpen:Oe,activeConv:re,isRefreshingHistory:Im,ides:h,handleRefreshHistory:Mm});const Am=l.useMemo(()=>!re||!Ze(re)||Ye(re)?null:sr(re),[re]),{versionMismatchDaemons:Tm,hasRequiredVersionDaemons:Xi,targetVersion:_m,versionBannerDismissed:Lm,setVersionBannerDismissed:Pm,upgradingDaemons:Rm,handleBannerUpgrade:Dm}=By({ides:h,sendDaemonCommand:e}),Qi=l.useCallback(We=>{X(We),he(We)},[he,X]),$m=l.useCallback(We=>{oe(We)},[oe]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[(!Lm||Xi)&&s.jsx(S1,{daemons:Tm,targetVersion:_m,required:Xi,upgradingDaemons:Rm,onUpgrade:Dm,onDismiss:()=>Pm(!0)}),s.jsx(g1,{showMobileChatMode:fs,isMobile:E,activeConv:re,wsStatus:v,isConnected:k,onOpenHistory:We=>{We&&Be(We),Et()},onOpenRemote:_e,onStopCli:vt,activeCliViewMode:Am,onSetActiveCliViewMode:Sm,mobileChatConversations:an,ides:h,actionLogs:be,sendDaemonCommand:e,setActionLogs:Z,setCliViewModeOverrides:ve,isStandalone:we,initialDataLoaded:b,userName:m.userName,requestedMobileTabKey:fe,onRequestedMobileTabConsumed:Ce,requestedMachineId:p,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:u,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:at,isSplitMode:ke,numGroups:Ae,groupSizes:D,groupedConvs:Qe,clearedTabs:ye,focusedGroup:$,focusGroup:_,moveTabToGroup:Ue,splitTabRelative:K,closeGroup:gt,handleResizeStart:U,groupActiveTabIds:P,setGroupActiveTab:q,groupTabOrders:A,setGroupTabOrder:B,toggleHiddenTab:We=>te(Te.get(We)||{tabKey:We}),visibleConversations:H,hiddenConversations:on,requestedDesktopTabKey:se,onRequestedDesktopTabConsumed:Ce,onDesktopActiveTabChange:ee,onRequestScrollToBottom:ge,onHideConversation:$m,onShowHiddenConversation:Qi,onShowAllHiddenConversations:L,scrollToBottomRequest:je,machineEntries:Se,layoutProfile:C,onBrowseMachineDirectory:gm,onSaveMachineWorkspace:ym,onLaunchMachineIde:vm,onLaunchMachineProvider:wm,onListMachineMeshes:jm,onLaunchMeshCoordinator:km,onListMachineSavedSessions:Nm,notifications:qe,notificationUnreadCount:Je,liveSessionInboxState:He,onMarkNotificationRead:st,onMarkNotificationUnread:Xe,onDeleteNotification:ct}),s.jsx("style",{children:`
87
+ body { overflow: hidden; overscroll-behavior: none; }
88
+ `}),s.jsx(N1,{historyModal:{open:Oe,targetConv:$e,ides:h,isCreatingChat:Ee,isRefreshingHistory:me?!1:kt,savedSessions:hs,savedHistoryFilters:Qr,missingWorkspaceResumePath:en||null,onSavedHistoryFiltersChange:Zr,isSavedSessionsLoading:tn,isResumingSavedSessionId:sn,onClose:de,onNewChat:et,onSwitchSession:De,onRefreshHistory:me?rn:Bt,onResumeSavedSession:nn},remoteDialog:{conversation:Pe,ideEntry:Ie,ides:h,connectionStates:w,actionLogs:be,sendDaemonCommand:e,setActionLogs:Z,isStandalone:we,userName:m.userName,onOpenHistory:We=>{We&&Be(We),Et()},onConversationChange:Be,onClose:ze},cliStopDialog:{open:Ve,targetConv:ut,onCancel:ft,onStopNow:async()=>{await pt("hard")},onSaveAndStop:async()=>{await pt("save")}},connectionBanner:{wsStatus:v,showReconnected:x,loginUrl:m.connectionLoginUrl,onReconnect:m.retryServerConnection},toastOverlay:{toasts:y,onDismiss:We=>f(Ft=>Ft.filter(rr=>rr.id!==We)),onClick:We=>{if(We.targetKey){const Ft=Le(We.targetKey);Ft&&(J(Ft.tabKey,ht),Qi(Ft),ge(Ft.tabKey,"toast-open"))}}},onboarding:{open:j,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}N(!1)}},interactivePrompt:Cm})]})}function T1({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const{launchCli:o}=pa(),[i,c]=l.useState([]),[d,p]=l.useState(null),[u,m]=l.useState(null),[h,b]=l.useState(!1),[g,f]=l.useState(null),[j,N]=l.useState(!1),[y,v]=l.useState(""),k=l.useRef(null),w=l.useCallback(M=>{k.current=M},[]),x=l.useCallback((M,E,z=!1)=>{c(Q=>[...Q.slice(-100),{timestamp:Date.now(),level:M,message:E}]),setTimeout(()=>{var Q;return(Q=a.current)==null?void 0:Q.scrollIntoView({behavior:"smooth"})},100),z&&tt.showToast(E,M==="error"||M==="warn"?"warning":"success")},[a]),C=l.useCallback(M=>{const E=M instanceof Error?M.message:String(M||"");return E.includes("P2P command timeout")||E.includes("P2P not connected")||E.includes("P2P not available")},[]),S=l.useCallback(async(M,E)=>{var z;if(!e||d)return!1;p(M),x("info",`Launching ${Nt(M)}${E!=null&&E.workspace?` in ${E.workspace}`:""}...`);try{const Q={ideType:M,enableCdp:!0};(z=E==null?void 0:E.workspace)!=null&&z.trim()?Q.workspace=E.workspace.trim():E!=null&&E.useDefaultWorkspace&&(Q.useDefaultWorkspace=!0);const J=await r(e,"launch_ide",Q);return x(J!=null&&J.success?"info":"error",J!=null&&J.success?`${Nt(M)} launched`:`Failed: ${J==null?void 0:J.error}`,!0),!!(J!=null&&J.success)}catch(Q){return x("error",`Launch error: ${Q.message}`,!0),!1}finally{p(null)}},[e,d,x,r]),I=l.useCallback(async M=>{if(!e)return{success:!1};const{cliType:E,dir:z,workspaceId:Q,useDefaultWorkspace:J,useHome:ae,argsStr:ne,model:ce,resumeSessionId:be}=M;if(!E)return x("warn","Select a CLI or ACP provider first",!0),{success:!1};const Z=ne?ne.split(/\s+/).filter(Boolean):void 0,Y=(z==null?void 0:z.trim())||(Q?"(saved id)":J?"(default workspace)":ae?"(home)":"");x("info",`Launching ${E}${Y?` in ${Y}`:""}${ce?` (model: ${ce})`:""}...`),m(E);try{const ve={cliType:E,cliArgs:Z,initialModel:ce||void 0};z!=null&&z.trim()?ve.dir=z.trim():Q?ve.workspaceId=Q:J?ve.useDefaultWorkspace=!0:ae&&(ve.useHome=!0),be&&(ve.resumeSessionId=be);const ye=await o(e,ve),xe=(ye==null?void 0:ye.result)||ye;return ye!=null&&ye.success?(x("info",`${E} launched`,!0),(xe==null?void 0:xe.launchSource)==="home"?x("info","📂 Running in home directory (explicit choice)"):(xe==null?void 0:xe.launchSource)==="defaultWorkspace"&&x("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:xe==null?void 0:xe.sessionId}):(x("error",`Failed: ${(ye==null?void 0:ye.error)||(xe==null?void 0:xe.error)}`,!0),(ye==null?void 0:ye.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&f({cliType:E,argsStr:ne,model:ce}),{success:!1,sessionId:xe==null?void 0:xe.sessionId})}catch(ve){return C(ve)?(x("warn",`${E} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(x("error",`Launch error: ${ve.message}`,!0),{success:!1})}finally{m(null)}},[e,x,C,r]),$=l.useCallback(async(M,E,z,Q)=>e?M?E.trim()?I({cliType:M,dir:E,argsStr:z,model:Q}):(f({cliType:M,argsStr:z,model:Q}),{success:!1}):(x("warn","Select a provider",!0),{success:!1}):{success:!1},[e,x,I]),R=l.useCallback(async(M,E,z)=>{if(e&&window.confirm(`Stop ${M}?
89
+ This will terminate the process.`))try{const Q=await r(e,"stop_cli",{cliType:M,dir:E,targetSessionId:z});Q!=null&&Q.success?x("info",`${M} stopped`,!0):x("error",`Stop failed: ${(Q==null?void 0:Q.error)||"Unknown error"}`,!0)}catch(Q){x("error",`Stop failed: ${Q.message}`,!0)}},[e,x,r]),_=l.useCallback(async M=>{try{await r(M.daemonId,"restart_ide",{ideType:M.type}),x("info",`${Nt(M.type)} restart initiated`,!0)}catch(E){x("error",`Restart failed: ${E.message}`,!0)}},[x,r]),P=l.useCallback(async M=>{if(window.confirm(`Stop ${Nt(M.type)}?
90
+ This will disconnect CDP and optionally kill the process.`))try{const E=await r(M.daemonId,"stop_ide",{ideType:M.type,killProcess:!0});E!=null&&E.success?x("info",`${Nt(M.type)} stopped`,!0):x("error",`Stop failed: ${(E==null?void 0:E.error)||"Unknown error"}`,!0)}catch(E){x("error",`Stop failed: ${E.message}`,!0)}},[x,r]),F=l.useCallback(async()=>{if(e)try{const M=await r(e,"detect_ides",{});x("info",`Found ${((M==null?void 0:M.result)||[]).length} IDE(s)`,!0)}catch(M){x("error",`Detection failed: ${M.message}`,!0)}},[e,x,r]),q=l.useCallback(async M=>{if(!e||!M.trim())return!1;b(!0);try{const E=await r(e,"workspace_add",{path:M.trim()});return E!=null&&E.success?(x("info",`Workspace added: ${M.trim()}`),!0):(x("error",(E==null?void 0:E.error)||"workspace_add failed"),!1)}catch(E){return x("error",E.message),!1}finally{b(!1)}},[e,x,r]),A=l.useCallback(async M=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){b(!0);try{const E=await r(e,"workspace_remove",{id:M});E!=null&&E.success?x("info","Workspace removed",!0):x("error",(E==null?void 0:E.error)||"workspace_remove failed",!0)}catch(E){x("error",E.message,!0)}finally{b(!1)}}},[e,x,r]),T=l.useCallback(async M=>{var E;if(e){b(!0);try{const z=await r(e,"workspace_set_default",M===null?{clear:!0}:{id:M});if(z!=null&&z.success){x("info",M?"Default workspace updated":"Default workspace cleared",!0);const Q=typeof z.defaultWorkspacePath=="string"?z.defaultWorkspacePath:"";Q&&((E=k.current)==null||E.call(k,Q))}else x("error",(z==null?void 0:z.error)||"workspace_set_default failed",!0)}catch(z){x("error",z.message,!0)}finally{b(!1)}}},[e,x,r]),B=l.useCallback(async M=>{var z;if(!e||!M.trim())return;const E=M.trim();b(!0);try{const Q=await r(e,"workspace_set_default",{path:E});Q!=null&&Q.success?(x("info","Default workspace set from history"),(z=k.current)==null||z.call(k,E)):x("error",(Q==null?void 0:Q.error)||"Could not set default (path missing on disk?)")}catch(Q){x("error",Q.message)}finally{b(!1)}},[e,x,r]),D=l.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:y}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:y})}catch(M){x("warn",`Live nickname updated, but account sync failed: ${M.message}`)}x("info",`Nickname set to "${y||"(cleared)"}"`),N(!1)}catch(M){x("error",`Failed: ${M.message}`)}},[e,y,t,x,n,r]);return{logs:i,launchingIde:d,launchingAgentType:u,workspaceBusy:h,launchPick:g,setLaunchPick:f,editingNickname:j,setEditingNickname:N,nicknameInput:y,setNicknameInput:v,addLog:x,handleLaunchIde:S,runLaunchCliCore:I,handleLaunchCli:$,handleStopCli:R,handleRestartIde:_,handleStopIde:P,handleDetectIdes:F,handleWorkspaceAdd:q,handleWorkspaceRemove:A,handleWorkspaceSetDefault:T,handleWorkspaceResumePath:B,handleSaveNickname:D,setOnDefaultWorkspaceChanged:w}}function _1({machine:e,ideSessions:t,cliSessions:r,acpSessions:n}){var d;const a=typeof e.uptime=="number"||typeof e.freeMem=="number"||typeof e.availableMem=="number"||Array.isArray(e.loadavg)&&e.loadavg.length>0,o=e.availableMem??e.freeMem??e.totalMem,i=a&&e.totalMem>0?Math.min(100,Math.max(0,Math.round((e.totalMem-o)/e.totalMem*100))):0,c=((d=e.loadavg)==null?void 0:d[0])||0;return s.jsxs("div",{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[s.jsx(dn,{icon:s.jsx(kd,{size:16}),label:"Uptime",value:typeof e.uptime=="number"?qf(e.uptime):"Waiting…"}),s.jsx(dn,{icon:s.jsx(Gt,{size:16}),label:"IDEs",value:`${t.length}`}),s.jsx(dn,{icon:s.jsx(oi,{size:16}),label:"CLIs",value:`${r.length}`}),s.jsx(dn,{icon:s.jsx(Kh,{size:16}),label:"ACPs",value:`${n.length}`})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),s.jsxs("div",{className:"flex gap-6",children:[s.jsx(bl,{value:a?Math.min(Math.round(c/e.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:a?`${c.toFixed(2)} avg / ${e.cpus} cores`:"Polled from machine page"}),s.jsx(bl,{value:i,max:100,label:"Memory",color:"#3b82f6",detail:a?`${Da(e.totalMem-o)} / ${Da(e.totalMem)}${e.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Da(e.totalMem)} total`})]})]})]})}function L1(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t;return!r.settings||typeof r.settings!="object"?null:{settings:r.settings,values:r.values&&typeof r.values=="object"?r.values:{}}}function P1(e,t,r){const n=[];for(const[a,o]of Object.entries(e.settings)){const i=r!=null&&r.filterSchema?r.filterSchema(o):o;if(i.length===0)continue;const c=t.find(d=>d.type===a);n.push({type:a,displayName:(c==null?void 0:c.displayName)||a,icon:(c==null?void 0:c.icon)||"",category:(c==null?void 0:c.category)||"unknown",schema:i,values:e.values[a]||{}})}return n}function fo(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 Gc(e){if(!e||typeof e!="object")return null;if(fo(e))return e;const t=e,r=t.result;return fo(r)?r:fo(t.sourceConfig)?t.sourceConfig:null}function R1(e){const t=e.trim();return t||null}function D1({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var w;const o=t.filter(x=>x.category==="ide"),[i,c]=l.useState(((w=o[0])==null?void 0:w.type)||""),[d,p]=l.useState(""),[u,m]=l.useState(""),[h,b]=l.useState(!1),[g,f]=l.useState(""),[j,N]=l.useState(!1),y=x=>{const C=x.toLowerCase().replace(/[^a-z0-9-]/g,"");p(C),(!u||u===v(d))&&m(v(C))},v=x=>x.split("-").map(C=>C.charAt(0).toUpperCase()+C.slice(1)).join(" "),k=async()=>{if(!(!d||!u||!i)){b(!0),f("");try{const x=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:i});x!=null&&x.success||x!=null&&x.created?(N(!0),a==null||a(d)):f((x==null?void 0:x.error)||"Failed to create provider")}catch(x){f((x==null?void 0:x.message)||"Connection failed")}b(!1)}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:x=>x.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:j?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:d})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:o.map(x=>s.jsxs("button",{onClick:()=>c(x.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:i===x.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:i===x.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:x.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:i===x.type?"#a78bfa":"var(--text-secondary)"},children:x.displayName})]},x.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:d,onChange:x=>y(x.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",d||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:u,onChange:x=>m(x.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"})]}),g&&s.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:g})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:j?s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:k,disabled:!d||!u||h,className:"machine-btn",style:{background:d&&u?"rgba(34,197,94,0.12)":void 0,borderColor:d&&u?"rgba(34,197,94,0.3)":void 0,color:d&&u?"#86efac":void 0,opacity:!d||!u||h?.4:1},children:h?"⏳ Creating...":"✨ Create Provider"})]})})]})})}const Vc={"user-custom":"Custom",trusted:"Official","trusted-with-scripts":"Official · runs JS","external-safe":"External · spec-only","external-untrusted":"⚠ External · untrusted JS"},$1={"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 E1({trust:e,sourceName:t,description:r}){const n=t&&(e==="external-safe"||e==="external-untrusted")?`${Vc[e]} · ${t}`:Vc[e];return s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded border whitespace-nowrap ${$1[e]}`,title:r,children:n})}function B1(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 F1={detected:"Detected",not_detected:"Not detected",enabled_unchecked:"Enabled (unchecked)",disabled:"Disabled"},qc={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"},O1={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 Yc(e){if(!e)return"—";const t=e.ok?"OK":"Failed",r=e.message||e.path||e.command||"";return r?`${t} — ${r}`:t}function z1(e){return e==="cli"||e==="acp"}function H1({prov:e,providerInfo:t,savingKey:r,onSetSetting:n,onEnableToggle:a,onDetect:o,onResetCommand:i}){const[c,d]=l.useState(!1),p=(t==null?void 0:t.enabled)===!0||e.values.enabled===!0,u=t==null?void 0:t.machineStatus,m=p&&u==="disabled"?"enabled_unchecked":u||(p?"enabled_unchecked":"disabled"),h=z1(e.category);return s.jsxs("div",{className:"rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("button",{onClick:()=>d(b=>!b),className:"w-full px-4 py-2.5 flex items-center gap-3 text-left",children:[s.jsx("span",{className:"text-base shrink-0",children:e.icon}),s.jsx("span",{className:"text-[13px] font-semibold text-text-primary truncate",children:e.displayName}),s.jsx("span",{className:`text-[9px] font-semibold px-1.5 py-px rounded border ${O1[e.category]??"border-border-subtle text-text-muted"}`,children:e.category.toUpperCase()}),(t==null?void 0:t.trust)&&s.jsx(E1,{trust:t.trust,sourceName:t.sourceName??null,description:t.trustDescription}),h&&s.jsx("span",{className:`text-[9px] font-semibold px-1.5 py-px rounded border ${qc[m]??qc.disabled}`,children:F1[m]??m}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[h&&s.jsx("button",{onClick:b=>{b.stopPropagation(),a(e.type,!p)},disabled:r===`${e.type}.enabled`,className:`machine-btn text-[10px] px-2 py-0.5 ${p?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:p?"Disable":"Enable"}),s.jsx("span",{className:"text-text-muted text-xs",children:c?"▾":"▸"})]})]}),c&&s.jsxs("div",{className:"border-t border-border-subtle px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{className:"grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Type:"})," ",s.jsx("span",{className:"font-mono",children:e.type})]}),(t==null?void 0:t.providerVersion)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Version:"})," ",t.providerVersion]}),(t==null?void 0:t.binary)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Binary:"})," ",s.jsx("span",{className:"font-mono",children:t.binary})]}),(t==null?void 0:t.status)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Status:"})," ",t.status]}),(t==null?void 0:t.details)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Details:"})," ",t.details]}),(t==null?void 0:t.sourceLayer)&&s.jsxs("div",{children:[s.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)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Trust:"})," ",t.trustDescription]}),(()=>{const b=t==null?void 0:t.links;if(!b)return null;const g=Object.entries(b).map(([f,j])=>({k:f,href:B1(j)})).filter(f=>f.href!==null);return g.length===0?null:s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Links:"})," ",g.map(({k:f,href:j})=>s.jsx("a",{href:j,target:"_blank",rel:"noopener noreferrer",className:"text-violet-400 hover:underline mr-2",children:f},f))]})})()]}),h&&s.jsxs("div",{className:"grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Detection:"})," ",Yc(t==null?void 0:t.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Verification:"})," ",Yc(t==null?void 0:t.lastVerification)]})]}),e.schema.length>0&&s.jsx("div",{className:"flex flex-col gap-1.5",children:e.schema.map(b=>s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-[11px] font-medium text-text-primary",children:[b.label||b.key,r===`${e.type}.${b.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving…"})]}),b.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:b.description})]}),s.jsx("div",{className:"shrink-0",children:b.type==="boolean"?s.jsx("button",{onClick:()=>void n(e.type,b.key,!(e.values[b.key]??b.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:e.values[b.key]??b.default?"#8b5cf6":"var(--border-subtle)"},children:s.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:e.values[b.key]??b.default?21:3}})}):b.type==="number"?s.jsx("input",{type:"number",value:Number(e.values[b.key]??b.default??0)||0,min:b.min,max:b.max,onChange:g=>{const f=parseInt(g.target.value)||0;b.min!==void 0&&f<b.min||b.max!==void 0&&f>b.max||n(e.type,b.key,f)},className:"machine-input w-20 text-center text-[11px]"}):b.type==="select"&&b.options?s.jsx("select",{value:String(e.values[b.key]??b.default??""),onChange:g=>void n(e.type,b.key,g.target.value),className:"machine-input text-[11px]",children:b.options.map(g=>s.jsx("option",{value:g,children:g},g))}):s.jsx("input",{type:"text",defaultValue:String(e.values[b.key]??b.default??""),onBlur:g=>void n(e.type,b.key,g.target.value),className:"machine-input w-[180px] text-[11px]"})})]},b.key))}),s.jsx("div",{className:"flex gap-1.5 flex-wrap pt-1 border-t border-border-subtle",children:h&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>void o(e.type),disabled:!p||r===`${e.type}.detect`,className:`machine-btn text-[10px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${p?"":"opacity-40 cursor-not-allowed"}`,title:p?"Run detection for the configured executable":"Enable provider before detection",children:"Detect"}),s.jsx("button",{onClick:()=>void i(e.type),className:"machine-btn text-[10px] px-2 py-0.5",children:"Reset command"})]})})]})]})}function Mn(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function W1({machineId:e,sendDaemonCommand:t,onChange:r}){const[n,a]=l.useState([]),[o,i]=l.useState([]),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,h]=l.useState(!1),[b,g]=l.useState(""),[f,j]=l.useState("main"),[N,y]=l.useState(""),[v,k]=l.useState(!1),[w,x]=l.useState(null),[C,S]=l.useState(null),I=l.useCallback(async()=>{if(e){d(!0),u(null);try{const P=Mn(await t(e,"list_provider_sources",{}));if(!(P!=null&&P.success)){u((P==null?void 0:P.error)||"Failed to load sources");return}a(P.sources||[]),i(P.conflicts||[])}catch(P){u((P==null?void 0:P.message)||String(P))}finally{d(!1)}}},[e,t]);l.useEffect(()=>{I()},[I]);const $=async()=>{if(b.trim()){k(!0),u(null);try{const P=Mn(await t(e,"add_provider_source",{url:b.trim(),ref:f.trim()||"main",...N.trim()?{name:N.trim()}:{}}));P!=null&&P.success?(h(!1),g(""),j("main"),y(""),await I(),r==null||r()):u((P==null?void 0:P.error)||"Failed to add source")}catch(P){u((P==null?void 0:P.message)||String(P))}finally{k(!1)}}},R=async P=>{if(confirm(`Remove provider source ${P}? This deletes the cloned manifests and clears any active-source entries that pointed here.`)){x(P),u(null);try{const F=Mn(await t(e,"remove_provider_source",{name:P}));F!=null&&F.success?(await I(),r==null||r()):u((F==null?void 0:F.error)||"Failed to remove source")}catch(F){u((F==null?void 0:F.message)||String(F))}finally{x(null)}}},_=async(P,F)=>{S(`${P}:${F}`),u(null);try{const q=Mn(await t(e,"set_active_provider_source",{type:P,sourceName:F}));q!=null&&q.success?(await I(),r==null||r()):u((q==null?void 0:q.error)||"Failed to set active source")}catch(q){u((q==null?void 0:q.message)||String(q))}finally{S(null)}};return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-sky-400",children:"External sources"}),s.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."})]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsxs("button",{onClick:()=>void I(),disabled:c,className:"machine-btn text-[10px]",children:[c?"⏳":"↻"," Refresh"]}),s.jsx("button",{onClick:()=>h(!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"})]})]}),p&&s.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:p}),n.length===0?s.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.'}):s.jsx("ul",{className:"flex flex-col gap-2",children:n.map(P=>s.jsxs("li",{className:"rounded border border-border-subtle bg-bg-primary/40 px-3 py-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"font-mono text-[12px] text-text-primary",children:P.name}),s.jsxs("div",{className:"text-[10px] text-text-muted truncate",children:[P.url," ",s.jsxs("span",{className:"opacity-60",children:["@ ",P.ref]})]})]}),s.jsx("button",{type:"button",onClick:()=>void R(P.name),disabled:w===P.name,className:"machine-btn text-[10px] text-red-400 hover:bg-red-500/[0.10]",children:w===P.name?"…":"Remove"})]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:Object.entries(P.providers).map(([F,q])=>s.jsxs("span",{className:"mr-3",children:[s.jsxs("span",{className:"text-text-secondary",children:[F,":"]})," ",q.length]},F))})]},P.name))}),o.length>0&&s.jsxs("div",{className:"mt-3 rounded border border-amber-500/30 bg-amber-500/[0.06] px-3 py-2",children:[s.jsx("div",{className:"text-[11px] font-semibold text-amber-300 mb-1.5",children:"Conflicts"}),s.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."}),s.jsx("ul",{className:"flex flex-col gap-1.5",children:o.map(P=>s.jsxs("li",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"font-mono text-[11px]",children:[P.type," ",s.jsxs("span",{className:"text-text-muted",children:["(",P.category,")"]})]}),s.jsx("div",{className:"flex gap-1.5 flex-wrap",children:P.candidates.map(F=>s.jsxs("button",{type:"button",onClick:()=>void _(P.type,F),disabled:C===`${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))})]}),m&&s.jsxs("div",{className:"mt-3 rounded border border-sky-500/30 bg-sky-500/[0.06] px-3 py-3",children:[s.jsx("div",{className:"text-[11px] font-semibold text-sky-300 mb-2",children:"Add external source"}),s.jsxs("div",{className:"grid md:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[10px] text-text-secondary md:col-span-3",children:[s.jsx("span",{children:"Git URL"}),s.jsx("input",{type:"text",value:b,onChange:P=>g(P.target.value),placeholder:"https://github.com/vendor/extra-providers",className:"machine-input text-[11px] font-mono"})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[10px] text-text-secondary",children:[s.jsx("span",{children:"Ref (branch/tag)"}),s.jsx("input",{type:"text",value:f,onChange:P=>j(P.target.value),placeholder:"main",className:"machine-input text-[11px]"})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[10px] text-text-secondary md:col-span-2",children:[s.jsx("span",{children:"Name (optional, auto-derived from URL)"}),s.jsx("input",{type:"text",value:N,onChange:P=>y(P.target.value),placeholder:"@vendor-extra-providers",className:"machine-input text-[11px] font-mono"})]})]}),s.jsxs("div",{className:"mt-3 flex items-center justify-end gap-2",children:[s.jsx("button",{type:"button",onClick:()=>h(!1),className:"machine-btn text-[10px]",children:"Cancel"}),s.jsx("button",{type:"button",onClick:()=>void $(),disabled:v||!b.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:v?"Cloning…":"Clone + register"})]})]})]})}function K1({machineId:e,providers:t,sendDaemonCommand:r}){var T;const[n,a]=l.useState([]),[o,i]=l.useState(!1),[c,d]=l.useState(null),[p,u]=l.useState("all"),[m,h]=l.useState(!1),[b,g]=l.useState(!1),[f,j]=l.useState(!1),[N,y]=l.useState(null),[v,k]=l.useState("normal"),[w,x]=l.useState(""),[C,S]=l.useState(!1),I=l.useCallback(async()=>{if(e)try{const B=await r(e,"get_provider_source_config",{}),D=Gc(B);D&&(y(D),k(D.sourceMode),x(D.explicitProviderDir||""))}catch{}},[e,r]),$=l.useCallback(async()=>{if(e){i(!0);try{const B=await r(e,"get_provider_settings",{}),D=L1(B);if(D){const M=P1(D,t,{filterSchema:E=>E.filter(z=>z.key!=="enabled")});M.sort((E,z)=>E.category.localeCompare(z.category)||E.displayName.localeCompare(z.displayName)),a(M)}}catch{}i(!1)}},[e,t,r]);l.useEffect(()=>{n.length===0&&$(),N||I()},[]);const R=async(B,D,M)=>{d(`${B}.${D}`),a(E=>E.map(z=>z.type===B?{...z,values:{...z.values,[D]:M}}:z));try{const E=await r(e,"set_provider_setting",{providerType:B,key:D,value:M});E!=null&&E.success||$()}catch{$()}d(null)},_=async(B,D)=>{await R(B,"enabled",D),await $()},P=async B=>{d(`${B}.detect`);try{await r(e,"detect_provider",{providerType:B})}finally{await $(),d(null)}},F=async B=>{await R(B,"executablePath",""),await R(B,"executableArgs",""),await $()},q=async()=>{S(!0);try{const B=await r(e,"set_provider_source_config",{providerSourceMode:v,providerDir:R1(w)}),D=Gc(B);D?(y(D),k(D.sourceMode),x(D.explicitProviderDir||"")):await I(),await $()}catch{await I()}S(!1)},A=n.filter(B=>p==="all"||B.category===p);return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[s.jsxs("div",{className:"flex gap-1 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(B=>s.jsx("button",{onClick:()=>u(B),className:`machine-btn text-[10px] px-2 py-0.5 ${p===B?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:B.toUpperCase()},B))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>g(B=>!B),className:`machine-btn text-[10px] ${b?"bg-sky-500/[0.10] border-sky-500/30 text-sky-300":""}`,title:"Manage 3rd-party provider sources",children:"🌐 Sources"}),s.jsx("button",{onClick:()=>h(!0),className:"machine-btn text-[10px]",title:"Create a new provider from an existing one",children:"✨ Create"}),s.jsxs("button",{onClick:$,disabled:o,className:"machine-btn text-[10px]",children:[o?"⏳":"↻"," Refresh"]}),s.jsx("button",{onClick:()=>j(B=>!B),className:"machine-btn text-[10px]",title:"Show source configuration (advanced)",children:"⚙ Advanced"})]})]}),b&&s.jsx(W1,{machineId:e,sendDaemonCommand:r,onChange:()=>{$()}}),f&&s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Where the daemon looks for provider manifests. Affects resolution and reloads."})]}),s.jsx("button",{onClick:I,className:"machine-btn text-[10px]",children:"↻ Refresh"})]}),s.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),s.jsxs("select",{value:v,onChange:B=>k(B.target.value),className:"machine-input text-[11px]",children:[s.jsx("option",{value:"normal",children:"normal"}),s.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),s.jsx("input",{type:"text",value:w,onChange:B=>x(B.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void q(),disabled:C,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:C?"Applying…":"Apply + Reload"})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"User root:"})," ",(N==null?void 0:N.userDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Upstream root:"})," ",(N==null?void 0:N.upstreamDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Provider roots:"})," ",((T=N==null?void 0:N.providerRoots)==null?void 0:T.join(" → "))||"—"]})]})]}),o&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings…"}):A.length===0?s.jsx("div",{className:"px-4.5 py-8 rounded-xl border border-border-subtle bg-bg-secondary text-center",children:s.jsx("div",{className:"text-[12px] text-text-muted",children:p==="all"?'No providers installed yet. Open "Add provider" above to install one.':`No ${p.toUpperCase()} providers installed.`})}):s.jsx("div",{className:"flex flex-col gap-1.5",children:A.map(B=>s.jsx(H1,{prov:B,providerInfo:t.find(D=>D.type===B.type),savingKey:c,onSetSetting:R,onEnableToggle:_,onDetect:P,onResetCommand:F},B.type))}),m&&s.jsx(D1,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>h(!1),onCreated:()=>{h(!1),$()}})]})}const U1=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function G1({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function V1(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function q1(e){return e.trim().toLowerCase()}function Ia(e,t){const r=q1(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function Vi(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function er(e,t=220){const r=Vi(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function Y1(e){const t=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(t))return{kind:t.length>0?"structured":"empty",entries:t.map(r=>{const n=r;return{timestamp:Number(n.ts)||0,level:n.level||"info",message:`[${String(n.category||"daemon")}] ${String(n.message||"")}`.trim()}}),rawText:""};if(typeof t=="string"){const r=t.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function J1(e,t){return e.filter(r=>Ia([r.level,r.message],t))}function Jc(e){return`${e.timestamp}:${e.level}:${e.message}`}function X1(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const i of e.entries)n.set(Jc(i),i);for(const i of t.entries)n.set(Jc(i),i);const a=Array.from(n.values()).sort((i,c)=>i.timestamp-c.timestamp).slice(-r),o=a.reduce((i,c)=>Math.max(i,Number(c.timestamp||0)),e.lastTs);return{entries:a,kind:"structured",rawText:"",lastTs:o}}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 Q1(e,t,r=120){if(t.length===0)return e;const n=new Map;for(const a of e)n.set(a.id,a);for(const a of t)n.set(a.id,a);return Array.from(n.values()).sort((a,o)=>a.ts-o.ts).slice(-r)}function Z1(e,t){return e.split(`
91
+ `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>Ia([r],t))}function eN(e,t){return e.filter(r=>Ia([r.level,r.category,r.stage,r.interactionId,Vi(r.payload)],t))}function tN(e,t){return e.filter(r=>Ia([r.kind,r.topic,r.interactionId,Vi(r.payload)],t))}function Xc(e){return e==="warn"||e==="error"}function sN({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){return{all:e.length+t.length+r.length+n.length,info:e.filter(a=>a.level!=="debug").length+r.filter(a=>a.level!=="debug").length+n.length,issues:e.filter(a=>Xc(a.level)).length+r.filter(a=>Xc(a.level)).length}}function rN({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(o=>`${new Date(o.timestamp).toISOString()} ${o.level.toUpperCase()} ${o.message}`)].join(`
92
+ `)):t.length>0&&a.push(["[daemon logs]",...t].join(`
93
+ `)),r.length>0&&a.push(["[trace]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${er(o.payload,500)}`.trim())].join(`
94
+ `)),n.length>0&&a.push(["[browser events]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${er(o.payload,500)}`.trim())].join(`
95
+ `)),a.join(`
96
+
97
+ `)}function nN({machineId:e,sendDaemonCommand:t}){const[r,n]=l.useState([]),[a,o]=l.useState("empty"),[i,c]=l.useState(""),[d,p]=l.useState([]),[u,m]=l.useState([]),[h,b]=l.useState(null),[g,f]=l.useState(!0),[j,N]=l.useState("info"),[y,v]=l.useState("all"),[k,w]=l.useState(!0),[x,C]=l.useState(!0),[S,I]=l.useState(""),[$,R]=l.useState(""),[_,P]=l.useState(0),F=l.useRef(0),q=l.useRef(0),A=l.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),T=l.useRef([]),B=l.useCallback(()=>{const ae={entries:[],kind:"empty",rawText:"",lastTs:0};A.current=ae,F.current=0,n([]),c(""),o("empty"),w(!0)},[]),D=l.useCallback(()=>{T.current=[],q.current=0,p([]),C(!0)},[]),M=l.useCallback(ae=>{ae!==j&&(B(),N(ae))},[j,B]),E=l.useCallback(ae=>{v(ne=>ne===ae?ne:ae)},[]),z=l.useCallback(()=>{B(),D(),m([]),b(null),I(""),R(""),Us.clear()},[B,D]),Q=l.useCallback(()=>{P(ae=>ae+1)},[]),J=l.useCallback(async()=>{if(!e)return;const ae=F.current,ne=q.current,[ce,be]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:j,since:ae}),t(e,"get_debug_trace",G1({count:120,since:ne,category:y}))]);if(ce.status==="fulfilled"){const Z=ce.value,Y=(Z==null?void 0:Z.result)||Z,ve=Y1(Y),ye=X1(A.current,ve,300);A.current=ye,F.current=ye.lastTs,w(!1),I((Z==null?void 0:Z.success)===!1?String((Z==null?void 0:Z.error)||"Could not load daemon logs"):""),o(ye.kind),c(ye.rawText),n(ye.entries)}else w(!1),I(ce.reason instanceof Error?ce.reason.message:"Could not load daemon logs");if(be.status==="fulfilled"){const Z=be.value,Y=(Z==null?void 0:Z.result)||Z;if((Z==null?void 0:Z.success)===!1)R(String((Z==null?void 0:Z.error)||"Could not load daemon trace"));else if(Array.isArray(Y==null?void 0:Y.trace)){const ve=Y.trace,ye=Q1(T.current,ve,120),xe=ve.reduce((Se,ie)=>Math.max(Se,Number(ie.ts||0)),ne);T.current=ye,xe>ne&&(q.current=xe),R(""),p(ye)}else R("");C(!1)}else C(!1),R(be.reason instanceof Error?be.reason.message:"Could not load daemon trace");m(Us.list({limit:120})),b(Date.now())},[j,e,t,y]);return l.useEffect(()=>{D()},[D,y]),l.useEffect(()=>{if(!e||(J(),!g))return;const ae=setInterval(()=>{J()},3e3);return()=>clearInterval(ae)},[g,J,e,_]),{daemonLogs:r,daemonLogKind:a,daemonRawText:i,debugTrace:d,webEvents:u,lastUpdatedAt:h,autoRefresh:g,logLevel:j,traceCategory:y,daemonLoading:k,traceLoading:x,daemonFetchError:S,traceFetchError:$,setAutoRefresh:f,setLogLevel:M,setTraceCategory:E,refresh:Q,clear:z}}function aN({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:i,traceCount:c,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":o>0||i>0?"ok":"empty",detail:r||(a==="text"?`${i} raw file-fallback line(s)`:`${o} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:n?"error":t?"loading":c>0?"ok":"empty",detail:n||`${c} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:d>0?"ok":"empty",detail:d>0?`${d} local browser event(s)`:"No browser events captured"}]}function Qc(e){return e==="warn"||e==="error"}function oN(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 iN(e,t){const r=e.match(/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\b/);if(r){const n=Date.parse(r[0]);if(Number.isFinite(n))return n}return Number.MAX_SAFE_INTEGER-1e5+t}function Zc(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function lN(e){const t=er(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function cN(e){const t=er(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function dN({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.forEach((o,i)=>{a.push({id:`daemon-log-${o.timestamp}-${i}`,source:"daemon_log",ts:Number(o.timestamp||0),severity:o.level,message:o.message,raw:o.message})}),n.forEach(o=>{a.push({id:`browser-event-${o.id}`,source:"browser_event",ts:Number(o.ts||0),severity:"info",message:cN(o),topic:o.topic,interactionId:o.interactionId,payload:o.payload})}),r.forEach(o=>{a.push({id:`daemon-trace-${o.id}`,source:"daemon_trace",ts:Number(o.ts||0),severity:o.level,message:lN(o),category:o.category,stage:o.stage,interactionId:o.interactionId,payload:o.payload})}),t.forEach((o,i)=>{a.push({id:`raw-file-${i}`,source:"raw_file",ts:iN(o,i),severity:oN(o),message:o,raw:o})}),a.sort((o,i)=>o.ts!==i.ts?o.ts-i.ts:Zc(o.source)-Zc(i.source))}function uN(e){return`${e.source}:${e.severity}:${e.message}`}function pN(e){const t=e.filter(n=>Qc(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!Qc(n.severity))continue;const a=uN(n),o=r.get(a);o?(o.count+=1,o.firstTs=Math.min(o.firstTs,n.ts),o.lastTs=Math.max(o.lastTs,n.ts)):r.set(a,{key:a,source:n.source,severity:n.severity,message:n.message,count:1,firstTs:n.ts,lastTs:n.ts})}return{totalCount:e.length,issueCount:t.length,latestIssue:t[0]||null,repeatedPatterns:Array.from(r.values()).filter(n=>n.count>1).sort((n,a)=>a.count!==n.count?a.count-n.count:a.lastTs-n.lastTs).slice(0,5)}}function mN(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function ed(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${mN(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function hN({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
98
+ `)),a.push(["[source status]",...r.map(i=>`${i.label}: ${i.status} - ${i.detail}`)].join(`
99
+ `)),t.latestIssue&&a.push(["[latest issue]",ed(t.latestIssue)].join(`
100
+ `)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(i=>`${i.count}x ${i.severity.toUpperCase()} ${i.source} ${i.message}`)].join(`
101
+ `));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(ed):["No diagnostic events captured."]].join(`
102
+ `)),a.join(`
103
+
104
+ `)}function fN(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function xN(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function bN({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:i,searchQuery:c,daemonLoading:d,traceLoading:p,daemonFetchError:u,traceFetchError:m}){const h=V1(n,o),b=J1(e,c),g=Z1(t,c),f=eN(h,c),j=tN(a,c),N=fN(b,i),y=i==="all"?g:[],v=xN(f,i),k=i==="issues"?[]:j,w=sN({daemonLogs:b,daemonRawLines:g,trace:f,webEvents:j}),x=dN({daemonLogs:N,daemonRawLines:y,trace:v,webEvents:k}),C=pN(x),S=aN({daemonLoading:d,traceLoading:p,daemonFetchError:u,traceFetchError:m,daemonLogKind:r,daemonLogsCount:b.length,daemonRawLineCount:g.length,traceCount:f.length,webEventCount:j.length});return{filteredDaemonLogs:b,filteredDaemonRawLines:g,filteredTraceEntries:f,filteredWebEvents:j,visibleDaemonLogs:N,visibleDaemonRawLines:y,visibleTraceEntries:v,visibleWebEvents:k,quickFilterCounts:w,diagnosticEvents:x,diagnosticsSummary:C,sourceStates:S}}function gN(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function cm(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Jo(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 xo(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 qi(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function yN({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Jo(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:cm(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:qi(e.source)}),e.category&&e.stage&&s.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&s.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&s.jsxs("span",{children:["ix=",e.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function vN({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:i,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:p,onClear:u}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(m=>s.jsx("button",{type:"button",onClick:()=>a(m.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===m.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:m.label},m.id))}),s.jsx("input",{value:r,onChange:m=>o(m.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:i,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:d,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:p,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function wN({logLevel:e,traceCategory:t,onLogLevelChange:r,onTraceCategoryChange:n}){return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-3",children:s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(a=>s.jsxs("button",{onClick:()=>r(a),className:`machine-btn text-[10px] px-2 py-0.5 ${e===a?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",a.toUpperCase(),"+"]},a))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:U1.map(a=>s.jsx("button",{onClick:()=>n(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function jN({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:i,traceFetchError:c}){var u,m;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((m=e.latestIssue)==null?void 0:m.severity)==="warn"?"warning":"good",p=i||c?"danger":o?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${xo(e.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:n.trim()?`Filtered by “${n.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${xo(d)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[qi(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:cm(e.latestIssue.ts)})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${xo(p)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:i||c?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",gN(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(h=>s.jsxs("div",{children:[h.label,": ",h.status]},h.id))})]})]})}function kN({patterns:e}){return e.length===0?null:s.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(t=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[s.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[t.count,"× ",t.severity.toUpperCase()," · ",qi(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function NN({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:i,visibleWebEvents:c,quickFilter:d,searchQuery:p}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,timeline:!u.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(u=>s.jsx(yN,{event:u},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,daemon:!u.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&o.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:d==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((u,m)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${m}`)),e.daemonLogKind!=="text"&&a.map((u,m)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Jo(u.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:u.level==="error"?"ERR":u.level==="warn"?"WRN":u.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:u.message})]},`log-${m}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,trace:!u.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[i.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&i.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:p.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."}),i.map(u=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Jo(u.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.level.toUpperCase()}),s.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:er(u.payload,360)||"No payload"})]},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,web:!u.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[c.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:p.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),c.map(u=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.kind}),u.topic&&s.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:er(u.payload,360)||"No payload"})]},u.id))]})]})]})}function SN({machineId:e,sendDaemonCommand:t}){const r=nN({machineId:e,sendDaemonCommand:t}),[n,a]=l.useState("info"),[o,i]=l.useState(""),[c,d]=l.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),p=l.useRef(null),u=l.useRef(!1),m=l.useMemo(()=>bN({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:o,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,o,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);l.useEffect(()=>{if(r.autoRefresh&&m.diagnosticEvents.length>0){const g=u.current?"smooth":"instant";setTimeout(()=>{var f;(f=p.current)==null||f.scrollIntoView({behavior:g}),u.current=!0},50)}},[m.diagnosticEvents.length,r.autoRefresh]);const h=l.useCallback(async()=>{var f;const g=rN({daemonLogs:m.visibleDaemonLogs,daemonRawLines:m.visibleDaemonRawLines,trace:m.visibleTraceEntries,webEvents:m.visibleWebEvents});if(!g.trim()){tt.showToast("No visible logs to copy.","info");return}try{await((f=navigator.clipboard)==null?void 0:f.writeText(g)),tt.showToast("Copied visible logs to clipboard.","success")}catch(j){tt.showToast(j instanceof Error?j.message:"Could not copy visible logs","warning")}},[m.visibleDaemonLogs,m.visibleDaemonRawLines,m.visibleTraceEntries,m.visibleWebEvents]),b=l.useCallback(async()=>{var f;const g=hN({events:m.diagnosticEvents,summary:m.diagnosticsSummary,sources:m.sourceStates});try{await((f=navigator.clipboard)==null?void 0:f.writeText(g)),tt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(j){tt.showToast(j instanceof Error?j.message:"Could not copy diagnostic bundle","warning")}},[m.diagnosticEvents,m.diagnosticsSummary,m.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(vN,{quickFilter:n,quickFilterCounts:m.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:()=>{b()},onCopyVisible:()=>{h()},onToggleAutoRefresh:()=>r.setAutoRefresh(g=>!g),onRefresh:r.refresh,onClear:r.clear}),s.jsx(wN,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(jN,{diagnosticsSummary:m.diagnosticsSummary,diagnosticEventsCount:m.diagnosticEvents.length,sourceStates:m.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(kN,{patterns:m.diagnosticsSummary.repeatedPatterns}),s.jsx(NN,{streams:r,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:m.diagnosticEvents,visibleDaemonLogs:m.visibleDaemonLogs,visibleDaemonRawLines:m.visibleDaemonRawLines,visibleTraceEntries:m.visibleTraceEntries,visibleWebEvents:m.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:p})]})}function CN(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 dm(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 IN(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=dm((o==null?void 0:o.meta)||void 0),d=((a=o==null?void 0:o.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(i)?t.push(o):(i==="stopped"||i==="failed")&&(d||c)?r.push(o):n.push(o)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function MN(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function bo(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 go(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function yo(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function td(e){if(!e)return"unknown";const t=Date.now()-e,r=Math.max(0,Math.round(t/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const a=Math.round(n/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function AN(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function TN(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 _N(e){var r;const t=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const a=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!a)continue;const o=`${n.providerType}::${n.workspace}::${a}`;t.set(o,(t.get(o)||0)+1)}return Array.from(t.values()).filter(n=>n>1).length}function LN({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=l.useState(""),[o,i]=l.useState(null),[c,d]=l.useState(!1),p=z0(e,{enabled:!!e,includeSessions:!0,limit:$l,intervalMs:hb}),u=p.diagnostics,m=p.loading,h=p.applyDiagnostics,b=l.useMemo(()=>CN({diagnostics:u,loading:m,refreshing:c,error:n}),[u,m,c,n]),g=l.useMemo(()=>new Map(t.map(R=>[R.sessionId||R.id,R])),[t]),f=l.useCallback(async()=>{if(e){d(!0);try{const R=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:$l}),_=go(R);if(!(_!=null&&_.success))throw new Error((_==null?void 0:_.error)||"Could not load hosted runtime diagnostics");h(_.diagnostics||_.result||null),a("")}catch(R){const _=R instanceof Error?R.message:"Could not load hosted runtime diagnostics";a(_)}finally{d(!1)}}},[h,e,r]);l.useEffect(()=>{!e||u||m||c||f()},[u,m,e,f,c]);const j=l.useCallback(async(R,_)=>{const P=`${R}:${_.sessionId}`;if(!(R==="session_host_stop_session"&&!window.confirm(`Stop ${_.displayName}?
105
+ This will terminate the hosted runtime.`))){i(P);try{const F=await r(e,R,{sessionId:_.sessionId}),q=go(F);if(!(q!=null&&q.success))throw new Error((q==null?void 0:q.error)||"Session host action failed");const A=R==="session_host_resume_session"?"resumed":R==="session_host_restart_session"?"restarted":"stopped";tt.showToast(`Session host ${A}: ${_.displayName}`,"success"),await f()}catch(F){const q=F instanceof Error?F.message:"Session host action failed";tt.showToast(q,"warning"),a(q)}finally{i(F=>F===P?null:F)}}},[e,f,r]),N=l.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
106
+ The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const _=await r(e,"session_host_prune_duplicate_sessions",{}),P=go(_);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const F=P.result||{},q=Array.isArray(F.prunedSessionIds)?F.prunedSessionIds.length:0,A=typeof F.duplicateGroupCount=="number"?F.duplicateGroupCount:0;tt.showToast(`Pruned ${q} duplicate runtime(s) across ${A} group(s)`,"success"),await f()}catch(_){const P=_ instanceof Error?_.message:"Duplicate prune failed";tt.showToast(P,"warning"),a(P)}finally{i(_=>_==="session_host_prune_duplicate_sessions"?null:_)}}},[e,f,r]),y=l.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((R,_)=>(_.lastActivityAt||0)-(R.lastActivityAt||0)),[u==null?void 0:u.sessions]),v=l.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:IN(y),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,y]),k=v.liveRuntimes,w=v.recoverySnapshots,x=v.inactiveRecords,C=l.useMemo(()=>_N(k),[k]),S=l.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),I=l.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(R=>R.level==="warn"||R.level==="error")||null,[u==null?void 0:u.recentLogs]),$=(R,_)=>{var E;const P=o===`session_host_resume_session:${R.sessionId}`,F=o===`session_host_restart_session:${R.sessionId}`,q=o===`session_host_stop_session:${R.sessionId}`,A=dm(R.meta),T=g.get(R.sessionId),B=R.attachedClients.length===1?"1 client":`${R.attachedClients.length} clients`,D=_==="recovery"?"Recover":"Resume",M=MN(_);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:R.displayName||(T==null?void 0:T.cliName)||R.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${TN(R.lifecycle)}`,children:R.lifecycle}),A&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:A})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:R.workspaceLabel||(T==null?void 0:T.runtimeWorkspaceLabel)||R.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:R.runtimeKey}),R.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",R.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((E=R.writeOwner)==null?void 0:E.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:AN(R.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(yd,{size:11})," ",B]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",td(R.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",M]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[_==="recovery"&&(R.lifecycle==="interrupted"||R.lifecycle==="failed"||R.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{j("session_host_resume_session",R)},children:P?`${D}ing…`:D}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{j("session_host_restart_session",R)},children:F?"Restarting…":"Restart"}),_==="live"&&(R.lifecycle==="running"||R.lifecycle==="starting"||R.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{j("session_host_stop_session",R)},children:q?"Stopping…":"Stop"})]})]})},R.sessionId)};return s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(ps,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Hg()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[C>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{N()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${C})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${b.toneClass}`,children:b.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{f()},disabled:m||c,children:[s.jsx(ha,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),n&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(qs,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:w.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:td(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:yo(u.hostStartedAt)})]})]}),I&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(qs,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:I.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[yo(I.timestamp),I.sessionId?` · ${I.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(oi,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:bo("live")}),k.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:k.map(R=>$(R,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(ps,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:bo("recovery")}),w.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:w.map(R=>$(R,"recovery"))})]}),x.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:bo("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:x.map(R=>$(R,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),S.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:S.map(R=>{var P;const _=y.find(F=>F.sessionId===R.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(_==null?void 0:_.displayName)||((P=g.get(R.sessionId))==null?void 0:P.cliName)||R.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[R.action,R.lifecycle?` · ${R.lifecycle}`:"",R.detail?` · ${R.detail}`:"",R.error?` · ${R.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${R.success===!1?"text-red-300":"text-text-secondary"}`,children:yo(R.timestamp)})]},`${R.sessionId}:${R.timestamp}:${R.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function PN({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(o=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{a(null),n({cliType:t.cliType,workspaceId:o.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:o.label||o.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:o.path})]},o.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function RN(e,t){const r=Zu(e),n=zs(e,t),a=ki(e,n),o=Ar(e,n),i=r==="preview"?"Update to preview":"Update daemon";return a?{visible:!0,showButton:!0,title:o?"Daemon update required":"Version mismatch detected",description:o?"This machine is on an incompatible daemon version. Update it before starting more sessions.":r==="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:i,targetVersion:n,channel:r,required:o,tone:"warn"}:r==="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:i,targetVersion:n,channel:r,required:!1,tone:n?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:i,targetVersion:n,channel:r,required:!1,tone:"info"}}function vo({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function wo({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function DN({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:i}){const c=n.slice(0,6),d=r.slice(0,4),u=RN(e,"0.9.82");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[c.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(vo,{icon:s.jsx(Ls,{size:13}),children:"Current Chats"}),s.jsx(wo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(m=>{const h=Uo(m);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(m),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:it(m)}),h>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:fa(h)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:As(m)})]},m.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(vo,{icon:s.jsx(kd,{size:13}),children:"Recent Launches"}),s.jsx(wo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(m=>{const{metaText:h,updatedLabel:b}=pp(m);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>o(m),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:m.label}),b&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:b})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:h})]},m.id)})})})]}),u.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(vo,{icon:s.jsx(qs,{size:13}),children:"Daemon Update"}),s.jsx(wo,{className:u.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":u.tone==="info"?"border-sky-500/20 bg-sky-500/5":"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[u.description,u.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",u.targetVersion,u.channel?` (${u.channel})`:""]})]}),u.showButton?s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[s.jsx(ha,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:u.buttonLabel})]}):s.jsx("div",{className:u.tone==="good"?"text-xs font-medium text-emerald-300":"text-xs font-medium text-sky-300",children:"No preview update action is needed."})]})})]})]})}function $N({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:p,handleWorkspaceSetDefault:u}=o,[m,h]=l.useState(!1),[b,g]=l.useState(""),[f,j]=l.useState([]),[N,y]=l.useState(!1),[v,k]=l.useState(""),w=l.useCallback(async C=>{y(!0),k("");try{const S=await _i(i,e,C);g(S.path),j(S.directories)}catch(S){k(S instanceof Error?S.message:"Could not load folder")}finally{y(!1)}},[e,i]),x=l.useCallback(()=>{h(!0);const C=[...r.map(I=>I.workspace),...n.map(I=>I.workspace),...a.map(I=>I.workspace)],S=Ti(t.platform,Ai(C,t.defaultWorkspacePath,(t.workspaces||[]).map(I=>I.path)));w(S)},[a,n,r,w,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-4 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(Vs,{size:14})," Workspaces"]}),s.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:c,onClick:x,children:"+ Add workspace"})]}),(t.workspaces||[]).length===0?s.jsxs("div",{className:"text-[11px] text-text-muted py-4 text-center",children:["No saved workspaces yet. Click ",s.jsx("span",{className:"text-text-secondary",children:"+ Add workspace"})," to pick a folder."]}):s.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(C=>{const S=C.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${S?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:S?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void u(S?null:C.id),className:`text-base leading-none shrink-0 transition-colors ${S?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary truncate",children:Od(C.path,C.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:C.path,children:C.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void p(C.id),children:"Remove"})]},C.id)})})]}),m&&s.jsx(Pi,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:b,directories:f,busy:N,error:v,confirmLabel:"Add workspace",onClose:()=>h(!1),onNavigate:C=>{w(C)},onConfirm:C=>{(async()=>{if(!C)return;await d(C)&&h(!1)})()}})]})}function EN({machine:e,machineId:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i}){return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspaces"}),s.jsx("div",{className:"text-sm text-text-secondary",children:'Save folders as workspaces on this machine. Use the dashboard "+" button to launch a session.'})]}),i&&s.jsx($N,{machineId:t,machine:e,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function BN({onNicknameSynced:e}={}){var Se,ie,we,pe,W,O,V,oe,te,X;const{id:t}=oh(),r=zr(),n=ti(),{sendCommand:a}=lt(),o=Ur(),i=Bu(),c=mu(),d=c.ides||[],p=c.initialLoaded??!0,u=d.find(L=>L.id===t&&L.type==="adhdev-daemon"),m=d.some(L=>L.type==="adhdev-daemon"),h=t?(Se=c.connectionRetryStatuses)==null?void 0:Se[t]:void 0,b=!!(h!=null&&h.blocked),[g,f]=l.useState("workspace"),[j,N]=l.useState(null);l.useCallback((L,ue)=>{N({daemonId:L,workspace:ue})},[]);const[,y]=l.useState("ide"),v=l.useRef(null),[k,w]=l.useState(null),x=l.useRef("__home__"),[C,S]=l.useState("__home__"),[I,$]=l.useState(!1),R=l.useRef(null);l.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||o(t,{minFreshMs:3e4}).catch(()=>{})},[o,u,t]),l.useEffect(()=>{if(!t||!u||g!=="overview")return;const L=u.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")&&i(t,{minFreshMs:3e4}).catch(()=>{})},[g,i,u,t]),O0(t&&g==="overview"?[t]:[],{enabled:g==="overview",intervalMs:db});const _=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},P=T1({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:R});l.useEffect(()=>tt.onToast(ue=>{c.setToasts(le=>{if(le.some(Te=>Te.message===ue.message&&ue.timestamp-Te.timestamp<3e3))return le;const Le={id:ue.id,message:ue.message,type:ue.type,timestamp:ue.timestamp,targetKey:ue.targetKey,actions:ue.actions};return[...le.slice(-4),Le]});const H=ue.duration||5e3;setTimeout(()=>c.setToasts(le=>le.filter(G=>G.id!==ue.id)),H)}),[c]);const F=(u==null?void 0:u.availableProviders)||[],q={};for(const L of F)q[L.type]=L.icon;const A=u?{id:u.id,hostname:zd(u,{fallbackId:u.id}),platform:((ie=u.machine)==null?void 0:ie.platform)||"unknown",arch:((we=u.machine)==null?void 0:we.arch)||"",cpus:((pe=u.machine)==null?void 0:pe.cpus)||0,totalMem:((W=u.machine)==null?void 0:W.totalMem)||0,freeMem:(O=u.machine)==null?void 0:O.freeMem,availableMem:(V=u.machine)==null?void 0:V.availableMem,loadavg:(oe=u.machine)==null?void 0:oe.loadavg,uptime:(te=u.machine)==null?void 0:te.uptime,release:((X=u.machine)==null?void 0:X.release)||"",cdpConnected:!!u.cdpConnected,machineNickname:u.machineNickname||null,p2p:u.p2p?{screenshotActive:!1,...u.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:u.detectedIdes||[],workspaces:u.workspaces||[],defaultWorkspaceId:u.defaultWorkspaceId??u.activeWorkspaceId??null,defaultWorkspacePath:u.defaultWorkspacePath??u.activeWorkspacePath??null}:null,T=d.filter(L=>L.daemonId===t&&L.type!=="adhdev-daemon").filter(L=>!Dr(L)&&!Ws(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:sx(L.aiAgents||(L.agents||[]).map(ue=>({id:ue.name,name:ue.name,status:ue.status,version:ue.version}))),activeChat:L.activeChat||null,chats:L.chats||[],childSessions:L.childSessions||[],cdpConnected:L.cdpConnected||!1,daemonId:t,lastMessageAt:L.lastMessageAt})),B=d.filter(L=>L.daemonId===t&&Dr(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})),D=d.filter(L=>L.daemonId===t&&Ws(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=u?$t(u,{fallbackId:t}):"",E="workspace",z=n.state,Q=z==null?void 0:z.initialMachineTab,J=z==null?void 0:z.initialWorkspaceCategory;z==null||z.initialWorkspaceId,z==null||z.initialWorkspacePath;const ae=Q==="ides"||Q==="clis"||Q==="acps"?"workspace":Q||E,ne=Q==="ides"?"ide":Q==="clis"?"cli":Q==="acps"?"acp":J,ce=[...T.map(L=>{var ue;return{id:`ide:${L.type}:${L.workspace||""}`,label:((ue=L.activeChat)==null?void 0:ue.title)||L.type,kind:"ide",providerType:L.type,subtitle:L.workspace||void 0,workspace:L.workspace||void 0,lastLaunchedAt:L.lastMessageAt||0}}),...B.map(L=>{var ue;return{id:`cli:${L.type}:${L.workspace||""}`,label:((ue=L.activeChat)==null?void 0:ue.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}}),...D.map(L=>{var ue;return{id:`acp:${L.type}:${L.workspace||""}`,label:((ue=L.activeChat)==null?void 0:ue.title)||L.acpName,kind:"acp",providerType:L.type,providerSessionId:L.providerSessionId,subtitle:Ms(L.summaryMetadata)||L.workspace||void 0,workspace:L.workspace||void 0,lastLaunchedAt:L.lastMessageAt||0}})].sort((L,ue)=>(ue.lastLaunchedAt||0)-(L.lastLaunchedAt||0)),be=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(L=>({id:L.id,label:L.title||L.providerName||L.providerType,kind:L.kind,providerType:L.providerType,providerSessionId:L.providerSessionId,subtitle:Ms(L.summaryMetadata)||L.workspace||void 0,workspace:L.workspace,summaryMetadata:L.summaryMetadata,lastLaunchedAt:L.lastLaunchedAt})):ce,Z=l.useMemo(()=>{var ue;const L=((ue=c.connectionStates)==null?void 0:ue[t||""])||void 0;return d.filter(H=>H.daemonId===t&&H.type!=="adhdev-daemon").flatMap(H=>ji(H,{connectionStates:t&&L?{[t]:L}:void 0,defaultConnectionState:L})).filter(H=>!(H.transport==="pty"&&H.mode==="terminal")).sort((H,le)=>Uo(le)-Uo(H))},[d,c.connectionStates,t]),Y=l.useCallback(L=>{const ue=np(L);ue&&r(Br(ue))},[r]),ve=l.useCallback(()=>{v.current&&($(!0),v.current().finally(()=>{v.current=null,$(!1),w(null)}))},[]),ye=l.useCallback(L=>{if(!A)return;const{options:ue,selectedKey:H}=up({machine:A,currentWorkspacePath:L.workspace}),le=async()=>{y(L.kind),f("workspace")};v.current=async()=>{const G=ue.find(Me=>Me.key===x.current),Le=(G==null?void 0:G.workspacePath)??null,Te=(G==null?void 0:G.workspaceId)??null;if(L.kind==="ide"&&L.providerType){await P.handleLaunchIde(L.providerType,Le?{workspace:Le}:void 0);return}if((L.kind==="cli"||L.kind==="acp")&&L.providerType){await P.runLaunchCliCore({cliType:L.providerType,dir:Te?void 0:Le||"",workspaceId:Te||void 0,model:L.kind==="acp"&&Wd(L.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:L.providerSessionId});return}await le()},x.current=H,S(H),w({title:L.kind==="ide"?ea("restart-ide",L.label):L.providerSessionId?ku(L.label):ea("start-fresh",L.label),description:L.kind==="ide"?ta("restart-ide"):L.providerSessionId?Nu():ta("start-fresh"),confirmLabel:L.kind==="ide"?sa("restart-ide"):L.providerSessionId?Zn(!0):sa("start-fresh"),busyLabel:L.kind==="ide"?ra("restart-ide"):L.providerSessionId?vi(!0):ra("start-fresh"),workspaceOptions:ue,details:[{label:"Mode",value:L.kind.toUpperCase()},...L.providerType?[{label:"Provider",value:L.providerType}]:[]]})},[P,A]);if(l.useEffect(()=>{f(ae)},[E,ae,t]),l.useEffect(()=>{ne&&y(ne)},[ne,t]),!A)return p?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:_,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const xe=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Gt,{size:14})," Workspace"]}),count:T.length+B.length+D.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ps,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ma,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(zh,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Eh,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:_,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[P.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.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]"}),s.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"}),s.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"})]}):s.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(A.machineNickname||"")},title:"Click to set nickname",children:M}),b?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),c.retryConnection&&t&&s.jsx("button",{onClick:()=>c.retryConnection(t),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:"Reconnect"})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[A.platform," · ",A.arch]}),s.jsxs("span",{children:[A.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),A.p2p.available&&s.jsxs("span",{children:["P2P ",A.p2p.state==="connected"?"connected":A.p2p.state]}),A.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:A.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:xe.map(L=>s.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 ${g===L.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[L.label,L.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${g===L.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:L.count})]},L.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[g==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(DN,{machineEntry:u,providers:F,recentLaunches:be,currentConversations:Z,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",ep(u))}catch{}},onOpenRecent:ye,onOpenConversation:Y}),s.jsx(EN,{machine:A,machineId:t,ideSessions:T,cliSessions:B,acpSessions:D,actions:P,sendDaemonCommand:a})]}),g==="providers"&&s.jsx(K1,{machineId:t,providers:F,sendDaemonCommand:a}),g==="overview"&&s.jsx(_1,{machine:A,ideSessions:T,cliSessions:B,acpSessions:D}),g==="session-host"&&s.jsx(LN,{machineId:t,cliSessions:B,sendDaemonCommand:a}),g==="logs"&&s.jsx(SN,{machineId:t,sendDaemonCommand:a})]})})}),P.launchPick&&A&&s.jsx(PN,{machine:A,launchPick:P.launchPick,actions:P}),k&&s.jsx(dp,{title:k.title,description:k.description,details:k.details,workspaceOptions:k.workspaceOptions,selectedWorkspaceKey:C,onWorkspaceChange:L=>{x.current=L,S(L)},confirmLabel:k.confirmLabel,busyLabel:k.busyLabel,busy:I,onConfirm:ve,onCancel:()=>{v.current=null,w(null)}}),j&&s.jsx(lm,{daemonId:j.daemonId,workspace:j.workspace,onClose:()=>N(null)}),s.jsx(Cu,{toasts:c.toasts||[],onDismiss:L=>c.setToasts(ue=>ue.filter(H=>H.id!==L)),onClickToast:L=>{L.targetKey&&r(Br(L.targetKey))}}),s.jsx("style",{children:`
107
+ @keyframes toast-in {
108
+ from { opacity: 0; transform: translateX(40px); }
109
+ to { opacity: 1; transform: translateX(0); }
110
+ }
111
+ `})]})}const FN={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},um=l.createContext(null);function ON(){const e=l.useContext(um);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function da({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("polyline",{points:"1 20 1 14 7 14"}),s.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 zN({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"6",cy:"18",r:"3"}),s.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function HN({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"3 6 5 6 21 6"}),s.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 WN({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function pm({status:e}){const r={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 s.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-md",style:{background:r.color+"15",color:r.color,border:`1px solid ${r.color}25`},children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:r.color}}),r.label]})}function KN(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function UN({meshes:e,loading:t,error:r,onDismissError:n,daemons:a,features:o,showCreate:i,onToggleCreate:c,createName:d,onCreateNameChange:p,createRepoIdentity:u,onCreateRepoIdentityChange:m,createRepoRemoteUrl:h,onCreateRepoRemoteUrlChange:b,newMeshDaemonId:g,onNewMeshDaemonIdChange:f,newMeshWorkspace:j,onNewMeshWorkspaceChange:N,createPickerWorkspaces:y,onSelectMesh:v,onCreate:k,onCancelCreate:w}){return s.jsxs(Yr,{icon:s.jsx(rs,{}),title:"Repo Meshes",subtitle:`${e.length} mesh${e.length!==1?"es":""}`,widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,children:"+ Create Mesh"}),children:[r&&s.jsx(us,{variant:"error",onDismiss:n,className:"mb-4",children:r}),i&&s.jsxs(dt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:"Create Repo Mesh"}),o.createDaemonPicker&&s.jsx(St,{label:"Create on machine",hint:"Mesh setup is stored by the selected daemon.",children:s.jsx("select",{className:"input w-full",value:g,onChange:x=>f(x.target.value),disabled:!a.length,children:a.length===0?s.jsx("option",{value:"",children:"No connected daemon"}):a.map(x=>s.jsx("option",{value:x.id,children:KN(x)},x.id))})}),o.createDaemonPicker&&s.jsx(St,{label:"Workspace",hint:"Choose from workspaces registered by the selected daemon.",children:s.jsx("select",{className:"input w-full",value:j,onChange:x=>N(x.target.value),disabled:!g||!y.length,children:g?y.length===0?s.jsx("option",{value:"",children:"No registered workspaces"}):y.map(x=>s.jsx("option",{value:x.path,children:x.label?`${x.label} · ${x.path}`:x.path},x.id||x.path)):s.jsx("option",{value:"",children:"Select a machine first"})})}),s.jsx(St,{label:"Name",children:s.jsx(Mr,{value:d,onChange:x=>p(x.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(St,{label:"Repo remote URL (optional)",hint:"Provide a remote URL OR a stable identity.",children:s.jsx(Mr,{value:h,onChange:x=>b(x.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(St,{label:"Repo identity (optional)",hint:"Provide a remote URL OR a stable identity.",children:s.jsx(Mr,{value:u,onChange:x=>m(x.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:k,disabled:!d.trim()||!h.trim()&&!u.trim()||o.createDaemonPicker&&(!g||!j),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:w,children:"Cancel"})]})]}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):e.length===0?s.jsx(va,{icon:s.jsx(rs,{}),title:"No Repo Meshes",description:a.length>0?"Create a mesh to get started.":"Connect an ADHDev daemon first.",action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!a.length,onClick:c,children:"Create First Mesh"})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(x=>{var C;return s.jsx("button",{type:"button",onClick:()=>v(x.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:s.jsxs("div",{className:"flex justify-between items-start",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(rs,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:x.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:x.repoIdentity||x.repo_identity||"No repo identity"}),(x.defaultBranch||x.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(zN,{size:11}),x.defaultBranch||x.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(x.createdAt||x.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((C=x.nodes)==null?void 0:C.length)??x.nodeCount??0," node(s)"]})]})]})},x.id)})})]})}function sd(e){if(e.status!=="completed"&&e.status!=="failed")return null;const t=e.dispatchTimestamp?new Date(e.dispatchTimestamp).getTime():NaN,r=e.updatedAt?new Date(e.updatedAt).getTime():NaN;if(!Number.isFinite(t)||!Number.isFinite(r)||r<t)return null;const n=Math.round((r-t)/1e3);if(n<60)return`${n}s`;const a=Math.floor(n/60);return a<60?`${a}m ${n%60}s`:`${Math.floor(a/60)}h ${a%60}m`}function GN({queueSummary:e,queueLoading:t,queueError:r,activeDaemonId:n,onRefresh:a}){return s.jsxs(dt,{title:"Queue",description:"Inspect active queue work separately from historical completed, failed, and cancelled task records.",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[s.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(([o,i,c])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-text-muted",children:o}),s.jsx("div",{className:`text-lg font-bold ${c}`,children:i})]},String(o)))}),s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:a,disabled:t||!n,children:[s.jsx(da,{size:13}),t?"Loading...":"Refresh Queue"]})]}),r&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:r}),e?e.recent.length===0?s.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."}):s.jsx("div",{className:"flex flex-col gap-2",children:e.recent.map(o=>{var i;return s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"font-mono text-[11px] text-text-muted",children:o.id.slice(0,12)}),s.jsx(pm,{status:o.status}),o.staleAssigned&&s.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:o.staleReason||"Stale assignment",children:"stale"}),(((i=o.waitingOn)==null?void 0:i.length)??0)>0&&s.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: ${o.waitingOn.join(", ")}`,children:["waits on ",o.waitingOn.length," task",o.waitingOn.length>1?"s":""]}),o.blockedReason&&s.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:o.blockedReason,children:"blocked"}),sd(o)&&s.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:[sd(o),(o.requeueCount??0)>0?` · ${o.requeueCount} retr${o.requeueCount===1?"y":"ies"}`:""]})]}),o.message&&s.jsx("div",{className:"text-[12px] text-text-primary truncate",children:o.message})]}),s.jsxs("div",{className:"text-right text-[10px] text-text-muted shrink-0",children:[o.nodeId&&s.jsxs("div",{children:["node ",o.nodeId.slice(0,10)]}),o.sessionId&&s.jsxs("div",{children:["session ",o.sessionId.slice(0,10)]}),o.updatedAt&&s.jsx("div",{children:new Date(o.updatedAt).toLocaleTimeString()})]})]})},o.id)})}):s.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 VN(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 qN(e){if(!e)return null;const t=typeof e.stage=="string"?e.stage:null,r=e.passed===!0;if(!t)return null;const n={ran:r?"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 YN({file:e}){const r={added:"text-green-400",deleted:"text-red-400",modified:"text-amber-400",renamed:"text-blue-400"}[e.status??""]??"text-text-muted";return s.jsxs("div",{className:"flex items-center justify-between gap-2 py-0.5",children:[s.jsx("span",{className:`text-[11px] font-mono truncate flex-1 ${r}`,children:e.path}),(e.insertions!=null||e.deletions!=null)&&s.jsxs("span",{className:"text-[10px] text-text-muted shrink-0",children:[e.insertions!=null&&s.jsxs("span",{className:"text-green-400",children:["+",e.insertions]}),e.deletions!=null&&s.jsxs("span",{className:"text-red-400 ml-1",children:["-",e.deletions]})]})]})}function JN({item:e,activeDaemonId:t,sendCommand:r,onDismiss:n,onRefineNode:a,onRequeueLast:o}){var k,w,x;const[i,c]=l.useState(null),[d,p]=l.useState(null),[u,m]=l.useState(!1),[h,b]=l.useState(null),{label:g,color:f}=VN(e.reviewReason),j=qN(e.evidence.bootstrap),N=((k=e.diffSummary)==null?void 0:k.files)??[],y=((w=e.diffSummary)==null?void 0:w.baseRef)??null,v=l.useCallback(async C=>{if(!(!e.workspace||!t)){if(i===C){c(null),p(null);return}c(C),p(null),m(!0),b(null);try{const S=await r(t,"git_diff_file",{workspace:e.workspace,path:C,...y?{base:y}:{}});(S==null?void 0:S.success)!==!1&&typeof(S==null?void 0:S.diff)=="string"?p(S.diff):(S==null?void 0:S.diff)!=null?p(String(S.diff)):b((S==null?void 0:S.error)||"No diff available")}catch(S){b((S==null?void 0:S.message)||"Failed to load diff")}finally{m(!1)}}},[e.workspace,t,r,i,y]);return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary p-4 space-y-3",children:[s.jsxs("div",{className:"flex flex-wrap items-start gap-2 justify-between",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2 min-w-0",children:[s.jsx("span",{className:"text-[12px] font-semibold text-text-primary font-mono truncate max-w-[240px]",children:e.branch??e.nodeId}),s.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${f}`,children:g}),j&&s.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${j.color}`,children:j.label}),e.activeRefineJob&&s.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"})]}),s.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[s.jsx("button",{className:"btn btn-primary btn-sm text-[11px]",onClick:()=>a(e.nodeId),disabled:!!e.activeRefineJob,children:"Refine"}),s.jsx("button",{className:"btn btn-secondary btn-sm text-[11px]",onClick:()=>o(e.nodeId),children:"Requeue"}),s.jsx("button",{className:"btn btn-secondary btn-sm text-[11px]",onClick:()=>n(e.nodeId),children:"Dismiss"})]})]}),e.workspace&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate",children:e.workspace}),e.evidence.available&&s.jsxs("div",{className:"text-[11px] text-text-secondary space-y-0.5",children:[e.evidence.source==="task_completion"&&e.evidence.worker&&s.jsxs("span",{children:["Last task: ",s.jsx("span",{className:e.evidence.worker.status==="success"?"text-green-400":"text-red-400",children:e.evidence.worker.status}),e.evidence.worker.classification&&s.jsxs("span",{className:"text-text-muted ml-1",children:["(",e.evidence.worker.classification,")"]}),e.evidence.worker.errors.length>0&&s.jsxs("span",{className:"text-red-400 ml-1",children:["· ",e.evidence.worker.errors[0]]})]}),e.evidence.source==="refine_job"&&s.jsxs("span",{children:["Refinery: ",s.jsx("span",{className:"text-amber-400",children:e.convergence.status}),e.convergence.nextStep&&s.jsxs("span",{className:"text-text-muted ml-1",children:["→ ",e.convergence.nextStep]})]})]}),e.diffSummary&&e.diffSummary.files.length>0&&s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-3",children:[s.jsxs("span",{children:[e.diffSummary.totalFiles," file",e.diffSummary.totalFiles!==1?"s":""]}),s.jsxs("span",{className:"text-green-400",children:["+",e.diffSummary.totalInsertions]}),s.jsxs("span",{className:"text-red-400",children:["-",e.diffSummary.totalDeletions]}),e.diffSummary.truncated&&s.jsx("span",{className:"text-amber-400",children:"truncated"}),y&&s.jsxs("span",{className:"font-mono",children:["vs ",y]})]}),s.jsxs("div",{className:"border border-border-subtle rounded px-2 py-1 bg-bg-primary space-y-0.5",children:[N.slice(0,20).map(C=>s.jsxs("div",{children:[s.jsx("button",{className:"w-full text-left hover:bg-bg-secondary rounded px-1 transition-colors",onClick:()=>v(C.path),children:s.jsx(YN,{file:C})}),i===C.path&&s.jsx("div",{className:"mt-1 mb-1",children:s.jsx(im,{diff:d??"",loading:u,error:h??void 0,truncated:!1,className:"text-[10px]"})})]},C.path)),N.length>20&&s.jsxs("div",{className:"text-[10px] text-text-muted px-1 pt-0.5",children:["+",N.length-20," more files"]})]})]}),((x=e.diffSummary)==null?void 0:x.error)&&s.jsxs("div",{className:"text-[11px] text-amber-400",children:["Diff probe: ",e.diffSummary.error]})]})}function XN({items:e,loading:t,error:r,remoteNodesExcluded:n,meshId:a,activeDaemonId:o,onRefresh:i,onDismiss:c,onRefineNode:d,onRequeueLast:p,sendCommand:u}){return s.jsxs(dt,{title:"Review Inbox",description:"Local worktree nodes that need review: merge candidates and Refinery-blocked results. Click a file to preview its diff.",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[e.length>0&&s.jsxs("span",{className:"text-[12px] font-semibold text-accent-primary",children:[e.length," item",e.length!==1?"s":""]}),n&&s.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"})]}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:i,disabled:t,children:[s.jsx(da,{size:12}),t?"Loading...":"Refresh"]})]}),r&&s.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:r}),!t&&!r&&e.length===0&&s.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."]}),s.jsx("div",{className:"space-y-3",children:e.map(m=>s.jsx(JN,{item:m,activeDaemonId:o,sendCommand:u,onDismiss:c,onRefineNode:d,onRequeueLast:p},m.nodeId))})]})}function QN(e){const t=new Map;for(const r of e)r!=null&&r.id&&t.set(r.id,Xs(r.availableProviders||[]));return t}function ZN(e,t){const r=String(e.daemon_id||e.daemonId||"");return r&&t.has(r)?t.get(r):[]}function eS(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function tS(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",r=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${r}`}function mm(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function sS(e){const t=mm(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 rS(e){return e.isLocalWorktree===!0}function nS(e,t){const r=t;return[...Array.isArray(r==null?void 0:r.cliSessions)?r.cliSessions:[],...Array.isArray(r==null?void 0:r.acpSessions)?r.acpSessions:[],...Array.isArray(r==null?void 0:r.sessions)?r.sessions:[]].filter(a=>{var o;return((o=a==null?void 0:a.settings)==null?void 0:o.meshNodeId)===e.id||(a==null?void 0:a.workspace)===e.workspace}).map(a=>{var o;return{id:a.sessionId||a.id||a.instanceId||"unknown",provider:a.providerType||a.cliType||a.acpType||a.type||"unknown",status:a.status||((o=a.activeChat)==null?void 0:o.status)||"unknown"}})}function rd(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function aS(e,t){var r;return(e==null?void 0:e.ownerName)||(e==null?void 0:e.userName)||((r=e==null?void 0:e.user)==null?void 0:r.name)||t||"You"}function oS({nodes:e,meshQueue:t,activeDaemon:r,daemons:n,selectedMeshId:a,userName:o,features:i,coordinatorDaemonId:c,nodeProviderPriorityDrafts:d,onNodeProviderPriorityDraftChange:p,availableCliProviders:u,savingNodePolicyId:m,onUpdateNodeProviderPriority:h,nodeSystemPromptDrafts:b,onNodeSystemPromptDraftChange:g,savingNodeSystemPromptId:f,onSaveNodeSystemPrompt:j,selectedNodeId:N,onSelectNode:y,showAddNode:v,onShowAddNode:k,onCancelAddNode:w,nodeWorkspace:x,onNodeWorkspaceChange:C,nodeProviderPriority:S,onNodeProviderPriorityChange:I,nodeDaemonId:$,onNodeDaemonIdChange:R,nodeCustomPath:_,onNodeCustomPathChange:P,nodePickerWorkspaces:F,nodePickerProviders:q,attachableDaemons:A,onAddNode:T,onRemoveNode:B}){const D=l.useMemo(()=>QN(n),[n]);return s.jsxs(dt,{title:i.addNodeDaemonPicker?`Attached machine daemons (${e.length})`:"Nodes",description:i.addNodeDaemonPicker?"Setup inventory only. Live graph, git, session, queue, and node detail truth is owned by the Mesh Host status above.":"Workspaces participating in this mesh.",children:[i.addNodeDaemonPicker&&s.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Machine daemon candidates"}),s.jsx("div",{className:"text-[12px] text-text-muted",children:"Choose connected daemons to attach to the selected Mesh Host setup."})]}),s.jsxs("span",{className:"text-[11px] text-text-muted",children:[A.length," available"]})]}),n.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:"No connected machine daemons are currently available."}):A.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:"All connected machine daemons are already attached."}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:A.map(M=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${M.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{R(M.id),C(""),P(!1),I(Er(Xs(M.availableProviders||[]))),k()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate",children:rd(M)}),M.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary",children:"selected host"})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:M.id}),s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted",children:[(M.workspaces||[]).length," workspace(s) detected"]})]},M.id))})]}),!v&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:k,children:[s.jsx(WN,{size:13})," ",i.addNodeDaemonPicker?"Attach Machine Daemon":"+ Add Node"]}),v&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:i.addNodeDaemonPicker?"Attach Machine Daemon":"Add Node"}),s.jsx("button",{onClick:()=>{w(),R(""),P(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(yt,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(St,{label:"Machine",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:$,onChange:M=>{var E;R(M.target.value),C(""),P(!1),I(Er(Xs(((E=n.find(z=>z.id===M.target.value))==null?void 0:E.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:"Select a machine..."}),n.map(M=>s.jsx("option",{value:M.id,children:rd(M)},M.id))]})}),(i.addNodeDaemonPicker?$:!0)&&s.jsx(St,{label:"Workspace Path",children:i.addNodeDaemonPicker&&!_&&F.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:F.map(M=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${x===M.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:()=>C(M.path),children:[s.jsx("span",{className:"font-medium block truncate",children:M.label||M.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:M.path})]},M.id||M.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{P(!0),C("")},children:"Or enter a custom path →"})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(Mr,{value:x,onChange:M=>C(M.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:M=>{M.key==="Enter"&&T()}}),F.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{P(!1),C("")},children:"← Pick from saved workspaces"})]}):(()=>{var z;const M=Array.isArray(r==null?void 0:r.workspaces)?r.workspaces:[],E=`mesh-add-node-workspaces-${a||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(Mr,{value:x,onChange:Q=>C(Q.target.value),placeholder:((z=M[0])==null?void 0:z.path)||"/Users/dev/projects/myapp",list:M.length>0?E:void 0,autoFocus:!0}),M.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:E,children:M.map(Q=>s.jsx("option",{value:Q.path,children:Q.label||Q.path},Q.id||Q.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:M.slice(0,6).map(Q=>s.jsx("button",{type:"button",onClick:()=>C(Q.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:Q.path,children:Q.label||Q.path.split("/").filter(Boolean).pop()||Q.path},Q.id||Q.path))})]})]})})()})}),s.jsx(St,{label:i.addNodeDaemonPicker?"Default CLI providers":"Provider Priority",hint:"Order used when launching without an explicit provider.",children:s.jsx(Ql,{value:S,availableProviders:i.addNodeDaemonPicker?q:u,onChange:I})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:T,disabled:!x.trim()||i.addNodeDaemonPicker&&!$,className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>{w(),R(""),P(!1)},className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),i.addNodeDaemonPicker&&s.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?s.jsx(va,{icon:s.jsx(Vs,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:e.map(M=>{const E=sS(M),z=eS(M,t),Q=nS(M,r),J=N===M.id,ae=rS(M),ne=M.status||M.machine_status||(z.length>0||Q.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${i.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${J?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:i.addNodeDaemonPicker?void 0:"button",tabIndex:i.addNodeDaemonPicker?void 0:0,onClick:i.addNodeDaemonPicker?void 0:()=>y(J?null:M.id),onKeyDown:i.addNodeDaemonPicker?void 0:ce=>{(ce.key==="Enter"||ce.key===" ")&&(ce.preventDefault(),y(J?null:M.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.addNodeDaemonPicker?s.jsx("span",{className:"font-semibold text-sm text-text-primary truncate",children:M.machine_label||M.machine_nickname||M.hostname||M.workspace}):s.jsx("span",{className:"text-sm font-medium",children:M.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx(pm,{status:ne}),z.length>0&&!i.addNodeDaemonPicker&&s.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-orange-500/15 text-orange-300 border border-orange-500/25",children:[z.length," active task",z.length===1?"":"s"]}),ae&&s.jsx("span",{className:`text-[10px] px-2 py-0.5 rounded-full ${i.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"}),i.addNodeDaemonPicker&&s.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"})]}),i.addNodeDaemonPicker&&s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Owner: ",aS(n.find(ce=>ce.id===String(M.daemon_id||"")),o)," · Machine: ",M.machine_label||M.daemon_id||M.workspace]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:M.workspace}),ae&&s.jsxs("div",{className:`mt-2 rounded-lg px-3 py-2 text-[11px] ${i.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",M.worktreeBranch?` · ${M.worktreeBranch}`:"",". Provider priority saved here is node-local and disappears when removed."]}),i.addNodeDaemonPicker&&s.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."}),s.jsxs("div",{className:`mt-3 max-w-2xl ${i.addNodeDaemonPicker,""}`,onClick:ce=>ce.stopPropagation(),children:[s.jsxs(St,{label:i.addNodeDaemonPicker?"Default CLI providers":"Provider priority",hint:ae?"Worktree-local launch defaults. Configure the source node for durable defaults.":i.addNodeDaemonPicker?"Used for coordinator/session launches when no provider is selected explicitly.":"Used when launches omit an explicit provider.",children:[s.jsx(Ql,{value:d[M.id]??mm(M),availableProviders:ZN(M,D),onChange:ce=>p(M.id,ce),disabled:m===M.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:ce=>{ce.stopPropagation(),h(M)},disabled:m===M.id,children:m===M.id?"Saving...":i.addNodeDaemonPicker?"Save defaults":"Save policy"})}),s.jsxs("div",{className:"mt-2 text-[12px]",children:[s.jsx("span",{className:"text-text-muted",children:i.addNodeDaemonPicker?"Saved default order: ":"Effective provider priority: "}),s.jsx("span",{className:E.configured?"text-text-primary font-mono":"text-amber-400",children:E.label}),!E.configured&&E.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",E.launchBlockedMessage,")"]})]})]}),i.nodeInstruction&&s.jsxs(St,{label:"Node instruction (optional)",hint:"Surfaced in the coordinator system prompt as 📌 Node instruction.",children:[s.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:b[M.id]??"",onChange:ce=>{const be=ce.target.value;g(M.id,be)},onClick:ce=>ce.stopPropagation(),disabled:f===M.id,placeholder:"e.g. 'Run only smoke tests here', 'Use opus on this node'"}),s.jsx("div",{className:"mt-2 flex items-center gap-2",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:ce=>{ce.stopPropagation(),j(M)},disabled:f===M.id,children:f===M.id?"Saving…":"Save instruction"})})]})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${i.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:ce=>{ce.stopPropagation(),B(M.id)},title:"Remove node",children:i.addNodeDaemonPicker?s.jsx(HN,{size:14}):s.jsx(yt,{size:14})})]}),!i.addNodeDaemonPicker&&J&&s.jsxs("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Node ID:"})," ",s.jsx("span",{className:"font-mono",children:M.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:E.configured?"text-green-400":"text-amber-400",children:E.configured?"yes":"provider priority not configured"})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Repo root:"})," ",s.jsx("span",{className:"font-mono",children:M.repoRoot||M.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",Q.length]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),z.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:z.map(ce=>s.jsx("li",{className:"font-mono",children:tS(ce)},ce.id))})]}),Q.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active sessions"}),s.jsx("ul",{className:"m-0 pl-4",children:Q.map(ce=>s.jsxs("li",{className:"font-mono",children:[ce.provider," / ",ce.status," / ",ce.id]},ce.id))})]})]}),i.addNodeDaemonPicker&&s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:[s.jsxs("span",{className:"mr-3",children:["Node ID: ",M.id.slice(0,16),"..."]}),s.jsxs("span",{children:["Added: ",new Date(M.created_at||M.createdAt||Date.now()).toLocaleDateString()]})]})]},M.id)})})]})}function iS(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function lS({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:r,coordinatorCliType:n,onCoordinatorCliTypeChange:a,launchingCoordinator:o,launchResult:i,attachedDaemonIds:c,isHostNodeAttached:d,selectedHostNode:p,onLaunchCoordinator:u,onAttachSelectedHost:m}){return s.jsxs(dt,{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:[s.jsxs(us,{variant:"info",className:"mb-4",children:[s.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."]}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-[1fr_180px_auto] items-end",children:[s.jsx(St,{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:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:t,onChange:h=>r(h.target.value),children:[s.jsx("option",{value:"",children:"Select a Mesh Host..."}),e.map(h=>s.jsxs("option",{value:h.id,children:[iS(h)," · ",c.has(h.id)?"attached":"not attached"]},h.id))]})}),s.jsx(St,{label:"CLI provider",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:n,onChange:h=>a(h.target.value),children:[s.jsx("option",{value:"",children:"Use node provider priority"}),s.jsx("option",{value:"claude-cli",children:"Claude Code"}),s.jsx("option",{value:"codex-cli",children:"Codex"}),s.jsx("option",{value:"gemini-cli",children:"Gemini"}),s.jsx("option",{value:"hermes-cli",children:"Hermes"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm",onClick:u,disabled:!t||!d||o,title:!d&&t?"Attach this Mesh Host daemon first.":void 0,children:o?"Launching...":"Launch Host Coordinator"})]}),s.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?d?s.jsxs(s.Fragment,{children:["Host setup node: ",s.jsx("span",{className:"font-mono text-text-primary",children:p==null?void 0:p.workspace}),". Live graph/status/detail renders only from this daemon."]}):s.jsx(s.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."}),!d&&t&&s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm mt-3",onClick:m,children:"Attach selected host daemon"}),i&&s.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:i})]})}function cS({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const o=a.id.toLowerCase();return o==="hermes-cli"||o.includes("hermes")||a.name.toLowerCase().includes("hermes")}),n=rp(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(dt,{title:"Hermes MCP Config",description:"Hermes does not auto-import repo-local .mcp.json. Add this YAML under mcp_servers in Hermes config, then start a fresh Hermes session.",children:s.jsx(Cp,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}const jo=[{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."}],dS={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function Xo(e){return{...dS,...(e==null?void 0:e.policy)||{}}}function uS({selectedMesh:e,error:t,onDismissError:r,onBack:n,onDelete:a,displayedMeshStatus:o,graphLoading:i,graphError:c,graphProvenance:d,graphBootstrapFallback:p=!1,onRefreshGraph:u,queueSummary:m,queueLoading:h,queueError:b,onLoadQueue:g,savingPolicy:f,onUpdatePolicy:j,coordinatorPromptDraft:N,onCoordinatorPromptDraftChange:y,savingCoordinatorPrompt:v,onSaveCoordinatorPrompt:k,daemons:w,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:C,coordinatorCliType:S,onCoordinatorCliTypeChange:I,launchingCoordinator:$,launchResult:R,attachedDaemonIds:_,isHostNodeAttached:P,selectedHostNode:F,onLaunchCoordinator:q,activeDaemon:A,activeDaemonId:T,meshQueue:B,userName:D,nodeProviderPriorityDrafts:M,onNodeProviderPriorityDraftChange:E,availableCliProviders:z,savingNodePolicyId:Q,onUpdateNodeProviderPriority:J,nodeSystemPromptDrafts:ae,onNodeSystemPromptDraftChange:ne,savingNodeSystemPromptId:ce,onSaveNodeSystemPrompt:be,selectedNodeId:Z,onSelectNode:Y,showAddNode:ve,onShowAddNode:ye,onCancelAddNode:xe,nodeWorkspace:Se,onNodeWorkspaceChange:ie,nodeProviderPriority:we,onNodeProviderPriorityChange:pe,nodeDaemonId:W,onNodeDaemonIdChange:O,nodeCustomPath:V,onNodeCustomPathChange:oe,nodePickerWorkspaces:te,nodePickerProviders:X,attachableDaemons:L,onAddNode:ue,onRemoveNode:H,availableCliAgents:le,features:G,reviewInboxItems:Le,reviewInboxLoading:Te,reviewInboxError:Me,reviewInboxRemoteNodesExcluded:He,onLoadReviewInbox:qe,onDismissReviewInboxItem:Je,onRefineNode:st,onRequeueLast:Xe,sendCommand:ct}){var Ae;const at=Xo(e),ht=e.nodes||[];return s.jsxs(Yr,{icon:s.jsx(rs,{}),title:e.name,subtitle:e.repoIdentity||e.repo_identity||"Repo Mesh",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:n,children:"← Back"}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>u(!0),disabled:i,children:[s.jsx(da,{size:13}),i?"Probing...":"Refresh"]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>a(e.id),children:"Delete"})]}),children:[t&&s.jsx(us,{variant:"error",onDismiss:r,className:"mb-4",children:t}),s.jsxs(dt,{title:"Policy",description:"Coordinator safety defaults and session cleanup behavior.",children:[s.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[[{label:"Checkpoint before task",key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:ke=>ke?"yes":"no",parse:ke=>ke==="yes"},{label:"Checkpoint after task",key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:ke=>ke?"yes":"no",parse:ke=>ke==="yes"},{label:"Push approval",key:"requireApprovalForPush",opts:[["required","Require approval before push"],["not_required","Do not require approval"]],val:ke=>ke?"required":"not_required",parse:ke=>ke==="required"},{label:"Submodule main auto-publish",key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled","Require explicit approval"],["enabled","Allow Refinery non-force publish"]],val:ke=>ke?"enabled":"disabled",parse:ke=>ke==="enabled"},{label:"Destructive git approval",key:"requireApprovalForDestructiveGit",opts:[["required","Require approval"],["not_required","Do not require approval"]],val:ke=>ke?"required":"not_required",parse:ke=>ke==="required"},{label:"Dirty workspace behavior",key:"dirtyWorkspaceBehavior",opts:[["warn","Warn and continue"],["block","Block task"],["checkpoint_then_continue","Checkpoint then continue"]],val:ke=>ke||"warn",parse:ke=>ke}].map(({label:ke,key:Qe,opts:Ue,val:gt,parse:U})=>s.jsx(St,{label:ke,children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:gt(at[Qe]),onChange:K=>j({[Qe]:U(K.target.value)}),disabled:f,children:Ue.map(([K,re])=>s.jsx("option",{value:K,children:re},K))})},Qe)),s.jsx(St,{label:"Max parallel tasks",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:String(at.maxParallelTasks??2),onChange:ke=>j({maxParallelTasks:Number(ke.target.value)}),disabled:f,children:[1,2,3,4,5,6,7,8].map(ke=>s.jsx("option",{value:ke,children:ke},ke))})})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(St,{label:"Node removal session cleanup",hint:"Separate transcript cleanup from runtime/process cleanup.",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:at.sessionCleanupOnNodeRemove||"preserve",onChange:ke=>j({sessionCleanupOnNodeRemove:ke.target.value}),disabled:f,children:jo.map(ke=>s.jsx("option",{value:ke.value,children:ke.label},ke.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((Ae=jo.find(ke=>ke.value===at.sessionCleanupOnNodeRemove))==null?void 0:Ae.description)||jo[0].description})]}),f&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),G.coordinatorPrompt&&s.jsxs(dt,{title:"Coordinator prompt",description:"Customize the system prompt for coordinator sessions. Supports placeholders: {{meshName}}, {{repo}}, {{defaultBranch}}, {{cliType}}, {{nodes}}, {{policy}}, {{tools}}, {{workflow}}, {{rules}}, {{toolExposurePreflight}}.",children:[s.jsx(St,{label:"Override (replaces default)",hint:"When set, replaces the daemon's default base prompt. Leave empty to keep the default.",children:s.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:N.override,onChange:ke=>y({...N,override:ke.target.value}),disabled:v,placeholder:"(empty — daemon default applies)"})}),s.jsx(St,{label:"Append (added after the base)",hint:"Always added after whichever base prompt wins.",children:s.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:N.append,onChange:ke=>y({...N,append:ke.target.value}),disabled:v,placeholder:"(empty — nothing appended)"})}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:k,disabled:v,children:v?"Saving…":"Save coordinator prompt"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>y({override:"",append:""}),disabled:v,title:"Clear both fields. Click Save to commit.",children:"Clear"})]})]}),G.meshHostDaemonSection&&s.jsx(lS,{daemons:w,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:ke=>{C(ke),u()},coordinatorCliType:S,onCoordinatorCliTypeChange:I,launchingCoordinator:$,launchResult:R,attachedDaemonIds:_,isHostNodeAttached:P,selectedHostNode:F,onLaunchCoordinator:q,onAttachSelectedHost:()=>{O(x),ye()}}),G.queueSection&&s.jsx(GN,{queueSummary:m,queueLoading:h,queueError:b,activeDaemonId:T,onRefresh:g}),s.jsxs(dt,{title:"Mesh",description:"Overview cards (missions, ledger, queue, nodes, sessions) with the live topology graph behind the Graph tab.",children:[s.jsxs("div",{className:"mb-4 flex flex-wrap items-center justify-between gap-3",children:[s.jsx("div",{className:"text-[12px] text-text-muted max-w-2xl",children:G.meshHostDaemonSection?s.jsxs(s.Fragment,{children:["Direct aggregate mesh_status from the selected Mesh Host is preferred. Refresh asks the host for the latest peer git provenance.",d==="settling"&&s.jsx("span",{className:"ml-1 text-amber-300",children:"Refreshing peer data..."})]}):s.jsx(s.Fragment,{children:"Overview shows live mesh state as cards; switch to the Graph tab for the topology view."})}),s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>u(!0),disabled:i||G.meshHostDaemonSection&&!T,children:[s.jsx(da,{size:13}),i?"Loading...":"Refresh"]})]}),p&&s.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:[s.jsx("span",{className:"mt-0.5 shrink-0 text-amber-400","aria-hidden":!0,children:"⚠"}),s.jsx("span",{children:"Connecting to coordinator — showing setup inventory. Live data will appear shortly."})]}),c&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:c}),o?s.jsx(rm,{status:o,emptyMessage:G.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:T,sendDaemonCommand:ct,bootstrapFallback:p}):s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:i?"Loading graph...":G.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."})]}),G.reviewInbox&&s.jsx(XN,{items:Le,loading:Te,error:Me,remoteNodesExcluded:He,meshId:e.id,activeDaemonId:T,onRefresh:qe,onDismiss:Je,onRefineNode:st,onRequeueLast:Xe,sendCommand:ct}),s.jsx(oS,{nodes:ht,meshQueue:B,activeDaemon:A,daemons:w,selectedMeshId:e.id,userName:D,features:{addNodeDaemonPicker:G.addNodeDaemonPicker,nodeInstruction:G.nodeInstruction},coordinatorDaemonId:x,nodeProviderPriorityDrafts:M,onNodeProviderPriorityDraftChange:E,availableCliProviders:z,savingNodePolicyId:Q,onUpdateNodeProviderPriority:J,nodeSystemPromptDrafts:ae,onNodeSystemPromptDraftChange:ne,savingNodeSystemPromptId:ce,onSaveNodeSystemPrompt:be,selectedNodeId:Z,onSelectNode:Y,showAddNode:ve,onShowAddNode:ye,onCancelAddNode:xe,nodeWorkspace:Se,onNodeWorkspaceChange:ie,nodeProviderPriority:we,onNodeProviderPriorityChange:pe,nodeDaemonId:W,onNodeDaemonIdChange:O,nodeCustomPath:V,onNodeCustomPathChange:oe,nodePickerWorkspaces:te,nodePickerProviders:X,attachableDaemons:L,onAddNode:ue,onRemoveNode:H}),G.hermesMcpConfig&&s.jsx(cS,{meshId:e.id,availableCliAgents:le}),G.meshHostDaemonSection&&s.jsxs(us,{variant:"info",className:"mt-4",children:[s.jsx("strong",{children:"MCP Mode:"})," ",s.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 pS({daemons:e,primaryDaemonId:t,sendCommand:r,unwrapResult:n,normalizeMesh:a,features:o}){const[i,c]=l.useState([]),[d,p]=l.useState(null),[u,m]=l.useState(!0),[h,b]=l.useState(null),[g,f]=l.useState(!1),[j,N]=l.useState(""),[y,v]=l.useState(""),[k,w]=l.useState(""),[x,C]=l.useState(""),[S,I]=l.useState(""),$=l.useMemo(()=>e.find(T=>T.id===x),[e,x]),R=($==null?void 0:$.workspaces)||[],_=l.useMemo(()=>Xs(($==null?void 0:$.availableProviders)||[]),[$]),P=l.useCallback(async()=>{m(!0);try{if(o.createDaemonPicker){const T=await Promise.allSettled(e.map(async D=>{if(!D.id)return[];const M=await r(D.id,"list_meshes",{}),E=n(M);if((E==null?void 0:E.success)===!1)throw new Error(E.error||"Failed to load meshes");return(Array.isArray(E==null?void 0:E.meshes)?E.meshes:[]).map(z=>a(z,D.id)).filter(z=>z.id)})),B=new Map;for(const D of T)if(D.status==="fulfilled")for(const M of D.value)B.has(M.id)||B.set(M.id,M);c(Array.from(B.values()))}else{if(!t)return;const T=await r(t,"list_meshes");T!=null&&T.success?(c((T.meshes||[]).map(B=>a(B,t))),b(null)):b((T==null?void 0:T.error)||"Failed to load meshes")}}catch(T){b((T==null?void 0:T.message)||"Failed to load meshes")}finally{m(!1)}},[e,t,r,n,a,o.createDaemonPicker]);async function F(){var M,E;const T=o.createDaemonPicker?x:t;if(!T||!j.trim())return;const B=k.trim(),D=y.trim();if(!(!B&&!D))try{const z={name:j.trim()};B&&(z.repoRemoteUrl=B),D&&(z.repoIdentity=D);const Q=await r(T,"create_mesh",z),J=n(Q);if((J==null?void 0:J.success)===!1)throw new Error(J.error||"Create failed");const ae=typeof((M=J==null?void 0:J.mesh)==null?void 0:M.id)=="string"?J.mesh.id:"";if(ae&&o.createDaemonPicker&&S){const ne=await r(T,"add_mesh_node",{meshId:ae,daemonId:T,machineId:$==null?void 0:$.machineId,workspace:S,role:"host",providerPriority:Er(_)}),ce=n(ne);if((ce==null?void 0:ce.success)===!1)throw new Error(ce.error||"Mesh created but failed to attach workspace")}f(!1),N(""),v(""),w(""),I(""),await P(),(E=J==null?void 0:J.mesh)!=null&&E.id&&p(J.mesh.id)}catch(z){b((z==null?void 0:z.message)||"Create failed")}}async function q(T){var D;if(!confirm("Delete this mesh? This cannot be undone."))return;const B=((D=i.find(M=>M.id===T))==null?void 0:D.__sourceDaemonId)||t;try{const M=await r(B,"delete_mesh",{meshId:T}),E=n(M);if((E==null?void 0:E.success)===!1)throw new Error(E.error||"Failed to delete");d===T&&p(null),await P()}catch(M){b((M==null?void 0:M.message)||"Delete failed")}}function A(){f(!1),N(""),v(""),w("")}return{meshes:i,setMeshes:c,selectedMeshId:d,setSelectedMeshId:p,loading:u,error:h,setError:b,showCreate:g,setShowCreate:f,createName:j,setCreateName:N,createRepoIdentity:y,setCreateRepoIdentity:v,createRepoRemoteUrl:k,setCreateRepoRemoteUrl:w,newMeshDaemonId:x,setNewMeshDaemonId:C,newMeshWorkspace:S,setNewMeshWorkspace:I,createPickerWorkspaces:R,createPickerProviders:_,loadMeshes:P,handleCreate:F,handleDelete:q,cancelCreate:A}}function mS({selectedMesh:e,selectedMeshId:t,primaryDaemonId:r,activeDaemonId:n,daemons:a,availableCliProviders:o,sendCommand:i,unwrapResult:c,loadLiveMesh:d,resolveCommandTarget:p,launchCoordinator:u,features:m,loadMeshes:h,loadQueue:b,queueSection:g,setError:f}){const[j,N]=l.useState({}),[y,v]=l.useState(null),[k,w]=l.useState(null),[x,C]=l.useState(!1),[S,I]=l.useState(""),[$,R]=l.useState([]),[_,P]=l.useState(""),[F,q]=l.useState(!1),[A,T]=l.useState(""),[B,D]=l.useState(!1),[M,E]=l.useState(null),[z,Q]=l.useState(!1),[J,ae]=l.useState({override:"",append:""}),[ne,ce]=l.useState(!1),[be,Z]=l.useState({}),[Y,ve]=l.useState(null),ye=l.useMemo(()=>a.find(te=>te.id===_),[a,_]),xe=(ye==null?void 0:ye.workspaces)||[],Se=l.useMemo(()=>Xs((ye==null?void 0:ye.availableProviders)||[]),[ye]);async function ie(){const te=(e==null?void 0:e.__sourceDaemonId)||r;if(!t||!te)return;const X=S.trim();if(X)try{const L={meshId:t,workspace:X};m.addNodeDaemonPicker&&_?(L.daemonId=_,L.machineId=ye==null?void 0:ye.machineId,L.providerPriority=Pn($,Se)):L.providerPriority=Pn($,o);const ue=await i(te,"add_mesh_node",L),H=c(ue);if((H==null?void 0:H.success)===!1)throw new Error(H.error||"Add node failed");C(!1),I(""),R([]),P(""),q(!1),await h(),g||await b(t)}catch(L){f((L==null?void 0:L.message)||"Add node failed")}}async function we(te){var H;if(!e)return;const X=Xo(e),L=((H=[{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(le=>le.value===X.sessionCleanupOnNodeRemove))==null?void 0:H.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
112
+
113
+ Node removal cleanup policy: ${L}`))return;const ue=e.__sourceDaemonId||r;try{const le=await i(ue,"remove_mesh_node",{meshId:e.id,nodeId:te}),G=c(le);if((G==null?void 0:G.success)===!1)throw new Error(G.error||"Remove failed");k===te&&w(null),await h(),g||await b(t)}catch(le){f((le==null?void 0:le.message)||"Remove node failed")}}async function pe(te){if(!e)return;const X={...Xo(e),...te},L=e.__sourceDaemonId||r;try{Q(!0),f(null);const ue=await i(L,"update_mesh",{meshId:e.id,policy:X}),H=c(ue);if((H==null?void 0:H.success)===!1)throw new Error(H.error||"Policy update failed");await h()}catch(ue){f((ue==null?void 0:ue.message)||"Policy update failed")}finally{Q(!1)}}async function W(te){if(!t)return;const X=(e==null?void 0:e.__sourceDaemonId)||r,L=m.addNodeDaemonPicker?Se:o,ue=j[te.id]||hS(te),H=L.length>0?Pn(ue,L):qr(ue),le={...te.policy||{}};delete le.provider_priority,H.length?le.providerPriority=H:delete le.providerPriority;try{v(te.id),f(null);const G=await i(X,"update_mesh_node",{meshId:t,nodeId:te.id,policy:le,providerPriority:H}),Le=c(G);if((Le==null?void 0:Le.success)===!1){f(Le.error||"Node policy update failed");return}await h()}catch(G){f((G==null?void 0:G.message)||"Node policy update failed")}finally{v(null)}}async function O(){if(!r||!t)return;const X={...(e==null?void 0:e.coordinator)||{}};J.override.trim()?X.systemPromptOverride=J.override:delete X.systemPromptOverride,J.append.trim()?X.systemPromptAppend=J.append:delete X.systemPromptAppend,delete X.systemPromptSuffix;try{ce(!0),f(null);const L=await i(r,"update_mesh",{meshId:t,coordinator:X}),ue=c(L);if((ue==null?void 0:ue.success)===!1){f(ue.error||"Coordinator prompt save failed");return}await h()}catch(L){f((L==null?void 0:L.message)||"Coordinator prompt save failed")}finally{ce(!1)}}async function V(te){if(!r||!t)return;const X=(be[te.id]||"").trim();try{ve(te.id),f(null);const L=await i(r,"update_mesh_node",{meshId:t,nodeId:te.id,systemPrompt:X}),ue=c(L);if((ue==null?void 0:ue.success)===!1){f(ue.error||"Node instruction save failed");return}await h()}catch(L){f((L==null?void 0:L.message)||"Node instruction save failed")}finally{ve(null)}}async function oe(){if(e){f(null),E(null);try{D(!0);const te=d?await d(n,e.id,e):null,X=p(n,e.id,e,e.nodes||[],te);if("error"in X)throw new Error(X.error);const L=await u(X.targetDaemonId,{meshId:e.id,inlineMesh:X.inlineMesh,coordinatorNodeId:X.coordinatorNodeId,cliType:A.trim()||void 0});E(L.message)}catch(te){f((te==null?void 0:te.message)||"Coordinator launch failed")}finally{D(!1)}}}return{nodeProviderPriorityDrafts:j,setNodeProviderPriorityDrafts:N,savingNodePolicyId:y,selectedNodeId:k,setSelectedNodeId:w,showAddNode:x,setShowAddNode:C,nodeWorkspace:S,setNodeWorkspace:I,nodeProviderPriority:$,setNodeProviderPriority:R,nodeDaemonId:_,setNodeDaemonId:P,nodeCustomPath:F,setNodeCustomPath:q,nodePickerWorkspaces:xe,nodePickerProviders:Se,coordinatorCliType:A,setCoordinatorCliType:T,launchingCoordinator:B,launchResult:M,savingPolicy:z,coordinatorPromptDraft:J,setCoordinatorPromptDraft:ae,savingCoordinatorPrompt:ne,nodeSystemPromptDrafts:be,setNodeSystemPromptDrafts:Z,savingNodeSystemPromptId:Y,handleAddNode:ie,handleRemoveNode:we,handleUpdatePolicy:pe,handleUpdateNodeProviderPriority:W,handleSaveCoordinatorPrompt:O,handleSaveNodeSystemPrompt:V,handleLaunchCoordinator:oe}}function hS(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function fS(e){const t=e.filter(n=>n.status==="pending"||n.status==="assigned"),r=e.filter(n=>n.status==="completed"||n.status==="failed"||n.status==="cancelled");return{active:t.length,historical:r.length,activeCounts:{pending:t.filter(n=>n.status==="pending").length,assigned:t.filter(n=>n.status==="assigned").length},historicalCounts:{completed:r.filter(n=>n.status==="completed").length,failed:r.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 xS({primaryDaemonId:e,activeDaemonId:t,sendCommand:r,unwrapResult:n,loadLiveMesh:a,resolveCommandTarget:o}){const[i,c]=l.useState([]),[d,p]=l.useState(null),[u,m]=l.useState(!1),[h,b]=l.useState(null),g=l.useCallback(async j=>{if(!e||!j){c([]);return}try{const N=await r(e,"get_mesh_queue",{meshId:j});c(N!=null&&N.success?Array.isArray(N.queue)?N.queue:[]:[])}catch{c([])}},[e,r]);async function f(j){var N,y;if(j){m(!0),b(null);try{const v=a?await a(t,j.id,j):null,k=o(t,j.id,j,j.nodes||[],v);if("error"in k)throw new Error(k.error);const w=await r(k.targetDaemonId,"get_mesh_queue",{meshId:j.id}),x=n(w);if((x==null?void 0:x.success)===!1)throw new Error(x.error||"Queue load failed");const C=Array.isArray(((N=x==null?void 0:x.result)==null?void 0:N.rows)??(x==null?void 0:x.rows)??(x==null?void 0:x.queue))?((y=x==null?void 0:x.result)==null?void 0:y.rows)??(x==null?void 0:x.rows)??(x==null?void 0:x.queue):[];p(fS(C))}catch(v){b((v==null?void 0:v.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:d,queueLoading:u,queueError:h,loadQueue:g,handleLoadQueue:f}}function bS(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}function gS({selectedMeshId:e,loadMeshStatus:t,extractStatus:r,normalizeNode:n,gateIncompleteGraph:a}){const[o,i]=l.useState(null),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,h]=l.useState("idle"),[b,g]=l.useState(!1),f=l.useRef(!1);async function j(N,y=e,v=!1){if(!(!N||!y))try{d(!v&&o===null),h(v?"settling":"first_paint"),u(null);const k=await t(N,y,{refresh:v,retryProfile:v?"settled":"interactive"});g(bS(k));const w=r(k),x=n&&w?{...w,nodes:(w.nodes??[]).map(C=>n(C,w.meshId??y,""))}:w;if(x){if(a&&!v&&o!==null&&!wk(tm(x))){h("settling"),f.current||(f.current=!0,Promise.resolve().then(()=>j(N,y,!0)).finally(()=>{f.current=!1}));return}i(x),h("settled")}else i(null),u("mesh_status returned an unexpected payload."),h("idle")}catch(k){o||i(null),u((k==null?void 0:k.message)||"Failed to load mesh graph"),h("idle")}finally{d(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:p,setGraphError:u,graphProvenance:m,graphBootstrapFallback:b,loadGraph:j}}function yS({primaryDaemonId:e,sendCommand:t}){const[r,n]=l.useState([]),[a,o]=l.useState(!1),[i,c]=l.useState(null),[d,p]=l.useState(!1),[u,m]=l.useState(new Set),h=l.useCallback(async f=>{if(!e||!f){n([]);return}o(!0),c(null);try{const j=await t(e,"get_mesh_review_inbox",{meshId:f});j!=null&&j.success?(n(Array.isArray(j.inbox)?j.inbox:[]),p(j.remoteNodesExcluded===!0)):(c((j==null?void 0:j.error)||"Failed to load review inbox"),n([]))}catch(j){c((j==null?void 0:j.message)||"Failed to load review inbox"),n([])}finally{o(!1)}},[e,t]),b=l.useCallback(f=>{m(j=>new Set([...j,f]))},[]);return{items:r.filter(f=>!u.has(f.nodeId)),allItems:r,loading:a,error:i,remoteNodesExcluded:d,dismissedNodeIds:u,loadInbox:h,dismissItem:b}}function vS(){const e=ON(),{sendCommand:t,sendData:r,daemons:n,userName:a,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:d,unwrapResult:p,normalizeMesh:u,normalizeNode:m,resolveCommandTarget:h,features:b,gateIncompleteGraph:g}=e,f=n[0],j=(f==null?void 0:f.id)||"",N=l.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(et=>et.category==="cli").map(et=>({id:et.type||et.id,name:et.displayName||et.name||et.type,meshCoordinator:et.meshCoordinator})),[f]),y=l.useMemo(()=>Xs((f==null?void 0:f.availableProviders)||[]),[f]),{meshes:v,selectedMeshId:k,setSelectedMeshId:w,loading:x,error:C,setError:S,showCreate:I,setShowCreate:$,createName:R,setCreateName:_,createRepoIdentity:P,setCreateRepoIdentity:F,createRepoRemoteUrl:q,setCreateRepoRemoteUrl:A,newMeshDaemonId:T,setNewMeshDaemonId:B,newMeshWorkspace:D,setNewMeshWorkspace:M,createPickerWorkspaces:E,loadMeshes:z,handleCreate:Q,handleDelete:J,cancelCreate:ae}=pS({daemons:n,primaryDaemonId:j,sendCommand:t,unwrapResult:p,normalizeMesh:u,features:b}),ne=v.find(De=>De.id===k)||null,{meshGraphStatus:ce,setMeshGraphStatus:be,graphLoading:Z,graphError:Y,setGraphError:ve,graphProvenance:ye,graphBootstrapFallback:xe,loadGraph:Se}=gS({selectedMeshId:k,loadMeshStatus:o,extractStatus:d,normalizeNode:m,gateIncompleteGraph:g}),[ie,we]=l.useState(""),pe=b.meshHostDaemonSection&&ie||j,{meshQueue:W,queueSummary:O,queueLoading:V,queueError:oe,loadQueue:te,handleLoadQueue:X}=xS({primaryDaemonId:j,activeDaemonId:pe,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:h}),{items:L,loading:ue,error:H,remoteNodesExcluded:le,loadInbox:G,dismissItem:Le}=yS({primaryDaemonId:j,sendCommand:t}),{nodeProviderPriorityDrafts:Te,setNodeProviderPriorityDrafts:Me,savingNodePolicyId:He,selectedNodeId:qe,setSelectedNodeId:Je,showAddNode:st,setShowAddNode:Xe,nodeWorkspace:ct,setNodeWorkspace:at,nodeProviderPriority:ht,setNodeProviderPriority:Ae,nodeDaemonId:ke,setNodeDaemonId:Qe,nodeCustomPath:Ue,setNodeCustomPath:gt,nodePickerWorkspaces:U,nodePickerProviders:K,coordinatorCliType:re,setCoordinatorCliType:he,launchingCoordinator:ge,launchResult:je,savingPolicy:ee,coordinatorPromptDraft:se,setCoordinatorPromptDraft:fe,savingCoordinatorPrompt:Ce,nodeSystemPromptDrafts:Pe,setNodeSystemPromptDrafts:Ie,savingNodeSystemPromptId:Re,handleAddNode:Be,handleRemoveNode:_e,handleUpdatePolicy:ze,handleUpdateNodeProviderPriority:Ve,handleSaveCoordinatorPrompt:ut,handleSaveNodeSystemPrompt:vt,handleLaunchCoordinator:ft}=mS({selectedMesh:ne,selectedMeshId:k,primaryDaemonId:j,activeDaemonId:pe,daemons:n,availableCliProviders:y,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:h,launchCoordinator:i,features:{addNodeDaemonPicker:b.addNodeDaemonPicker},loadMeshes:z,loadQueue:te,queueSection:b.queueSection,setError:S}),pt=l.useMemo(()=>n.find(De=>De.id===pe)||f,[n,pe,f]),Oe=l.useMemo(()=>new Set(((ne==null?void 0:ne.nodes)||[]).map(De=>String(De.daemon_id||De.daemonId||""))),[ne]),Et=l.useMemo(()=>n.filter(De=>De.id&&!Oe.has(De.id)),[n,Oe]),de=(ne==null?void 0:ne.nodes)||[],$e=l.useMemo(()=>de.find(De=>String(De.daemon_id||De.daemonId||"")===ie),[de,ie]),me=b.meshHostDaemonSection?!!$e:!0,Ee=l.useMemo(()=>ce?[...new Set((ce.nodes??[]).map(De=>String(De.daemonId||De.daemon_id||"")).filter(Boolean))]:[],[ce]),kt=am({status:ce,daemonId:pe||null,extraDaemonIds:Ee,meshId:k,sendData:r});return l.useEffect(()=>{Me(Object.fromEntries(((ne==null?void 0:ne.nodes)||[]).map(De=>[De.id,wS(De)])))},[ne]),l.useEffect(()=>{const De=(ne==null?void 0:ne.coordinator)||{};fe({override:typeof De.systemPromptOverride=="string"?De.systemPromptOverride:"",append:typeof De.systemPromptAppend=="string"?De.systemPromptAppend:typeof De.systemPromptSuffix=="string"?De.systemPromptSuffix:""}),Ie(Object.fromEntries(((ne==null?void 0:ne.nodes)||[]).map(et=>[et.id,typeof et.systemPrompt=="string"?et.systemPrompt:""])))},[ne]),l.useEffect(()=>{const De=b.addNodeDaemonPicker?Er(K):Er(y);st&&ht.length===0&&De.length>0&&Ae(De)},[st,y,K,ht.length,b.addNodeDaemonPicker]),l.useEffect(()=>{const De=new Set(((ne==null?void 0:ne.nodes)||[]).map(et=>et.id));qe&&!De.has(qe)&&Je(null)},[ne,qe]),l.useEffect(()=>{if(b.meshHostDaemonSection){if(!n.length){we("");return}(!ie||!n.some(De=>De.id===ie))&&we(n[0].id)}},[n,ie,b.meshHostDaemonSection]),l.useEffect(()=>{if(b.createDaemonPicker){if(!n.length){B("");return}(!T||!n.some(De=>De.id===T))&&B(n[0].id)}},[n,T,b.createDaemonPicker]),l.useEffect(()=>{var De;if(!b.createDaemonPicker||!T){M("");return}if(!E.length){M("");return}E.some(et=>et.path===D)||M(((De=E[0])==null?void 0:De.path)||"")},[T,D,E,b.createDaemonPicker]),l.useEffect(()=>{k&&(be(null),ve(null),Se(pe,k))},[k,pe]),l.useEffect(()=>{b.queueSection||te(k)},[k,b.queueSection]),l.useEffect(()=>{!b.reviewInbox||!k||G(k)},[k,b.reviewInbox]),l.useEffect(()=>{z()},[z]),j?ne?s.jsx(uS,{selectedMesh:ne,error:C,onDismissError:()=>S(null),onBack:()=>{w(null),be(null)},onDelete:J,displayedMeshStatus:kt,graphLoading:Z,graphError:Y,graphProvenance:ye,graphBootstrapFallback:xe,onRefreshGraph:()=>Se(pe,k,!0),queueSummary:O,queueLoading:V,queueError:oe,onLoadQueue:()=>X(ne),savingPolicy:ee,onUpdatePolicy:ze,coordinatorPromptDraft:se,onCoordinatorPromptDraftChange:fe,savingCoordinatorPrompt:Ce,onSaveCoordinatorPrompt:ut,daemons:n,coordinatorDaemonId:ie,onCoordinatorDaemonIdChange:De=>{we(De),be(null)},coordinatorCliType:re,onCoordinatorCliTypeChange:he,launchingCoordinator:ge,launchResult:je,attachedDaemonIds:Oe,isHostNodeAttached:me,selectedHostNode:$e,onLaunchCoordinator:ft,activeDaemon:pt,activeDaemonId:pe,meshQueue:W,userName:a,nodeProviderPriorityDrafts:Te,onNodeProviderPriorityDraftChange:(De,et)=>Me(Bt=>({...Bt,[De]:et})),availableCliProviders:y,savingNodePolicyId:He,onUpdateNodeProviderPriority:Ve,nodeSystemPromptDrafts:Pe,onNodeSystemPromptDraftChange:(De,et)=>Ie(Bt=>({...Bt,[De]:et})),savingNodeSystemPromptId:Re,onSaveNodeSystemPrompt:vt,selectedNodeId:qe,onSelectNode:Je,showAddNode:st,onShowAddNode:()=>Xe(!0),onCancelAddNode:()=>Xe(!1),nodeWorkspace:ct,onNodeWorkspaceChange:at,nodeProviderPriority:ht,onNodeProviderPriorityChange:Ae,nodeDaemonId:ke,onNodeDaemonIdChange:Qe,nodeCustomPath:Ue,onNodeCustomPathChange:gt,nodePickerWorkspaces:U,nodePickerProviders:K,attachableDaemons:Et,onAddNode:Be,onRemoveNode:_e,availableCliAgents:N,features:{coordinatorPrompt:b.coordinatorPrompt,meshHostDaemonSection:b.meshHostDaemonSection,queueSection:b.queueSection,hermesMcpConfig:b.hermesMcpConfig,addNodeDaemonPicker:b.addNodeDaemonPicker,nodeInstruction:b.nodeInstruction,reviewInbox:b.reviewInbox??!1},reviewInboxItems:L,reviewInboxLoading:ue,reviewInboxError:H,reviewInboxRemoteNodesExcluded:le,onLoadReviewInbox:()=>k&&void G(k),onDismissReviewInboxItem:Le,onRefineNode:async De=>{k&&(await t(pe,"refine_mesh_node",{meshId:k,nodeId:De,inlineMesh:ne}),G(k))},onRequeueLast:async De=>{k&&(await t(pe,"requeue_mesh_queue_task",{meshId:k,nodeId:De}),G(k))},sendCommand:t}):s.jsx(UN,{meshes:v,loading:x,error:C,onDismissError:()=>S(null),daemons:n,features:{createDaemonPicker:b.createDaemonPicker},showCreate:I,onToggleCreate:()=>$(!I),createName:R,onCreateNameChange:_,createRepoIdentity:P,onCreateRepoIdentityChange:F,createRepoRemoteUrl:q,onCreateRepoRemoteUrlChange:A,newMeshDaemonId:T,onNewMeshDaemonIdChange:B,newMeshWorkspace:D,onNewMeshWorkspaceChange:M,createPickerWorkspaces:E,onSelectMesh:w,onCreate:Q,onCancelCreate:ae}):s.jsx(Yr,{icon:s.jsx(rs,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})})}function wS(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function jS({children:e}){const{sendCommand:t,sendData:r}=lt(),{ides:n}=es(),a=l.useMemo(()=>n.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[n]),o=l.useMemo(()=>({sendCommand:t,sendData:r,daemons:a,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var h;const d={meshId:c.meshId};c.cliType&&(d.cliType=c.cliType);const p=await t(i,"launch_mesh_coordinator",d),u=(p==null?void 0:p.result)??p;if((u==null?void 0:u.success)===!1)throw new Error(u.error||"Coordinator launch failed");const m=(u==null?void 0:u.sessionId)||((h=u==null?void 0:u.session)==null?void 0:h.id)||(u==null?void 0:u.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Hp,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:FN}),[t,r,a]);return s.jsx(um.Provider,{value:o,children:e})}function Yi(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function kS(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=Yi();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Yt(e,t){return await fetch(kS(e),{credentials:"same-origin",...t})}function hm(){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 NS{constructor(){Ke(this,"adapters",new Map);Ke(this,"states",new Map);Ke(this,"runtimeListeners",new Map);Ke(this,"screenshotCallbacks",new Map);Ke(this,"statusCallbacks",new Set);Ke(this,"stateChangeCallbacks",new Set);Ke(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r);const n=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(a=>a(n,r))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,r){return!1}sendPtyInput(t,r,n){return this.ptyInputSender?this.ptyInputSender(t,r,n):!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,o,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:o,rows:i})}emitSessionOutput(t,r,n){!t||typeof r!="string"||!r||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(t,r){const n=this.runtimeListeners.get(t)||new Set;return n.add(r),this.runtimeListeners.set(t,n),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,r,n){if(!r)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`,window.location.origin);typeof(n==null?void 0:n.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(n.sinceSeq));const o=await Yt(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const i=await o.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const qt=new NS;function SS(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Yi();return r?`${t}?token=${encodeURIComponent(r)}`:t}const An=SS(),nd=3e3,CS=3e4;let Ht=null,IS=0;const ua=new Map;let gs=null,_r=null;function ad(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function gr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function MS(e){return e==="connected"?"connected":e}async function Lr(e,t,r){const n=Tu(e,r||{}),a=Ht;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++IS}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{ua.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);ua.set(o,{resolve:p=>{clearTimeout(d),i(p)},reject:p=>{clearTimeout(d),c(p)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Qo(e,t){const r=Ht;if(!r||r.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(t)),!0}catch{return!1}}function fm(e,t,r){const n=Ht;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Tu(e,{sessionId:t,targetSessionId:t,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}qt.registerPtyInputSender(fm);class AS{constructor(t){Ke(this,"daemonId");Ke(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Ht==null?void 0:Ht.readyState)===WebSocket.OPEN}get connectionState(){return(Ht==null?void 0:Ht.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Lr(this.daemonId,t,r)}async sendInput(t,r){return Lr(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,gs&&(clearInterval(gs),gs=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Lr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(o=>o.blob());qt.emitScreenshot(this.daemonId,a)}}catch{}};r(),gs=setInterval(r,2e3)}stopScreenshots(t){gs&&(clearInterval(gs),gs=null)}}let Rt=null;function TS(e){return(!Rt||Rt.daemonId!==e)&&(Rt=new AS(e)),Rt}function _S({children:e}){const t=l.useRef(Rr()),r=Rr();t.current=r;const{setUserName:n}=es(),a=l.useRef(n);a.current=n;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((f,j)=>{c(f),_r==null||_r(f,j)},[]),p=l.useRef(null),u=l.useRef(),m=l.useRef(nd),h=l.useRef(!0),b=l.useRef(!1),g=l.useRef("initial_connect");return l.useEffect(()=>{h.current=!0,b.current=!1;function f(){var y,v;if(!h.current||((y=p.current)==null?void 0:y.readyState)===WebSocket.OPEN||((v=p.current)==null?void 0:v.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${An}...`),gr("connect_attempt",{url:An,reason:g.current,delayMs:m.current});let N;try{N=new WebSocket(An)}catch(k){console.error("[Standalone WS] Failed to create WebSocket:",k),j();return}p.current=N,N.onopen=()=>{if(!h.current){N.close();return}d("connected"),m.current=nd,gr("open",{url:An,reason:g.current}),Zt.resubscribeAll({sendData:Qo}),console.log("[Standalone WS] Connected")},Ht=N,N.onmessage=k=>{var w,x;try{const C=JSON.parse(k.data);if((C.type==="command_result"||C.type==="error")&&C.requestId){const S=ua.get(C.requestId);S&&(ua.delete(C.requestId),C.type==="error"?S.reject(new Error(((w=C.data)==null?void 0:w.message)||"Command failed")):S.resolve(C.data));return}if(C.type==="session_output"){const S=C.sessionId||C.cliId||C.cliType;S&&qt.emitSessionOutput(S,typeof C.data=="string"?C.data:"",typeof C.seq=="number"?C.seq:void 0);return}if(C.type==="runtime_snapshot"){qt.emitRuntimeSnapshot(C.sessionId,typeof C.text=="string"?C.text:"",typeof C.seq=="number"?C.seq:0,!!C.truncated,typeof C.cols=="number"?C.cols:void 0,typeof C.rows=="number"?C.rows:void 0);return}if(C.type==="topic_update"){const S=C.update;S&&Zt.publish(S);return}if(C.type==="status"||C.type==="initial_state"){const S=C.data;if(!S)return;const{injectEntries:I,markLoaded:$,getIdes:R}=t.current,_=S.instanceId||"standalone",P=R().find(A=>A.id===_),F=TS(_);qt.register(_,F),qt.setState(_,"connected"),d("connected",_),qt.emitStatus(_,S);const q=Jn(S,{daemonId:_,existingDaemon:P,existingEntries:R()});ad("ws_status",{type:C.type,daemonId:_,sessions:(S.sessions||[]).map(A=>({id:A.id,parentId:A.parentId,providerType:A.providerType,kind:A.kind,transport:A.transport,unread:A.unread,inboxBucket:A.inboxBucket,lastSeenAt:A.lastSeenAt,lastUpdated:A.lastUpdated,title:A.title})),recentLaunches:(S.recentLaunches||[]).map(A=>({id:A.id,providerType:A.providerType,kind:A.kind,workspace:A.workspace,lastLaunchedAt:A.lastLaunchedAt}))}),ad("entries",{daemonId:_,entries:q.filter(A=>A.type!=="adhdev-daemon").map(A=>({id:A.id,type:A.type,unread:A.unread,inboxBucket:A.inboxBucket,lastSeenAt:A.lastSeenAt,lastUpdated:A.lastUpdated,sessionId:A.sessionId}))}),q.length>0&&I(q,{authoritativeDaemonIds:[_]}),$(),i.current!==_&&((x=o.current)==null||x.call(o),i.current=_,o.current=Zt.subscribe({sendData:Qo},_,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${_}`,params:{includeSessions:!0}},A=>{if(A.topic!=="daemon.metadata")return;const T=t.current.getIdes(),B=T.find(M=>M.id===_),D=Jn(A.status,{daemonId:_,existingDaemon:B,existingEntries:T,timestamp:A.timestamp});D.length>0&&t.current.injectEntries(D,{authoritativeDaemonIds:[_]}),A.userName&&a.current&&a.current(A.userName)}))}}catch(C){console.error("[Standalone WS] Parse error:",C)}},N.onclose=k=>{h.current&&(Rt==null||Rt.stopScreenshots(),Rt&&qt.setState(Rt.daemonId,"disconnected"),d("disconnected"),p.current=null,g.current=`close:${k.code}${k.wasClean?":clean":":unclean"}`,gr("close",{code:k.code,reason:k.reason||"",wasClean:k.wasClean}),j())},N.onerror=k=>{b.current||!h.current||(g.current="error",gr("error",{message:k instanceof Event?"event":String(k),readyState:N.readyState}),console.warn("[Standalone WS] Error, will reconnect:",k))}}function j(){if(!h.current)return;clearTimeout(u.current);const N=m.current;console.log(`[Standalone WS] Reconnecting in ${N}ms...`),gr("schedule_reconnect",{reason:g.current,delayMs:N}),u.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,CS),f()},N)}return f(),()=>{var N;h.current=!1,b.current=!0,(N=o.current)==null||N.call(o),o.current=null,i.current=null,clearTimeout(u.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,Ht=null),Rt&&(Rt.stopScreenshots(),qt.unregister(Rt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function LS({children:e}){const[t,r]=l.useState("disconnected"),[n,a]=l.useState(null);l.useEffect(()=>(_r=(i,c)=>{r(i),c&&a(c)},()=>{_r=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=MS(t),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d}},[t,n]);return s.jsx(kh,{connectionOverrides:o,children:s.jsx(_S,{children:e})})}const xm="adhdev_standalone_font_preferences",Is={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Ma=[{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"}],Or=[{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"}],PS=new Set(Ma.map(e=>e.id)),RS=new Set(Or.map(e=>e.id));function Xt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Wn("chat",t.chat),code:Wn("code",t.code),terminal:Wn("terminal",t.terminal)}}function Wn(e,t){const r=Is[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",o=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?PS:RS).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Kn(e,t){var a;const r=Wn(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?Ma:Or;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function DS(e){const t=Xt(e),r=Kn("chat",t.chat),n=Kn("code",t.code),a=Kn("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function vs(e,t=document.documentElement){const r=Xt(e),n=DS(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function Zo(e){const t=Xt(e);try{localStorage.setItem(xm,JSON.stringify(t))}catch{}return t}function $S(){try{const e=localStorage.getItem(xm);if(e)return Xt(JSON.parse(e))}catch{}return Is}function ES(){return vs($S())}function yr(e,t){var n;const r=e==="chat"?Ma:Or;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const BS=[{id:"dashboard",path:"/dashboard",icon:s.jsx(gd,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(ps,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(Ys,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(ma,{}),label:"Settings"}];function FS({children:e}){const t=zr(),r=ti(),n=l.useMemo(()=>BS.map(o=>({...o,active:r.pathname.startsWith(o.path),onSelect:()=>t(o.path)})),[r.pathname,t]),a=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Docs"}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(vd,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(wd,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(d0,{brand:({collapsed:o})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!o&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:o})=>o?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.82"]}),footerActions:({collapsed:o,toggleCollapsed:i})=>s.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":"mt-1"}`,onClick:i,title:o?"Expand sidebar":"Collapse sidebar",children:[s.jsx("span",{className:"nav-icon text-base",children:o?"›":"‹"}),!o&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const OS=[{icon:s.jsx(ps,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ls,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(jd,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Gt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Ys,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(vd,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],zS=[{icon:s.jsx(Wh,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(gd,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Hr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx($h,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(yd,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Fh,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],HS=[{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 WS(){return s.jsxs(Yr,{icon:s.jsx(wd,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.9.82"]}),children:[s.jsx(dt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),s.jsx(dt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:OS.map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(dt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:_u.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Pu.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Lu.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(dt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:zS.map(e=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(dt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),s.jsx("tbody",{children:HS.map((e,t)=>s.jsxs("tr",{className:t%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),s.jsx(va,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:"Cloud is optional, not required",description:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(Qh,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function ko(e,t,r){return{...e,[t]:r}}function No({surface:e,title:t,description:r,value:n,options:a,onChange:o}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:i=>{const c=i.target.value;o(c==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:c})},children:a.map(i=>s.jsx("option",{value:i.id,children:i.label},i.id))}),n.preset==="custom"&&s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:i=>o({preset:"custom",customFamily:i.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:Kn(e,n)})]})]})]})}function KS({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:d}){const p=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&s.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&s.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(No,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Ma,onChange:u=>o(ko(e,"chat",u))}),s.jsx(No,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Or,onChange:u=>o(ko(e,"code",u))}),s.jsx(No,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Or,onChange:u=>o(ko(e,"terminal",u))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",yr("chat",e.chat.preset)," · Code: ",yr("code",e.code.preset)," · Terminal: ",yr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",yr("chat",Is.chat.preset)," / ",yr("code",Is.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:i,disabled:r||!p,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),s.jsx("button",{type:"button",onClick:c,disabled:r||!p,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),s.jsx("button",{type:"button",onClick:d,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function US(){const{ides:e}=es(),t=e.find(Z=>Z.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=lt(),{userName:a}=es(),[o,i]=l.useState(a||""),[c,d]=l.useState(null),[p,u]=l.useState(null),[m,h]=l.useState(Is),[b,g]=l.useState(!1),[f,j]=l.useState(""),[N,y]=l.useState(""),[v,k]=l.useState("127.0.0.1"),[w,x]=l.useState(""),[C,S]=l.useState(""),[I,$]=l.useState(""),[R,_]=l.useState(""),[P,F]=l.useState(""),[q,A]=l.useState(!1),T=async()=>{const Y=await(await Yt("/auth/session")).json();d(Y)},B=async()=>{const Y=await(await Yt("/api/v1/standalone/preferences")).json();u(Y),k(Y.standaloneBindHost);const ve=Xt(Y.standaloneFontPreferences);h(ve),vs(ve),Zo(ve)};l.useEffect(()=>{a!==void 0&&i(a)},[a]),l.useEffect(()=>{Promise.all([T(),B()]).catch(Z=>{_(Z instanceof Error?Z.message:String(Z))})},[]),l.useEffect(()=>{vs(m)},[m]);const D=Z=>{const Y=Z.target.value.trim();t!=null&&t.id&&Y!==a&&n(t.id,"set_user_name",{userName:Y}).catch(console.error)},[M,E]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),z=Z=>{E(Z);try{localStorage.setItem("adhdev_sound",Z?"1":"0")}catch{}},Q=async()=>{j(""),y(""),g(!0);try{const Z=Xt(m),Y=await Yt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:Z})}),ve=await Y.json();if(!Y.ok)throw new Error((ve==null?void 0:ve.error)||"Failed to save standalone font preferences");const ye=Xt(ve.standaloneFontPreferences);u(ve),h(ye),vs(ye),Zo(ye),y("Standalone chat fonts saved for this self-hosted dashboard.")}catch(Z){j(Z instanceof Error?Z.message:String(Z))}finally{g(!1)}},J=()=>{const Z=Xt(p==null?void 0:p.standaloneFontPreferences);j(""),y(""),h(Z),vs(Z)},ae=()=>{j(""),y(""),h(Is),vs(Is)},ne=async()=>{_(""),F(""),A(!0);try{const Z=await Yt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:v})}),Y=await Z.json();if(!Z.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to save standalone network preference");u(Y),k(Y.standaloneBindHost),F(Y.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(Z){_(Z instanceof Error?Z.message:String(Z))}finally{A(!1)}},ce=async()=>{if(_(""),F(""),C.trim().length<4){_("Password must be at least 4 characters.");return}if(C!==I){_("New password and confirmation do not match.");return}A(!0);try{const Z=await Yt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,newPassword:C})}),Y=await Z.json();if(!Z.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to save password");d(Y),await B(),x(""),S(""),$(""),F(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),hm()}catch(Z){_(Z instanceof Error?Z.message:String(Z))}finally{A(!1)}},be=async()=>{_(""),F(""),A(!0);try{const Z=await Yt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,clear:!0})}),Y=await Z.json();if(!Z.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to clear password");d(Y),await B(),x(""),S(""),$(""),F("Standalone password disabled.")}catch(Z){_(Z instanceof Error?Z.message:String(Z))}finally{A(!1)}};return s.jsxs(Yr,{icon:s.jsx(ma,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(us,{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."}),(c==null?void 0:c.publicHostWarning)&&s.jsx(us,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),s.jsx(dt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:"Version"}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.82"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(p==null?void 0:p.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(p==null?void 0:p.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:c!=null&&c.hasPasswordAuth?"Password enabled":c!=null&&c.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(dt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:v==="127.0.0.1",onChange:()=>k("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:v==="0.0.0.0",onChange:()=>k("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:()=>{ne()},disabled:q,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:q?"Saving…":"Save default network mode"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(p==null?void 0:p.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(dt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:c!=null&&c.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),R&&s.jsx(us,{variant:"error",children:R}),P&&s.jsx(us,{variant:"success",children:P}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:c!=null&&c.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:w,onChange:Z=>x(Z.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:c!=null&&c.hasPasswordAuth?"New password":"New standalone password",value:C,onChange:Z=>S(Z.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:I,onChange:Z=>$(Z.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{ce()},disabled:q,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:q?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{be()},disabled:q,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),s.jsx(dt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(Z=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${Z.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:Z.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:Z.type})]},Z.type))})}),s.jsx(dt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(y0,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(dt,{title:"Coordinator prompts",description:"User-level overrides for the mesh coordinator system prompt. Per-mesh overrides live in the Repo Mesh page.",children:s.jsx(k0,{daemonId:t==null?void 0:t.id})}),s.jsx(dt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(S0,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI."}),s.jsx(P0,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),s.jsx(KS,{value:m,savedValue:Xt(p==null?void 0:p.standaloneFontPreferences),saving:b,error:f,notice:N,onChange:h,onSave:()=>{Q()},onResetToSaved:J,onResetToDefaults:ae})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),s.jsx($0,{})]})]})}),s.jsx(dt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(x0,{}),s.jsx(ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xh,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:M,onChange:z})]})}),s.jsx(dt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(Dh,{size:16,className:"text-text-secondary"})," Display Name"]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:o,onChange:Z=>i(Z.target.value),onBlur:D,onKeyDown:Z=>{Z.key==="Enter"&&Z.currentTarget.blur()}})]})})})]})}const GS=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],kr="adhdev_onboarding_done",VS=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],qS={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function YS({onDone:e}){const[t,r]=l.useState([]),[n,a]=l.useState(new Set(GS)),[o,i]=l.useState(!0),[c,d]=l.useState(null),[p,u]=l.useState(!1),[m,h]=l.useState(null),[b,g]=l.useState("all");l.useEffect(()=>{let w=!1;const x=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${x}/providers?sort=popular&limit=100`).then(C=>{if(!C.ok)throw new Error(`HTTP ${C.status}`);return C.json()}).then(C=>{w||r(C.providers??[])}).catch(C=>{w||d(C instanceof Error?C.message:String(C))}).finally(()=>{w||i(!1)}),()=>{w=!0}},[]);const f=t.filter(w=>b==="all"||w.category===b),j=["cli","ide","extension","acp"].map(w=>({category:w,items:f.filter(x=>x.category===w)})).filter(w=>w.items.length>0),N=l.useCallback(w=>{a(x=>{const C=new Set(x);return C.has(w)?C.delete(w):C.add(w),C})},[]),y=l.useCallback(async()=>{if(n.size===0){localStorage.setItem(kr,"1"),e();return}u(!0);const w=[];for(const x of n)try{const S=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:x})})).json().catch(()=>({}));w.push({type:x,ok:!!S.success,error:S.error})}catch(C){w.push({type:x,ok:!1,error:C instanceof Error?C.message:String(C)})}h(w),u(!1),w.every(x=>x.ok)&&localStorage.setItem(kr,"1")},[n,e]),v=l.useCallback(()=>{localStorage.setItem(kr,"1"),e()},[e]),k=l.useCallback(()=>{m&&m.every(w=>w.ok)?e():p||v()},[m,p,e,v]);return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60",onClick:k,children:s.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:w=>w.stopPropagation(),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Welcome to ADHDev"}),s.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 ",s.jsx("span",{className:"text-text-secondary",children:"Burrow → Providers → Add provider"}),"."]})]}),!o&&!c&&t.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:VS.map(w=>{const x=w.key==="all"?t.length:t.filter(C=>C.category===w.key).length;return x===0&&w.key!=="all"?null:s.jsxs("button",{onClick:()=>g(w.key),className:`machine-btn text-[10px] px-2 py-0.5 ${b===w.key?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:[w.label," ",s.jsxs("span",{className:"opacity-60",children:["(",x,")"]})]},w.key)})}),o&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"Loading registry…"}),!o&&c&&s.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: ",c]}),!o&&!c&&f.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"No providers in this category."}),!o&&!c&&f.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:j.map(w=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:qS[w.category]??w.category}),s.jsx("div",{className:"grid gap-1.5",children:w.items.map(x=>{var R,_;const C=n.has(x.type),S=m==null?void 0:m.find(P=>P.type===x.type),I=((R=x.manifest)==null?void 0:R.icon)??"📦",$=((_=x.manifest)==null?void 0:_.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${C?"bg-violet-500/[0.06] border-violet-500/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:C,onChange:()=>N(x.type),disabled:p,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:I}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:x.displayName}),$&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:$})]}),S&&s.jsx("span",{className:`text-[10px] font-semibold ${S.ok?"text-green-400":"text-red-400"}`,children:S.ok?"✓ installed":`✗ ${S.error??"failed"}`})]},x.type)})})]},w.category))}),s.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-border-subtle",children:[s.jsxs("div",{className:"text-[11px] text-text-muted",children:[n.size," provider",n.size!==1?"s":""," selected"]}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx("button",{onClick:v,disabled:p,className:"machine-btn text-[11px] px-3 py-1",children:"Skip"}),s.jsx("button",{onClick:()=>{m?(localStorage.setItem(kr,"1"),e()):y()},disabled:p||!m&&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:p?"Installing…":m?"Done":`Install ${n.size}`})]})]})]})})}function JS(){try{return localStorage.getItem(kr)==="1"}catch{return!1}}l0();_0();ES();const XS=md({baseUrl:"",getToken:Yi});function QS({children:e}){const[t,r]=l.useState(null),[n,a]=l.useState(!0),[o,i]=l.useState(""),[c,d]=l.useState(""),[p,u]=l.useState(!1),m=async()=>{a(!0),d("");try{const g=await(await Yt("/auth/session")).json();r(g)}catch(b){d(b instanceof Error?b.message:String(b))}finally{a(!1)}};l.useEffect(()=>{m()},[]),l.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let b=!1;return(async()=>{try{const g=await Yt("/api/v1/standalone/preferences");if(!g.ok)return;const f=await g.json();if(b)return;const j=Xt(f.standaloneFontPreferences);vs(j),Zo(j)}catch{}})(),()=>{b=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const h=async b=>{b.preventDefault(),u(!0),d("");try{const g=await Yt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),f=await g.json();if(!g.ok)throw new Error((f==null?void 0:f.error)||"Login failed");r(f),i(""),hm()}catch(g){d(g instanceof Error?g.message:String(g))}finally{u(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:h,children:[s.jsx("input",{type:"password",value:o,onChange:b=>i(b.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled:p||!o,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:p?"Signing in…":"Unlock dashboard"})]}):s.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),c&&s.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:c})]})}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",c||"unknown error"]})}function od(){const{ides:e,initialLoaded:t}=es();if(!t)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?s.jsx(Io,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Io,{to:"/dashboard",replace:!0})}function ZS(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let r=!1;if(!JS())return fetch("/api/v1/providers/installed").then(n=>n.ok?n.json():{providers:[]}).then(n=>{r||(n.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{r=!0}},[]),e?s.jsx(YS,{onDone:()=>t(!1)}):null}function eC(){const{ides:e}=es(),t=l.useMemo(()=>{for(const p of e)if(p.activeInteractivePrompt)return p.instanceId??p.id;return null},[e]),{promptSession:r,hasActivePrompt:n,responseError:a,isSubmitting:o,submit:i,cancel:c,reopen:d}=Wu(t);return n?s.jsxs("div",{className:"relative",children:[!r&&s.jsx("button",{type:"button",onClick:d,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:"Awaiting your input ↑"}),s.jsx(Ed,{promptSession:r,isSubmitting:o,error:a,onSubmit:i,onCancel:c})]}):null}function tC(){const e=l.useMemo(()=>({sendCommand:Lr,sendData:Qo,sendPtyInput:fm}),[]);return s.jsx(ih,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Ch,{client:XS,children:s.jsx(QS,{children:s.jsx(LS,{children:s.jsx(Mh,{value:e,children:s.jsxs(Lh,{sendDaemonCommand:Lr,children:[s.jsx(eC,{}),s.jsxs(FS,{children:[s.jsx(ZS,{}),s.jsxs(lh,{children:[s.jsx(is,{path:"/dashboard",element:s.jsx(A1,{})}),s.jsx(is,{path:"/machine",element:s.jsx(od,{})}),s.jsx(is,{path:"/machines/:id",element:s.jsx(BN,{})}),s.jsx(is,{path:"/machines",element:s.jsx(od,{})}),s.jsx(is,{path:"/about",element:s.jsx(WS,{})}),s.jsx(is,{path:"/settings",element:s.jsx(US,{})}),s.jsx(is,{path:"/mesh",element:s.jsx(jS,{children:s.jsx(vS,{})})}),s.jsx(is,{path:"*",element:s.jsx(Io,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}ig({connectionManager:qt});ch(document.getElementById("root")).render(s.jsx(tC,{}));