@adhdev/daemon-standalone 0.9.82-rc.556 → 0.9.82-rc.558

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,116 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-D_AgDYO_.js","assets/vendor-MlvUnxKA.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
- var oh=Object.defineProperty;var ih=(e,t,r)=>t in e?oh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var et=(e,t,r)=>ih(e,typeof t!="symbol"?t+"":t,r);import{r as l,j as s,M as mi,a as lh,b as ch,c as dh,t as uh,d as ph,e as ur,R as It,u as cn,f as Do,g as $o,D as mh,E as hh,i as fh,C as xh,h as bh,B as gh,k as yh,l as vh,m as wh,H as xn,P as js,n as jh,o as kh,p as Nh,q as Sh,s as Ch,v as Ih,w as hi,x as Ah,y as Mh,z as _h,A as Th,F as ks,N as Eo,G as Lh}from"./vendor-MlvUnxKA.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 Rh(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 pr=Rh();function xl(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 Ph(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function bl(e){return Array.isArray(e)?[...e]:[]}function kd(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?bl(e.messages):i?[]:t.messages,activeModal:n?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...r?{messages:bl(e.messages)}:{},...n?{activeModal:e.activeModal??null}:{}}}function Wr(e,t){const r=Ph(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:kd(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),muted:e.muted??(t==null?void 0:t.muted),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 Nd(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?Wr(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 gl(e){return!!e&&typeof e=="object"&&"text"in e}function fi(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:gl(o)?String(o.text||""):"").join(r):gl(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function mr(e){return fi(e,{normalizeWhitespace:!0})}function Dh(e){let t="";for(let r=0;r<e.length;r++){const n=e[r],a=e.charCodeAt(r);if(!(a<=31&&n!==`
3
- `&&n!==" ")&&!(a>=127&&a<=159)&&!(a>=8203&&a<=8207||a>=8234&&a<=8238||a===8288||a===65279)&&a!==65533){if(a===65038||a===65039){const o=t.length>0?t[t.length-1]:"";if(!o||o===`
4
- `||o===" "||o===" ")continue}t+=n}}return t}function yl(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 Sd(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 $h(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 Fa(e){if(!e||typeof e!="object")return"";const t=e,r=$h(mr(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 Eh(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=Fa(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:Fa(e[0]),last:Fa(e[e.length-1])}}function Bo(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function Fo(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(Bo(e)&&Bo(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)Fo(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"&&Fo(n[i],a[i],r)}function Gr(e,t){return Array.isArray(e)?e.map(r=>Gr(r,t)):!e||typeof e!="object"?e:Bo(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Eh(a,t):Gr(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,Gr(n,t)]))}function Bh(e,t){try{const r=new WeakSet;return Fo(e,t,r),JSON.stringify(Gr(e,r))===JSON.stringify(Gr(t,r))}catch{return!1}}function Oo(e,t,r){return Bh(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Cd(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 vl(e,t,r,n){var d;const a=(d=t.chats)!=null&&d.length?t.chats:e.chats,o=Nd(e.childSessions,t.childSessions,{preserveMissing:n}),i=kd(t.activeChat,e.activeChat),c=t.workspace||e.workspace;return Sd(e,t,{...e,...t,chats:a,childSessions:o,activeChat:i,workspace:c,_lastUpdate:r})}function Oh(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=Nd(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(n.chats=t.chats),t.workspace&&(n.workspace=t.workspace);for(const i of["title","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","activeInteractivePrompt","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","muted","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 Hh(e,t,r,n){const a=Oh(e,t,n),o=Object.keys(a).length>0?Sd(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return Oo(e,o,r)}function Wh(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=Cd(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 Kh(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 Uh(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function zh(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}=Wh(e);for(const h of e){const y=o.get(h.id);if(!y){o.set(h.id,{...h,_lastUpdate:n});continue}const x=yl(h),f=yl(y),v=Cd(h),k=!a.has(v);if(x>f){const C=vl(y,h,n,k);o.set(h.id,Oo(y,C,n));continue}if(x<f){o.set(h.id,Hh(y,h,n,k));continue}const b=h.timestamp||n,j=y._lastUpdate||y.timestamp||0;if(b>=j){const C=vl(y,h,n,k);o.set(h.id,Oo(y,C,n));continue}(u=h.chats)!=null&&u.length&&!((m=y.chats)!=null&&m.length)&&o.set(h.id,{...y,chats:h.chats})}for(const[h,y]of o){const x=y.daemonId||h.split(":")[0];if(!c.has(x))continue;if(a.has(x)&&p.has(x)&&!i.has(h)){o.delete(h);continue}const f=n-(y._lastUpdate||y.timestamp||0);Kh(y,x,f,i,a,d)&&o.delete(h)}for(const[h,y]of o){const x=y.daemonId||h.split(":")[0];if(Uh(y,x,c,d,o))continue;n-(y._lastUpdate||y.timestamp||0)>3e5&&y.status!=="online"&&o.delete(h)}return Array.from(o.values())}function Gh(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}const Id=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}),Ad=l.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Vh({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((k,b)=>{n(j=>{let C=!1;const w=j.map(g=>g.id!==k||g.chats===b?g:(C=!0,{...g,chats:b}));return C?w:j})},[]),h=l.useCallback((k,b)=>{n(j=>{const C=j.length===0?k:zh(k,j,b),w=!Gh(j,C);return w&&pr.record({kind:"dashboard.entries_applied",payload:{incoming:xl(k),next:xl(C)}}),w?C:j})},[]),y=l.useCallback(()=>o(!0),[]),x=l.useMemo(()=>({injectEntries:h,markLoaded:y,getIdes:()=>u.current}),[h,y]),f=t,v=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(Ad.Provider,{value:x,children:s.jsx(Id.Provider,{value:v,children:e})})}function hs(){return l.useContext(Id)}function en(){return l.useContext(Ad)}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,y=setTimeout(()=>h.abort(),15e3);try{const x=await fetch(m,{...d,headers:p,signal:h.signal});if(x.status===401)throw n==null||n(),new Error("Unauthorized");if(!x.ok){const f=await x.json().catch(()=>({error:x.statusText}));throw new Error(f.error||`API Error: ${x.status}`)}return x.json()}finally{clearTimeout(y)}}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 qh=Md({baseUrl:"http://localhost:3847"}),Yh=l.createContext(qh);function Jh({client:e,children:t}){return s.jsx(Yh.Provider,{value:e,children:t})}const Xh={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},_d=l.createContext(Xh);function Qh({value:e,children:t}){return s.jsx(_d.Provider,{value:e,children:t})}function xt(){return l.useContext(_d)}function Td(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function Zh(e){const t=Td(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 ef(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=Zh(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=Td(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 tf({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 Ld=l.createContext(null);function sf({sendDaemonCommand:e,children:t}){const r=ef(e),n=l.useMemo(()=>({launchCli:r.launchCli}),[r.launchCli]);return s.jsxs(Ld.Provider,{value:n,children:[t,r.pending&&s.jsx(tf,{providerType:r.pending.providerType,sourceName:r.pending.sourceName,description:r.pending.description,onConfirm:r.confirm,onCancel:r.cancel})]})}function ga(){const e=l.useContext(Ld);return e||{launchCli:async()=>{throw new Error("useLaunchCli must be used inside <LaunchCliProvider>")}}}function Rd(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function rf(e,t,r){return Number(e.receivedAt||r[Xn(e)]||0)||0}function Pd(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function nf(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 Oa(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 af(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t^e.charCodeAt(r),t|=0;return(t>>>0).toString(36)}function Xn(e,t){const r=e,n=fi(e.content,{joiner:`
5
- `}),a=[e.id?`id:${e.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",e.bubbleId?`bubble:${e.bubbleId}`:"",e.providerUnitKey?`unit:${e.providerUnitKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",typeof e.sequence=="number"?`seq:${e.sequence}`:""].filter(Boolean);if(a.length>0)return a.join("|");const o=e.receivedAt||e.timestamp||0;return[e.role?`role:${e.role}`:"role:",`chash:${af(n)}`,o?`ts:${o}`:""].filter(Boolean).join("|")}function of(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 lf(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Dd(e){return e?of([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),lf(e.content)]):""}const xi=200,cf=80,wl=650,Mr=new Map;function Qn(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function df(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}:${Dd(n)}`}function uf(e,t,r,n){return e||!t?!1:Qn(r,n)}function pf({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=cf,bottomThresholdPx:a=xi}){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 mf(e){return pf({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Kr(e,t=xi){return!!e&&e.fromBottom>=t}function hf(e,t){return Qn(e,t)?!Kr(e):!0}function ff({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function xf({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function Ha(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}const ze={size:18};function $d({size:e=ze.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 bi({size:e=ze.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 Is({size:e=ze.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 Ed({size:e=ze.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 bf({size:e=ze.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 gf({size:e=ze.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 Bd({size:e=ze.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 Fd({size:e=ze.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 yf({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"20 6 9 17 4 12"})})}function ya({size:e=ze.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 gi({size:e=ze.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 vf({size:e=ze.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 wf({size:e=ze.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 Xs({size:e=ze.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 os({size:e=ze.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 yi({size:e=ze.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 hr({size:e=ze.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 va({size:e=ze.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 Vs({size:e=ze.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 tn({size:e=ze.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 Yt({size:e=ze.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 jf({size:e=ze.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 Od({size:e=ze.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 vi({size:e=ze.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 Hd({size:e=ze.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 kf({size:e=ze.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 wi({size:e=ze.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 Nf({size:e=ze.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 Wd({size:e=ze.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 ji({size:e=ze.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 wt({size:e=ze.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 Sf({size:e=ze.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 Cf({size:e=ze.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 If({size:e=ze.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 Af({size:e=ze.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 jr({size:e=ze.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 Kd({size:e=ze.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:"M8.7 3A6 6 0 0 1 18 8c0 3 .6 5 1.4 6.5"}),s.jsx("path",{d:"M17 17H3s3-2 3-9a5.98 5.98 0 0 1 .6-2.6"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"}),s.jsx("line",{x1:"2",y1:"2",x2:"22",y2:"22"})]})}function Mf({size:e=ze.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 _f({size:e=ze.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 Tf({size:e=ze.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 Ud({size:e=ze.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 Lf({size:e=ze.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 Rf({size:e=ze.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 Pf({size:e=ze.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 Df({size:e=ze.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 $f({size:e=ze.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 Ef({size:e=ze.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 Bf({size:e=ze.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 Ff({size:e=ze.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 zd="adhdev_chat_activity_visible",jl=new Set(["hidden","debug","internal"]),kl=new Set(["visible","user","chat"]),Of=new Set(["debug","trace","internal"]),Hf=new Set(["tool_call","terminal_command","runtime_activity"]),Wf=new Set(["runtime_status","provider_chrome","control"]),Kf=new Set(["thought","tool","terminal"]);function Gd(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function sr(e){return typeof e=="string"?e.trim().toLowerCase():""}function Wa(e,t,r){return e[r]??(t==null?void 0:t[r])}function Nl(e,t,r){const n=e;return r.some(a=>n[a]===!0||(t==null?void 0:t[a])===!0)}function Uf(e,t){const r=sr(e.kind);return r||(t==="tool"?"tool":"standard")}function Ka(e,t,r){const n=Gd(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 zf(e){const t=e.content;return Array.isArray(t)&&t.some(r=>!!r&&typeof r=="object"&&r.type!=="text")}function ki(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=Gd(e),r=sr(e.role),n=Uf(e,r),a=sr(Wa(e,t,"visibility")),o=sr(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),i=sr(Wa(e,t,"audience")),c=sr(Wa(e,t,"source")),d=jl.has(a)||jl.has(o)||Of.has(i)||Nl(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),p=kl.has(a)||kl.has(o)||i==="chat"||Nl(e,t,["userFacing"]),u=Kf.has(n)||Hf.has(c);if(d)return{surface:u?"activity":"internal",isUserFacing:!1,isActivityFacing:u,isInternal:!u,role:r,kind:n,label:Ka(e,n,c)};if(p)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:Ka(e,n,c)};if((r==="system"||n==="system")&&zf(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:"Chat"};if(Wf.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:Ka(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 Gf(e){return(Array.isArray(e)?e:[]).filter(t=>ki(t).isUserFacing)}function Vd(e){return(Array.isArray(e)?e:[]).filter(t=>ki(t).isActivityFacing)}function qd(e){const t=e.content;return typeof t=="string"?t:(()=>{try{return JSON.stringify(t??"")}catch{return String(t??"")}})()}function Vf(e){return`${String(e.role||"")}::${qd(e)}`}function qf(e){if(e.length<2)return e;const t=[];let r="";for(const n of e){const a=Vf(n);qd(n).trim().length>0&&a===r||(t.push(n),r=a)}return t}function Yf(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 Sl(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(zd))==="1"}catch{return!1}}function Jf({text:e}){const[t,r]=l.useState(!1),n=l.useCallback(()=>{navigator.clipboard.writeText(e).catch(()=>{}),r(!0),setTimeout(()=>r(!1),1500)},[e]);return s.jsx("button",{type:"button",onClick:n,"aria-label":"메시지 복사",className:"chat-copy-btn",children:t?s.jsx(yf,{size:11}):s.jsx(Fd,{size:11})})}const Yd=[lh,{singleTilde:!1}],Jd=[Yd,ch,dh],Xf=[Yd];function bn(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 Cl(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Pd(e)?s.jsx(mi,{remarkPlugins:Jd,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}const Qf=l.memo(function({content:t,renderAsPreformatted:r,renderAsMarkdown:n}){return r?s.jsx("pre",{className:"chat-preformatted",children:t}):n?s.jsx(mi,{remarkPlugins:Jd,children:t}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:t})});function _r({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:Cl(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=Oa(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:bn("Image",o,r.mimeType)},`image-fallback-${n}`)}if(r.type==="audio"){const a=Oa(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:bn("Audio",Ar(r.uri,"audio"),r.transcript||r.mimeType)},`audio-fallback-${n}`)}if(r.type==="video"){const a=Oa(r),o=r.title||r.name||r.alt||Ar(r.uri,"video"),i=[r.transcript,r.description,r.mimeType].filter(Boolean).join(`
6
- `);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"}):bn("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(`
7
- `);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}):bn("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}),Cl(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})})}const Zf=l.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(mi,{remarkPlugins:Xf,children:t.text}),s.jsx("span",{className:"action-time",children:Rd(t.timestamp)})]})},(e,t)=>e.log===t.log);function Il(e){const t=e.meta;return[Dd(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 ex=l.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:i,onToggleTextExpanded:c}){var N,I,R;const d=(t.role||"").toLowerCase(),p=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),m=ki(t),h=nf(t.content)?t.content:null,y=!!(h!=null&&h.some(L=>L.type!=="text")),x=fi(t.content,{joiner:`
8
- `});if(m.isActivityFacing&&u!=="thought"&&u!=="tool"&&u!=="terminal"){const L=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:L})]}),y&&h?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(_r,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:x})]})}if(u==="thought"){const L=typeof((N=t.meta)==null?void 0:N.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(If,{size:13}),s.jsx("span",{children:L})]}),s.jsx("div",{className:"chat-msg-body",children:x})]})}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"})]}),y&&h?s.jsx("div",{className:"tool-text w-full",children:s.jsx(_r,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:x})]});if(u==="terminal"){const L=(I=t.meta)!=null&&I.isRunning?"⏳":"✅",_=typeof((R=t.meta)==null?void 0:R.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:L}),s.jsx("span",{children:_})]}),y&&h?s.jsx("div",{className:"chat-msg-body",children:s.jsx(_r,{parts:h,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:x})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:y&&h?s.jsx(_r,{parts:h,renderAsPreformatted:!1}):x.slice(0,100)});const f=t.meta,k=(typeof(f==null?void 0:f.renderMode)=="string"?f.renderMode.trim():"")==="preformatted",b=x,j=!1,C=b,w=k,g=!p&&!w&&Pd(C),S=["chat-message-row",p?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:S,children:(b||y||p)&&s.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${b||y?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:p?a||"You":t.senderName||n}),s.jsxs("span",{className:"chat-bubble-header-end",children:[(b||y)&&s.jsx(Jf,{text:x}),r!=null&&s.jsx("span",{className:"chat-time",children:Rd(r)})]})]}),(b||y)&&s.jsx("div",{className:"chat-markdown",children:y&&h?s.jsx(_r,{parts:h,renderAsPreformatted:w}):s.jsx(Qf,{content:C,renderAsPreformatted:w,renderAsMarkdown:g})}),j]})})},(e,t)=>(e.message===t.message||Il(e.message)===Il(t.message))&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),tx=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:y,hasMoreHistory:x,hiddenLiveCount:f=0,loadError:v,scrollToBottomRequestNonce:k,isVisible:b=!0},j){const C=l.useRef(null),w=l.useRef(null),g=l.useRef(null),S=l.useRef(0),N=l.useRef(""),I=l.useRef(""),R=l.useRef(!1),L=l.useRef(null),_=l.useRef(!1),P=l.useRef(null),B=l.useRef(!1),[Y,M]=l.useState(new Set),[H,q]=l.useState({showTop:!1,showBottom:!1}),A=l.useRef(!1),$=l.useRef(!1),T=l.useRef(b),F=l.useRef(b),z=l.useRef(null);F.current=b;const U=()=>{const ue=C.current;return ue?ue.scrollHeight-ue.scrollTop-ue.clientHeight<xi:!0},te=l.useCallback(()=>{const ue=C.current,D=ue?mf(ue):{showTop:!1,showBottom:!1};q(me=>me.showTop===D.showTop&&me.showBottom===D.showBottom?me:D)},[]),Z=l.useCallback((ue="auto")=>{var me;const D=C.current;D&&(D.scrollTo({top:D.scrollHeight,behavior:ue}),(me=D.ownerDocument.defaultView)==null||me.requestAnimationFrame(()=>te()))},[te]),se=l.useCallback((ue="auto")=>{var me;const D=C.current;D&&(D.scrollTo({top:0,behavior:ue}),(me=D.ownerDocument.defaultView)==null||me.requestAnimationFrame(()=>te()))},[te]),G=l.useCallback(()=>{var oe;const ue=C.current,D=(oe=window.getSelection)==null?void 0:oe.call(window);if(!ue||!D||D.rangeCount===0||D.isCollapsed){B.current=!1;return}const me=D.anchorNode,Se=D.focusNode;B.current=!!(me&&Se&&ue.contains(me)&&ue.contains(Se))},[]),O=l.useMemo(()=>{const ue=Gf(t),D=Vd(t);return qf(Yf(ue,D,u))},[t,u]),V=O.length===t.length?p:void 0,pe=df(O,V),fe=l.useCallback(()=>{const ue=C.current;if(!ue||!c||!F.current)return;const D={top:ue.scrollTop,fromBottom:Math.max(0,ue.scrollHeight-ue.scrollTop-ue.clientHeight),messageFingerprint:pe};z.current={contextKey:c,snapshot:D},Mr.set(c,D)},[c,pe]),de=l.useCallback((ue="auto")=>{L.current!=null&&cancelAnimationFrame(L.current),L.current=requestAnimationFrame(()=>{L.current=null,Z(ue)})},[Z]),ke=l.useCallback(()=>{A.current=!1,_.current=!0,$.current=!0,P.current!=null&&window.clearTimeout(P.current),P.current=window.setTimeout(()=>{_.current=!1,P.current=null},wl)},[]);l.useEffect(()=>{const ue=!R.current,D=I.current!==c;if(I.current=c,ue||D){R.current=!0;const Se=c?Mr.get(c):null,oe=!!Se&&Qn(Se,pe);A.current=oe?Kr(Se):!1,_.current=hf(Se,pe),B.current||(oe?requestAnimationFrame(()=>{const Q=C.current;Q&&(Ha(Q,Se),A.current=Kr(Se),te(),$.current=!0)}):de("auto")),S.current=O.length,N.current=pe;return}O.length>S.current;const me=pe!==N.current;ff({hasSelection:B.current,userScrolledUp:A.current,hasChatContentChanged:me})&&de("auto"),S.current=O.length,N.current=pe},[pe,c,O.length,de,te]),l.useEffect(()=>{k&&(ke(),B.current||de("auto"))},[ke,de,k]),l.useEffect(()=>{const ue=T.current;ue&&!b&&fe(),F.current=b,T.current=b;const D=c?Mr.get(c):null;if(uf(ue,b,D,pe)){if(!D)return;A.current=Kr(D),_.current=!1,B.current||requestAnimationFrame(()=>{const me=C.current;me&&(Ha(me,D),te())});return}},[b,c,pe,ke,fe,de,te]),l.useEffect(()=>()=>{const ue=z.current;ue&&Mr.set(ue.contextKey,ue.snapshot),L.current!=null&&cancelAnimationFrame(L.current),P.current!=null&&window.clearTimeout(P.current)},[]),l.useEffect(()=>{const ue=w.current,D=C.current;if(!ue||!D)return;const me=()=>{P.current!=null&&window.clearTimeout(P.current),P.current=window.setTimeout(()=>{_.current=!1,P.current=null},wl)},Se=new ResizeObserver(()=>{te();const oe=_.current;xf({hasSelection:B.current,userScrolledUp:A.current,contextAutoScrollActive:oe})&&(de("auto"),oe&&me())});return Se.observe(ue),D!==ue&&Se.observe(D),()=>{Se.disconnect(),P.current!=null&&(window.clearTimeout(P.current),P.current=null)}},[de,c,te]),l.useImperativeHandle(j,()=>({scrollToBottom:(ue="smooth")=>{Z(ue)}}),[Z]),l.useEffect(()=>{const ue=C.current;if(!ue)return;let D;const me=()=>{fe(),clearTimeout(D),D=setTimeout(()=>{A.current=!U(),te()},50)};return ue.addEventListener("scroll",me,{passive:!0}),()=>{ue.removeEventListener("scroll",me),clearTimeout(D)}},[fe,te]),l.useEffect(()=>(document.addEventListener("selectionchange",G),()=>document.removeEventListener("selectionchange",G)),[G]);const ye=l.useRef(0),we=l.useRef(!1);l.useEffect(()=>{const ue=C.current;if(!ue||!we.current||ye.current===0)return;const D=ue.scrollHeight-ye.current;D>0&&(ue.scrollTop=D),te(),fe(),ye.current=0,we.current=!1},[O.length,fe,te]),l.useEffect(()=>{if($.current||!c)return;const ue=Mr.get(c),D=C.current;if(!(!ue||!D)){if(!Qn(ue,pe)){Z("auto"),$.current=!0;return}Ha(D,ue),A.current=Kr(ue),te(),$.current=!0}},[c,pe,O.length,Z,te]);const he=()=>{const ue=C.current;ue&&(ye.current=ue.scrollHeight),we.current=!0,h==null||h()},K=()=>{A.current=!0,se("smooth"),fe()},E=()=>{ke(),Z("smooth"),fe()},J=l.useMemo(()=>{const ue=O.map((oe,Q)=>({type:"message",data:oe,index:Q,ts:rf(oe,Q,d)}));if(!r||r.length===0)return ue;const D=[...r].sort((oe,Q)=>oe.timestamp-Q.timestamp).map((oe,Q)=>({type:"action",data:oe,index:Q,ts:oe.timestamp})),me=[];let Se=0;for(const oe of ue){for(;Se<D.length&&oe.ts>0&&D[Se].ts<oe.ts;)me.push(D[Se++]);me.push(oe)}for(;Se<D.length;)me.push(D[Se++]);return me},[O,r,d]),re=f>0||!!x,be=f>0?`↑ Show ${Math.min(f,80)} earlier messages${f>80?` (${f} hidden)`:""}`:v?`↻ ${v}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:C,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:w,className:"chat-container-content",children:[y&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),re&&!y&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:he,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${v&&f===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:be})}),J.length===0&&!re&&(m||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),J.map(ue=>{if(ue.type==="action"){const ve=ue.data;return s.jsx(Zf,{log:ve},`action-${ue.index}`)}const D=ue.data;ue.index;const me=Xn(D),Se=D.receivedAt||d[me],oe=`${c}-${me}`,Q=Y.has(oe);return s.jsx(ex,{message:D,receivedAt:Se,agentName:n,userName:a,isCliMode:o,isTextExpanded:Q,onToggleTextExpanded:()=>M(ve=>{const Ne=new Set(ve);return Q?Ne.delete(oe):Ne.add(oe),Ne})},`msg-${me}`)}),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:g})]})}),(H.showTop||H.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[H.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:K,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),H.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:E,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),sx=l.memo(tx,(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),rx="modulepreload",nx=function(e){return"/"+e},Al={},ax=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=nx(d),d in Al)return;Al[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":rx,p||(m.as="script"),m.crossOrigin="",m.href=d,c&&m.setAttribute("nonce",c),document.head.appendChild(m),p)return new Promise((h,y)=>{m.addEventListener("load",h),m.addEventListener("error",()=>y(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 Ml=!1;const Xd=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),y=l.useRef(!1),x=l.useRef(!1),f=()=>{const v=c.current;if(v){m.current&&(v.clear(),m.current=!1);for(const k of u.current)v.write(k.data,k.onProcessed);u.current=[],h.current&&(v.fit(),h.current=!1),y.current&&(v.bumpResize(),y.current=!1),x.current&&(v.scrollToTop(),x.current=!1)}};return l.useImperativeHandle(i,()=>({write:(v,k)=>{c.current?c.current.write(v,k):u.current.push({data:v,onProcessed:k})},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:(v,k)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(v,k)},fit:()=>{c.current?c.current.fit():h.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():y.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():x.current=!0},getSelection:()=>{var v,k;return((k=(v=c.current)==null?void 0:v.getSelection)==null?void 0:k.call(v))||""},getVisibleText:()=>{var v,k;return((k=(v=c.current)==null?void 0:v.getVisibleText)==null?void 0:k.call(v))||""}}),[]),l.useEffect(()=>{d&&f()},[d]),l.useEffect(()=>{let v=!1;return ax(()=>import("./terminal-D_AgDYO_.js"),__vite__mapDeps([0,1,2])).then(k=>{Ml||(Ml=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),v||p(()=>k.GhosttyTerminalView)}).catch(k=>{console.error("[CliTerminal] failed to load terminal renderer",k)}),()=>{v=!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"}})});Xd.displayName="CliTerminal";function $t(...e){return uh(ph(e))}const ox={lg:"rounded-lg",xl:"rounded-xl","2xl":"rounded-2xl"},ix={none:"",sm:"p-3",md:"px-4 py-3.5",lg:"px-5 py-4"},ys=l.forwardRef(function({radius:t="xl",padding:r="md",className:n,...a},o){return s.jsx("div",{ref:o,className:$t("border border-border-subtle bg-bg-secondary",ox[t],ix[r],n),...a})});function gn({label:e,value:t,sub:r,icon:n}){return s.jsxs(ys,{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 _l({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 lx({cursorPos:e,viewportRef:t,imgRef:r}){var b;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(b=t.current)==null?void 0:b.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,y;d>p?(u=a.width,m=a.width/d,h=0,y=(a.height-m)/2):(m=a.height,u=a.height*d,h=(a.width-u)/2,y=0);const x=a.left-o.left+h+u*e.nx,f=a.top-o.top+y+m*e.ny,v=Math.max(8,Math.min(o.width-8,x)),k=Math.max(8,Math.min(o.height-8,f));return s.jsxs("div",{style:{position:"absolute",left:v-8,top:k-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 cx({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:y,onZoomReset:x,onZoomIn:f,transportType:v,screenshotUsage:k,lastActionStatus:b}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:j=>j.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(j=>!j),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:j=>j.stopPropagation(),onChange:j=>c(j.target.value),onKeyDown:j=>{d(j)},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(j=>!j),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),"%"]}),v==="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"}),v==="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"}),k&&k.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:k.budgetExhausted?"#ef4444":"#c4b5fd",background:k.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:k.budgetExhausted?"TURN blocked":`TURN ${k.dailyUsedMinutes}/${k.dailyBudgetMinutes}m`}),b&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:b})]})]}),a&&s.jsxs("div",{onTouchStart:j=>j.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:j=>{j.stopPropagation(),y()},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:j=>{j.stopPropagation(),x()},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:j=>{j.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 dx({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 ux(){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 Tl(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 dn(e,t){const r=l.useRef(null),n=l.useRef(0);l.useEffect(()=>{if(!ux())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,Tl(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,Tl(t[i])]))}),r.current=t})}function px({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:y,setLastActionStatus:x,spawnRippleFromNormalized:f,clampPan:v,isMobile:k,mobileFillZoom:b}){const[j,C]=l.useState(null),w=l.useRef(null),g=l.useRef(null),S=l.useRef(null),N=l.useRef(!1),I=l.useRef(null),R=l.useRef(0),L=l.useRef(null),_=l.useRef(1),P=l.useRef({x:0,y:0}),B=l.useRef(!1),Y=l.useRef(n),M=l.useRef(y),H=30,q=550,A=18,$=60,T=400,F=12,z=()=>{if(w.current)return;const Z={nx:.5,ny:.5};w.current=Z,C(Z)};return l.useEffect(()=>{Y.current=n,n==="mouse"&&z()},[n]),l.useEffect(()=>{M.current=y},[y]),l.useEffect(()=>{const Z=e.current;if(!Z)return;const se=de=>{if(!r.current)return null;const ke=r.current.getBoundingClientRect();return!ke.width||!ke.height?null:{nx:Math.max(0,Math.min(1,(de.clientX-ke.left)/ke.width)),ny:Math.max(0,Math.min(1,(de.clientY-ke.top)/ke.height))}},G=(de,ke)=>{if(!r.current)return{dnx:0,dny:0};const ye=r.current,we=ye.getBoundingClientRect(),he=ye.naturalWidth||we.width,K=ye.naturalHeight||we.height,E=he/K,J=we.width/we.height;let re,be;return E>J?(re=we.width,be=we.width/E):(be=we.height,re=we.height*E),{dnx:de/re,dny:ke/be}},O=(de,ke,ye)=>{if(ye<=1.05)return;const we=-(de-.5)*100,he=-(ke-.5)*100,K=v(we,he,ye);(Math.abs(K.x-c.current)>.1||Math.abs(K.y-d.current)>.1)&&(p(K.x),u(K.y),c.current=K.x,d.current=K.y)},V=de=>{const ke=t.current;if(ke&&de.target instanceof Node&&ke.contains(de.target))de.preventDefault();else return;if(de.touches.length===1){const ye=de.touches[0];g.current={x:ye.clientX,y:ye.clientY,time:Date.now()},S.current={x:ye.clientX,y:ye.clientY},B.current||(N.current=!1),I.current=setTimeout(()=>{if(!N.current&&!B.current)if(N.current=!0,Y.current==="mouse"){const we=w.current||{nx:.5,ny:.5};x("Right Click"),f(we.nx,we.ny,"right"),M.current("input_click",{...we,button:"right"}).catch(()=>{})}else{const we=se(ye);we&&(x("Right Click"),f(we.nx,we.ny,"right"),M.current("input_click",{...we,button:"right"}).catch(()=>{}))}},500);return}if(de.touches.length===2){I.current&&clearTimeout(I.current),N.current=!0,B.current=!0;const ye=de.touches[1].clientX-de.touches[0].clientX,we=de.touches[1].clientY-de.touches[0].clientY;L.current=Math.sqrt(ye*ye+we*we),_.current=i.current,P.current={x:(de.touches[0].clientX+de.touches[1].clientX)/2,y:(de.touches[0].clientY+de.touches[1].clientY)/2}}},pe=de=>{const ke=t.current;if(ke&&de.target instanceof Node&&ke.contains(de.target)&&de.preventDefault(),de.touches.length===1&&S.current){const ye=de.touches[0],we=ye.clientX-S.current.x,he=ye.clientY-S.current.y;if(!N.current&&g.current){const K=ye.clientX-g.current.x,E=ye.clientY-g.current.y;Math.sqrt(K*K+E*E)>8&&(N.current=!0,I.current&&clearTimeout(I.current))}if(N.current)if(Y.current==="mouse"){const K=G(we,he),E=w.current||{nx:.5,ny:.5},J=Math.max(0,Math.min(1,E.nx+K.dnx)),re=Math.max(0,Math.min(1,E.ny+K.dny));w.current={nx:J,ny:re},C({nx:J,ny:re}),x(`Cursor: ${Math.round(J*100)}%, ${Math.round(re*100)}%`),O(J,re,i.current);const be=Date.now();be-h.current>=30&&(h.current=be,M.current("input_mouseMoved",{nx:J,ny:re}).catch(()=>{}))}else if(i.current>1){const K=t.current;if(K){const E=K.clientWidth,J=K.clientHeight,re=c.current+we/E*100,be=d.current+he/J*100,ue=v(re,be,i.current);p(ue.x),u(ue.y),c.current=ue.x,d.current=ue.y}}else{const K=se(ye);if(K){const E=Date.now();E-h.current>=40&&(h.current=E,x("Scroll"),M.current("input_wheel",{nx:K.nx,ny:K.ny,deltaX:Math.round(-we*2.5),deltaY:Math.round(-he*2.5)}).catch(()=>{}))}}S.current={x:ye.clientX,y:ye.clientY};return}if(de.touches.length===2&&L.current!==null){const ye=de.touches[1].clientX-de.touches[0].clientX,we=de.touches[1].clientY-de.touches[0].clientY,K=Math.sqrt(ye*ye+we*we)/L.current,E=(de.touches[0].clientX+de.touches[1].clientX)/2,J=(de.touches[0].clientY+de.touches[1].clientY)/2,re=E-P.current.x,be=J-P.current.y,ue=Math.abs(K-1)>.03;if(Y.current==="mouse"){if(ue){const D=Math.max(o,Math.min(5,_.current*K));m(D),i.current=D}else if(Math.abs(re)>2||Math.abs(be)>2){const D=w.current||{nx:.5,ny:.5},me=Date.now();me-h.current>=30&&(h.current=me,x("Scroll"),M.current("input_wheel",{nx:D.nx,ny:D.ny,deltaX:Math.round(-re*3),deltaY:Math.round(-be*3)}).catch(()=>{}))}}else{const D=Math.max(o,Math.min(5,_.current*K));m(D),i.current=D;const me=t.current;if(me&&D>1){const Se=me.clientWidth,oe=me.clientHeight,Q=c.current+re/Se*100,ve=d.current+be/oe*100,Ne=v(Q,ve,D);p(Ne.x),u(Ne.y),c.current=Ne.x,d.current=Ne.y}}P.current={x:E,y:J}}},fe=de=>{var ke;if(I.current&&clearTimeout(I.current),L.current=null,de.touches.length===1&&B.current){const ye=de.touches[0];g.current={x:ye.clientX,y:ye.clientY,time:Date.now()},S.current={x:ye.clientX,y:ye.clientY},N.current=!0;return}if(de.touches.length===0){if(B.current){B.current=!1,N.current=!1;return}if(de.changedTouches.length===1){const ye=de.changedTouches[0],we=Date.now(),he=we-(((ke=g.current)==null?void 0:ke.time)||0),K=g.current?ye.clientX-g.current.x:0,E=g.current?ye.clientY-g.current.y:0,J=Math.sqrt(K*K+E*E);if(Y.current==="mouse"){if(he<H||he>q||J>A){N.current=!1;return}const re=w.current||se(ye);re&&(x(`Click: ${Math.round(re.nx*100)}%, ${Math.round(re.ny*100)}%`),f(re.nx,re.ny,"left"),M.current("input_click",{...re}).catch(()=>{}))}else{if(N.current){N.current=!1;return}if(he<$||he>T||J>F){N.current=!1;return}const re=se(ye);if(!re)return;we-R.current<300?(x("Double tap"),f(re.nx,re.ny,"double"),M.current("input_click",{...re,clickCount:2}).catch(()=>{}),R.current=0):(x(`Tap: ${Math.round(re.nx*100)}%, ${Math.round(re.ny*100)}%`),f(re.nx,re.ny,"left"),M.current("input_click",{...re}).catch(()=>{}),R.current=we)}}N.current=!1}};return Z.addEventListener("touchstart",V,{passive:!1}),Z.addEventListener("touchmove",pe,{passive:!1}),Z.addEventListener("touchend",fe,{passive:!1}),()=>{Z.removeEventListener("touchstart",V),Z.removeEventListener("touchmove",pe),Z.removeEventListener("touchend",fe),I.current&&clearTimeout(I.current)}},[e,t,r,o,i,c,d,p,u,m,h,x,f,v]),{cursorPos:j,cursorPosRef:w,handleToggleInputMode:()=>{a(Z=>{const se=Z==="touch"?"mouse":"touch";return se==="mouse"&&z(),se})},handleZoomReset:()=>{const Z=k?b:1;m(Z),i.current=Z,p(0),u(0),c.current=0,d.current=0}}}function Qd({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(""),[,y]=l.useState(!1),[x,f]=l.useState([]),v=l.useRef(0),[k,b]=l.useState(!1),[j,C]=l.useState(!1),w=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[g,S]=l.useState(w?"mouse":"touch"),[N,I]=l.useState(1),R=l.useRef(!1),[L,_]=l.useState(1),[P,B]=l.useState(0),[Y,M]=l.useState(0);dn("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:g,zoom:L,panX:P,panY:Y,isMenuOpen:k,isImeOpen:j});const H=l.useRef(0),q=l.useRef(L),A=l.useRef(P),$=l.useRef(Y);l.useEffect(()=>{q.current=L},[L]),l.useEffect(()=>{A.current=P},[P]),l.useEffect(()=>{$.current=Y},[Y]),l.useEffect(()=>{var he;(he=i.current)==null||he.focus()},[]);const T=r==="connected",F=n,z=T?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",U=T?"The remote stream is warming up":"Waiting for the remote stream to catch up";l.useEffect(()=>{if(!w||R.current||!F)return;const he=d.current,K=c.current;if(!he||!K)return;const E=()=>{const J=K.clientWidth,re=K.clientHeight,be=he.naturalWidth,ue=he.naturalHeight;if(!be||!ue||!J||!re)return;const D=Math.min(J/be,re/ue),Se=Math.max(J/be,re/ue)/D;Se>1.01&&(I(Se),_(Se),q.current=Se),R.current=!0};he.complete&&he.naturalWidth?E():he.addEventListener("load",E,{once:!0})},[F,w]);const te=.5;l.useEffect(()=>{L<=te&&(B(0),M(0))},[L,te]);const Z=(he,K,E)=>{if(E<=te)return{x:0,y:0};const J=(E-1)/(2*E)*100,re=(E-1)/(2*E)*100;return{x:Math.max(-J,Math.min(J,he)),y:Math.max(-re,Math.min(re,K))}},se=(he,K)=>{if(!d.current)return null;const E=d.current.getBoundingClientRect();return!E.width||!E.height?null:{nx:Math.max(0,Math.min(1,(he-E.left)/E.width)),ny:Math.max(0,Math.min(1,(K-E.top)/E.height))}},G=(he,K,E)=>{const J=c.current;if(!J)return;const re=J.getBoundingClientRect(),be=++v.current;f(ue=>[...ue,{id:be,x:he-re.left,y:K-re.top,type:E}]),setTimeout(()=>f(ue=>ue.filter(D=>D.id!==be)),600)},O=(he,K,E)=>{const J=d.current,re=c.current;if(!J||!re)return;const be=J.getBoundingClientRect(),ue=re.getBoundingClientRect(),D=J.naturalWidth||be.width,me=J.naturalHeight||be.height,Se=D/me,oe=be.width/be.height;let Q,ve,Ne,Le;Se>oe?(Q=be.width,ve=be.width/Se,Ne=0,Le=(be.height-ve)/2):(ve=be.height,Q=be.height*Se,Ne=(be.width-Q)/2,Le=0);const We=be.left-ue.left+Ne+Q*he,le=be.top-ue.top+Le+ve*K,Ee=++v.current;f(Be=>[...Be,{id:Ee,x:We,y:le,type:E}]),setTimeout(()=>f(Be=>Be.filter(Je=>Je.id!==Ee)),600)},V=async he=>{var E;const K=se(he.clientX,he.clientY);if(K){u(`Click: ${Math.round(K.nx*100)}%, ${Math.round(K.ny*100)}%`),G(he.clientX,he.clientY,"left"),(E=i.current)==null||E.focus();try{const J=await e("input_click",{nx:K.nx,ny:K.ny});J!=null&&J.success||t(`❌ Click failed: ${J==null?void 0:J.error}`)}catch(J){t(`❌ Click error: ${J.message||J}`)}}},pe=async(he,K,E,J=0)=>{try{await e("input_key",{type:E?"char":"keyDown",key:he,code:K,text:E?he:void 0,unmodifiedText:E?he:void 0,modifiers:J})}catch(re){t(`❌ Key error: ${re.message||re}`)}},fe=async he=>{if(he.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(he.key)&&he.preventDefault();let E=0;he.altKey&&(E|=1),he.ctrlKey&&(E|=2),he.metaKey&&(E|=4),he.shiftKey&&(E|=8),u(`Key: ${he.key}`),await pe(he.key,he.code,he.key.length===1,E)},de=async he=>{if(he.key==="Enter"){if(he.nativeEvent.isComposing)return;if(m){const K=m;h(""),u(`IME Sent: ${K}`);try{const E=await e("input_type",{text:K});E!=null&&E.success||t(`❌ IME error: ${E==null?void 0:E.error}`)}catch(E){t(`❌ IME error: ${E.message}`)}}else u("Key: Enter"),await pe("Enter","Enter",!1)}};l.useEffect(()=>{const he=i.current;if(!he)return;const K=E=>{var J;if((J=d.current)!=null&&J.contains(E.target)){E.preventDefault();const re=Date.now();if(re-H.current<40)return;H.current=re;const be=se(E.clientX,E.clientY);if(!be)return;u(`Scroll: ${Math.round(E.deltaY)}`),e("input_wheel",{nx:be.nx,ny:be.ny,deltaX:Math.round(E.deltaX),deltaY:Math.round(E.deltaY)}).catch(()=>{})}};return he.addEventListener("wheel",K,{passive:!1}),()=>he.removeEventListener("wheel",K)},[e]);const{cursorPos:ke,handleToggleInputMode:ye,handleZoomReset:we}=px({containerRef:i,viewportRef:c,imgRef:d,inputMode:g,setInputMode:S,minZoom:te,zoomRef:q,panXRef:A,panYRef:$,setPanX:B,setPanY:M,setZoom:_,lastWheelTimeRef:H,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:O,clampPan:Z,isMobile:w,mobileFillZoom:N});return s.jsxs("div",{ref:i,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:fe,onContextMenu:he=>he.preventDefault(),onFocus:()=>y(!0),onBlur:()=>y(!1),tabIndex:0,children:[s.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[F?s.jsx("img",{ref:d,src:F,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${L}) translate(${P}%, ${Y}%)`,transformOrigin:"center center",cursor:g==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:V,onContextMenu:he=>he.preventDefault(),onDragStart:he=>he.preventDefault()}):s.jsx(dx,{waitingLabel:z,waitingHint:U,transportType:o}),g==="mouse"&&F&&s.jsx(lx,{cursorPos:ke,viewportRef:c,imgRef:d}),x.map(he=>{const E={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[he.type];return s.jsxs("div",{style:{position:"absolute",left:he.x,top:he.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${E}, 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(${E}, 0.9)`,boxShadow:`0 0 12px rgba(${E}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},he.id)})]}),s.jsx(cx,{inputMode:g,onToggleInputMode:ye,isImeOpen:j,setIsImeOpen:C,isMenuOpen:k,setIsMenuOpen:b,imeText:m,setImeText:h,handleImeSubmit:de,isConnActive:T,zoom:L,isMobile:w,mobileFillZoom:N,onZoomOut:()=>_(he=>Math.max(.5,he-.25)),onZoomReset:we,onZoomIn:()=>_(he=>Math.min(5,he+.25)),transportType:o,screenshotUsage:a,lastActionStatus:p}),s.jsx("style",{children:`
9
- @keyframes slideUp {
10
- from { opacity: 0; transform: translateY(6px); }
11
- to { opacity: 1; transform: translateY(0); }
12
- }
13
- @keyframes slideUpSidebar {
14
- from { opacity: 0; transform: translateY(6px); }
15
- to { opacity: 1; transform: translateY(0); }
16
- }
17
- @keyframes click-ripple-ring {
18
- 0% { transform: scale(0.3); opacity: 1; }
19
- 100% { transform: scale(2.2); opacity: 0; }
20
- }
21
- @keyframes click-ripple-dot {
22
- 0% { transform: scale(1); opacity: 0.9; }
23
- 50% { transform: scale(1.8); opacity: 0.6; }
24
- 100% { transform: scale(0.5); opacity: 0; }
25
- }
26
- @keyframes remote-float {
27
- 0% { transform: translateY(0px); }
28
- 50% { transform: translateY(-7px); }
29
- 100% { transform: translateY(0px); }
30
- }
31
- `})]})}function Ll(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 mx(e){var t;return Ll(e.activeInteractivePrompt)||Ll((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function hx(e){return e.sessionId||e.instanceId||e.id}function fx(e,t){const r=typeof t=="string"?t.trim():"";for(const n of e){const a=mx(n);if(!a)continue;const o=hx(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 Zd(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}}const xx=200;function Rl(e){const t={};for(const r of(e==null?void 0:e.prompt.questions)||[])t[r.questionId]={selectedLabels:[],freeformText:""};return t}function Pl(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 bx({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-default bg-surface-secondary text-text-secondary hover:bg-surface-secondary 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-subtle"}`,children:r?s.jsx(Ud,{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 line-clamp-3 block text-xs leading-5 text-text-muted",children:t})]})]})})}function eu({promptSession:e,isSubmitting:t=!1,error:r,onSubmit:n,onCancel:a}){var R;const[o,i]=l.useState(()=>Rl(e)),[c,d]=l.useState(0),[p,u]=l.useState(!1),m=l.useRef(!1);l.useEffect(()=>{if(i(Rl(e)),d(0),u(!1),m.current=!1,!(e==null?void 0:e.prompt.promptId))return;const _=setTimeout(()=>{m.current=!0,u(!0)},xx);return()=>clearTimeout(_)},[e==null?void 0:e.prompt.promptId]);const h=(e==null?void 0:e.prompt.questions)||[],y=h.length,x=c===y-1,f=y===1,v=h[c],k=v?o[v.questionId]:void 0,b=v?Pl(v,k):!1,j=l.useMemo(()=>e?e.prompt.questions.every(L=>Pl(L,o[L.questionId])):!1,[e,o]);if(!e)return null;const C=(L,_)=>{i(P=>{const B=P[L.questionId]||{selectedLabels:[]},Y=B.selectedLabels||[],M=L.multiSelect?Y.includes(_)?Y.filter(H=>H!==_):[...Y,_]:[_];return{...P,[L.questionId]:{...B,selectedLabels:M}}})},w=(L,_)=>{i(P=>({...P,[L]:{...P[L]||{selectedLabels:[]},freeformText:_}}))},g=()=>{c<y-1&&d(L=>L+1)},S=()=>{c>0&&d(L=>L-1)},N=()=>{!j||t||!m.current||n(o)},I=Zd(e.prompt,o);return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50 px-4 pt-[calc(24px+env(safe-area-inset-top,0px))] pb-[calc(24px+env(safe-area-inset-bottom,0px))]",children:s.jsxs("div",{className:"flex max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-48px)] w-full max-w-2xl flex-col overflow-hidden rounded-lg border border-border-default bg-surface-primary shadow-2xl",children:[s.jsxs("div",{className:"flex shrink-0 items-start justify-between gap-4 border-b border-border-default 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(Vs,{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:[!f&&s.jsxs("span",{className:"text-xs text-text-muted",children:[c+1," / ",y]}),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(wt,{size:16})})]})]}),!f&&s.jsx("div",{className:"flex shrink-0 gap-1.5 px-5 pt-3",children:h.map((L,_)=>s.jsx("div",{className:`h-1.5 flex-1 rounded-full transition-colors ${_<c?"bg-accent-primary":_===c?"bg-accent-primary/60":"bg-border-default"}`},L.questionId))}),s.jsxs("div",{className:"min-h-0 flex-1 space-y-4 overflow-y-auto px-5 py-4",children:[v&&s.jsxs("section",{className:"space-y-3",children:[s.jsxs("div",{children:[v.header&&s.jsx("div",{className:"mb-1 text-xs font-semibold uppercase tracking-normal text-text-muted",children:v.header}),s.jsxs("div",{className:"text-sm font-semibold text-text-primary",children:[f?"":`${c+1}. `,v.question]}),v.multiSelect&&v.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:v.multiSelect?"group":"radiogroup","aria-label":v.question,children:v.options.map(L=>{var _;return s.jsx(bx,{label:L.label,description:L.description||L.preview,selected:(((_=I.answers[v.questionId])==null?void 0:_.selectedLabels)||[]).includes(L.label),multiSelect:v.multiSelect,disabled:t,onClick:()=>C(v,L.label)},L.label)})}),v.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:((R=o[v.questionId])==null?void 0:R.freeformText)||"",disabled:t,onChange:L=>w(v.questionId,L.currentTarget.value),className:"w-full min-h-20 rounded-md border border-border-default 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 shrink-0 items-center justify-between gap-2 border-t border-border-default px-5 pt-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))]",children:[s.jsx("div",{children:!f&&c>0&&s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:S,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"}),f||x?s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:N,disabled:!j||t||!p,children:t?"Submitting...":"Submit"}):s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:g,disabled:!b||t,children:"Next"})]})]})]})})}function wa(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 tu=e=>wa(e);function gx(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden,muted:!!e.muted,completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function kr(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating"||e.status==="no_progress"||e.status==="long_generating"||e.status==="streaming",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function su(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...gx(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 Ms(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,muted:!1,completionMarker:"",seenCompletionMarker:""}}function ja(e,t,r){const n=Ms(e,t),a=kr(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 yx(e,t,r){return ja(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function ru({activeConv:e,onModalButton:t}){const[r,n]=l.useState(null);if(l.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!kr(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(Vs,{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,y=r!==null;return s.jsx("button",{onClick:()=>o(c),disabled:y,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"} ${y&&!h?"opacity-40":"opacity-100"} ${y?"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 Ni="adhdev_controls_bar_visible",Ho="adhdev:controlsbarvisibilitychange";function Ua(e){if(!e)return!1;try{return e.getItem(Ni)==="1"}catch{return!1}}function vx(e,t){if(t)try{t.setItem(Ni,e?"1":"0")}catch{}}function wx(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Ho,{detail:{visible:e}}))}function Si(){const[e,t]=l.useState(()=>typeof window>"u"?!1:Ua(window.localStorage)),r=l.useRef(e),n=l.useCallback((i,c=!0)=>{r.current=i,t(i),typeof window<"u"&&vx(i,window.localStorage),c&&wx(i)},[]);l.useEffect(()=>{const i=d=>{const p=d.detail,u=typeof(p==null?void 0:p.visible)=="boolean"?p.visible:Ua(window.localStorage);r.current=u,t(u)},c=d=>{if(d.key!==Ni)return;const p=Ua(window.localStorage);r.current=p,t(p)};return window.addEventListener(Ho,i),window.addEventListener("storage",c),()=>{window.removeEventListener(Ho,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 jx=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function kx(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function qt(e,t){if(kx(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":jx.has(r)?"generating":r==="error"?"error":r==="stopped"?"stopped":r==="starting"?"starting":r==="panel_hidden"?"panel_hidden":r==="not_monitored"?"not_monitored":r==="disconnected"?"disconnected":"idle"}function Wo(e){return qt(e)==="generating"}function Dl(e,t){return qt(e,t)==="waiting_approval"}function pt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function _e(...e){for(const t of e){if(typeof t!="string")continue;const r=t.trim();if(r)return r}}function Wt(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function _t(...e){for(const t of e)if(typeof t=="boolean")return t}function za(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function Nx(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 Ci(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 Sx(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=pt(n),o=_e(a.path),i=_e(a.commit),c=_e(a.repoPath,a.repo_root)??Nx(t,o);if(!o||!i)return null;const d={path:o,commit:i,dirty:_t(a.dirty)??!1,outOfSync:_t(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:Wt(a.lastCheckedAt,a.last_checked_at)??Date.now()};c&&(d.repoPath=c);const p=_e(a.error);return p&&(d.error=p),d}).filter(n=>n!==null);return r.length>0?r:void 0}function Cx(e){return _t(e.isGitRepo)!==void 0||!!_e(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||!!_e(e.repoRoot,e.repo_root,e.workspace)||Wt(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 Bn(e,t,r){const n=_t(e.isGitRepo);if(!Object.keys(e).length||!Cx(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(j=>typeof j=="string"):[],i=Wt(e.conflicts)??o.length,c=_t(e.hasConflicts)??i>0,d=_e(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,p=Sx(e.submodules,d),u=_e(e.upstreamStatus,e.upstream_status),m=Wt(e.upstreamFetchedAt,e.upstream_fetched_at),h=_e(e.upstreamFetchError,e.upstream_fetch_error),y=_e(e.error),x=Wt(e.staged)??0,f=Wt(e.modified)??0,v=Wt(e.untracked)??0,k=Wt(e.deleted)??0,b=Wt(e.renamed)??0;return{workspace:_e(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:a,branch:_e(e.branch)??null,headCommit:_e(e.headCommit)??null,headMessage:_e(e.headMessage)??null,upstream:_e(e.upstream)??null,upstreamStatus:u??"unchecked",...m!==void 0?{upstreamFetchedAt:m}:{},...h?{upstreamFetchError:h}:{},ahead:Wt(e.ahead)??0,behind:Wt(e.behind)??0,staged:x,modified:f,untracked:v,deleted:k,renamed:b,dirty:_t(e.dirty,e.isDirty,e.is_dirty)??(x+f+v+k+b>0||c),hasConflicts:c,conflictFiles:o,stashCount:Wt(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??Wt(e.lastCheckedAt,e.last_checked_at)??Date.now(),...p?{submodules:p}:{},...y?{error:y}:{}}}function Ix(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+=Ci(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 Ax(e,t){const r=pt(e.lastGit??e.last_git),n=pt(r.result),a=pt(r.status),o=pt(n.status),i=pt(e.lastProbe??e.last_probe),c=pt(i.git),d=pt(c.result),p=pt(c.status),u=pt(d.status),m=t==null?void 0:t.lastCheckedAt;let h=null;for(const y of[a,o,p,u]){const x=Bn(y,e,{lastCheckedAt:m??Date.now()});if(!x)continue;const f=Ix(x);(!h||f>h.score)&&(h={git:x,score:f})}return h==null?void 0:h.git}function Mx(e){const t=[_e(e.workspace),_e(e.providerType,e.provider),_e(e.role),_e(e.state,e.status),_e(e.title),_e(e.createdAt,e.created_at),_e(e.startedAt,e.started_at)].filter(r=>!!r);if(t.length!==0)return`synthetic:${t.join("|")}`}function Ko(e){const t=pt(e),r=_e(t.sessionId,t.session_id,t.id)??Mx(t);return r?{sessionId:r,..._e(t.providerType,t.provider)?{providerType:_e(t.providerType,t.provider)}:{},..._e(t.state,t.status)?{state:_e(t.state,t.status)}:{},..._e(t.chatStatus,t.chat_status)?{chatStatus:_e(t.chatStatus,t.chat_status)}:{},..._e(t.lifecycle)?{lifecycle:_e(t.lifecycle)}:{},..._e(t.surfaceKind,t.surface_kind)?{surfaceKind:_e(t.surfaceKind,t.surface_kind)}:{},..._e(t.recoveryState,t.recovery_state)?{recoveryState:_e(t.recoveryState,t.recovery_state)}:{},..._e(t.workspace)?{workspace:_e(t.workspace)}:{},..._e(t.title)?{title:_e(t.title)}:{},..._e(t.role)?{role:_e(t.role)}:{},..._t(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:_t(t.isSelfCoordinator,t.is_self_coordinator)}:{},..._e(t.statusNote,t.status_note)?{statusNote:_e(t.statusNote,t.status_note)}:{},..._e(t.createdAt,t.created_at)?{createdAt:_e(t.createdAt,t.created_at)}:{},..._e(t.startedAt,t.started_at)?{startedAt:_e(t.startedAt,t.started_at)}:{},..._e(t.lastActivityAt,t.last_activity_at)?{lastActivityAt:_e(t.lastActivityAt,t.last_activity_at)}:{},..._t(t.isCached,t.is_cached)!==void 0?{isCached:_t(t.isCached,t.is_cached)}:{}}:null}function _x(e){const t=e&&typeof e=="object"?e:{};return _e(t.id,t.nodeId,t.node_id)}function Tx(e,t){if(!t)return!1;const r=t.trim();return r?_x(e)===r:!1}var Lx=["daemon_","standalone_"];function $l(e){const t=_e(e);if(t){for(const r of Lx)if(t.startsWith(r))return t.slice(r.length).trim()||void 0;return t}}function Fs(e,t){const r=$l(e),n=$l(t);return!r||!n?!1:r===n}var Rx=["easy","medium","difficult","freeform"];function At(e){return(typeof e=="string"?e.trim():"")||void 0}function bs(e,t){const r=At(t);return r?`${e}:${r}`:void 0}function Ss(e,t,r){const n=bs(t,r),a=At(r);n&&e.push(n),a&&e.push(a)}function lr(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function nu(e){return At(e.providerSessionId)||At(e.sessionId)||At(e.tabKey)||At(e.routeId)}function ka(e){return lr([At(e.historySessionId),At(e.providerSessionId),At(e.sessionId)])}function Vr(e){const t=[];return Ss(t,"provider",e.providerSessionId),Ss(t,"session",e.sessionId),Ss(t,"tab",e.tabKey),Ss(t,"route",e.routeId),lr(t)}function Px(e){const t=[];return At(e.providerSessionId)?(Ss(t,"provider",e.providerSessionId),lr(t)):At(e.sessionId)?(Ss(t,"session",e.sessionId),lr(t)):At(e.tabKey)?(Ss(t,"tab",e.tabKey),lr(t)):At(e.routeId)?(Ss(t,"route",e.routeId),lr(t)):[]}function au(e){return bs("provider",e.providerSessionId)||bs("session",e.sessionId)||bs("tab",e.tabKey)||bs("route",e.routeId)||"unknown:"}function Na(e){return ka(e)[0]}function Sa(e){const t=At(e.sessionId),r=Na(e);if(r&&!(t&&r===t))return r}function Dx(e){const t=At(e.providerSessionId),r=At(e.sessionId),n=At(e.tabKey),a=At(e.routeId),o=[bs("provider",t),bs("session",r),bs("tab",n),bs("route",a)].filter(d=>typeof d=="string"),i=Vr({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),c=au({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:c,targetKey:c,targetValue:nu({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:Na({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:i}}function Uo(e,t){const r=Dx(e);return Px(t).some(n=>r.lookupKeys.includes(n))}function ou(e){const t=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return t&&r.startsWith(`${t}:`)?r.slice(t.length+1):r}function zo(e){if(String(e.ownerDaemonId||"").trim())return!0;const t=e.settings;return t?!!t.meshNodeFor||!!t.meshNodeId||t.launchedByCoordinator===!0||t._remoteOwnedSession===!0:!1}function $x(e,t){const r=String(e.daemonId||"").trim(),n=String(e.id||"").trim(),a=ou(e);if(a&&t.has(a))return`mesh:${a}`;const o=String(e.ownerDaemonId||"").trim()||r;return o?a?`${o}:${a}`:o:n}function Ga(e,t){return t||e||"unknown"}function Ex(e,t){return e.ownerDaemonId&&(t==null?void 0:t[e.ownerDaemonId])||e.ownerMachineName||void 0||e.daemonId&&(t==null?void 0:t[e.daemonId])||void 0}function Tt(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Bx(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 Va(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function iu(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 Fx(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 Ox(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Hx(e){return Fx(e.trim().replace(/\.local$/i,""))}function Wx(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function lu(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&&!Ox(i));if(r&&r!=="Unknown")return Hx(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Jt(e,t={}){return Wx(e)||lu(e,t)}function cu(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 du(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 qs(e,t){return cu(e).join(" · ")}function sn(e){return e.transport==="pty"}function cr(e){return e.transport==="acp"}function Kx(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:Tt(e)}function El(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),i=Tt(r||"").trim().toLowerCase();return n===a||n===o||n===i}function Ux(e,t=[],r=[]){var d,p,u,m;const n=qt(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=>Dl(h.status,{activeModal:h.activeModal})||Wo(h.status));if(a)return qt(a.status,{activeModal:a.activeModal});const o=r.find(h=>Dl(h.status,{activeModal:h.activeModal})||Wo(h.status));if(o)return qt(o.status,{activeModal:o.activeModal});if(n&&n!=="idle")return n;const i=qt((d=t[0])==null?void 0:d.status,{activeModal:(p=t[0])==null?void 0:p.activeModal});if(i!=="idle")return i;const c=qt((u=r[0])==null?void 0:u.status,{activeModal:(m=r[0])==null?void 0:m.activeModal});return c!=="idle"?c:"idle"}function zx(e){return qt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Gx(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=qt(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 Vx(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 qx(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&&Vx(t.receivedAt)||0}function Yx(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Go(e){return Math.max(Yx(e),qx(e.activeChat))}function Jx(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 Ii(e,t){return Jx(Go(e),Go(t),Jt(e,{fallbackId:e.id}),Jt(t,{fallbackId:t.id}),e.id,t.id)}const uu="adhdev_notification_prefs",Bl={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Xx(){try{const e=localStorage.getItem(uu);if(e){const t=JSON.parse(e);return{...Bl,...t}}}catch{}return{...Bl}}function Qx(e){try{localStorage.setItem(uu,JSON.stringify(e))}catch{}}let xs=Xx(),Fn=[];function Zx(){Fn.forEach(e=>e())}function eb(e){xs={...xs,...e},Qx(xs),Zx()}function tb(){const[,e]=l.useState(0);l.useEffect(()=>{const r=()=>e(n=>n+1);return Fn.push(r),()=>{Fn=Fn.filter(n=>n!==r)}},[]);const t=l.useCallback(r=>{eb(r)},[]);return[{...xs},t]}function qr(e){if(!xs.globalEnabled)return!1;switch(e){case"disconnect":return xs.disconnectAlert;case"completion":return xs.completionAlert;case"approval":return xs.approvalAlert;case"browser":return xs.browserNotifications;default:return!0}}const sb={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function pu(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function mu(){return"Notification"in window&&Notification.permission==="granted"}let Ps=null;function rb(e){return e!==!1}async function nb(){if(Ps!==null)return Ps;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Ps=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Ps=!!await e.pushManager.getSubscription(),Ps):(Ps=!1,!1)}catch{return Ps=!1,!1}}function Vo(e,t,r){if(mu())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 ab(e,t={}){const r={...sb,...t},n=l.useRef(new Map),a=l.useRef(0),[o,i]=l.useState(null);l.useEffect(()=>{let d=!1;return nb().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,Vo(d,p,u))},[r.throttleMs]);l.useEffect(()=>{var d;if(!(!r.enabled||!mu())&&qr("browser")&&!rb(o)){if(document.hasFocus()){for(const p of e)n.current.set(p.id,qt(p.status,{activeModal:p.activeModal}));return}for(const p of e){const u=n.current.get(p.id),m=qt(p.status,{activeModal:p.activeModal}),h=p.name||p.id;if(p.muted){n.current.set(p.id,m);continue}if(r.onApproval&&qr("approval")&&m==="waiting_approval"&&u!=="waiting_approval"){const y=((d=p.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${h} — Approval needed`,y.slice(0,120),`approval-${p.id}`)}r.onComplete&&qr("completion")&&Wo(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 ob=/^(run|approve|accept|yes|allow|always)/,ib=/^(run|approve|accept|yes|allow|always|proceed|save)/,lb=/^(reject|deny|delete|remove|abort|cancel|no)/;function Ai(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function cb(e){const t=Ai(e).toLowerCase();return ob.test(t)?"primary":lb.test(t)?"danger":"default"}function db(e){return ib.test(Ai(e).toLowerCase())?"approve":"reject"}function ub(e){return e.map((t,r)=>({label:Ai(t),variant:cb(t),action:db(t),button:t,buttonIndex:r}))}function pb(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function mb(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 hb{constructor(){et(this,"dedupMap",new Map);et(this,"DEDUP_WINDOW_MS",5e3);et(this,"DEDUP_MAX_SIZE",50);et(this,"DEDUP_CLEANUP_AGE_MS",1e4);et(this,"toastCallbacks",[]);et(this,"statusEventCallbacks",[]);et(this,"resolveActionFn",null);et(this,"viewRequestRespondFn",null);et(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}isConversationEventMuted(t){const r=t.targetSessionId;if(!r)return!1;for(const n of this.ides){if(n.id===r||n.sessionId===r)return!!n.muted;const o=(Array.isArray(n.childSessions)?n.childSessions:[]).find(i=>(i==null?void 0:i.id)===r);if(o)return!!o.muted}return!1}handleRawEvent(t,r){var f;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 v of this.statusEventCallbacks)v(t);const d=this.isConversationEventMuted(t),p=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,u=(p==null?void 0:p.type)||"";let m=Tt(u);const h=this.resolveOwningDaemon(t);if(h){const v=Jt(h,{fallbackId:h.id});v&&(m=!u||u==="adhdev-daemon"?v:`${v}/${m}`)}let y="",x="info";if(t.event==="agent:generating_completed"){const v=t.duration?` (${t.duration}s)`:"";if(y=`✅ ${m} agent task completed${v}`,x="success",!d)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(y=`⚡ ${m} approval needed`,x="warning",d)y="";else if((f=t.modalButtons)!=null&&f.length&&this.resolveActionFn){const v=this.resolveActionRouteTarget(t);if(!v)return;const k=this.resolveActionFn,b=ub(t.modalButtons).map(w=>({label:w.label,variant:w.variant,onClick:()=>{k(v,"resolve_action",{action:w.action,button:w.button,buttonIndex:w.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),j=pb(m,t.modalMessage,y),C=Date.now();this.emitToast({id:C,message:j,type:x,timestamp:C,targetKey:n||v,actions:b,duration:15e3}),y=""}}else if(t.event==="monitor:no_progress"||t.event==="monitor:long_generating"){const v=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";y=`⚠️ ${m} agent shows no progress${v}`,x="warning",!d&&qr("browser")&&!document.hasFocus()&&Vo(`⚠️ ${m} — No Progress`,`Agent has shown no progress for over ${v.replace(/[()]/g,"")}`,`no-progress-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const v=t.requesterName||"A team member",k=t.requestId,b=t.orgId;if(y=`👁️ ${v} wants to view your session`,x="warning",k&&b&&this.viewRequestRespondFn){const j=Date.now(),C=mb(b,k,this.viewRequestRespondFn,(w,g)=>console.error(`[EventManager] ${w} view request failed:`,g));this.emitToast({id:j,message:y,type:x,timestamp:j,actions:C,duration:3e4}),y=""}qr("browser")&&!document.hasFocus()&&Vo("👁️ View Request",`${v} wants to view your session`,`view-request-${k}`)}else t.event==="team:view_request_approved"?(y="✅ View request approved",x="success"):t.event==="team:view_request_rejected"&&(y=`❌ ${t.targetName||"Team member"} declined your view request`,x="warning");if(y&&!d){const v=Date.now();this.emitToast({id:v,message:y,type:x,timestamp:v,targetKey:n||t.daemonId,duration:5e3})}}}const ct=new hb,Fl=new Map;function Zn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function dr(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Ca(e){return Zn(e)?Zn(e.result)?e.result:e:null}function fb(e){const t=Ca(e);return!t||!Zn(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function yn(e){const t=Ca(e);return!t||!Zn(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Tr(e){const t=Ca(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function vn(e){const t=Ca(e);return!!t&&t.success===!1}function xb(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";ct.showToast(n.toast.message,a);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const a=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";ct.showToast(n.notification.body,a)}}}function bb(e,t){return e&&dr(e.currentValue)?e.currentValue:t}function gb(e,t){const r=Object.keys(e).filter(a=>t[a]!==void 0);if(r.length===0)return e;const n={...e};for(const a of r)delete n[a];return n}function yb(e,t){return dr(t)?dr(e)?typeof e=="string"&&e.trim()==="":!0:!1}function vb(e,t){var o,i;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if(dr(c))return c}const n=(o=t.controlValues)==null?void 0:o[e];if(dr(n))return n;const a=(i=t.defaultValues)==null?void 0:i[e];return dr(a)?a:void 0}function On(e,t){return e.options||t[e.id]||[]}const wb={antigravity:new Set(["new_session"]),"claude-cli":new Set(["compact","new_session","stop"]),"claude-code-vscode":new Set(["new_session"]),codex:new Set(["new_session"])};function jb(e,t,r){var n;return((n=wb[t])==null?void 0:n.has(r.id))===!0}function kb(e){if(e)switch(e){case"idle":return["idle"];case"generating":case"streaming":case"working":case"starting":case"no_progress":case"long_generating":return["busy","generating","starting"];case"waiting_approval":case"approval":return["approval"];case"waiting_choice":return["picker"];default:return}}function Nb(e,t){const r=e.visibleWhenState;if(!r||r.length===0)return!0;const n=kb(t);return n?n.some(a=>r.includes(a)):!0}function Mi(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!jb(t.hostIdeType,t.providerType,r)&&Nb(r,t.currentStatus)).sort((r,n)=>(r.order??50)-(n.order??50))}function qa(e,t){return{value:t}}function Sb(e,t,r){var a;return r?((a=On(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const Cb={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Ib({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:i,currentStatus:c,coordinatorHint:d}){const{sendCommand:p}=xt(),u=`${e}:${t||n}`,m=Cb[n]||"#94a3b8",[h,y]=l.useState({}),x=l.useRef({}),f=l.useRef(i);x.current=h,f.current=i;const v=l.useRef(0),k={};for(const A of o||[])A.defaultValue!==void 0&&(k[A.id]=A.defaultValue);const b={...k,...i||{},...Date.now()<v.current?h:{}};l.useEffect(()=>{i&&Date.now()>v.current&&y(A=>gb(A,i))},[i]);const[j,C]=l.useState(Fl.get(u)||{}),[w,g]=l.useState(null),[S,N]=l.useState(null),I=l.useCallback(async(A,$={})=>{const T={...$,...t&&{targetSessionId:t},...d??{}};return await p(e,A,T)},[e,t,p,d]),R=l.useCallback(async(A,$={})=>{const T=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await I("invoke_provider_script",{...T,scriptName:A,...$})},[I,n,r,t]),L=l.useCallback((A,$,T)=>{const F=bb(T,$);y(z=>({...z,[A.id]:F})),xb(T==null?void 0:T.effects)},[]),_=l.useCallback((A,$)=>{y(T=>{const F={...T};return $===void 0?delete F[A.id]:F[A.id]=$,F}),v.current=0},[]);if(!o||o.length===0)return null;const P=Mi(o,{hostIdeType:r,providerType:n,currentStatus:c});if(P.length===0)return null;const B=async A=>{if(w===A.id){g(null);return}if(On(A,j).length>0){g(A.id);return}if(A.dynamic&&A.listScript){N(A.id);try{const T=await R(A.listScript,{}),F=fb(T);if(!F){const te=Tr(T);te&&ct.showToast(te,"warning");return}const z=F.options;C(te=>{const Z={...te,[A.id]:z};return Fl.set(u,Z),Z});const U=vb(A.id,{localOverrideUntil:v.current,localValues:x.current,controlValues:f.current,defaultValues:k});if(yb(U,F.currentValue)){const te=F.currentValue;y(Z=>({...Z,[A.id]:te}))}g(A.id)}catch(T){const F=T instanceof Error?T.message:`Could not load ${A.label}`;ct.showToast(F,"warning")}finally{N(null)}}},Y=async(A,$)=>{g(null);const T=(i==null?void 0:i[A.id])??k[A.id];y(F=>({...F,[A.id]:$})),v.current=Date.now()+5e3;try{if(!A.setScript)return;const F=await R(A.setScript,qa(A,$)),z=yn(F);if(z&&!z.ok||vn(F))throw new Error((z==null?void 0:z.error)||Tr(F)||`Could not update ${A.label}`);L(A,$,z)}catch(F){_(A,T);const z=F instanceof Error?F.message:`Could not update ${A.label}`;ct.showToast(z,"warning")}},M=async A=>{const $=On(A,j).map(Z=>Z.value);if($.length===0)return;const T=String(b[A.id]||""),z=($.indexOf(T)+1)%$.length,U=$[z];if(typeof U!="string")return;const te=(i==null?void 0:i[A.id])??k[A.id];y(Z=>({...Z,[A.id]:U})),v.current=Date.now()+5e3;try{if(!A.setScript)return;const Z=await R(A.setScript,qa(A,U)),se=yn(Z);if(se&&!se.ok||vn(Z))throw new Error((se==null?void 0:se.error)||Tr(Z)||`Could not update ${A.label}`);L(A,U,se)}catch(Z){_(A,te);const se=Z instanceof Error?Z.message:`Could not update ${A.label}`;ct.showToast(se,"warning")}},H=async A=>{const T=!b[A.id],F=(i==null?void 0:i[A.id])??k[A.id];y(z=>({...z,[A.id]:T})),v.current=Date.now()+5e3;try{if(!A.setScript)return;const z=await R(A.setScript,qa(A,T)),U=yn(z);if(U&&!U.ok||vn(z))throw new Error((U==null?void 0:U.error)||Tr(z)||`Could not update ${A.label}`);L(A,T,U)}catch(z){_(A,F);const U=z instanceof Error?z.message:`Could not update ${A.label}`;ct.showToast(U,"warning")}},q=async A=>{if(!A.invokeScript)return;if(A.confirmMessage){const T=[A.confirmTitle,A.confirmMessage,A.confirmLabel].filter(z=>typeof z=="string"&&z.trim().length>0);if(!window.confirm(T.join(`
32
-
33
- `)))return}const $=(i==null?void 0:i[A.id])??k[A.id];try{const T=await R(A.invokeScript),F=yn(T);if(F&&!F.ok||vn(T))throw new Error((F==null?void 0:F.error)||Tr(T)||`Could not run ${A.label}`);F&&L(A,$??!0,F)}catch(T){_(A,$);const F=T instanceof Error?T.message:`Could not run ${A.label}`;ct.showToast(F,"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:`${m}33`,background:`${m}12`,color:m},children:a}),P.map(A=>{const $=String(b[A.id]||""),T=Sb(A,j,$),F=w===A.id,z=S===A.id,U=On(A,j),te="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(A.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${te} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:F?`${m}55`:"var(--border-default)",background:F?`${m}10`:"var(--surface-tertiary)",color:$?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void B(A),title:A.label,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:z?"Loading…":T||A.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),F&&U.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[var(--z-dropdown)]",onClick:()=>g(null)}),s.jsxs("div",{className:"absolute bottom-full left-0 z-[var(--z-dropdown)] 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:A.label}),U.map(Z=>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:Z.value===$?`${m}14`:"transparent",color:Z.value===$?"var(--text-primary)":"var(--text-secondary)",borderLeft:Z.value===$?`2px solid ${m}`:"2px solid transparent"},title:Z.description||Z.label,onMouseEnter:se=>{se.currentTarget.style.background=`${m}10`},onMouseLeave:se=>{se.currentTarget.style.background=Z.value===$?`${m}14`:"transparent"},onClick:()=>void Y(A,Z.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:Z.label}),Z.value===$&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},Z.value))]})]})]},A.id);case"cycle":return s.jsxs("button",{type:"button",className:`${te} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:$?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void M(A),title:`Click to cycle: ${U.map(Z=>Z.label).join(" → ")}`,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:T||A.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},A.id);case"toggle":return s.jsxs("button",{type:"button",className:`${te} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:$?`${m}44`:"var(--border-default)",background:$?`${m}14`:"var(--surface-tertiary)",color:$?m:"var(--text-muted)"},onClick:()=>void H(A),"aria-pressed":!!$,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),A.label]},A.id);case"action":return s.jsxs("button",{type:"button",className:`${te} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void q(A),children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:A.resultDisplay==="inline"&&$?`${A.label}: ${$}`:A.label})]},A.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:$?"var(--text-primary)":"var(--text-muted)"},children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:$?`${A.label}: ${$}`:A.label})]},A.id);default:return null}})]})})}function Ab({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:c,controlValues:d,currentStatus:p,coordinatorHint:u}){const{isVisible:m}=Si(),h=Mi(c,{hostIdeType:a,providerType:o,currentStatus:p});return!e||t||h.length===0||!m?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(Ib,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:h,controlValues:d,currentStatus:p,coordinatorHint:u})})}const Lr=5,hu=10*1024*1024;function Mb({hasDraft:e,isBusy:t=!1}){return!e||t}function _b(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 Tb(e){if(e.size>hu)return null;const t=await _b(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 Lb(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const fu=l.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,inlineStatusMessage:i=null,onSend:c,onForceSend:d,canForceSend:p=!1,isActive:u=!0,showControlsToggle:m=!1,animateVisibility:h=!0,onControlsToggle:y,messageInput:x}){const f=l.useRef(null),v=l.useRef(null),[k,b]=l.useState(""),[j,C]=l.useState([]),[w,g]=l.useState(null),[S,N]=l.useState(!1),I=l.useRef(!1),{isVisible:R,toggleVisibility:L}=Si(),_=Lb(x),P=!!k.trim()||j.length>0;l.useEffect(()=>{b(""),C([]),g(null)},[t]),l.useEffect(()=>{var T;u&&((T=f.current)==null||T.focus({preventScroll:!0}))},[t,u]),l.useEffect(()=>{const T=f.current;T&&(T.style.height="auto",T.style.height=`${Math.min(T.scrollHeight,160)}px`)},[k]);const B=l.useCallback(async T=>{g(null);const F=Array.from(T).filter(G=>G.type.startsWith("image/"));if(F.length===0)return;const z=Lr-j.length;if(z<=0){g(`Max ${Lr} images`);return}const U=F.slice(0,z);if(U.filter(G=>G.size>hu).length>0){g("Image too large (max 10 MB)");return}const se=(await Promise.all(U.map(Tb))).filter(G=>G!==null);C(G=>[...G,...se])},[j.length]),Y=l.useCallback(T=>{C(F=>F.filter((z,U)=>U!==T))},[]),M=l.useCallback(async()=>{const T=k.trim();if(!T&&j.length===0||a||I.current)return;I.current=!0;const F=j.length>0?[...j]:void 0;try{await c(T,F)!==!1&&(b(""),C([]),g(null))}finally{I.current=!1}},[k,j,a,c]),H=l.useCallback(async()=>{if(!p||!d)return;const T=k.trim();if(!T&&j.length===0||I.current)return;I.current=!0;const F=j.length>0?[...j]:void 0;try{await d(T,F)!==!1&&(b(""),C([]),g(null))}finally{I.current=!1}},[j,p,k,d]),q=l.useCallback(T=>{_&&(T.preventDefault(),N(!0))},[_]),A=l.useCallback(()=>N(!1),[]),$=l.useCallback(T=>{_&&(T.preventDefault(),N(!1),T.dataTransfer.files.length>0&&B(T.dataTransfer.files))},[_,B]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",h?"transition-all duration-200 ease-out":"",S?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:u?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:u?200:0,opacity:u?1:0,transform:u?"translateY(0)":"translateY(10px)",padding:u?"10px 12px":"0 12px",pointerEvents:u?"auto":"none"},"aria-hidden":!u,onDragOver:q,onDragLeave:A,onDrop:$,children:[j.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:j.map((T,F)=>s.jsxs("div",{className:"relative group w-14 h-14 rounded-lg overflow-hidden border border-border-subtle shrink-0",style:{background:"var(--surface-secondary)"},children:[s.jsx("img",{src:T.previewUrl,alt:T.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>Y(F),className:"absolute top-0.5 right-0.5 w-4 h-4 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-[10px] leading-none","aria-label":`Remove ${T.name}`,children:"✕"})]},F))}),s.jsxs("div",{className:"flex gap-2 items-center",title:u?`Send message to ${r}`:void 0,children:[m&&s.jsx("button",{type:"button",onClick:()=>{L(),y==null||y()},"aria-label":R?"Hide controls":"Show controls","aria-pressed":R,title:R?"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"})]})}),_&&s.jsxs(s.Fragment,{children:[s.jsx("input",{ref:v,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:T=>{T.target.files&&B(T.target.files),T.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var T;return(T=v.current)==null?void 0:T.click()},disabled:j.length>=Lr,title:j.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:f,rows:1,placeholder:o||(_&&j.length>0?"Add a message (optional)...":`Send message to ${r}... (Shift+Enter for newline)`),value:k,onChange:T=>b(T.target.value),onPaste:T=>{if(_&&T.clipboardData.files.length>0&&Array.from(T.clipboardData.files).some(V=>V.type.startsWith("image/"))){T.preventDefault(),B(T.clipboardData.files);return}const F=T.clipboardData.getData("text/plain"),z=Dh(F);if(z===F)return;T.preventDefault();const U=f.current,te=(U==null?void 0:U.selectionStart)??k.length,Z=(U==null?void 0:U.selectionEnd)??k.length,se=k.slice(0,te)+z+k.slice(Z);b(se);const G=te+z.length;requestAnimationFrame(()=>{U==null||U.setSelectionRange(G,G)})},onKeyDown:T=>{T.key==="Enter"&&(T.nativeEvent.isComposing||T.shiftKey||(T.preventDefault(),M()))},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:()=>{M()},disabled:Mb({hasDraft:P,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${P&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:P&&!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:P?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})}),p&&s.jsx("button",{type:"button",onClick:()=>{H()},disabled:!P,className:`h-10 px-3 rounded-full text-[11px] font-medium border border-border-subtle shrink-0 transition-colors ${P?"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"})]}),(w||_&&S)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${w?"text-red-400":"text-[var(--accent-primary)]"}`,children:w||"Drop image here"}),i&&!w&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),Rb=l.createContext(null);function _i(){return l.useContext(Rb)}function Pb(e){return Ax(e,{lastCheckedAt:Date.now()})}function Db(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 $b(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 ea(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=Db(e);return t.outOfSync?"degraded":t.dirty||$b(e)?"dirty":"online"}function Eb(e,t){const r=t?ea(t):void 0;return!e||e==="unknown"?r:e}function Bb(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(Ko).filter(i=>i!==null);if(o.length>0)return o}const r=pt(e.activeSession??e.active_session),n={...r,sessionId:_e(r.sessionId,r.id,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id)},a=Ko(n);return a?[a]:void 0}function Fb(e){const t=pt(e.connection);return Object.keys(t).length>0?t:void 0}function Ob(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 Ti(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 Ol(e){var n,a,o,i,c,d;let t=0;const r=e.git;return Ti(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+=Ci(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 Hb(e,t){var x,f,v,k;const r=Ol(e),a=Ol(t)>r?t:e,o=a===t?e:t,i=a.git??o.git,c=(((x=a.providers)==null?void 0:x.length)??0)>0?a.providers:o.providers,d=(((f=a.activeSessions)==null?void 0:f.length)??0)>0?a.activeSessions:o.activeSessions,p=(((v=a.activeSessionDetails)==null?void 0:v.length)??0)>0?a.activeSessionDetails:o.activeSessionDetails,u=(((k=a.providerPriority)==null?void 0:k.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")?ea(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}:{}},y=pt(a.branchConvergence);return Object.keys(y).length>0?Object.assign(h,{branchConvergence:y}):delete h.branchConvergence,i&&(delete h.gitProbePending,delete h.error),h}function xu(e){const t=pt(e),r=_e(t.nodeId,t.id);if(!r)return null;const n=pt(t.cachedStatus),a=Pb(t),o=a?void 0:Bn(pt(t.git),t)??Bn(t,t),i=a??o,c=i?void 0:Bn(pt(n.git),t),d=i??c,p=_e(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),u=_e(t.health),m=a?ea(d):Eb(u,i)||(d?ea(d):void 0)||_e(n.health)||p||_e(t.status)||"unknown",y=(a?void 0:_e(t.error))??(i?void 0:_e(n.error)),x=Bb(t),f=za(t.activeSessions),v=(x==null?void 0:x.map(N=>N.sessionId))??[],k=za(t.providerPriority),b=_t(t.gitProbePending,t.git_probe_pending),j=i?void 0:b,C=Fb(t),w=pt(t.branchConvergence??t.branch_convergence),g=C==null?void 0:C.state,S=a&&(!(C!=null&&C.reported)||g==="unknown")?Ob(C):C;return{nodeId:r,machineLabel:_e(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:_e(t.workspace,d==null?void 0:d.workspace)||"",..._e(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:_e(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},..._e(t.daemonId,t.daemon_id)?{daemonId:_e(t.daemonId,t.daemon_id)}:{},..._e(t.machineId,t.machine_id)?{machineId:_e(t.machineId,t.machine_id)}:{},...p?{machineStatus:p}:{},..._t(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:_t(t.isLocalWorktree,t.is_local_worktree)}:{},..._e(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:_e(t.worktreeBranch,t.worktree_branch)}:{},..._e(t.clonedFromNodeId,t.cloned_from_node_id)?{clonedFromNodeId:_e(t.clonedFromNodeId,t.cloned_from_node_id)}:{},health:m,...d?{git:d}:{},...j!==void 0?{gitProbePending:j}:{},providers:za(t.providers),activeSessions:f.length>0?f:v,...x&&x.length>0?{activeSessionDetails:x}:{},...k.length>0?{providerPriority:k}:{},..._t(t.launchReady)!==void 0?{launchReady:_t(t.launchReady)}:a?{launchReady:!0}:{},..._e(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:_e(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},..._e(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:_e(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...S?{connection:S}:{},...Object.keys(w).length>0?{branchConvergence:w}:{},...t.scheduling&&typeof t.scheduling=="object"?{scheduling:t.scheduling}:{},..._t(t.autoFastForwardEligible,t.auto_fast_forward_eligible)===!0?{autoFastForwardEligible:!0}:{},...t.worktreeBootstrap&&typeof t.worktreeBootstrap=="object"?{worktreeBootstrap:t.worktreeBootstrap}:{},...t.staleDaemonBuild&&typeof t.staleDaemonBuild=="object"?{staleDaemonBuild:t.staleDaemonBuild}:{},...t.providerVersions&&typeof t.providerVersions=="object"&&!Array.isArray(t.providerVersions)?{providerVersions:t.providerVersions}:{},..._e(t.daemonBuildVersion,t.daemon_build_version)?{daemonBuildVersion:_e(t.daemonBuildVersion,t.daemon_build_version)}:{},...y?{error:y}:{}}}function Hl(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 bu(e,t){const r=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],n=r.map(Ko).filter(a=>a!==null);return n.length===0?t:t.map(a=>{const o=n.filter(c=>{const d=pt(r.find(h=>{const y=pt(h);return _e(y.sessionId,y.session_id,y.id)===c.sessionId})),p=_e(d.nodeId,d.node_id),u=_e(d.daemonId,d.daemon_id),m=_e(d.workspace);return p&&p===a.nodeId?!0:Fs(u,a.daemonId)?!m||!a.workspace||m===a.workspace:!!(m&&a.workspace&&m===a.workspace)});if(o.length===0)return a;const i=Hl([...a.activeSessionDetails??[],...o]);return{...a,activeSessionDetails:i,activeSessions:Hl([...a.activeSessionDetails??[],...o,...(a.activeSessions??[]).map(c=>({sessionId:c}))]).map(c=>c.sessionId)}})}function Wb(e){const t=pt(e);return Array.isArray(t.sessions)||Array.isArray(t.active_session_details)||_e(t.daemon_id,t.machine_id,t.repo_root,t.worktree_branch,t.cloned_from_node_id)!==void 0||_t(t.is_local_worktree)!==void 0}function gu(e){const t=new Map,r=[];for(const n of e){const a=Wb(n)?xu(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=Hb(o,a);t.set(a.nodeId,i);const c=r.findIndex(d=>d.nodeId===a.nodeId);c>=0&&(r[c]=i)}return r}function yu(e){const t=e??{},r=gu(t.nodes??[]);return{...t,nodes:bu(t,r)}}function Kb(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:Ti(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 Ub(e){const t=_e(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(d=>xu(d)).filter(d=>d!==null):null;if(!t||!n)return null;const a=bu(e,gu(n)),o=_e(e.meshName,e.mesh_name,e.name),i=_e(e.repoIdentity,e.repo_identity),c=_e(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 zb(e){var o;let t=0;const r=pt(e.sourceOfTruth),n=pt(r.directPeerTruth);_e(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+=Ci(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 Gb(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 Vb=20;function Wl(e){let t=null;for(const r of e){const n=Ub(pt(r));if(!n)continue;const a=zb(n),o=Gb(n);if(!t){t={status:n,score:a,refreshedAt:o};continue}(Math.abs(a-t.score)<=Vb?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 Li(e){const r=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,n=Wl([r==null?void 0:r.status,r]);return n||Wl([e==null?void 0:e.status,e])}function qb(e){var n;if(!e)return null;const t=(n=e.coordinator)==null?void 0:n.meshId;if(typeof t=="string"&&t.trim())return t.trim();const r=e.settings||{};for(const a of["meshNodeFor","meshCoordinatorFor"]){const o=r[a];if(typeof o=="string"&&o.trim())return o.trim()}return null}function Yb(e){const t=(e==null?void 0:e.settings)||{};for(const r of["meshNodeId","nodeId"]){const n=t[r];if(typeof n=="string"&&n.trim())return n.trim()}return null}function Jb(e,t){var a;if(!t)return null;const r=Li(e),n=(a=r==null?void 0:r.nodes)==null?void 0:a.find(o=>Tx(o,t));return n?{nodeId:n.nodeId,workspace:n.workspace,repoRoot:n.repoRoot,daemonId:n.daemonId,role:n.role,machineStatus:n.machineStatus,health:n.health,isLocalWorktree:n.isLocalWorktree,worktreeBranch:n.worktreeBranch,launchReady:n.launchReady,providers:n.providers,providerPriority:n.providerPriority,git:n.git?{branch:n.git.branch,headCommit:n.git.headCommit,ahead:n.git.ahead,behind:n.git.behind,dirty:n.git.dirty,upstream:n.git.upstream}:void 0,connection:n.connection?{transport:n.connection.transport,state:n.connection.state,rttMs:n.connection.rttMs}:void 0}:null}const Xb={sm:"max-w-md",md:"max-w-lg",lg:"max-w-3xl"};function vu({open:e,onClose:t,size:r="md",title:n,footer:a,children:o,showClose:i=!0,closeOnBackdrop:c=!0,closeOnEsc:d=!0,ariaLabel:p,className:u,contentClassName:m}){l.useEffect(()=>{if(!e||!d)return;const f=v=>{v.key==="Escape"&&t()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[e,d,t]);const h=l.useCallback(f=>{c&&f.target===f.currentTarget&&t()},[c,t]);if(!e)return null;const y=n!=null||i,x=s.jsx("div",{className:$t("fixed inset-0 flex items-center justify-center bg-black/60 p-4",u),style:{zIndex:"var(--z-modal-backdrop)"},onClick:h,children:s.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":n==null?p:void 0,className:$t("relative flex max-h-[calc(100dvh-2rem)] w-full flex-col overflow-hidden","rounded-xl border border-border-default bg-surface-primary shadow-2xl",Xb[r],m),style:{zIndex:"var(--z-modal)"},onClick:f=>f.stopPropagation(),children:[y&&s.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-4 border-b border-border-default px-5 py-4",children:[s.jsx("div",{className:"min-w-0",children:typeof n=="string"||typeof n=="number"?s.jsx("h2",{className:"truncate text-lg font-bold text-text-primary",children:n}):n}),i&&s.jsx("button",{type:"button",onClick:t,className:"btn btn-ghost btn-sm h-8 w-8 shrink-0 p-0","aria-label":"Close dialog",children:s.jsx(wt,{size:16})})]}),s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-5 py-4",children:o}),a!=null&&s.jsx("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border-default px-5 py-4",children:a})]})});return typeof document>"u"?x:ur.createPortal(x,document.body)}function Kl(e){if(!e||!Number.isFinite(e))return"—";try{return`${new Date(e).toLocaleString()} (${e})`}catch{return String(e)}}function Ul(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 Qb({sessionId:e,daemonId:t,conv:r,onClose:n}){var w,g;const{sendCommand:a}=xt(),o=_i(),[i,c]=l.useState(!0),[d,p]=l.useState(null),[u,m]=l.useState(null),[h,y]=l.useState(null),[x,f]=l.useState(null),v=l.useMemo(()=>qb(r),[r]),k=l.useMemo(()=>Yb(r),[r]),b=l.useCallback(async()=>{c(!0),m(null);try{const S=await a(t,"get_session_info",{targetSessionId:e}),N=S&&typeof S=="object"?S:{},I=N.result&&typeof N.result=="object"?N.result:N;I!=null&&I.success?p(I):(m((I==null?void 0:I.error)||"Failed to load session info"),p(null))}catch(S){m((S==null?void 0:S.message)||String(S)),p(null)}finally{c(!1)}},[a,t,e]);l.useEffect(()=>{b()},[b]);const j=l.useCallback(async()=>{if(y(null),f(null),!(!v||!k||!(o!=null&&o.loadMeshStatus)))try{const S=await o.loadMeshStatus(t,v,{refresh:!1}),N=Jb(S,k);if(!N){f("This session is stamped to a mesh node that the coordinator no longer reports.");return}y(N)}catch(S){f((S==null?void 0:S.message)||"Failed to load mesh node info")}},[o,t,v,k]);l.useEffect(()=>{j()},[j]);const C=s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:()=>void b(),className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:"Refresh"}),s.jsx("button",{type:"button",onClick:n,className:"px-3 py-1 text-sm rounded bg-accent text-white hover:opacity-90",children:"Close"})]});return s.jsx(vu,{open:!0,onClose:n,title:"Session info",size:"lg",footer:C,children:s.jsxs("div",{className:"text-sm space-y-4",children:[i&&s.jsx("div",{className:"text-text-secondary",children:"Loading…"}),u&&s.jsx("div",{className:"text-red-500",children:u}),(d==null?void 0:d.session)&&s.jsxs(rr,{title:"Session",children:[s.jsx(tt,{k:"Session ID",v:s.jsx(kt,{children:d.session.sessionId})}),s.jsx(tt,{k:"Provider",v:`${d.session.providerName||d.session.providerType} (${d.session.providerType})`}),d.session.transport&&s.jsx(tt,{k:"Transport",v:d.session.transport}),d.session.workspace&&s.jsx(tt,{k:"Workspace",v:s.jsx(kt,{children:d.session.workspace})}),s.jsx(tt,{k:"Spawned at",v:s.jsxs(s.Fragment,{children:[Kl(d.session.spawnedAtMs),d.session.spawnedAtMs?s.jsx("span",{className:"text-text-secondary ml-2",children:Ul(d.session.spawnedAtMs)}):null]})}),d.session.providerSessionId&&s.jsx(tt,{k:"Provider session ID",v:s.jsx(kt,{children:d.session.providerSessionId})}),!d.session.workspace&&(r==null?void 0:r.workspacePath)&&s.jsx(tt,{k:"Workspace",v:s.jsx(kt,{children:r.workspacePath})}),(r==null?void 0:r.machineName)&&s.jsx(tt,{k:"Machine",v:r.machineName}),(r==null?void 0:r.connectionState)&&s.jsx(tt,{k:"Connection",v:r.connectionState}),(r==null?void 0:r.git)&&s.jsx(tt,{k:"Workspace git",v:s.jsxs("span",{children:[r.git.branch||"(detached)",r.git.ahead?` ↑${r.git.ahead}`:"",r.git.behind?` ↓${r.git.behind}`:"",r.git.dirty?" · dirty":" · clean"]})})]}),((w=d==null?void 0:d.session)==null?void 0:w.launch)&&s.jsxs(rr,{title:"Launch",children:[d.session.launch.command&&s.jsx(tt,{k:"Command",v:s.jsx(kt,{children:d.session.launch.command})}),d.session.launch.cwd&&s.jsx(tt,{k:"Working directory",v:s.jsx(kt,{children:d.session.launch.cwd})}),Array.isArray(d.session.launch.args)&&d.session.launch.args.length>0&&s.jsx(tt,{k:"Args",v:s.jsx(kt,{children:d.session.launch.args.join(" ")})}),Array.isArray(d.session.launch.extraArgs)&&d.session.launch.extraArgs.length>0&&s.jsx(tt,{k:"Extra args",v:s.jsx(kt,{children:d.session.launch.extraArgs.join(" ")})}),Array.isArray(d.session.launch.extraEnvKeys)&&d.session.launch.extraEnvKeys.length>0&&s.jsx(tt,{k:"Extra env",v:s.jsx(kt,{children:d.session.launch.extraEnvKeys.join(", ")})})]}),h&&s.jsxs(rr,{title:"Mesh node",children:[h.nodeId&&s.jsx(tt,{k:"Node ID",v:s.jsx(kt,{children:h.nodeId})}),h.workspace&&s.jsx(tt,{k:"Workspace",v:s.jsx(kt,{children:h.workspace})}),h.repoRoot&&h.repoRoot!==h.workspace&&s.jsx(tt,{k:"Repo root",v:s.jsx(kt,{children:h.repoRoot})}),h.daemonId&&s.jsx(tt,{k:"Daemon ID",v:s.jsx(kt,{children:h.daemonId})}),h.role&&s.jsx(tt,{k:"Role",v:h.role}),h.machineStatus&&s.jsx(tt,{k:"Machine status",v:h.machineStatus}),h.health&&s.jsx(tt,{k:"Health",v:h.health}),h.isLocalWorktree&&s.jsx(tt,{k:"Worktree",v:h.worktreeBranch?s.jsx(kt,{children:h.worktreeBranch}):"yes"}),typeof h.launchReady=="boolean"&&s.jsx(tt,{k:"Launch ready",v:h.launchReady?"yes":"no"}),h.git&&s.jsx(tt,{k:"Git",v:s.jsxs("span",{children:[h.git.branch||"(detached)",h.git.headCommit?` @ ${String(h.git.headCommit).slice(0,10)}`:"",h.git.ahead?` ↑${h.git.ahead}`:"",h.git.behind?` ↓${h.git.behind}`:"",h.git.dirty?" · dirty":" · clean",h.git.upstream?` · ${h.git.upstream}`:""]})}),h.connection&&s.jsx(tt,{k:"Connection",v:s.jsxs("span",{children:[h.connection.transport||"—",h.connection.state?` · ${h.connection.state}`:"",typeof h.connection.rttMs=="number"?` · ${h.connection.rttMs}ms RTT`:""]})}),Array.isArray(h.providers)&&h.providers.length>0&&s.jsx(tt,{k:"Providers",v:s.jsx(kt,{children:h.providers.join(", ")})}),Array.isArray(h.providerPriority)&&h.providerPriority.length>0&&s.jsx(tt,{k:"Provider priority",v:s.jsx(kt,{children:h.providerPriority.join(" › ")})})]}),!h&&x&&(v||k)&&s.jsx(rr,{title:"Mesh node",children:s.jsx("div",{className:"text-text-secondary italic",children:x})}),(d==null?void 0:d.coordinator)&&s.jsxs(rr,{title:"Mesh coordinator",children:[s.jsx(tt,{k:"Mesh ID",v:s.jsx(kt,{children:d.coordinator.meshId})}),d.coordinator.cliType&&s.jsx(tt,{k:"Coordinator CLI",v:d.coordinator.cliType}),s.jsx(tt,{k:"Started at",v:s.jsxs(s.Fragment,{children:[Kl(d.coordinator.startedAt),d.coordinator.startedAt?s.jsx("span",{className:"text-text-secondary ml-2",children:Ul(d.coordinator.startedAt)}):null]})}),d.coordinator.injection&&s.jsx(tt,{k:"Prompt injection",v:`${d.coordinator.injection.mode}${d.coordinator.injection.target?` → ${d.coordinator.injection.target}`:""}`}),d.coordinator.mcpConfigPath&&s.jsx(tt,{k:"MCP config",v:s.jsx(kt,{children:d.coordinator.mcpConfigPath})}),d.coordinator.extraSystemPrompt&&s.jsx(qo,{title:"Per-launch extra prompt",body:d.coordinator.extraSystemPrompt,defaultOpen:!0}),d.coordinator.systemPrompt&&s.jsx(qo,{title:"Final system prompt (click to expand)",body:d.coordinator.systemPrompt})]}),((g=d==null?void 0:d.session)==null?void 0:g.runtimeMetadata)!=null&&s.jsx(Zb,{meta:d.session.runtimeMetadata}),d&&!d.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."})]})})}function rr({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 tt({k:e,v:t}){return s.jsxs("div",{className:"flex flex-col sm:flex-row gap-1 sm:gap-3",children:[s.jsx("div",{className:"w-full sm:w-36 sm:shrink-0 text-text-secondary font-medium sm:font-normal",children:e}),s.jsx("div",{className:"min-w-0 break-all",children:t})]})}function kt({children:e}){return s.jsx("code",{className:"font-mono text-xs",children:e})}function Zb({meta:e}){if(!e||typeof e!="object")return null;const t=e,r=d=>typeof d=="string"&&d.trim()?d:null,n=r(t.runtimeId),a=r(t.lifecycle),o=r(t.surfaceKind),i=r(t.recoveryState),c=Array.isArray(t.attachedClients)?t.attachedClients.length:null;return s.jsxs(rr,{title:"Runtime",children:[n&&s.jsx(tt,{k:"Runtime ID",v:s.jsx(kt,{children:n})}),a&&s.jsx(tt,{k:"Lifecycle",v:a}),o&&s.jsx(tt,{k:"Surface",v:o}),i&&s.jsx(tt,{k:"Recovery state",v:i}),typeof t.restoredFromStorage=="boolean"&&s.jsx(tt,{k:"Restored from storage",v:t.restoredFromStorage?"yes":"no"}),c!=null&&s.jsx(tt,{k:"Attached clients",v:String(c)}),s.jsx(qo,{title:"Raw runtime metadata (click to expand)",body:eg(e)})]})}function eg(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function qo({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 tg({sessionId:e,daemonId:t,conv:r}){const[n,a]=l.useState(!1);return!e||!t?null:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:()=>a(!0),title:"Session info — launch args, mesh node, system prompt, …","aria-label":"Session info",className:"inline-flex items-center justify-center w-6 h-6 rounded-full text-text-secondary hover:text-text-primary hover:bg-surface-secondary text-sm leading-none",style:{pointerEvents:"auto"},children:"ⓘ"}),n&&s.jsx(Qb,{sessionId:e,daemonId:t,conv:r,onClose:()=>a(!1)})]})}const sg=8e3;function rg({sessionId:e,daemonId:t,muted:r,sendDaemonCommand:n}){const[a,o]=l.useState(null),i=l.useRef(null);if(l.useEffect(()=>{a!==null&&r===a&&o(null)},[r,a]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]),!e||!t)return null;const c=a!==null?a:r,d=()=>{const p=!c;o(p),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>o(null),sg),n(t,"set_conversation_prefs",{sessionId:e,muted:p}).catch(u=>{console.warn("[conversation-prefs] toggle mute failed",u),o(null)})};return s.jsx("button",{type:"button",onClick:d,"aria-label":c?"Unmute this chat":"Mute this chat","aria-pressed":c,title:c?"Muted — notifications silenced. Click to unmute.":"Mute notifications for this chat",className:`inline-flex items-center justify-center w-6 h-6 rounded-full leading-none transition-colors ${c?"bg-amber-500 text-white hover:bg-amber-600":"text-text-secondary hover:text-text-primary hover:bg-surface-secondary"}`,style:{pointerEvents:"auto"},children:c?s.jsx(Kd,{size:13}):s.jsx(jr,{size:13})})}function wu(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}function ju(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function ng(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 Ya(e){return ng(e)?String(e.role||"").toLowerCase():""}const ag=4;function og(e,t){if(e.length===0)return[];for(let o=t.length-1;o>=0;o-=1)if(Ya(t[o])==="assistant")return[];const r=t.some(o=>Ya(o)==="user"),n=[];let a=!1;for(let o=e.length-1;o>=0&&n.length<ag;o-=1){const i=e[o],c=Ya(i);if(c){if(!a&&c==="assistant"){n.unshift(i),a=!0;continue}if(a&&c==="user"){r||n.unshift(i);break}}}return n}function ig(e){return e.map((t,r)=>({message:t,index:r,ts:wu(t)})).sort((t,r)=>t.ts-r.ts||t.index-r.index).map(t=>t.message)}function lg(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=og(o,i),d=c.length>0?[...c,...i]:i,p=t.length===0?d:[...t,...d];return ig(p)}const lt=e=>e.transport==="pty",Nr=(e,t)=>lt(e)&&e.mode||"chat",ku=(e,t)=>lt(e)&&Nr(e)==="terminal",it=e=>e.transport==="acp",cg=180;function As(e){return e.streamSource!=="agent-stream"}function _s(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Ia(e){var r;const t=typeof((r=e.settings)==null?void 0:r.meshCoordinatorDaemonId)=="string"?e.settings.meshCoordinatorDaemonId:void 0;return t?{meshCoordinatorDaemonId:t}:{}}function Nu(e){return e.machineName||""}function Qs(e){return _s(e)}function ms(e){return e.agentType||""}function ta(e){return e.hostIdeType||""}function Ri(e){return e.displayPrimary||e.agentName||"Agent"}function Su(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function dg(e,t){const r=ju(e,t);return[...r].reverse().find(n=>!(n!=null&&n._localId))||r[r.length-1]}function Cu(e,t){const r=dg(e,t),n=mr(r==null?void 0:r.content),a=mr(e.lastMessagePreview);return a&&e.lastMessageRole==="assistant"&&(r==null?void 0:r.role)==="user"?a:n||a||""}function ug(e,t=cg){const r=mr(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 pg(e){return ug(Cu(e)||e.displaySecondary||"")}function Iu(e){return[e.displaySecondary,Nu(e)].filter(Boolean)}function fr(e){return e.agentName||Tt(ms(e))}function mg(e){var t,r;if(!As(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return Tt(ta(e)||ms(e))}function Au(e){return As(e)?e.sessionId:e.nativeSessionId}function zl(e){return As(e)?"native":e.tabKey}function hg(e){return e.sessionId}function fg(e,t){if(t)return As(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function xg(e,t){const r=ms(e),n=As(e),a=lt(e)||it(e),o=n?a?fr(e)||(t==null?void 0:t.cliName)||Tt(ta(e)||r):t!=null&&t.type?Tt(t.type):Tt(ta(e)||r):fr(e);return{isNativeConversation:n,isCli:lt(e),isAcp:it(e),isCliTerminal:ku(e),providerType:r,displayLabel:o,targetEntry:fg(e,t)}}function Os(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:lt(e)||it(e)?{agentType:ms(e)}:e.streamSource==="agent-stream"?{agentType:ms(e)}:t}function Hs(e){return e?Qs(e):""}function nr(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Pi(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Gl(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 Mu(){return"select_session"}function bg(){return"open_panel"}function gg({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function Vl(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function wn(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Yr(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Di(e){return e instanceof Error?e.message:String(e||"")}function ql(e){const t=Di(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Yl(e,t){const r=Di(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function Jl(e,t,r,n={}){const a=Os(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 Aa({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(k,b)=>{if(!t||u.current)return!1;const j=k.trim(),C=Pi(t);if(gg({hasMessage:!!j,blockedMessage:C,sendInFlight:u.current}))return C&&p(C),!1;const w=Date.now(),g={tabKey:t.tabKey,message:j,timestamp:w};if(Vl(m.current,g))return p(null),!0;u.current=!0,c(!0),p(null),m.current=g;try{const S=Hs(t);if(!S)return m.current=wn(m.current,g),p("Unable to send message right now."),!1;const N=await e(S,"send_chat",Jl(j,b,t)),I=Yr(N);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(S){const N=Di(S);return N.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",N):console.warn("Send blocked/failed",S),m.current=wn(m.current,g),p(Gl(S)),!1}finally{u.current=!1,c(!1)}},[t,e]),y=l.useCallback(async(k,b)=>{if(!t||u.current)return!1;const j=k.trim();if(!j&&(!b||b.length===0))return!1;const C=Date.now(),w={tabKey:t.tabKey,message:`force:${j}`,timestamp:C};if(Vl(m.current,w))return p(null),!0;u.current=!0,c(!0),p(null),m.current=w;try{const g=Hs(t);if(!g)return m.current=wn(m.current,w),p("Unable to send message right now."),!1;const S=await e(g,"send_chat",Jl(j,b,t,{force:!0})),N=Yr(S);if((N==null?void 0:N.success)===!1||(N==null?void 0:N.sent)===!1)throw new Error((N==null?void 0:N.error)||"Send failed");return p(null),!0}catch(g){return console.warn("Force send blocked/failed",g),m.current=wn(m.current,w),p(Gl(g)),!1}finally{u.current=!1,c(!1)}},[t,e]),x=l.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(k){console.error("Relaunch failed",k)}},[t,e]),f=l.useCallback(async k=>{if(t)try{const j=(t.modalButtons||[]).indexOf(k),C=k.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),w=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(C),g=Hs(t);if(!g)return;const S=await e(g,"resolve_action",{button:k,action:w?"approve":"reject",...j>=0&&{buttonIndex:j},...Os(t),...Ia(t)}),N=Yr(S);N.success||r(I=>[...I,{routeId:t.tabKey,text:Yl(k,N==null?void 0:N.error),timestamp:Date.now()}])}catch(b){ql(b)||console.error("[ModalButton] Error:",b),r(j=>[...j,{routeId:t.tabKey,text:ql(b)?Yl(k,b):`❌ **${k}** error`,timestamp:Date.now()}])}},[t,e,r]),v=l.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,bg(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(k){console.error("Focus agent failed",k)}finally{o(!1)}}},[t,a,e]);return{isSendingChat:i,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:h,handleForceSendChat:y,handleRelaunch:x,handleModalButton:f,handleFocusAgent:v}}const yg=10,vg=8e3,wg=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function jg(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 Yo(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(wg.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=jg(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=>Yo(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,Yo(a,n,r+1)]))}function Rr(e,t){return Array.isArray(e)?e.slice(-t):[]}function kg(e,t=Date.now()){const r=e&&t-e.firstAt<=vg,n=r?e.count+1:1;return n>=yg?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function _u(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:Rr(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:Rr(t.messages,10),visibleMessagesTail:Rr(e.visibleMessages,5),historyMessagesTail:Rr(e.chatTailState.historyMessages,5),actionLogsTail:Rr(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 Yo(r)}function Tu(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 Lu(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 Ru(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(`
34
- `)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
35
-
36
- \`\`\`json
37
- ${JSON.stringify(t.bundle,null,2)}
38
- \`\`\``:`# ADHDev Chat Debug Bundle
39
-
40
- \`\`\`json
41
- ${JSON.stringify(t,null,2)}
42
- \`\`\``}function Ja(e,t){return`${e}:${t}`}function Ng(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function Sg(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function er(e,t){Sg()&&console.debug(`[subscription-manager] ${e}`,t)}class Cg{constructor(){et(this,"active",new Map);et(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var u,m;const i=Ja(n.topic,n.key),c=this.active.get(i);let d=!0;if(c)c.handlers.add(a),(!Ng(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),er("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),er("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 x;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 y={type:"unsubscribe",topic:n.topic,key:n.key};er("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(x=t.sendData)==null||x.call(t,r,y)};return p.initialSendAccepted=d,p}publish(t){const r=Ja(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,pr.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),n.handlers.forEach(a=>{a(t),pr.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,r,n){const a=Ja(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;er("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);er("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;er("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 rs=new Cg;function Ig(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 Ag(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 Xa(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function Mg(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function _g(e){Mg()&&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 sa(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}=Ag(d),m=Ig(o,n),h=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,y=p.filter(v=>v.kind==="workspace"&&v.transport==="cdp-page"),x=p.filter(v=>v.kind==="agent"&&v.transport==="pty"),f=p.filter(v=>v.kind==="agent"&&v.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:y.some(v=>!!v.cdpConnected)});for(const v of y){const k=m.get(v.id),b=Wr(v,k),j=(u.get(v.id)||[]).map(C=>Wr(C,m.get(C.id)));r.push({id:`${n}:ide:${v.id}`,sessionId:v.id,providerSessionId:v.providerSessionId??(k==null?void 0:k.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,status:b.cdpConnected?"online":"detected",daemonId:n,instanceId:Xa(n,v.id),workspace:b.workspace,terminals:0,childSessions:j,agents:j.map(C=>({id:C.id,name:C.providerName||C.providerType,type:C.providerType,status:C.status})),activeChat:b.activeChat,...b.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:b.activeInteractivePrompt},chats:[],cdpConnected:b.cdpConnected,...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,muted:b.muted,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},...b.settings!==void 0&&{settings:b.settings},...b.messageInput!==void 0&&{messageInput:b.messageInput},timestamp:c})}for(const v of x){const k=m.get(v.id),b=Wr(v,k);r.push({id:`${n}:cli:${v.id}`,sessionId:v.id,providerSessionId:v.providerSessionId??(k==null?void 0:k.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:Xa(n,v.id),cliName:b.providerName||b.providerType,mode:b.mode||(k==null?void 0:k.mode)||"terminal",workspace:b.workspace||"",...v.ownerDaemonId&&{ownerDaemonId:v.ownerDaemonId},...v.ownerMachineName&&{ownerMachineName:v.ownerMachineName},activeChat:b.activeChat,...b.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:b.activeInteractivePrompt},...b.resume!==void 0&&{resume:b.resume},...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,muted:b.muted,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},...b.settings!==void 0&&{settings:b.settings},...b.messageInput!==void 0&&{messageInput:b.messageInput},timestamp:c,_isCli:!0})}for(const v of f){const k=m.get(v.id),b=Wr(v,k);r.push({id:`${n}:acp:${v.id}`,sessionId:v.id,providerSessionId:v.providerSessionId??(k==null?void 0:k.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:Xa(n,v.id),cliName:b.providerName||b.providerType,mode:"chat",workspace:b.workspace||"",...v.ownerDaemonId&&{ownerDaemonId:v.ownerDaemonId},...v.ownerMachineName&&{ownerMachineName:v.ownerMachineName},activeChat:b.activeChat,...b.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:b.activeInteractivePrompt},...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,muted:b.muted,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},...b.settings!==void 0&&{settings:b.settings},...b.messageInput!==void 0&&{messageInput:b.messageInput},timestamp:c,_isAcp:!0})}return _g(r),r}const Tg=15e3,Lg=15e3,Rg=6e4,Xl=12,Pg=8e3,Dg=4e3;function $g(e){const{force:t,hasSubscription:r,loadedAt:n,now:a,minFreshMs:o}=e;return t||n<=0?!0:r?!1:a-n>=o}const Qa=new Map,Za=new Map,jn=new Set;function Eg(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 Sr(){const{sendCommand:e,sendData:t}=xt(),{injectEntries:r,getIdes:n}=en();return l.useCallback(async(a,o)=>{if(!a)return;const i=(o==null?void 0:o.minFreshMs)??Rg;if(!$g({force:o==null?void 0:o.force,hasSubscription:jn.has(a),loadedAt:Za.get(a)||0,now:Date.now(),minFreshMs:i}))return;const c=Qa.get(a);if(c)return c;const d=(async()=>{t&&!jn.has(a)&&(rs.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},f=>{const v=n(),k=v.find(j=>j.id===a),b=sa(f.status,{daemonId:a,existingDaemon:k,existingEntries:v,timestamp:f.timestamp});b.length>0&&r(b),Za.set(a,Date.now())}).initialSendAccepted?jn.add(a):jn.delete(a));const p=await e(a,"get_status_metadata"),u=Eg(p);if(!u)return;const m=n(),h=m.find(x=>x.id===a),y=sa(u,{daemonId:a,existingDaemon:h,existingEntries:m,timestamp:u.timestamp||Date.now()});y.length>0&&r(y,{authoritativeDaemonIds:[a]}),Za.set(a,Date.now())})().finally(()=>{Qa.delete(a)});return Qa.set(a,d),d},[n,r,e,t])}const Bg=60,Fg=50;function Pu(e={}){return e.isCliLike?Fg:Bg}function Og(e={}){return Pu(e)}const un=60,Hg=1e3,Wg=750,Ql=500,Ma=12e4,Du=new Set(["generating","waiting_approval","starting","streaming","working"]),rn=new Map;let $u=0;const Jo=new Set;function Kg(){$u+=1;for(const e of Jo)e()}function Ug(e){return Jo.add(e),()=>{Jo.delete(e)}}function Zl(){return $u}function pn(e,t,r){return`${e}::${t}::${r||t}`}function ra(e=un){return{liveMessages:[],hasLiveSnapshot:!1,cursor:zg([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function zg(e,t=un){return{tailLimit:t}}function ec(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 na(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(na).join(`
43
- `);if(typeof e=="object"){const t=e;return na(t.text??t.content??t.value??"")}return String(e)}function $i(e){return na(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function Gg(e){return e.length===0||e.every($i)}function tc(e){for(let t=e.length-1;t>=0;t-=1){const r=e[t],n=typeof(r==null?void 0:r.role)=="string"?r.role:"",a=typeof(r==null?void 0:r.kind)=="string"?r.kind:"";if(!(n==="system"||a==="system")&&!(a==="tool"||a==="thought"||a==="terminal"||a==="activity")&&!$i(e[t]))return n}return""}function sc(e){for(let t=e.length-1;t>=0;t-=1){const r=e[t],n=typeof(r==null?void 0:r.role)=="string"?r.role:"",a=typeof(r==null?void 0:r.kind)=="string"?r.kind:"";if(n==="system"||a==="system"||a==="tool"||a==="thought"||a==="terminal"||a==="activity"||$i(e[t]))continue;if(n!=="assistant")return"";const o=e[t];return`${String(o.bubbleId??o.providerUnitKey??o.id??"")}#${na(o.content).length}`}return""}function Eu(e,t){if(tc(t)!=="assistant")return!1;const r=Array.isArray(e.liveMessages)?e.liveMessages:[];return tc(r)!=="assistant"}function Vg(e){return!!e&&typeof e=="object"&&e.selected==="native-history"}function qg(e,t,r){return Vg(r)?Eu(e,t):!1}function Bu(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="generating"||t==="no_progress"||t==="long_generating"||t==="streaming"||t==="working"||t==="starting"}function Fu(e){const t=typeof e=="string"?e.trim().toLowerCase():"";return Du.has(t)}function Ou(e,t){return Math.max(Math.max(0,t),Array.isArray(e.liveMessages)?e.liveMessages.length:0)}function Yg(e,t,r,n,a,o){const i=Fu(n)||Bu(n),c=o&&e.hasLiveSnapshot;if(!i&&!c)return!1;const d=i?Ou(e,t):Array.isArray(e.liveMessages)?e.liveMessages.length:0;if(d<=0)return!1;if(Gg(r))return!0;if(c&&!i&&Eu(e,r))return!1;if(a&&typeof a=="object"){const p=a.selected,u=a.fallbackReason;if(p==="native-history"||typeof u=="string"&&u!==""&&!u.startsWith("native_history_"))return!1}return r.length<d}function Jg(e,t,r,n){if(r.length!==0||Ou(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 Xg(e,t,r,n,a,o){return Yg(e,t,r,n,a,o)?"defer-busy-shrink":Jg(e,t,r,a)?"skip-transient-empty":"apply"}function Qg(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}function rc(e,t){const r=e[t];return typeof r=="string"?r:""}class Zg{constructor(t){et(this,"manager");et(this,"sendData");et(this,"daemonId");et(this,"sessionId");et(this,"historySessionId");et(this,"subscriptionKey");et(this,"fallbackRecentCount");et(this,"snapshot");et(this,"transportSubscription",null);et(this,"listeners",new Set);et(this,"retainCount",0);et(this,"loadHistoryPromise",null);et(this,"pendingDisconnectTimer",null);et(this,"authoritativeRefreshPromise",null);et(this,"lastAuthoritativeRefreshAt",0);et(this,"now");et(this,"lastActiveStatusAt",0);this.manager=t.manager||rs,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.now=t.now??(()=>Date.now()),this.snapshot=ra(Math.max(0,t.tailLimit??un))}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.now&&(this.now=t.now),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={...ra(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>Ql?d.slice(d.length-Ql):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}refreshAuthoritativeTail(t,r={}){if(this.authoritativeRefreshPromise)return this.authoritativeRefreshPromise;const n=this.now();if(!r.force&&this.lastAuthoritativeRefreshAt>0&&n-this.lastAuthoritativeRefreshAt<Wg)return Promise.resolve();this.lastAuthoritativeRefreshAt=n;const a=(async()=>{try{const o=await t();o&&this.handleUpdate(o)}catch{}})().finally(()=>{this.authoritativeRefreshPromise=null});return this.authoritativeRefreshPromise=a,a}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:Hg}))}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=rc(t,"sessionId");if(r&&r!==this.sessionId)return;const n=rc(t,"historySessionId");if(n&&this.historySessionId&&n!==this.historySessionId)return;const a=Qg(t),o=t.messageSource,i=this.now(),c=this.lastActiveStatusAt>0&&i-this.lastActiveStatusAt<=Ma;(Fu(t.status)||Bu(t.status))&&(this.lastActiveStatusAt=i);const d=qg(this.snapshot,a,o);if(!d&&Xg(this.snapshot,this.fallbackRecentCount,a,t.status,o,c)!=="apply")return;const p={tailLimit:this.snapshot.cursor.tailLimit};!d&&ec(this.snapshot.liveMessages)===ec(a)&&sc(this.snapshot.liveMessages)===sc(a)&&this.snapshot.cursor.tailLimit===p.tailLimit||(this.snapshot={...this.snapshot,liveMessages:a,hasLiveSnapshot:!0,cursor:p,messageSource:o},this.emit())}}function Hu(e){const t=pn(e.daemonId,e.sessionId,e.historySessionId),r=rn.get(t);if(r)return r.updateOptions(e),r;const n=new Zg(e);return rn.set(t,n),Kg(),n}function ey(e,t,r){if(!e||!t)return;const n=`${e}::${t}::`,a=pn(e,t,r);for(const[o,i]of rn.entries())(o===a||o.startsWith(n))&&i.clearLiveSnapshot()}function Wu(e){const t=Qs(e),r=e.sessionId||"";if(!t||!r)return;const n=Sa(e),a=pn(t,r,n||r),o=rn.get(a);if(!o)return;const i=o.getSnapshot();return i.hasLiveSnapshot?i:void 0}function ty(e,t){return{...e,loadHistoryPage:t}}function sy(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||(e.historySessionId||"").localeCompare(t.historySessionId||"")}function ry(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Du.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??Ma)),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 ny(e=Ma){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function ay(e,t={}){const r=new Set,n=[];for(const a of e){if(!ry(a,t))continue;const o=Qs(a),i=a.sessionId||"";if(!o||!i)continue;const c=Sa(a),d=pn(o,i,c||i);r.has(d)||(r.add(d),n.push({daemonId:o,sessionId:i,historySessionId:c,subscriptionKey:`daemon:${o}:session:${i}`}))}return n.sort(sy),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function oy(e,t){const{sendData:r,sendCommand:n,isConnected:a}=xt(),o=(t==null?void 0:t.enabled)!==!1,i=Qs(e),c=e.sessionId||"",d=Sa(e),p=`daemon:${i}:session:${c}`,u=Math.max(0,(t==null?void 0:t.tailLimit)??un),m=e.messages.length,h=l.useMemo(()=>!o||!i||!c?null:Hu({daemonId:i,sessionId:c,historySessionId:d,subscriptionKey:p,sendData:r,tailLimit:u,fallbackRecentCount:m}),[i,o,d,r,c,p,u]);l.useEffect(()=>{h==null||h.updateOptions({fallbackRecentCount:m})},[h,m]);const[y,x]=l.useState(()=>(h==null?void 0:h.getSnapshot())||ra(u));l.useEffect(()=>{if(!h){x(ra(u));return}h.retain(),x(h.getSnapshot());const k=h.subscribe(b=>{x(b)});return()=>{k(),h.release()}},[h,u]);const f=l.useCallback(async()=>{!h||!i||!c||await h.loadHistoryPage(async({offset:k,excludeRecentCount:b})=>{const j=e.agentType,C=await n(i,"chat_history",{agentType:j,offset:k,limit:30,targetSessionId:c,historySessionId:d,excludeRecentCount:b}),w=C&&typeof C=="object"&&"result"in C?C.result||{}:C||{};return{messages:Array.isArray(w.messages)?w.messages:[],hasMore:w.hasMore===!0}})},[e.agentType,h,i,d,n,c]),v=l.useCallback((k=!1)=>!h||!i||!c?Promise.resolve():h.refreshAuthoritativeTail(async()=>{const b=await n(i,"read_chat",{agentType:e.agentType,targetSessionId:c,historySessionId:d,...u>0?{tailLimit:u}:{}}),j=b&&typeof b=="object"&&"result"in b?b.result:b;if(!j||typeof j!="object"||j.success===!1)return null;const C=Array.isArray(j.messages)?j.messages:Array.isArray(j.messagesTail)?j.messagesTail:[];return{topic:"session.chat_tail",key:p,sessionId:c,historySessionId:d,seq:0,timestamp:0,messages:C,status:typeof j.status=="string"?j.status:"idle",...j.messageSource&&typeof j.messageSource=="object"?{messageSource:j.messageSource}:{}}},{force:k}),[e.agentType,h,i,d,n,c,p,u]);return l.useEffect(()=>{if(!h||!o||!i||!c)return;v(!0);const k=()=>{typeof document<"u"&&document.visibilityState==="visible"&&v()};typeof document<"u"&&document.addEventListener("visibilitychange",k);let b=a?a(i):!0;const j=setInterval(()=>{if(!a)return;const C=a(i);C&&!b&&v(),b=C},2e3);return()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",k),clearInterval(j)}},[h,i,o,c,d]),l.useMemo(()=>ty(y,f),[f,y])}function iy(e,t){const{sendData:r}=xt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??un),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Ma)),i=ny(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(()=>ay(e,{recentActivityMs:o}),[e,o,c]);l.useEffect(()=>{if(!n||!r||p.descriptors.length===0)return;const u=p.descriptors.map(m=>Hu({...m,sendData:r,tailLimit:a}));return u.forEach(m=>{m.retain()}),()=>{u.forEach(m=>m.release())}},[p.signature,n,r,a])}function ly(e){const[t,r]=l.useState(0),n=l.useMemo(()=>{const i=[];for(const c of e){const d=Qs(c),p=c.sessionId||"";if(!d||!p)continue;const u=Sa(c);i.push(pn(d,p,u||p))}return i},[e]),a=n.join("|"),o=l.useSyncExternalStore(Ug,Zl,Zl);return l.useEffect(()=>{if(n.length===0)return;const i=[];for(const c of n){const d=rn.get(c);if(!d)continue;let p=!1;i.push(d.subscribe(()=>{if(!p){p=!0;return}r(u=>u+1)}))}return()=>{for(const c of i)c()}},[a,o]),t}function cy(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function dy(e){return cy(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Hn=new Map,Xo=new Set;function nc(e,t){!e||Hn.get(e)===t||(t?Hn.set(e,!0):Hn.delete(e),Xo.forEach(n=>n(e,t)))}function uy(e){return e?Hn.get(e)===!0:!1}function py(e){return Xo.add(e),()=>{Xo.delete(e)}}function my(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function hy(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function fy(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Ku(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 xy(e){return Ku(e)?!1:e.inboxBucket==="task_complete"&&Uu(e).length>0}function ac(e){return e.branch||"detached HEAD"}function by(e){if(e.error)return`${ac(e)} · Git error: ${e.error}`;const t=[ac(e)];return e.changedFiles>0?t.push(my(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 gy(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${by(t)}`}function yy(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function vy(e,t={}){if(t.enabled===!1)return[];if(!fy(e))return[];const r=Ku(e)?"working":xy(e)?"complete":null;if(!r)return[];const n=r==="complete"?Uu(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${hy(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:gy(r,e.git),timestamp:yy(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 wy=60;function jy(e){return e.status==="no_progress"||e.status==="long_generating"?"Agent shows no progress.":e.status==="generating"||e.status==="streaming"?"Agent is generating.":e.status==="waiting_approval"&&(!e.modalButtons||e.modalButtons.length===0)?"Agent is waiting for approval. Approval controls will appear when available.":null}function Qo({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 we,he,K,E,J,re,be,ue;const y=l.useRef(new Map),x=l.useRef(void 0),f=Sr(),{sendCommand:v}=xt(),{isVisible:k}=Si();dn("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:d.length,isSendingChat:a});const b=It.useMemo(()=>kr(e),[e.status,e.connectionState]);It.useEffect(()=>{const D=e.sessionId;if(D)return nc(D,b.isGenerating),()=>{nc(D,!1)}},[e.sessionId,b.isGenerating]);const j=l.useMemo(()=>xg(e,t),[e,t]),C=l.useMemo(()=>{var D;return Mi((D=j.targetEntry)==null?void 0:D.providerControls,{hostIdeType:e.hostIdeType,providerType:j.providerType})},[e.hostIdeType,j.providerType,(we=j.targetEntry)==null?void 0:we.providerControls]),w=Pu({isCliLike:j.isCli||j.isAcp}),g=Og({isCliLike:j.isCli||j.isAcp}),S=oy(e,{enabled:h&&!!e.sessionId,tailLimit:g}),[N,I]=l.useState(w),[R,L]=l.useState(()=>Sl()),_=e.tabKey,P=S.historyMessages,B=S.hasMoreHistory,Y=S.historyError,M=ju(e,S),H=Vd(M).length;l.useEffect(()=>{I(w)},[w,_]);const q=Math.max(0,M.length-N),A=Ri(e),$=Qs(e),T=dy(e),F=Pi(e),z=jy(e),U=o||F,te=U||z,Z=!!F,[se,G]=l.useState(!1);l.useEffect(()=>{const D=j.targetEntry;$&&(!D||D.providerControls===void 0||D.controlValues===void 0)&&f($,{minFreshMs:3e4}).catch(()=>{})},[$,j.isAcp,(he=j.targetEntry)==null?void 0:he.providerControls,(K=j.targetEntry)==null?void 0:K.controlValues,f]);const O=l.useCallback(async()=>{if(!se){if(M.length>N){I(D=>Math.min(M.length,D+wy));return}G(!0);try{await S.loadHistoryPage()}finally{G(!1)}}},[S,se,M.length,N]),{allMessages:V,receivedAtMap:pe}=l.useMemo(()=>{const D=lg({historyMessages:P,liveMessages:M,visibleLiveCount:N}),me=vy(e),Se=me.length>0?[...D,...me]:D,oe={};return Se.forEach((Q,ve)=>{const Ne=`${e.tabKey}:${Xn(Q)}`;let Le=wu(Q)||y.current.get(Ne)||0;Le||(Le=Date.now(),y.current.set(Ne,Le)),oe[Xn(Q)]=Le}),{allMessages:Se,receivedAtMap:oe}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,q,P,M,N]),fe=l.useMemo(()=>d.filter(D=>D.routeId===e.tabKey).sort((D,me)=>D.timestamp-me.timestamp),[d,e.tabKey]),de=l.useCallback(async()=>{var ve,Ne;if(!$)return;const D=_u({activeConv:e,visibleMessages:V,actionLogs:d,controls:(ve=j.targetEntry)==null?void 0:ve.providerControls,controlValues:(Ne=j.targetEntry)==null?void 0:Ne.controlValues,visibleBarControlCount:C.length,chatTailState:{liveMessages:S.liveMessages,hasLiveSnapshot:S.hasLiveSnapshot,hasMoreHistory:B,historyError:Y,historyMessages:P},ui:{controlsVisible:k,visibleLiveCount:N,activityVisible:R,activityCount:H,hiddenLiveCount:q,isInputActive:m,isVisible:h}}),me=await v($,"get_chat_debug_bundle",{agentType:j.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:D}),Se=Yr(me),oe=Ru(Se),Q=await Lu(oe);Q==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),ct.showToast(Tu(Se,{locatorCopyStatus:Q}),Q==="failed"?"warning":"success")},[e,d,H,V,k,S.hasLiveSnapshot,S.liveMessages,j.providerType,(E=j.targetEntry)==null?void 0:E.controlValues,(J=j.targetEntry)==null?void 0:J.providerControls,$,B,q,P,m,h,Y,v,R,C.length,N]);l.useEffect(()=>{const D=me=>{me.key===zd&&L(Sl())};return window.addEventListener("storage",D),()=>window.removeEventListener("storage",D)},[]);const ke=l.useCallback(()=>{const D=kg(x.current);x.current=D.state,D.shouldCollect&&de().catch(me=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",me),ct.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[de]),ye=l.useMemo(()=>{if(M.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((b.isGenerating||e.status==="streaming")&&G(!1),e.status==="not_monitored"&&T)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(tn,{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(hr,{size:14})," Open ",A," 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"&&T)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(Od,{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(hr,{size:14})," Open ",A," 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"&&!se)return!B&&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,T,i,B,P.length,c,se,M.length,A,b.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.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx(rg,{sessionId:e.sessionId,daemonId:e.daemonId,muted:!!((re=j.targetEntry)!=null&&re.muted),sendDaemonCommand:v}),s.jsx(tg,{sessionId:e.sessionId,daemonId:e.daemonId,conv:e})]})}),s.jsx(sx,{messages:V,actionLogs:fe,agentName:fr(e)||A||"Agent",userName:p,isCliMode:j.isCli||j.isAcp,isWorking:b.isGenerating,contextKey:e.tabKey,receivedAtMap:pe,lastMessageHash:e.lastMessageHash,showActivityMessages:R,onLoadMore:O,isLoadingMore:se,hasMoreHistory:B,hiddenLiveCount:q,loadError:Y??void 0,emptyState:ye,scrollToBottomRequestNonce:u,isVisible:h}),s.jsx(Ab,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:j.providerType,displayLabel:j.displayLabel,controls:(be=j.targetEntry)==null?void 0:be.providerControls,controlValues:(ue=j.targetEntry)==null?void 0:ue.controlValues,currentStatus:e.status,coordinatorHint:Ia(e),isActive:m,isCliTerminal:j.isCliTerminal}),!j.isCliTerminal&&s.jsx(fu,{contextKey:e.tabKey,panelLabel:A,isSending:a,isBusy:Z,statusMessage:te,inlineStatusMessage:U,onSend:r,onForceSend:n,canForceSend:!!n&&b.isGenerating&&!Z,isActive:m,showControlsToggle:C.length>0,onControlsToggle:ke,messageInput:e.messageInput})]})}let zu=hs;function Gu(){return zu()}class ky{constructor(){et(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 Vu=new ky;class Ny{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 bt=new Ny;function Sy(e){e.dashboardWS&&(Vu=e.dashboardWS),e.connectionManager&&(bt=e.connectionManager),e.useDaemonsHook&&(zu=e.useDaemonsHook)}const Cy=.5,Iy=1.25,Qt="\x1B",oc={ArrowUp:"A",ArrowDown:"B",ArrowLeft:"D",ArrowRight:"C"};function Ay(e){return 1+(e.shift?1:0)+(e.alt?2:0)+(e.ctrl?4:0)}function ic(e,t){let r=e;if(t.shift&&r.length===1&&(r=r.toUpperCase()),t.ctrl){const n=r.toUpperCase().charCodeAt(0);return String.fromCharCode(n&31)}return r}function My(e,t){if(t in oc){const n=oc[t],a=Ay(e);return a===1?`${Qt}[${n}`:`${Qt}[1;${a}${n}`}switch(t){case"Enter":return e.alt?`${Qt}\r`:"\r";case"Escape":return e.alt?`${Qt}${Qt}`:Qt;case"Backspace":{const n=e.ctrl?"\b":"";return e.alt?`${Qt}${n}`:n}case"Tab":{const n=e.shift?`${Qt}[Z`:" ";return e.alt&&!e.shift?`${Qt} `:n}case"Space":{const n=ic(" ",e);return e.alt?`${Qt}${n}`:n}}const r=ic(t,e);return e.alt?`${Qt}${r}`:r}function ft(e){return Ri(e)}function xr(e){return Iu(e).join(" · ")}function qu(e){var t,r;return!!e.daemonId&&!!((t=e.coordinator)!=null&&t.meshId||typeof((r=e.settings)==null?void 0:r.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0)}function _y(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 Ty(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 Yu(e,t){const r=Cu(e,t);return r||(e.title?e.title:xr(e)||"No messages yet")}function Ju(e,t){const{isReconnecting:r,isConnecting:n}=kr(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function Ly(e,t){const r=["Chat",...Iu(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function Ws(e){return Ju(e)||xr(e)}function Ry(e,t){return`${ft(e)} · ${Yu(e,t)}`}function Py(e){const t=ta(e),r=t?Tt(t):fr(e);return`${ft(e)} — ${r||"Agent"}`}function Dy(e){return fr(e)||"CLI"}function Xu(e){return Su(e)}function Qu(e){return e?`Remote · ${ft(e)||e.workspaceName||"Session"}`:"Remote"}const lc=[{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:""}})}],$y=[{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 Ey(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 Ei({cond:e,path:t,sections:r,onChange:n,onRemove:a,onPreview:o,preview:i}){const c=Ey(e),d=i[t],p=u=>{const m=lc.find(h=>h.kind===u);m&&n(m.make(r))};return s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary 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-bg-secondary text-text-primary text-[10px] font-mono rounded border border-border-default px-1 py-0.5",children:lc.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-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/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-status-online bg-status-online/20":"text-text-secondary bg-bg-glass"}`,children:d.result?"match ✓":"no match"}),d==="loading"&&s.jsx("span",{className:"text-[10px] text-text-muted",children:"testing…"}),a&&s.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error 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-bg-secondary text-accent-primary text-[10px] font-mono rounded border border-border-default 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-bg-secondary text-text-primary text-[10px] font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),c==="elapsed"&&s.jsx(Cs,{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(Cs,{label:"stable_ms",value:e.stable_ms,onChange:u=>n({...e,stable_ms:u})}),s.jsx(Cs,{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(Cs,{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-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:!!e.changed,onChange:u=>n({...e,changed:u.target.checked}),className:"accent-[var(--accent-primary)]"}),"changed"]})]}),(c==="all"||c==="any")&&s.jsx(By,{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-border-default",children:s.jsx(Ei,{cond:e.not,path:`${t}.not`,sections:r,onChange:u=>n({not:u}),onPreview:o,preview:i})})]})}function By({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-border-default space-y-1",children:[c.map((p,u)=>s.jsx(Ei,{cond:p,path:`${r}.${e}[${u}]`,sections:n,onChange:m=>d(c.map((h,y)=>y===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-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d([...c,{section:n[0],matches:""}]),children:"+ condition"}),$y.map(p=>s.jsxs("button",{type:"button",className:"text-[10px] text-accent-primary/80 hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:()=>d([...c,JSON.parse(JSON.stringify(p.cond))]),title:"insert verified pattern",children:["+ ",p.label]},p.label))]})]})}function Cs({label:e,value:t,onChange:r}){return s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary 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-bg-secondary text-text-primary rounded border border-border-default px-1 py-0.5 outline-none focus:border-accent"})]})}function Fy({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 y={};for(const[x,f]of Object.entries(e))y[x===m?h:x]=f;r(y)},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-text-secondary text-[10px] uppercase tracking-widest font-semibold",children:"Sections"}),s.jsx("span",{className:"text-text-muted text-[10px]",children:"— how the screen is split; conditions match against these"}),s.jsx("button",{type:"button",className:"ml-auto text-[10px] text-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/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-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:u,children:"+ section"})]}),a&&a!=="loading"&&"error"in a&&s.jsx("div",{className:"text-status-error bg-status-error/15 border border-status-error/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],y=h.anchor!=null?"anchor":"positional",x=v=>{v==="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-border-default/60 rounded bg-surface-secondary p-2 space-y-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{value:m,onChange:v=>c(m,v.target.value.trim()),className:"w-28 bg-bg-secondary text-accent-primary font-mono text-[11px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsxs("div",{className:"inline-flex rounded border border-border-default overflow-hidden text-[10px]",children:[s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${y==="positional"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>x("positional"),children:"positional"}),s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${y==="anchor"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>x("anchor"),children:"anchor"})]}),s.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-sm px-1",onClick:()=>p(m),children:"×"})]}),y==="positional"?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx(Cs,{label:"from_top",value:typeof h.from_top=="number"?h.from_top:0,onChange:v=>d(m,{...h,from_top:v,from_bottom:void 0})}),s.jsx(Cs,{label:"from_bottom",value:typeof h.from_bottom=="number"?h.from_bottom:0,onChange:v=>d(m,{...h,from_bottom:v||void 0})}),s.jsx(cc,{def:h,otherIds:t(m),onChange:v=>d(m,v)})]}):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-text-muted w-16",children:"anchor"}),s.jsx("input",{value:h.anchor??"",onChange:v=>d(m,{...h,anchor:v.target.value}),placeholder:"^regex locating section start",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-primary text-[10px] font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:!!h.anchor_last,onChange:v=>d(m,{...h,anchor_last:v.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"last"]})]}),s.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s.jsx(cc,{def:h,otherIds:t(m),onChange:v=>d(m,v)})}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-[10px] text-text-muted w-16",children:"ctx next"}),s.jsx("input",{value:((f=h.anchor_context)==null?void 0:f.next)??"",onChange:v=>d(m,{...h,anchor_context:{...h.anchor_context,next:v.target.value||void 0}}),placeholder:"optional: line after anchor must match",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-secondary text-[10px] font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]})]}),i[m]&&s.jsxs("div",{className:"border-t border-border-subtle pt-1",children:[s.jsxs("div",{className:"text-[9px] text-text-muted 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-text-secondary whitespace-pre-wrap break-all bg-bg-secondary rounded border border-border-subtle px-2 py-1 max-h-28 overflow-y-auto",children:i[m].text||"(empty)"})]})]},m)})})]})}function cc({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-text-secondary",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-bg-secondary text-accent-primary rounded border border-border-default 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-bg-secondary text-text-primary font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]})}function Oy({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((y,x)=>x===m?{...y,...h}:y)}),u=(m,h)=>d({transitions:e.transitions.map((y,x)=>x===m?{...y,...h}:y)});return s.jsxs("div",{className:"space-y-3",children:[s.jsx(Fy,{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-text-secondary text-[10px] uppercase tracking-widest font-semibold",children:"States"}),s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",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-border-default/60 rounded bg-surface-secondary 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-text-muted uppercase tracking-wide",children:"id (used by transitions)"}),s.jsx("input",{value:m.id,onChange:y=>p(h,{id:y.target.value}),placeholder:"idle",className:"w-32 bg-bg-secondary text-accent-primary font-mono text-[11px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),s.jsxs("label",{className:"flex flex-col gap-0.5 flex-1",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide",children:"label (shown in dashboard)"}),s.jsx("input",{value:m.label,onChange:y=>p(h,{label:y.target.value}),placeholder:"Ready",className:"w-full bg-bg-secondary text-text-primary text-[11px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),s.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1 pb-0.5",onClick:()=>d({states:e.states.filter((y,x)=>x!==h)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-text-secondary 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((y,x)=>({...y,initial:x===h}))}),className:"accent-[var(--accent-primary)]"}),"initial"]}),s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"checkbox",checked:!!m.modal,onChange:y=>p(h,{modal:y.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"modal"]}),s.jsxs("label",{className:"flex items-center gap-1",children:["status",s.jsxs("select",{value:m.status??"",onChange:y=>p(h,{status:y.target.value||void 0}),className:"bg-bg-secondary text-text-primary rounded border border-border-default 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-text-secondary text-[10px] uppercase tracking-widest font-semibold",children:"Transitions"}),s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",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-border-default/60 rounded bg-surface-secondary 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-text-muted",children:"from"}),s.jsx(Hy,{value:m.from,states:i,onChange:y=>u(h,{from:y})}),s.jsx("span",{className:"text-[10px] text-text-muted",children:"→"}),s.jsx("select",{value:m.to,onChange:y=>u(h,{to:y.target.value}),className:"bg-bg-secondary text-status-online font-mono text-[10px] rounded border border-border-default px-1 py-0.5",children:i.map(y=>s.jsx("option",{value:y,children:y},y))}),s.jsx("span",{className:"text-[10px] text-text-muted ml-1",children:"label"}),s.jsx("input",{value:m.label??"",onChange:y=>u(h,{label:y.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-bg-secondary text-text-secondary text-[10px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1",onClick:()=>d({transitions:e.transitions.filter((y,x)=>x!==h)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Cs,{label:"min_hold_ms",value:m.min_hold_ms??0,onChange:y=>u(h,{min_hold_ms:y||void 0})}),s.jsx(Cs,{label:"priority",value:m.priority??0,onChange:y=>u(h,{priority:y||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-text-muted",children:"when"}),!m.when&&s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>u(h,{when:{section:c[0],matches:""}}),children:"+ guard condition"}),m.when&&s.jsx("button",{type:"button",className:"text-[10px] text-text-muted hover:text-status-error",onClick:()=>u(h,{when:void 0}),children:"remove guard"})]}),m.when&&s.jsx(Ei,{cond:m.when,path:`t${h}`,sections:c,onChange:y=>u(h,{when:y}),onPreview:r,preview:n})]})]},h))})]})]})}function Hy({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-accent-primary bg-accent-primary/20 border-accent":"text-text-muted border-border-default hover:border-border-default"}`,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 dc(e){return e<=0?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}const Wy={busy_hold_expired:"text-status-warning bg-status-warning/20 border border-status-warning/40",idle_hold_committed:"text-status-online bg-status-online/20 border border-status-online/40",completion_idle_after:"text-accent-primary bg-accent-primary/20 border border-accent",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-text-secondary bg-bg-glass border border-border-default"},Ky={idle:"text-status-online bg-status-online/20 border border-status-online/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-accent-primary bg-accent-primary/20 border border-accent",signing_in:"text-accent-primary bg-accent-primary/20 border border-accent"};function eo(e){return Ky[e]??"text-text-primary bg-bg-glass border border-border-default"}function kn({children:e}){return s.jsx("div",{className:"text-text-secondary text-[10px] uppercase tracking-widest font-semibold mb-1.5 mt-0.5",children:e})}function Nn(){return s.jsx("div",{className:"border-t border-white/8 my-2"})}function Zu({node:e,depth:t=0}){var a;const r=e.result?"text-status-online":"text-text-muted",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-text-secondary",children:e.kind}),s.jsxs("span",{className:"text-text-muted",children:[" ",e.detail]}),e.remainingMs!=null&&e.remainingMs>0&&s.jsxs("span",{className:"text-status-warning",children:[" (",e.remainingMs,"ms left)"]}),(a=e.children)==null?void 0:a.map((o,i)=>s.jsx(Zu,{node:o,depth:t+1},i))]})}function Uy({t:e}){const[t,r]=l.useState(!1),n=e.fires?"text-status-online bg-status-online/20 border-status-online/40":e.holdSatisfied?"text-text-secondary bg-bg-glass border-border-default":"text-status-warning bg-status-warning/20 border-status-warning/40";return s.jsxs("div",{className:"border border-border-default rounded bg-surface-secondary overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-1 hover:bg-bg-glass-hover text-left",onClick:()=>r(a=>!a),children:[s.jsx("span",{className:"text-[10px] text-text-muted 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-text-secondary 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-status-online text-[10px] font-mono",children:"FIRES"}),!e.holdSatisfied&&s.jsxs("span",{className:"text-status-warning text-[10px] font-mono",children:["hold ",e.holdRemainingMs,"ms"]}),s.jsx("span",{className:`text-[10px] font-mono ${e.condResult?"text-status-online":"text-text-muted"}`,children:e.condResult?"cond✓":"cond✗"})]})]}),t&&e.cond&&s.jsx("div",{className:"px-3 pb-1.5 pt-0.5 bg-bg-secondary border-t border-border-default",children:s.jsx(Zu,{node:e.cond})})]})}function zy({activeConv:e,onClose:t}){var de,ke,ye,we,he;const{sendCommand:r}=xt(),[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"])),[y,x]=l.useState("Snapshot"),[f,v]=l.useState(!1),[k,b]=l.useState(null),[j,C]=l.useState(!1),[w,g]=l.useState(""),[S,N]=l.useState(!1),[I,R]=l.useState("idle"),[L,_]=l.useState(null),[P,B]=l.useState([]),[Y,M]=l.useState({}),[H,q]=l.useState(null),[A,$]=l.useState(!1),T=e.daemonId||((de=e.routeId)==null?void 0:de.split(":")[0])||e.routeId||"",F=e.sessionId||"",z=l.useCallback(async()=>{a(!0),d(null);try{const K=await r(T,"get_spec_debug",{targetSessionId:F}),E=K&&typeof K=="object"?K:{},J=E.result&&typeof E.result=="object"?E.result:E;J!=null&&J.success?i(J):(d((J==null?void 0:J.error)||"Failed to load spec debug"),i(null))}catch(K){d((K==null?void 0:K.message)||String(K)),i(null)}finally{a(!1)}},[r,T,F]);l.useEffect(()=>{z()},[z]),l.useEffect(()=>{if(!A)return;const K=setInterval(()=>{z()},1e3);return()=>clearInterval(K)},[A,z]),l.useEffect(()=>{const K=E=>{E.key==="Escape"&&!f&&t()};return window.addEventListener("keydown",K),()=>window.removeEventListener("keydown",K)},[t,f]);const U=l.useCallback(async K=>{try{const E=await r(T,"validate_spec",{content:JSON.stringify(K)}),J=E&&typeof E=="object"?E:{},re=J.result&&typeof J.result=="object"?J.result:J;B(re!=null&&re.valid?[]:(re==null?void 0:re.errors)??["validation failed"])}catch(E){B([(E==null?void 0:E.message)||String(E)])}},[r,T]),te=l.useCallback(async()=>{_(null),R("idle"),M({});try{const K=await r(T,"get_spec_source",{targetSessionId:F}),E=K&&typeof K=="object"?K:{},J=E.result&&typeof E.result=="object"?E.result:E;if(!(J!=null&&J.success)||typeof J.content!="string"){_((J==null?void 0:J.error)||"Failed to load spec source");return}g(J.content);let re=null;try{re=JSON.parse(J.content)}catch{}re&&re.$schema==="adhdev:cli/spec@4"?(b(re),C(!1),U(re)):(b(null),C(!0)),N(!1),v(!0)}catch(K){_((K==null?void 0:K.message)||String(K))}},[r,T,F,U]),Z=l.useCallback(K=>{b(K),g(JSON.stringify(K,null,2)),N(!0),R("idle"),U(K)},[U]),se=l.useCallback(async(K,E)=>{M(J=>({...J,[K]:"loading"}));try{const J=await r(T,"eval_condition_preview",{targetSessionId:F,condition:E}),re=J&&typeof J=="object"?J:{},be=re.result&&typeof re.result=="object"?re.result:re;!(be!=null&&be.success)||!be.result?M(ue=>({...ue,[K]:{result:!1,detail:be==null?void 0:be.error}})):M(ue=>({...ue,[K]:{result:be.result.result,detail:be.result.detail}}))}catch(J){M(re=>({...re,[K]:{result:!1,detail:J==null?void 0:J.message}}))}},[r,T,F]),G=l.useCallback(async K=>{q("loading");try{const E=await r(T,"resolve_section_preview",{targetSessionId:F,sections:K}),J=E&&typeof E=="object"?E:{},re=J.result&&typeof J.result=="object"?J.result:J;!(re!=null&&re.success)||!Array.isArray(re.sections)?q({error:(re==null?void 0:re.error)||"resolve failed"}):q({sections:re.sections,screenLineCount:re.screenLineCount??0})}catch(E){q({error:(E==null?void 0:E.message)||String(E)})}},[r,T,F]),O=l.useCallback(async()=>{var J,re;const K=(J=o==null?void 0:o.snapshot)==null?void 0:J.specPath;if(!K){_("No spec path on this session");return}if(!j&&P.length>0){_("Fix validation errors before saving");return}const E=!j&&k?JSON.stringify(k,null,2):w;R("saving"),_(null);try{const be=await r(T,"write_spec_source",{specPath:K,content:E}),ue=be&&typeof be=="object"?be:{},D=ue.result&&typeof ue.result=="object"?ue.result:ue;if(!(D!=null&&D.success)){R("error"),_(((re=D==null?void 0:D.validationErrors)==null?void 0:re.join(`
44
- `))||(D==null?void 0:D.error)||"Save failed");return}R("saved"),N(!1),setTimeout(()=>{z()},400),setTimeout(()=>R("idle"),1500)}catch(be){R("error"),_((be==null?void 0:be.message)||String(be))}},[r,T,(ke=o==null?void 0:o.snapshot)==null?void 0:ke.specPath,w,k,j,P,z]),V=o==null?void 0:o.snapshot,pe=async()=>{var D,me,Se;let K=o;K||(await z(),K=o);const E=K==null?void 0:K.snapshot,J=[];if(J.push("# Spec Debug Snapshot"),J.push(`Generated: ${new Date().toISOString()}`),J.push(`Session: ${(K==null?void 0:K.sessionId)??""} (${(K==null?void 0:K.providerType)??""})`),J.push(`Spec: ${(E==null?void 0:E.spec_id)??""} (${(E==null?void 0:E.specPath)??""})`),J.push(`Provider: ${(E==null?void 0:E.name)??""} (${(E==null?void 0:E.cliType)??""})`),J.push(`Working dir: ${(E==null?void 0:E.workingDir)??""}`),J.push(`Spawned: ${E!=null&&E.spawnedAtMs?new Date(E.spawnedAtMs).toISOString():""}`),J.push(""),J.push("## Current State"),J.push(`State: ${((D=E==null?void 0:E.current_state)==null?void 0:D.id)??"none"} (${((me=E==null?void 0:E.current_state)==null?void 0:me.label)??""})`),J.push(`Status: ${(E==null?void 0:E.status)??""}`),J.push(`Idle hold pending: ${(E==null?void 0:E.idleHoldPending)??!1}`),J.push(`Exited: ${(E==null?void 0:E.exited)??!1}`),J.push(`Last busy: ${E!=null&&E.lastBusyAt?Pr(E.lastBusyAt):""}`),J.push(`Cursor: ${(E==null?void 0:E.cursorPosition)!=null?`(${E.cursorPosition.row},${E.cursorPosition.col})`:"n/a"}`),(Se=E==null?void 0:E.completionIdleDebounce)!=null&&Se.active){const oe=E.completionIdleDebounce;J.push(`completion_idle_after: age=${oe.ageMs}ms hold=${oe.holdMs}ms force=${oe.forceAfterMs}ms remaining=${Math.max(0,oe.holdMs-oe.ageMs)}ms`)}if(J.push(""),J.push("## Modal"),E!=null&&E.current_modal){const oe=E.current_modal.buttons.map(Q=>Q.label).join(" / ");J.push(`${E.current_modal.title??""} [${oe}]`)}else J.push("none");J.push(""),J.push("## State History (last 20)");const re=E!=null&&E.stateHistory?[...E.stateHistory].reverse().slice(0,20):[];for(const oe of re){const Q=oe.reason!=null?typeof oe.reason=="string"?oe.reason:JSON.stringify(oe.reason):"",ve=oe.debounceKind!=null?typeof oe.debounceKind=="string"?oe.debounceKind:JSON.stringify(oe.debounceKind):"",Ne=oe.matchedStateId!=null?String(oe.matchedStateId):"",Le=(oe.matchedRules??[]).map(We=>typeof We=="string"?We:JSON.stringify(We)).join(", ");J.push(`- ${oe.stateId} @ ${new Date(oe.at).toISOString()} held ${oe.durationMs}ms | reason: ${Q} | debounce: ${ve} | eval→${Ne} | rules: ${Le}`)}if(J.push(""),J.push("## Sections"),E!=null&&E.sections)for(const[oe,Q]of Object.entries(E.sections)){const ve=Q.split(`
45
- `).slice(0,3).join(`
46
- `);J.push(`${oe}: ${ve}`)}J.push(""),J.push("## Last Assistant Message");const ue=[...(E==null?void 0:E.messages)??(E==null?void 0:E.committedMessages)??[]].reverse().find(oe=>oe.role==="assistant");J.push(ue?ue.content.slice(0,400):""),J.push(""),J.push("## Screen (first 50 lines)"),J.push(E!=null&&E.screen?E.screen.split(`
47
- `).slice(0,50).join(`
48
- `):"");try{await navigator.clipboard.writeText(J.join(`
49
- `)),x("Copied!"),setTimeout(()=>x("Snapshot"),1500)}catch(oe){console.error("[SpecDebugPanel] clipboard write failed",oe)}},fe=K=>{h(E=>{const J=new Set(E);return J.has(K)?J.delete(K):J.add(K),J})};return s.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Spec debug",className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center bg-black/60 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] px-0 sm:items-center sm:p-4",onClick:t,style:{pointerEvents:"auto"},children:s.jsxs("div",{className:"bg-bg-secondary text-text-primary border border-border-default rounded-t-xl sm:rounded-lg shadow-2xl max-w-2xl w-full max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[88vh] flex flex-col",onClick:K=>K.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-border-default 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-text-primary shrink-0",children:"Spec Debug"}),V&&s.jsx("span",{className:"text-[11px] text-text-secondary font-mono bg-surface-secondary px-1.5 py-0.5 rounded truncate",children:V.spec_id})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(V==null?void 0:V.specPath)&&s.jsx("button",{type:"button",className:`text-[11px] transition-colors px-2 py-1 rounded border ${f?"text-accent-primary bg-accent-primary/20 border-accent":"text-text-secondary hover:text-text-primary hover:bg-bg-glass-hover border-transparent hover:border-border-default"}`,onClick:()=>{f?v(!1):te()},disabled:n,children:f?"Close Editor":"Edit Spec"}),s.jsx("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors px-2 py-1 rounded hover:bg-bg-glass-hover border border-transparent hover:border-border-default",onClick:()=>{pe()},disabled:n,children:y}),s.jsx("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors px-2 py-1 rounded hover:bg-bg-glass-hover border border-transparent hover:border-border-default",onClick:()=>{z()},disabled:n,children:n?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"text-text-secondary hover:text-text-primary transition-colors text-xl leading-none w-7 h-7 flex items-center justify-center rounded hover:bg-bg-glass-hover",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-border-default overflow-hidden text-[10px]",children:[s.jsx("button",{type:"button",className:`px-2 py-0.5 ${j?"text-text-secondary hover:bg-bg-glass-hover":"bg-accent-primary/20 text-accent-primary"}`,onClick:()=>{if(j)try{const K=JSON.parse(w);b(K),U(K)}catch{return}C(!1)},disabled:!k&&j,children:"Form"}),s.jsx("button",{type:"button",className:`px-2 py-0.5 ${j?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>{k&&g(JSON.stringify(k,null,2)),C(!0)},children:"JSON"})]}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate flex-1",title:V==null?void 0:V.specPath,children:((V==null?void 0:V.specPath)??"").split("/").slice(-3).join("/")}),S&&s.jsx("span",{className:"text-status-warning text-[10px]",children:"unsaved"}),!j&&P.length>0&&s.jsxs("span",{className:"text-status-error 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"||!j&&P.length>0?"text-text-muted border-border-default cursor-not-allowed":"text-status-online bg-status-online/20 border-status-online/40 hover:bg-status-online/20"}`,onClick:()=>{O()},disabled:I==="saving"||!j&&P.length>0,children:I==="saving"?"Saving…":I==="saved"?"Saved ✓ (reloading)":"Save & Apply"})]}),L&&s.jsx("pre",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-2 text-[10px] whitespace-pre-wrap shrink-0 max-h-28 overflow-y-auto",children:L}),!j&&P.length>0&&s.jsx("div",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-1.5 text-[10px] shrink-0 max-h-24 overflow-y-auto space-y-0.5",children:P.map((K,E)=>s.jsx("div",{className:"font-mono",children:K},E))}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:j||!k?s.jsx("textarea",{value:w,onChange:K=>{g(K.target.value),N(!0),R("idle")},spellCheck:!1,className:"w-full h-full min-h-[300px] font-mono text-[11px] leading-relaxed bg-bg-secondary text-text-primary border border-border-default rounded p-3 resize-none outline-none focus:border-accent"}):s.jsx(Oy,{model:k,onChange:Z,onPreview:se,preview:Y,onTestSections:G,sectionPreview:H})}),s.jsx("div",{className:"text-[10px] text-text-muted shrink-0",children:j?"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 pb-[calc(12px+env(safe-area-inset-bottom,0px))] space-y-3 text-[12px]",children:[c&&s.jsx("div",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-2",children:c}),n&&!o&&s.jsx("div",{className:"text-text-muted text-center py-6",children:"Loading…"}),o&&!o.isSpecProvider&&s.jsxs("div",{className:"text-text-muted text-center py-6",children:["Not a spec-driven provider (",o.providerType||"unknown",")."]}),V&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-[11px] bg-surface-secondary rounded-md px-3 py-2 border border-border-default",children:[V.name&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Provider"}),s.jsxs("span",{className:"font-mono text-text-primary",children:[V.name," ",s.jsxs("span",{className:"text-text-muted",children:["(",V.cliType,")"]})]})]}),V.workingDir&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Dir"}),s.jsx("span",{className:"font-mono text-text-secondary truncate",title:V.workingDir,children:V.workingDir})]}),V.spawnedAtMs?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Spawned"}),s.jsx("span",{className:"text-text-secondary",children:Pr(V.spawnedAtMs)})]}):null,V.providerSessionId&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Session"}),s.jsx("span",{className:"font-mono text-text-muted text-[10px] truncate",title:V.providerSessionId,children:V.providerSessionId})]})]}),s.jsxs("div",{className:"flex items-center gap-2 flex-wrap bg-surface-secondary rounded-md px-3 py-2 border border-border-default",children:[s.jsx("span",{className:`font-semibold font-mono text-[12px] px-2 py-0.5 rounded ${V.current_state?eo(V.current_state.id):"text-text-muted"}`,children:V.current_state?V.current_state.id:"none"}),((ye=V.current_state)==null?void 0:ye.label)&&V.current_state.label!==V.current_state.id&&s.jsx("span",{className:"text-text-secondary text-[11px]",children:V.current_state.label}),V.status&&V.status!==((we=V.current_state)==null?void 0:we.id)&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["engine: ",s.jsx("span",{className:`font-mono ${eo(V.status)} px-1 py-0.5 rounded text-[10px]`,children:V.status})]}),V.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"}),V.exited&&s.jsx("span",{className:"text-status-error text-[10px] bg-status-error/20 border border-status-error/40 px-1.5 py-0.5 rounded font-mono",children:"exited"}),V.cursorPosition!=null&&s.jsxs("span",{className:"text-text-muted text-[11px] font-mono",children:["cursor: ",s.jsxs("span",{className:"text-text-secondary",children:[V.cursorPosition.row,",",V.cursorPosition.col]})]}),V.lastBusyAt>0&&s.jsxs("span",{className:"text-text-muted text-[11px] ml-auto",children:["last busy: ",s.jsx("span",{className:"text-text-secondary",children:Pr(V.lastBusyAt)})]})]}),((he=V.completionIdleDebounce)==null?void 0:he.active)&&s.jsxs("div",{className:"flex items-center gap-2 text-[11px] bg-accent-primary/20 border border-accent rounded-md px-3 py-1.5 font-mono",children:[s.jsx("span",{className:"text-accent-primary",children:"completion_idle_after"}),s.jsxs("span",{className:"text-text-secondary",children:["age: ",s.jsxs("span",{className:"text-accent-primary",children:[V.completionIdleDebounce.ageMs,"ms"]})]}),s.jsx("span",{className:"text-text-muted",children:"/"}),s.jsxs("span",{className:"text-text-secondary",children:["hold: ",s.jsxs("span",{className:"text-text-secondary",children:[V.completionIdleDebounce.holdMs,"ms"]})]}),s.jsxs("span",{className:"text-text-secondary",children:["force: ",s.jsxs("span",{className:"text-text-secondary",children:[V.completionIdleDebounce.forceAfterMs,"ms"]})]}),s.jsx("span",{className:"text-text-muted ml-auto",children:V.completionIdleDebounce.ageMs<V.completionIdleDebounce.holdMs?s.jsxs("span",{className:"text-status-warning",children:["hold remaining: ",V.completionIdleDebounce.holdMs-V.completionIdleDebounce.ageMs,"ms"]}):V.completionIdleDebounce.ageMs<V.completionIdleDebounce.forceAfterMs?s.jsxs("span",{className:"text-orange-300",children:["force in: ",V.completionIdleDebounce.forceAfterMs-V.completionIdleDebounce.ageMs,"ms"]}):s.jsx("span",{className:"text-status-error",children:"overdue"})})]}),V.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-text-secondary",children:V.current_modal.title||""}),V.current_modal.buttons.length>0&&s.jsxs("span",{className:"text-text-secondary ml-2",children:["[",V.current_modal.buttons.map(K=>K.label).join(" / "),"]"]})]}),V.fsm&&s.jsxs(s.Fragment,{children:[s.jsx(Nn,{}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsxs(kn,{children:["FSM — outgoing from ",s.jsx("span",{className:"text-accent-primary font-mono normal-case",children:V.fsm.currentState})," (held ",dc(V.fsm.stateAgeMs),")"]}),s.jsxs("label",{className:"ml-auto flex items-center gap-1 text-[10px] text-text-muted cursor-pointer select-none mb-1.5",children:[s.jsx("input",{type:"checkbox",checked:A,onChange:K=>$(K.target.checked),className:"accent-[var(--accent-primary)]"}),"live"]})]}),s.jsxs("div",{className:"space-y-1",children:[V.fsm.transitions.length===0&&s.jsx("div",{className:"text-text-muted text-[11px] italic px-1",children:"no outgoing transitions (terminal state)"}),V.fsm.transitions.map((K,E)=>s.jsx(Uy,{t:K},E))]})]})]}),s.jsx(Nn,{}),V.sections&&Object.keys(V.sections).length>0&&s.jsxs("div",{children:[s.jsx(kn,{children:"Sections"}),s.jsx("div",{className:"space-y-1",children:Object.entries(V.sections).map(([K,E])=>{var ue;const J=m.has(K),re=E.split(`
50
- `),be=((ue=re[0])==null?void 0:ue.slice(0,80))||"(empty)";return s.jsxs("div",{className:"border border-border-default rounded overflow-hidden bg-surface-secondary",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2.5 py-1.5 hover:bg-bg-glass-hover transition-colors text-left",onClick:()=>fe(K),children:[s.jsx("span",{className:"text-[10px] text-text-muted w-3",children:J?"▾":"▸"}),s.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-[11px]",children:K}),!J&&s.jsx("span",{className:"text-text-secondary truncate font-mono text-[11px]",children:be}),s.jsxs("span",{className:"ml-auto text-text-muted text-[10px] shrink-0",children:[re.length,"L"]})]}),J&&s.jsx("pre",{className:"px-3 pb-2.5 pt-1 font-mono text-[11px] text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary max-h-40 overflow-y-auto border-t border-border-default",children:E||"(empty)"})]},K)})})]}),s.jsx(Nn,{}),V.stateHistory&&V.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs(kn,{children:["State History (",V.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...V.stateHistory].reverse().slice(0,20).map((K,E)=>s.jsxs("div",{className:"rounded px-2 py-1 hover:bg-bg-glass-hover 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 ${eo(K.stateId)}`,children:K.stateId}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:Pr(K.at)}),K.durationMs>0&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["held ",s.jsx("span",{className:"text-text-secondary",children:dc(K.durationMs)})]}),K.reason&&s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${Wy[String(K.reason)]??"text-text-secondary bg-bg-glass border border-border-default"}`,children:String(K.reason)}),K.debounceKind&&String(K.debounceKind)!=="none"&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["debounce:",String(K.debounceKind)]}),K.matchedStateId&&String(K.matchedStateId)!==K.stateId&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["eval→",s.jsx("span",{className:"text-text-secondary",children:String(K.matchedStateId)})]})]}),K.matchedRules&&K.matchedRules.length>0&&s.jsxs("div",{className:"flex items-start gap-1 flex-wrap mt-0.5 ml-1 pl-1 border-l border-border-default",children:[K.matchedRules.slice(0,3).map((J,re)=>s.jsx("span",{className:"font-mono text-[10px] text-accent-primary bg-accent-primary/20 border border-accent px-1.5 py-0.5 rounded break-all",children:typeof J=="string"?J:JSON.stringify(J)},re)),K.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",K.matchedRules.length-3," more"]})]})]},E))})]}),s.jsx(Nn,{}),(()=>{const K=V.messages??V.committedMessages??[];if(K.length===0)return null;const E=K.filter(be=>be.role==="user").length,J=K.filter(be=>be.role==="assistant").length,re=[...K].reverse().find(be=>be.role==="assistant");return s.jsxs("div",{children:[s.jsxs(kn,{children:["Transcript (",K.length," — ",E,"u / ",J,"a)"]}),re&&s.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-md p-2.5 text-[11px]",children:[s.jsxs("div",{className:"text-text-muted mb-1 text-[10px]",children:["Last assistant ",re.receivedAt?Pr(re.receivedAt):""]}),s.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[re.content.slice(0,400),re.content.length>400?"…":""]})]})]})})(),V.specPath&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:V.specPath,children:V.specPath}),s.jsxs("div",{children:[s.jsxs("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors flex items-center gap-1.5",onClick:()=>u(K=>!K),children:[s.jsx("span",{className:"text-text-muted",children:p?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",V.screen?V.screen.split(`
51
- `).length:0," lines)"]})]}),p&&s.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-[11px] text-text-secondary whitespace-pre bg-bg-secondary rounded-md border border-border-default max-h-64 overflow-auto",children:V.screen||"(empty)"})]})]})]})]})})}function Gy({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var Ue;hs();const{sendPtyInput:d}=xt(),[p,u]=l.useState(!1),m=l.useRef(!1);m.current=p;const[h,y]=l.useState("Runtime terminal unavailable"),[x,f]=l.useState(!1),[v,k]=l.useState(null),[b,j]=l.useState(!1),[C,w]=l.useState(!1),[g,S]=l.useState(1),[N,I]=l.useState(!1),[R,L]=l.useState(!1),[_,P]=l.useState(!1),[B,Y]=l.useState(!1),[M,H]=l.useState(!1),[q,A]=l.useState({width:0,height:0}),[$,T]=l.useState({width:0,height:0}),[F,z]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[U,te]=l.useState(null),Z=l.useRef(null),se=l.useRef(null),G=l.useRef(!1),O=l.useRef(!1),V=l.useRef(i),pe=l.useRef(0),fe=l.useRef(!1),de=l.useRef(""),ke=l.useRef(null),ye=l.useRef(!1),we=l.useRef(!1),he=l.useRef(null),K=l.useRef(null),E=l.useRef(null),J=32*1024,re=()=>{var ae,ce,ge,$e;return((ce=(ae=Z.current)==null?void 0:ae.ownerDocument)==null?void 0:ce.defaultView)||(($e=(ge=se.current)==null?void 0:ge.ownerDocument)==null?void 0:$e.defaultView)||window},be=ae=>{const ce=re();return{ownerWindow:ce,frameId:ce.requestAnimationFrame(ae)}},ue=()=>{const ae=he.current;if(ae){try{ae.ownerWindow.cancelAnimationFrame(ae.frameId)}catch{}he.current=null}},D=()=>{const ae=K.current;if(ae){try{ae.ownerWindow.clearTimeout(ae.timeoutId)}catch{}K.current=null}},me=()=>{const ae=E.current;if(ae){try{ae.ownerWindow.clearTimeout(ae.timeoutId)}catch{}E.current=null}},Se=()=>{i&&he.current===null&&(he.current=be(()=>{Lt()}))},oe=e.tabKey,Q=e.sessionId||"",ve=e.daemonId||((Ue=e.routeId)==null?void 0:Ue.split(":")[0])||e.routeId||"",Ne=Pi(e),Le=p?o||Ne:h,We=Cy,le=Iy,Ee=.05,Be=()=>{const ae=$.width,ce=$.height;if(!Number.isFinite(q.width)||q.width<=0||!Number.isFinite(q.height)||q.height<=0||!Number.isFinite(ae)||ae<=0||!Number.isFinite(ce)||ce<=0)return 1;const ge=q.width/ae,$e=q.height/ce;return Number(Math.min(le,Math.max(We,Math.min(ge,$e))).toFixed(2))},Je=Be(),qe=G.current&&g>Je,je=Number.isFinite($.width)&&$.width>0?Math.max(q.width,Math.round($.width*g)):q.width,at=Number.isFinite($.height)&&$.height>0?Math.max(q.height,Math.round($.height*g)):q.height,Ie=()=>{be(()=>{const ae=se.current;ae&&(ae.scrollLeft=0,ae.scrollTop=ae.scrollHeight-ae.clientHeight)})},ot=()=>{var ae,ce;pe.current=0,fe.current=!1,de.current="",ke.current=null,ye.current=!1,we.current=!1,G.current||(O.current=!1,S(1)),he.current!==null&&ue(),u(!1),y("Runtime terminal unavailable"),me(),D(),k(null),te(null),I(!1),f(!1),j(!1),w(!1),(ce=(ae=r.current)==null?void 0:ae.reset)==null||ce.call(ae)},nt=()=>{var ae,ce;pe.current=0,fe.current=!1,de.current="",ke.current=null,ye.current=!1,we.current=!1,he.current!==null&&ue(),u(!0),y(""),me(),D(),k(null),te(null),I(!1),f(!1),j(!1),w(!1),(ce=(ae=r.current)==null?void 0:ae.reset)==null||ce.call(ae)},Qe=()=>{we.current&&(we.current=!1,be(()=>{var ae,ce;(ce=(ae=r.current)==null?void 0:ae.scrollToTop)==null||ce.call(ae)}))},Lt=()=>{if(he.current=null,!i)return;const ae=de.current;if(!ae)return;const ce=ae.slice(0,J);de.current=ae.slice(ce.length);const ge=r.current;if(!ge){de.current=ce+de.current,Se();return}ge.write(ce,()=>{if(de.current.length>0){Se();return}Qe()})},X=ae=>{ae&&(de.current+=ae,Se())},ee=(ae,ce=0,ge,$e,Fe={})=>{var Ze,rt,Ge,Nt;const Ye=!!Fe.force;!Ye&&ce>0&&pe.current>=ce||!Ye&&ce===0&&fe.current||(pe.current=ce,ce>0&&j(!0),u(!0),y(""),typeof ge=="number"&&typeof $e=="number"&&ge>0&&$e>0&&((rt=(Ze=r.current)==null?void 0:Ze.resize)==null||rt.call(Ze,ge,$e)),de.current="",(Nt=(Ge=r.current)==null?void 0:Ge.reset)==null||Nt.call(Ge),ae?X(ae):Qe())};l.useEffect(()=>{ot()},[Q]),l.useEffect(()=>{var ce;if(!Q)return;const ae=((ce=bt.onRuntimeEvent)==null?void 0:ce.call(bt,Q,ge=>{if(!(!ge||ge.sessionId!==Q)){if(ge.type==="runtime_snapshot"){if(!i){ke.current={text:ge.text||"",seq:ge.seq||0,cols:ge.cols,rows:ge.rows,force:!!ge.force};return}ee(ge.text||"",ge.seq||0,ge.cols,ge.rows,{force:!!ge.force});return}if(ge.type==="session_output"){fe.current=!0,typeof ge.seq=="number"&&(pe.current=Math.max(pe.current,ge.seq),ge.seq>0&&j(!0)),m.current||u(!0),m.current||y(""),typeof ge.data=="string"&&X(ge.data);return}if(ge.type==="session_cleared"){if(!i){ye.current=!0,de.current="",ke.current=null;return}nt();return}if(ge.type==="session_io_error"){const $e=typeof ge.error=="string"&&ge.error?ge.error:typeof ge.reason=="string"&&ge.reason?ge.reason:"unknown error";u(!1),y(`Runtime input failed: ${$e}`);return}}},ve))||(()=>{});return()=>{ae()}},[ve,Q,r,i]);const ne=async(ae={})=>{var ce;if(!ve||!Q)return{success:!1,error:"daemonId and sessionId are required"};ae.preserveStatus||y(ae.loadingMessage||"Loading runtime terminal...");try{const ge=await((ce=bt.requestRuntimeSnapshot)==null?void 0:ce.call(bt,ve,Q,{sinceSeq:ae.sinceSeq,force:ae.force}));return ge&&ge.success===!1?(ae.preserveStatus||(u(!1),y(`Runtime terminal unavailable: ${ge.error}`)),ge):ge||{success:!0}}catch(ge){const $e=(ge==null?void 0:ge.message)||String(ge);return ae.preserveStatus||(u(!1),y(`Runtime terminal unavailable: ${$e}`)),{success:!1,error:$e}}},ie=async ae=>{var Ye,Ze;const ce=((Ye=Z.current)==null?void 0:Ye.ownerDocument)||document,ge=ce.defaultView||window,$e=(Ze=ge.navigator)==null?void 0:Ze.clipboard;if($e!=null&&$e.writeText&&ge.isSecureContext)try{return await $e.writeText(ae),!0}catch{}let Fe=null;try{return Fe=ce.createElement("textarea"),Fe.value=ae,Fe.setAttribute("readonly","true"),Fe.style.position="fixed",Fe.style.left="-9999px",Fe.style.top="0",ce.body.appendChild(Fe),Fe.focus(),Fe.select(),ce.execCommand("copy")}catch{return!1}finally{Fe==null||Fe.remove()}},xe=ae=>{D(),te(ae);const ce=re();K.current={ownerWindow:ce,timeoutId:ce.setTimeout(()=>{K.current=null,te(ge=>ge===ae?null:ge)},2200)}},Ae=ae=>{me(),k(ae);const ce=re();E.current={ownerWindow:ce,timeoutId:ce.setTimeout(()=>{E.current=null,k(ge=>ge===ae?null:ge)},2200)}},De=async()=>{var Fe,Ye,Ze,rt;const ae=((Ye=(Fe=r.current)==null?void 0:Fe.getSelection)==null?void 0:Ye.call(Fe))||"",ce=((rt=(Ze=r.current)==null?void 0:Ze.getVisibleText)==null?void 0:rt.call(Ze))||"",ge=ae.trimEnd()||ce.trimEnd();if(!ge){xe("Nothing to copy");return}if(!await ie(ge)){xe("Copy failed");return}xe(ae.trimEnd()?"Copied selection":"Copied visible terminal")},Ce=ae=>{if(!p||!i)return;((d==null?void 0:d(ve,Q,ae))??!1)||xe("Terminal input failed")},Re=ae=>{Ce(My({ctrl:R,alt:_,shift:B},ae)),L(!1),P(!1),Y(!1)},He=async()=>{if(x)return;f(!0),k("Loading older terminal output..."),we.current=!0;const ae=await ne({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:p});if(f(!1),(ae==null?void 0:ae.success)===!1){we.current=!1,k(`Older terminal output unavailable: ${ae.error}`);return}w(!0),Ae("Older terminal output loaded"),be(()=>{var ce;(ce=r.current)==null||ce.bumpResize()})};l.useEffect(()=>{var ce,ge;if(!Q)return;ve&&((ce=bt.getState)==null?void 0:ce.call(bt,ve))==="connected"&&ne();const ae=(ge=bt.onStateChange)==null?void 0:ge.call(bt,($e,Fe)=>{$e!==ve||Fe!=="connected"||ne()});return()=>{ae==null||ae()}},[ve,Q,r]),l.useEffect(()=>{t&&ot()},[t,oe,r]),l.useEffect(()=>{var $e,Fe;const ae=Z.current,ce=(Fe=($e=ae==null?void 0:ae.ownerDocument)==null?void 0:$e.defaultView)==null?void 0:Fe.ResizeObserver;if(!ae||!ce)return;const ge=new ce(Ye=>{const Ze=Ye[0];if(!Ze)return;const{width:rt,height:Ge}=Ze.contentRect;A(Nt=>{const Xt=Math.round(rt),Ht=Math.round(Ge);return Nt.width===Xt&&Nt.height===Ht?Nt:{width:Xt,height:Ht}})});return ge.observe(ae),()=>ge.disconnect()},[]),l.useEffect(()=>{if(G.current)return;const ae=Be();!Number.isFinite(ae)||ae<=0||S(ce=>O.current?ae<ce-Ee?ae:ce:(O.current=!0,ae))},[$.height,$.width,q.height,q.width]),l.useEffect(()=>{qe&&Ie()},[qe,at,je]),l.useEffect(()=>{var ge;const ae=V.current;if(V.current=i,!i)return;ae||w(!1),ye.current&&(ye.current=!1,nt());const ce=ke.current;ce&&(ke.current=null,ee(ce.text,ce.seq,ce.cols,ce.rows,{force:!!ce.force})),ve&&Q&&((ge=bt.getState)==null?void 0:ge.call(bt,ve))==="connected"&&ne(),de.current&&he.current===null&&Se(),be(()=>{var $e;($e=r.current)==null||$e.bumpResize()})},[ve,i,Q]),l.useEffect(()=>()=>{he.current!==null&&ue(),D(),me()},[]),l.useEffect(()=>{const ae=$e=>{var Ye;const Fe=$e.detail;Fe!=null&&Fe.sessionId&&Fe.sessionId!==Q||p&&((Ye=r.current)==null||Ye.bumpResize())},ce=re(),ge=ce===window?[window]:[window,ce];for(const $e of ge)$e.addEventListener("adhdev:fit-cli-terminal",ae);return()=>{for(const $e of ge)$e.removeEventListener("adhdev:fit-cli-terminal",ae)}},[p,Q,r]);const Oe=p&&b&&!C&&(F.atTop||!F.canScroll)||x||!!v;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:Z,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[Oe&&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:()=>{He()},disabled:!Q||x,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:x?"Loading older...":"Load older terminal output"}),v&&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:v})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[U&&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:U}),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:()=>H(ae=>!ae),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:()=>{De()},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(ae=>!ae),disabled:!p,"aria-label":"Open terminal control keys","aria-expanded":N,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),N&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":"Terminal control keys",className:"absolute right-0 top-10 w-72 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.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",R,L],["Alt",_,P],["Shift",B,Y]].map(([ae,ce,ge])=>s.jsx("button",{type:"button","aria-pressed":ce,className:`h-9 rounded-lg border text-[12px] font-semibold transition-colors ${ce?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>ge($e=>!$e),children:ae},ae))}),s.jsx("div",{className:"grid grid-cols-6 gap-1",children:"abcdefghijklmnopqrstuvwxyz0123456789".split("").map(ae=>s.jsx("button",{type:"button",className:"h-8 rounded-md border border-white/10 bg-white/[0.06] text-[12px] font-semibold uppercase hover:bg-white/[0.12]",onClick:()=>Re(ae),children:ae},ae))}),s.jsx("div",{className:"my-2 h-px bg-white/10"}),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:()=>Re("Escape"),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:()=>Re("Tab"),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:()=>Re("Enter"),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:()=>Re("ArrowUp"),"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:()=>Re("ArrowLeft"),"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:()=>Re("ArrowDown"),"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:()=>Re("ArrowRight"),"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:()=>Ce(""),title:"Send SIGINT (Ctrl-C)",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:()=>Re("Space"),children:"Space"}),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:()=>Re("Backspace"),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:()=>{G.current=!0,S(ae=>{const ce=Math.max(Je,Number((ae-.1).toFixed(2)));return ce>Je&&Ie(),ce})},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:()=>{G.current=!0,S(ae=>{const ce=Math.min(le,Number((ae+.1).toFixed(2)));return ce>Je&&Ie(),ce})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:se,className:qe?"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:je>0?`${je}px`:"100%",height:at>0?`${at}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:$.width>0?`${$.width}px`:"100%",height:$.height>0?`${$.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:g},children:s.jsx(Xd,{ref:r,readOnly:!p||!i,sizingMode:"measured",onViewportMetrics:T,onScrollMetrics:z,onInput:ae=>{!p||(d==null||d(ve,Q,ae))}})})})}),!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(fu,{contextKey:e.tabKey,panelLabel:ft(e),isSending:a,isBusy:!!Ne,statusMessage:Le,inlineStatusMessage:Le,onSend:async ae=>Ne?!1:n(ae),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),M&&s.jsx(zy,{activeConv:e,onClose:()=>H(!1)})]})}const Vy=5e3,qy=12e3;function Yy(e){return e==="disconnected"||e==="reconnecting"}function Jy({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=Vy,reconnectActionDelayMs:o=qy}){const i=Yy(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",y=!!(n&&e!=="auth_failed"&&(!i||p)),x=l.useMemo(()=>!t||e!=="connected"?!1:a<=0||m.current,[a,t,e]),f=e==="auth_failed"?"red":e==="offline"?"orange":"accent",v={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},k={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)"},b={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},j="fixed left-1/2 top-4 z-[var(--z-toast)] flex items-center justify-center pointer-events-none",C={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[h&&s.jsx("div",{className:j,style:C,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:v[f],border:k[f],color:b[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.")]}),y&&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"})]})}),x&&s.jsx("div",{className:j,style:C,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 ep({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(wi,{size:n}):s.jsx(Xs,{size:n})})}const us="New session",tp="A connected machine is ready. Start a new session with any installed provider — CLI, ACP, or IDE.";function Xy(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 Qy(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 Zy(e){switch(e){case"conflict":return"border-status-error/40 bg-status-error/10 text-status-error";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-status-online/40 bg-status-online/10 text-status-online"}}function aa({git:e,className:t="",compact:r=!1}){const n=Xy(e),a=Qy(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 ${Zy(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 e0({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 uc({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function pc({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const i=wa(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 t0({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:y,inboxOpen:x,onInboxOpenChange:f,hiddenOpen:v,onHiddenOpenChange:k,onOpenNewSession:b,onOpenDashboardGuide:j,guideNudgeVisible:C=!1,actionShortcuts:w,notifications:g,notificationUnreadCount:S,onOpenNotification:N,onMarkNotificationRead:I,onMarkNotificationUnread:R,onDeleteNotification:L,onOpenGitDialog:_,onOpenMeshGraph:P}){var K;const{ides:B,p2pStates:Y={}}=hs(),M=!!e&&lt(e)&&!it(e),H=!!e&&it(e),q=!!(e!=null&&e.daemonId)&&!!((K=e==null?void 0:e.coordinator)!=null&&K.meshId),A=c||(e?ku(e)?"terminal":"chat":null),[$,T]=l.useState(!1),[F,z]=l.useState(!1),U=l.useRef(null),te=l.useRef(null),Z=l.useRef(null),se=B.filter(E=>E.type==="adhdev-daemon"),G=e0({wsStatus:t,isConnected:r,daemonCount:se.length,p2pStates:Y}),O=G.subtitle,V=G.tone==="connected"?"#22c55e":G.tone==="limited"?"#eab308":"#ef4444",pe=G.tone==="connected"?"0 0 4px #22c55e80":G.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",fe=l.useMemo(()=>g.filter(E=>!E.readAt),[g]),de=l.useMemo(()=>g.filter(E=>!!E.readAt),[g]),ke=l.useMemo(()=>fe.slice(0,9),[fe]),ye=S;l.useEffect(()=>{if(!x)return;const E=J=>{var re;(re=te.current)!=null&&re.contains(J.target)||f(!1)};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[x,f]),l.useEffect(()=>{if(!v)return;const E=J=>{var re;(re=Z.current)!=null&&re.contains(J.target)||k(!1)};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[v,k]),l.useEffect(()=>{if(!v&&!x)return;const E=J=>{if(!J.altKey)return;const re=J.code.match(/^Digit([1-9])$/);if(!re)return;const be=Number(re[1])-1,ue=v?u[be]:void 0,D=x?ke[be]:void 0;if(!(!ue&&!D)){if(J.preventDefault(),J.stopPropagation(),ue){m==null||m(ue),k(!1);return}D&&(N(D),f(!1))}};return window.addEventListener("keydown",E,!0),()=>window.removeEventListener("keydown",E,!0)},[u,v,x,ke,k,f,N,m]),l.useEffect(()=>{const E=u.length;if(U.current===null){U.current=E;return}E>U.current&&z(!0),U.current=E},[u.length]);const we=()=>z(!1),he=E=>{if(!E)return;const J=n.find(re=>re.tabKey===E);J&&(p==null||p(J))};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(Xs,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?ft(e):"Dashboard"}),s.jsx("span",{title:G.title,"aria-label":G.title,className:"header-title-status-dot",style:{background:V,boxShadow:pe}}),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:V,boxShadow:pe}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[O&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",O]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${us}${w!=null&&w.openNewSession?` (${w.openNewSession})`:""}`,"aria-label":us,children:s.jsx(ji,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[j&&s.jsxs("button",{type:"button",onClick:j,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:"?"}),C&&s.jsx("span",{children:"Guide"})]}),e&&(M||H||!it(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:xr(e)||ft(e),children:ft(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(aa,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(aa,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),q&&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(Yt,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:"Mesh graph"})]}),(M||H)&&i&&s.jsxs(s.Fragment,{children:[M&&d&&A&&s.jsx(ep,{mode:A,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:H?"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(wt,{size:14})})]}),!it(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(yi,{size:14})}),!M&&!it(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(os,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:te,children:[s.jsxs("div",{className:`dashboard-header-hidden${$?" is-drop-target":""}${F?" hidden-spawn-flash":""}`,onAnimationEnd:we,ref:Z,onDragEnter:E=>{E.dataTransfer.types.includes("text/tab-key")&&(E.preventDefault(),T(!0))},onDragOver:E=>{E.dataTransfer.types.includes("text/tab-key")&&(E.preventDefault(),E.dataTransfer.dropEffect="move",T(!0))},onDragLeave:E=>{E.currentTarget.contains(E.relatedTarget)||T(!1)},onDrop:E=>{const J=E.dataTransfer.getData("text/tab-key");E.preventDefault(),T(!1),he(J)},children:[s.jsxs("button",{type:"button",onClick:()=>k(!v),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(vi,{size:16}),u.length>0&&s.jsx("span",{className:`dashboard-header-hidden-badge${F?" hidden-badge-pop":""}`,children:u.length})]}),v&&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(uc,{value:w==null?void 0:w.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[y&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:y,children:"Reset panels"}),u.length>0&&h&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{h(),k(!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(uc,{value:w==null?void 0:w.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:ft(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(E=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(E),k(!1)},children:[s.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[E.status==="generating"&&s.jsx("span",{className:"tab-spinner dashboard-header-inbox-item-spinner","aria-label":"generating"}),ft(E)]}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(E)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(E)+1]}):null,xr(E)]})]},E.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>f(!x),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(jr,{size:16}),ye>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ye})]}),x&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[fe.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),fe.map(E=>s.jsx(pc,{notification:E,shortcutIndex:ke.indexOf(E)>=0?ke.indexOf(E)+1:void 0,onOpen:()=>N(E),onMarkRead:()=>I(E.id),onMarkUnread:()=>R(E.id),onDelete:()=>L(E.id)},E.id))]}),de.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),de.map(E=>s.jsx(pc,{notification:E,onOpen:()=>N(E),onMarkRead:()=>I(E.id),onMarkUnread:()=>R(E.id),onDelete:()=>L(E.id)},E.id))]}),g.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function Dt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function s0(e,t){return String(e||"")!==String(t||"")}function r0(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(`
52
- `).includes(r)||n&&!String(i.workspace||"").toLowerCase().includes(n)||a&&!cu(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
53
- `).includes(a)))}function n0(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 sp(e,t={}){return n0(r0(e,t),t.sortMode||"recent")}function oa(e){return e?"Resume saved history":"Start fresh"}function Bi(e){return e?"Resuming saved history…":"Starting fresh…"}function a0(){return"Start fresh"}function o0(e,t=!1){return e==="cli"?oa(t):e==="ide"?"Start IDE":"Start ACP session"}function i0(e,t=!1){return e==="cli"?Bi(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function l0(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function c0(){return"Open saved history"}function d0(){return"Saved History"}function Fi(){return"Use saved history when you want continuity in the same provider conversation."}function u0(){return"No saved history found yet."}function p0(){return"Refresh saved history"}function m0(){return"Refreshing saved history…"}function ia(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function la(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 ca(e){return e==="start-fresh"?"Start fresh":"Restart"}function da(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function rp(e){return`Resume saved history with ${e}?`}function np(){return"Review or change the target workspace before resuming saved history."}function h0(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 ap({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:y,onResumeSavedSession:x}){var L;const f=t.find(_=>_.id===e.routeId),v=(f==null?void 0:f.chats)||[],k=(L=f==null?void 0:f.activeChat)==null?void 0:L.id,b=lt(e)&&!it(e),[j,C]=l.useState(()=>Dt()),w=c||j,g=String(d||"").trim(),S=_=>{if(p){p(_);return}C(_)},N=l.useMemo(()=>a.map(_=>{const P=String(_.workspace||"").trim();return _.canResume||P||!g?_:{..._,workspace:g,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[g,a]),I=l.useMemo(()=>sp(N,{textQuery:w.textQuery,workspaceQuery:w.workspaceQuery,modelQuery:w.modelQuery,resumableOnly:w.resumableOnly,sortMode:w.sortMode}),[N,w.modelQuery,w.resumableOnly,w.sortMode,w.textQuery,w.workspaceQuery]),R=s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] 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:b?d0():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Py(e)}),b&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Fi()})]}),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(wt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!b&&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"}),b?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:_=>S({...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:_=>S({...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:_=>S({...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:_=>S({...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:_=>S({...w,resumableOnly:_.target.checked})}),"Resume-ready only"]})]}),I.map(_=>{const P=e.providerSessionId===_.providerSessionId,B=P||!_.canResume||!!i,Y=_.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{B||!x||x(_)},disabled:B,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"} ${B?"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:h0(_.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",Y?" · selected workspace":"",qs(_.summaryMetadata)?` · ${qs(_.summaryMetadata)}`:"",_.messageCount>0?` · ${_.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:P?"ACTIVE":_.canResume?Y?"RESUME IN SELECTED WORKSPACE":i===_.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},_.id)})]}):v.map(_=>s.jsxs("div",{onClick:()=>{h(e.routeId,_.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${k===_.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 ${k===_.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),"..."]}),k===_.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},_.id)),(b&&!o&&I.length===0||!b&&v.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(Af,{size:32})}),s.jsx("div",{className:"text-[13px]",children:b?a.length>0?"No saved history matches these filters.":u0():"No recent chat sessions found."})]}),b&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:m0()})})]}),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:y,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(va,{size:13})," ",b?p0():"Refresh History"]})})})]})]});return typeof document>"u"?R:ur.createPortal(R,document.body)}const mc={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 op({toasts:e,onDismiss:t,onClickToast:r}){return s.jsx("div",{className:"fixed right-4 z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const a=mc[n.type]||mc.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(wt,{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 f0=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function x0(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function b0(e,t){return ip(e)||t}function ip(e){var a,o,i;const t=(o=(a=e.summaryMetadata)==null?void 0:a.items)==null?void 0:o.find(c=>(c==null?void 0:c.id)==="model"),r=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(r)return r;const n=(i=e.controlValues)==null?void 0:i.model;return typeof n=="string"&&n.trim()?n.trim():""}function g0(e){return ip(e)||void 0}function y0(e){return e.sessionId||e.instanceId||e.agentType}function lp(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Jt(r,{fallbackId:r.id}));return t}function cp(e,t={}){var n;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:Ex(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[r]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Oi(e,t={}){return v0(e,cp(e,t))}function v0(e,t={}){var h,y,x,f,v,k,b,j,C;const r=[],n=t.machineName,a=t.connectionState,o=x0(e),i=e.workspace||"",c=Kx(e.type,{agentName:e.cliName}),d=lt(e)||it(e)?c:Tt(e.type),p=b0(e,d),u=Array.isArray(e.childSessions)?e.childSessions.map(w=>{var g,S,N;return{sessionId:w.id,instanceId:w.id,providerSessionId:w.providerSessionId,activeChatId:(g=w.activeChat)==null?void 0:g.id,transport:w.transport,sessionCapabilities:w.capabilities,agentType:w.providerType,agentName:w.providerName||Tt(w.providerType),model:g0(w),status:w.status,title:w.title,lastMessagePreview:w.lastMessagePreview,lastMessageRole:w.lastMessageRole,lastMessageAt:w.lastMessageAt,lastMessageHash:w.lastMessageHash,messages:((S=w.activeChat)==null?void 0:S.messages)||[],activeModal:((N=w.activeChat)==null?void 0:N.activeModal)||void 0,unread:w.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,inboxBucket:w.inboxBucket,completionMarker:w.completionMarker,surfaceHidden:w.surfaceHidden,muted:w.muted,git:w.git,settings:w.settings,coordinator:w.coordinator,messageInput:w.messageInput}}):[],m=f0(e);if(m){const w=e.sessionId||e.instanceId,g=(h=e.settings)==null?void 0:h.meshCoordinatorFor,S=((y=e.settings)==null?void 0:y.meshNodeFor)||!((x=e.settings)!=null&&x.meshCoordinatorFor)&&((f=e.settings)==null?void 0:f.launchedByCoordinator),N=g?" (Coordinator)":S?" (Mesh Node)":"",I=c+N,R=(v=e.activeChat)==null?void 0:v.activeModal,L=R&&Array.isArray(R.buttons)&&R.buttons.length>0,_=Ux(e.activeChat,[{status:e.status,activeModal:(k=e.activeChat)==null?void 0:k.activeModal}],e.agents||[]),P=e.activeChat||{title:"",messages:[]};let B=P.title&&String(P.title).trim()?String(P.title).trim():"";const Y=(b=e.activeChat)==null?void 0:b.id,M=e.chats;if(Y&&Array.isArray(M)&&M.length>0){const U=M.find(te=>te.id===Y||te.id&&String(te.id)===String(Y));U!=null&&U.title&&String(U.title).trim()&&(B=String(U.title).trim())}const H=(lt(e)||it(e),e.type),q=(lt(e)||it(e))&&El(B,I,H)?"":B,A=P.messages||[],$=typeof Y=="string"?Y.trim():"",T=(lt(e)||it(e))&&$===String(e.type||"").trim(),F=$&&!T?$:e.providerSessionId,z=e.coordinator||(typeof((j=e.settings)==null?void 0:j.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:w,providerSessionId:e.providerSessionId,historySessionId:F,nativeSessionId:w,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:lt(e)&&e.mode||"chat",agentName:I,agentType:H,status:_,title:q,messages:A,resume:e.resume,hostIdeType:!lt(e)&&!it(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||q||(lt(e)?e.mode==="chat"?I:`Terminal${N}`:I),displaySecondary:p,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:L?R.buttons:void 0,modalMessage:L?R.message:void 0,streamSource:"native",tabKey:Ga(w,e.id),machineName:n,connectionState:a,settings:e.settings,coordinator:z,messageInput:e.messageInput})}if(m&&(lt(e)||it(e)))return r;for(const w of u){const g=w.activeModal&&Array.isArray(w.activeModal.buttons)&&w.activeModal.buttons.length>0,S=zx(w),N=y0(w),I=`${e.id}:${N}`,R=w.title&&String(w.title).trim()||"",L=El(R,w.agentName,w.agentType)?"":R,_=w.messages||[];if(!(w.transport==="cdp-webview"||!!w.sessionId||!!w.providerSessionId||_.length>0||g||!!L||!["idle","panel_hidden","disconnected","not_monitored"].includes(S)))continue;const B=w.coordinator||(typeof((C=w.settings)==null?void 0:C.meshCoordinatorFor)=="string"&&w.settings.meshCoordinatorFor?{meshId:w.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:w.sessionId||w.instanceId,providerSessionId:w.providerSessionId,historySessionId:w.activeChatId||w.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:w.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:w.sessionCapabilities,mode:"chat",agentName:w.agentName,agentType:w.agentType,status:S,title:L,messages:_,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:w.git||e.git,displayPrimary:o||L||w.agentName||d,displaySecondary:w.model&&w.model.trim()?w.model.trim():`${d} · ${w.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:w.lastMessagePreview,lastMessageRole:w.lastMessageRole,lastMessageAt:w.lastMessageAt,lastMessageHash:w.lastMessageHash,lastUpdated:w.lastUpdated||e.lastUpdated,inboxBucket:w.inboxBucket,completionMarker:w.completionMarker,modalButtons:g?w.activeModal.buttons:void 0,modalMessage:g?w.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Ga(w.sessionId||w.instanceId,I),machineName:n,connectionState:a,settings:w.settings,coordinator:B,messageInput:w.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:p,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Ga(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function dp(e){return String(e.type||e.id||"").trim()}function ua(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function w0(e,t){const r=(t||"").trim();if(!r)return[];const n=(e||[]).find(a=>a.type===r);return ua(n==null?void 0:n.modelOptions)}function j0(e,t){const r=(t||"").trim();if(!r)return[];const n=(e||[]).find(a=>a.type===r);return ua(n==null?void 0:n.thinkingLevelOptions)}function up(e){const t=new Map;for(const r of e||[])r!=null&&r.type&&t.set(r.type,{models:ua(r.modelOptions),thinking:ua(r.thinkingLevelOptions)});return t}function k0(e){var t;return e.category!=="cli"||!dp(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 br(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!k0(a))continue;const o=dp(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,...Array.isArray(a.modelOptions)&&a.modelOptions.length?{modelOptions:a.modelOptions}:{},...Array.isArray(a.thinkingLevelOptions)&&a.thinkingLevelOptions.length?{thinkingLevelOptions:a.thinkingLevelOptions}:{}})}return r}function gr(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 nn(e){return e.map(t=>t.type)}function N0(e,t){const r=gr(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function S0(e,t){return gr(e).filter(r=>r!==t)}function hc(e,t,r){const n=gr(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 fc({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 C0({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(()=>gr(e),[e]),p=d.filter(h=>!c.has(h)).length,u=t.filter(h=>!d.includes(h.type)),m=()=>{o&&(r(N0(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,y)=>{const x=c.get(h),f=!!x;return s.jsxs("div",{className:`flex flex-col gap-2 rounded-md border border-border-subtle px-3 py-2 sm:flex-row sm:items-center sm:justify-between ${f?"bg-bg-primary":"bg-bg-primary/40"}`,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:["#",y+1]}),(x==null?void 0:x.icon)&&s.jsx("span",{"aria-hidden":"true",children:x.icon}),s.jsx("span",{className:`font-mono text-[12px] ${f?"text-text-primary":"text-text-muted"}`,children:h}),f?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("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-[9px] font-semibold text-amber-400",children:"not on this machine"})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:x?`${x.label} · ${x.statusLabel}`:"Kept in order; skipped at launch until detected here."})]}),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||y===0,title:"Move up",onClick:()=>r(hc(d,h,"up")),children:s.jsx(fc,{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||y===d.length-1,title:"Move down",onClick:()=>r(hc(d,h,"down")),children:s.jsx(fc,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(S0(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:["Launches use this order, top to bottom.",p>0?` ${p} provider${p===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function I0(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 pp(e,t){const r=I0(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const mp=[{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:"🏄"}],hp=[{id:"antigravity-cli",name:"Antigravity CLI",icon:"🪐"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"hermes-cli",name:"Hermes",icon:"⚕️"},{id:"kimi",name:"Kimi",icon:"🌙"},{id:"opencode",name:"OpenCode CLI",icon:"◆"}],fp=[{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:"🟠"}],A0=mp,M0=hp,_0=fp;function T0({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:$t("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 mn({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(T0,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:$t("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const Zo="adhdev:themechange";function L0(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ar(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function or(e){return e==="system"?L0():e}function xp(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Wn(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Zo,{detail:{preference:e,theme:t}}))}function R0(){const e=ar(),t=or(e);xp(t),Wn(e,t)}function Ts(){const[e,t]=l.useState(ar),[r,n]=l.useState(()=>or(ar()));l.useEffect(()=>{xp(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),Wn("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:ar()),n(m==="dark"||m==="light"?m:or(ar()))},c=d=>{if(d.key!=="theme")return;const p=ar(),u=or(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=or(i);t(i),n(c);try{localStorage.setItem("theme",i)}catch{}Wn(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=or(c);n(d);try{localStorage.setItem("theme",c)}catch{}return Wn(c,d),c})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const xc={dark:"Dark",light:"Light",system:"System"};function P0({collapsed:e}){const{preference:t,cycleTheme:r}=Ts(),n=t==="dark"?s.jsx(_f,{size:16}):t==="light"?s.jsx(Mf,{size:16}):s.jsx(Tf,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${xc[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:xc[t]})]})}function to(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}}),y=()=>u(!0),x=()=>u(!1),f=()=>{h(j=>{const C=!j;try{localStorage.setItem(d,C?"1":"0")}catch{}return C})},v=l.useMemo(()=>({collapsed:m,mobileMenuOpen:p,openMobileMenu:y,closeMobileMenu:x,toggleCollapsed:f}),[m,p]),k=j=>`nav-item${j.active?" active":""} cursor-pointer ${m?"justify-center py-2.5 px-0":""}${j.className?` ${j.className}`:""}`,b=j=>s.jsxs("div",{className:k(j),id:`nav-${j.id}`,onClick:()=>{j.onSelect(),x()},title:m?j.title??(typeof j.label=="string"?j.label:void 0):j.title,children:[s.jsx("span",{className:"nav-icon",children:j.icon}),!m&&j.label]},j.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:y,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:x,onKeyDown:j=>j.key==="Escape"&&x()}),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:to(t,v)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:x,children:s.jsx(wt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(b)}),n.map(j=>s.jsxs("div",{className:j.className??"border-t border-border-subtle pt-2 mt-2",children:[!m&&j.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:j.title}):null,j.items.map(b)]},j.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(b),to(o,v),s.jsx(P0,{collapsed:m}),to(i,v)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function mt({title:e,icon:t,description:r,accentColor:n,className:a,collapsible:o,defaultOpen:i=!0,badge:c,children:d}){const[p,u]=l.useState(i),m=o?p:!0,h=(e||r)&&s.jsxs("div",{className:$t("flex items-start justify-between gap-3",m&&"mb-4"),children:[s.jsxs("div",{className:"min-w-0",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary flex items-center gap-1.5",children:[t&&s.jsx("span",{children:t}),s.jsx("span",{children:e}),c]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),o&&s.jsx("span",{className:$t("mt-0.5 shrink-0 text-text-muted transition-transform select-none",m?"rotate-90":"rotate-0"),"aria-hidden":!0,children:"▸"})]});return s.jsxs("div",{className:$t("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:[o&&h?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>u(y=>!y),"aria-expanded":m,children:h}):h,m&&d]})}function _a({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:$t("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 $0={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"},E0={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ft({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:$t("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",$0[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:E0[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 yt({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:$t("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 ss(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:$t("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 B0={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},gs=l.forwardRef(function({variant:t="secondary",size:r="md",type:n,className:a,...o},i){return s.jsx("button",{ref:i,type:n??"button",className:$t("btn",B0[t],r==="sm"&&"btn-sm",a),...o})}),F0=l.forwardRef(function({options:t,children:r,className:n,...a},o){return s.jsx("select",{ref:o,className:$t("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none cursor-pointer","focus:border-accent transition-colors",n),...a,children:r??(t==null?void 0:t.map(i=>s.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})}),O0={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 W0({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:$t("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",O0[e],r),children:[s.jsx("span",{className:$t("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",H0[e])}),n]})}function Es({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 K0({onPrefChange:e}){const[t,r]=tb(),[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(Es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(jr,{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(Es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(os,{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-status-warning",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{pu().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-status-warning",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-status-warning",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(Es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ud,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:i=>o("completionAlert",i)}),s.jsx(Es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Lf,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:i=>o("approvalAlert",i)}),s.jsx(Es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(tn,{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 ei(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const r=t[4]??null;let n=null;if(r){const a=r.match(/(?:^|\.)(\d+)$/);n=a?Number(a[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:n,isPrerelease:r!==null}}function pa(e){var t;return((t=ei(e))==null?void 0:t.base)??null}function U0(e,t){const r=pa(e),n=pa(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 z0(e,t){const r=ei(e),n=ei(t);if(!r||!n)return e!==t;for(let a=0;a<3;a+=1){if(r.base[a]<n.base[a])return!0;if(r.base[a]>n.base[a])return!1}return r.isPrerelease&&n.isPrerelease?r.prereleaseNumber===null||n.prereleaseNumber===null?!1:r.prereleaseNumber<n.prereleaseNumber:!1}function Hi(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:z0(r,t)}function Jr(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||U0(r,t)>=0)return!1;const n=pa(r),a=pa(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 so(e,t){return e instanceof Error?e.message:t}function V0({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(_a,{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(Y0,{ide:i,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},i.id))})}function bc({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:o}){const i=n==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return ur.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:"var(--z-modal)"},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 q0(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...A0,...M0,..._0].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 Y0({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var B,Y;const[o,i]=l.useState("idle"),[c,d]=l.useState(""),[p,u]=l.useState(null),[m,h]=l.useState("idle"),[y,x]=l.useState(""),f=e.version||null,v=((B=e.machine)==null?void 0:B.platform)||((Y=e.system)==null?void 0:Y.platform)||"",k=Jt(e,{fallbackId:e.id}),b=v==="win32"?"🪟":v==="darwin"?"🍎":"🐧",j=t.filter(M=>M.daemonId===e.id&&M.transport==="cdp-page"),C=t.filter(M=>M.daemonId===e.id&&M.transport==="pty"),w=t.filter(M=>M.daemonId===e.id&&M.transport==="acp"),g=e.p2p,S=async()=>{if(r){i("upgrading"),d("Starting upgrade...");try{const M=G0(await r(e.id,"daemon_upgrade",{}));M.alreadyLatest?(i("done"),d(`Already on v${M.version||"latest"}.`)):M.upgraded||M.success?(i("done"),d(`Upgrade to v${M.version||"latest"} started. Daemon is restarting...`)):(i("error"),d(M.error||"Upgrade failed"))}catch(M){i("error"),d(so(M,"Connection lost during upgrade"))}}},N=async()=>{if(u(null),!!n){h("loading");try{await n(e.id),h("done"),x("Machine disconnected.")}catch(M){h("error"),x(so(M,"Failed to disconnect"))}}},I=async()=>{if(u(null),!!a){h("loading");try{await a(e.id),h("done"),x("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(M){h("error"),x(so(M,"Failed to revoke token"))}}},R="0.9.82",L=Hi(e,R),_=Jr(e,R),P=j.length+C.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:b}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:k}),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] ${L?"":"bg-bg-secondary"}`,style:L?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",f,!L&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&L&&s.jsx("button",{onClick:S,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${R}`,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${R}`}`}`}),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(W0,{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:[g&&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 ${g.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${g.state==="connecting"||g.state==="new"?"animate-pulse":""}`,style:g.state==="connecting"||g.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",g.state==="connected"?"connected":g.state==="connecting"||g.state==="new"?"connecting...":g.state||"off"]}),g.peers!==void 0&&g.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",g.peers," peer",g.peers!==1?"s":"",")"]})]}),g&&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:[j.map(M=>{const H=q0(M.type),q=M.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:H.icon}),s.jsx("span",{children:H.name}),q!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${q?"bg-status-online":"animate-pulse"}`,style:q?void 0:{background:"var(--status-warning)"},title:q?"CDP connected":"CDP connecting..."})]},M.id)}),C.map(M=>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:M.cliName||"CLI"})]},M.id)),w.map(M=>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:M.cliName||"ACP"})]},M.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(c||y)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||m==="error"?"text-status-error":o==="done"||m==="done"?"text-status-online":"text-text-muted"}`,children:y||c})]}),p==="disconnect"&&s.jsx(bc,{title:"🔌 Disconnect Machine",message:`Disconnect "${k}" from ADHDev?
54
-
55
- This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
56
-
57
- Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:N,onCancel:()=>u(null)}),p==="revoke"&&s.jsx(bc,{title:"⚠️ Remove Machine",message:`Remove "${k}" from your dashboard?
58
-
59
- This will:
60
- • Immediately disconnect the machine
61
- • Delete the machine registration
62
- • Require restarting ADHDev on that machine
63
-
64
- 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 X0({daemonId:e,knownCliTypes:t=J0}){const{sendCommand:r}=xt(),[n,a]=l.useState({}),[o,i]=l.useState({}),[c,d]=l.useState(!0),[p,u]=l.useState(null),[m,h]=l.useState(null),[y,x]=l.useState(""),f=l.useCallback(async()=>{if(e){d(!0),h(null);try{const b=await r(e,"list_coordinator_prompts",{}),j=b!=null&&b.result&&typeof b.result=="object"?b.result:b;if(!(j!=null&&j.success)){h((j==null?void 0:j.error)||"Failed to load");return}const C=j.entries||{};x(j.dir||"");const w={};for(const g of t)w[g]=C[g]||{override:"",append:""};for(const g of Object.keys(C))w[g]||(w[g]=C[g]);a(w),i(JSON.parse(JSON.stringify(w)))}catch(b){h((b==null?void 0:b.message)||String(b))}finally{d(!1)}}},[r,e,t]);l.useEffect(()=>{f()},[f]);const v=l.useCallback(async(b,j)=>{var C;if(e){u(`${b}:${j}`),h(null);try{const w=((C=n[b])==null?void 0:C[j])||"",g=await r(e,"write_coordinator_prompt",{key:b,kind:j,content:w}),S=g!=null&&g.result&&typeof g.result=="object"?g.result:g;if(!(S!=null&&S.success)){h((S==null?void 0:S.error)||"Save failed");return}i(N=>({...N,[b]:{...N[b]||{override:"",append:""},[j]:w}}))}catch(w){h((w==null?void 0:w.message)||String(w))}finally{u(null)}}},[r,e,n]),k=l.useMemo(()=>(b,j)=>{var C,w;return(((C=n[b])==null?void 0:C[j])||"")!==(((w=o[b])==null?void 0:w[j])||"")},[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:y||"~/.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-status-error bg-status-error/10 border border-status-error/40 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(([b,j])=>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:b}),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:j.override,onChange:C=>a(w=>({...w,[b]:{...w[b],override:C.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:p===`${b}: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 v(b,"override"),disabled:p===`${b}:override`||!k(b,"override"),children:p===`${b}:override`?"Saving…":k(b,"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:j.append,onChange:C=>a(w=>({...w,[b]:{...w[b],append:C.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:p===`${b}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void v(b,"append"),disabled:p===`${b}:append`||!k(b,"append"),children:p===`${b}:append`?"Saving…":k(b,"append")?"Save append":"Saved"})})]},b))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const Q0=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Z0(){const{preference:e,setPreference:t}=Ts();return s.jsx("div",{className:"flex gap-2",children:Q0.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 ev(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 tv(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function ro(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function gc(e){const{r:t,g:r,b:n}=tv(e);return .2126*ro(t)+.7152*ro(r)+.0722*ro(n)}function yc(e,t){const r=gc(e),n=gc(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function bp(e){const t=ev(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return yc(t,r)>=yc(t,n)?r:n}const ti={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},si={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},sv=[{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"}}}],gp="adhdev-chat-theme",yp="adhdev-chat-theme-custom";function Kn(){if(typeof window>"u")return"ember";try{return localStorage.getItem(gp)||"ember"}catch{return"ember"}}function ts(e){try{const t=localStorage.getItem(yp);if(t){const r=JSON.parse(t);return{...e==="dark"?ti:si,...r[e]}}}catch{}return e==="dark"?ti:si}function Sn(e,t){try{localStorage.setItem(yp,JSON.stringify({dark:e,light:t}))}catch{}}function Gt(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 ma(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 rv={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Xr(e,t){var a;const r=(a=rv[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",ma(r,24)),n.style.setProperty("--accent-on-primary",bp(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${ma(r,18)})`),n.style.setProperty("--border-accent",Gt(r,.35)),n.style.setProperty("--nav-active-bg",Gt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Gt(r,.06)}`)}function Ks(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Gt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Gt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Gt(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",Gt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Gt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",ma(e.accentColor,30)),t.style.setProperty("--accent-on-primary",bp(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${ma(e.accentColor,40)})`),t.style.setProperty("--border-accent",Gt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Gt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Gt(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 ${Gt(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 Wi(){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 nv(e){try{localStorage.setItem(gp,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Us()?"dark":"light";Ks(ts(t))}else Wi(),Xr(e,Us()?"dark":"light")}function av(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Kn();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Us()?"dark":"light";Ks(ts(t))}else Wi(),Xr(e,Us()?"dark":"light")}function Us(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Pt({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 Dr({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 ov({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=l.useState(()=>ts(r));l.useEffect(()=>{a(ts(r))},[r]);const o=l.useCallback((i,c)=>{a(d=>{const p={...d,[i]:c},m=ts(r==="dark"?"light":"dark");return r==="dark"?Sn(p,m):Sn(m,p),Ks(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(Dr,{title:"App Background",children:[s.jsx(Pt,{label:"Background",value:n.bgPrimary,onChange:i=>o("bgPrimary",i)}),s.jsx(Pt,{label:"Surface",value:n.bgSecondary,onChange:i=>o("bgSecondary",i)}),s.jsx(Pt,{label:"Card",value:n.surfacePrimary,onChange:i=>o("surfacePrimary",i)})]}),s.jsxs(Dr,{title:"App Text",children:[s.jsx(Pt,{label:"Primary",value:n.textPrimary,onChange:i=>o("textPrimary",i)}),s.jsx(Pt,{label:"Secondary",value:n.textSecondary,onChange:i=>o("textSecondary",i)}),s.jsx(Pt,{label:"Muted",value:n.textMuted,onChange:i=>o("textMuted",i)})]}),s.jsxs(Dr,{title:"Borders & Accent",children:[s.jsx(Pt,{label:"Border subtle",value:n.borderSubtle,onChange:i=>o("borderSubtle",i)}),s.jsx(Pt,{label:"Border default",value:n.borderDefault,onChange:i=>o("borderDefault",i)}),s.jsx(Pt,{label:"Accent",value:n.accentColor,onChange:i=>o("accentColor",i)})]})]}),s.jsxs("div",{children:[s.jsxs(Dr,{title:"Chat Bubbles",children:[s.jsx(Pt,{label:"User bubble",value:n.userBubble,onChange:i=>o("userBubble",i)}),s.jsx(Pt,{label:"User text",value:n.userText,onChange:i=>o("userText",i)}),s.jsx(Pt,{label:"Agent bubble",value:n.assistantBubble,onChange:i=>o("assistantBubble",i)}),s.jsx(Pt,{label:"Agent text",value:n.assistantText,onChange:i=>o("assistantText",i)})]}),s.jsxs(Dr,{title:"Chat Layout",children:[s.jsx(Pt,{label:"Chat BG",value:n.containerBg,onChange:i=>o("containerBg",i)}),s.jsx(Pt,{label:"Send button",value:n.sendButton,onChange:i=>o("sendButton",i)}),s.jsx(Pt,{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?ti:si,d=ts(e?"light":"dark");e?Sn(i,d):Sn(d,i),a(i),Ks(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 iv(){const[e,t]=l.useState(Kn),[r,n]=l.useState(!0),[a,o]=l.useState(()=>ts("dark"));l.useEffect(()=>{n(Us());const d=new MutationObserver(()=>{const m=Us();n(m);const h=Kn();h==="custom"?Ks(ts(m?"dark":"light")):Xr(h,m?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const m=Us();n(m);const h=Kn();h==="custom"?Ks(ts(m?"dark":"light")):Xr(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"?Ks(ts(r?"dark":"light")):(Wi(),Xr(e,r?"dark":"light"))},[e,r]),l.useEffect(()=>{o(ts(r?"dark":"light"))},[r]);const i=d=>{t(d),nv(d)},c=[...sv,{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(ov,{dark:r,onColorsChange:d=>o(d)})]})}const Ki="adhdev_mobileDashboardMode_v1",ri="adhdev:mobile-dashboard-mode-change";function Ui(){try{return localStorage.getItem(Ki)==="workspace"?"workspace":"chat"}catch{return"chat"}}function lv(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Ui())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==Ki||t()};return window.addEventListener(ri,r),window.addEventListener("storage",n),()=>{window.removeEventListener(ri,r),window.removeEventListener("storage",n)}}function cv(e){try{localStorage.setItem(Ki,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ri,{detail:e}))}function dv(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(Ui()==="chat")},[]),s.jsx(Es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xs,{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),cv(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const uv="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",pv="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function mv({themeDescription:e=uv,mobileDescription:t=pv,fontsSlot:r}){return s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(Z0,{})]}),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:e}),s.jsx(iv,{})]}),r,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:t}),s.jsx(dv,{})]})]})}const no=new Map,vc=new Map;function hv(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 fv(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 vp(){const{sendCommand:e}=xt(),{injectEntries:t,getIdes:r}=en();return l.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??Lg,i=vc.get(n)||0;if(!(a!=null&&a.force)&&i>0&&Date.now()-i<o)return;const c=no.get(n);if(c)return c;const d=(async()=>{const p=await e(n,"get_machine_runtime_stats"),u=hv(p);if(!u)return;const m=r().find(y=>y.id===n),h=fv(m,n,u.machine,u.timestamp||Date.now());t([h]),vc.set(n,Date.now())})().finally(()=>{no.delete(n)});return no.set(n,d),d},[r,t,e])}function xv(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 bv(e,t){const{sendData:r}=xt(),{injectEntries:n,getIdes:a}=en(),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=>rs.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(y=>y.id===d),h=xv(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 gv(e,t){const{sendData:r}=xt(),[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=rs.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)},Dg):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 yv(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function wp(e){const{sendData:t}=xt(),[r,n]=l.useState({});return l.useEffect(()=>{const a=yv(e);if(!a||!e.sessionId||!t){n({});return}const o=rs.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}),pr.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}function vv(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function wv(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 jv(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 kv({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(!vv(o))throw new Error(wv(o));return}await jv(e.sessionId,t,a)}function jp(e){const{ides:t,isP2PActive:r,p2pStates:n}=hs(),{sendCommand:a}=xt(),[o,i]=l.useState(null),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useRef(!1),h=l.useMemo(()=>fx(t,e),[t,e]),y=!!h,x=l.useMemo(()=>h?h.prompt.promptId===o?null:h:null,[o,h]),f=l.useCallback(async b=>{if(!x||m.current)return;m.current=!0;const j=Zd(x.prompt,b);d(!0),u(null);try{const C=(n==null?void 0:n[x.daemonId])==="connected"||r===!0;await kv({promptSession:x,response:j,useP2PCommand:C,sendCommand:a}),i(x.prompt.promptId)}catch(C){throw u(C instanceof Error?C.message:String(C)),C}finally{d(!1),m.current=!1}},[r,n,x,a]),v=l.useCallback(()=>{x&&i(x.prompt.promptId)},[x]),k=l.useCallback(()=>{i(null),u(null)},[]);return{promptSession:x,hasActivePrompt:y,responseError:p,isSubmitting:c,submit:f,cancel:v,reopen:k}}function kp(e){return e instanceof Error?e.message:String(e||"")}function Nv(e){const t=kp(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 Sv(e){const t=kp(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Np({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!lt(e)||it(e))return;const o=Nr(e);if(o===t)return;const i=e.sessionId;i&&a(c=>({...c,[i]:t}));try{await n(_s(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:ms(e),mode:t})}catch(c){const d=Sv(c);i&&!d&&a(p=>{const u={...p};return o===Iv(r,i)?delete u[i]:u[i]=o,u}),Nv(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 wc(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 Cv(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=wc(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(d=>wc(d,t)):a.childSessions,c=i!==a.childSessions;return o!==a||c?(r=!0,{...o,...c?{childSessions:i}:{}}):a});return r?n:e}function Iv(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 Av({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n,isConversationMuted:a}){l.useEffect(()=>{pu()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:Xu(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null,target:{providerSessionId:i.providerSessionId,sessionId:i.sessionId,tabKey:i.tabKey,routeId:i.routeId},muted:a?a(i):!1})),[e,a]);return ab(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(d=>{const p=Date.now(),u={};for(const[m,h]of Object.entries(d))p-h<5e3&&(u[m]=h);return Object.keys(u).length===Object.keys(d).length?d:u})},5500);return()=>clearTimeout(c)},[t,r]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(d=>{const p=d.filter(u=>u.timestamp>c).slice(-100);return p.length===d.length?d:p})},6e4);return()=>clearInterval(i)},[n]),null}function jc(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 zs(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=jc(t==null?void 0:t.receivedAt)||jc(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function ni(e,t=0){return zs(e)||e.lastUpdated||t||0}function Sp(e){return zs(e)||e.lastUpdated||0}function Cp(e,t,r=Sp){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 ai(e){var r;const t=qt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function Mv(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!ai(e)&&!e.title.trim()}function _v(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(ai(r))-Number(ai(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:Cp(t,r)})[0]||null}function ns(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=_v(a);return n?o&&Mv(n)?o:n:o||r[0]||null}function Tv(e){const t=e.filter(a=>a.type!=="adhdev-daemon"),r=new Set;for(const a of t){if(!zo(a))continue;const o=ou(a);o&&r.add(o)}const n=new Map;for(const a of t){const o=$x(a,r),i=n.get(o);if(!i){n.set(o,a);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),d=c(i),p=c(a),u=p>d||p===d&&(a.timestamp||0)>(i.timestamp||0)?a:i;n.set(o,Lv(u,u===a?i:a))}return Array.from(n.values())}function Lv(e,t){const r=zo(t),n=zo(e);if(!r&&!n)return e;const a=n?r?void 0:t:e,o=n?e:r?t:void 0,i=a&&String(a.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,d=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...d&&!n&&{settings:{...d,...e.settings??{}}}}}function ao(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 Rv(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 kc(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Rv(mr(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 Pv(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||""),kc(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||""),kc(r.activeChat)].join(":"))].join("|")}function Dv(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 $v(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of Vr({routeId:n.routeId}))r.set(o,a);for(const o of Vr({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Vr({tabKey:n.tabKey}))r.set(o,n)}return r}function Ev(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Bv(e){const t=Ev(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=mr(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Fv({ides:e,connectionStates:t,clearedTabs:r}){const n=l.useMemo(()=>Tv(e),[e]),a=l.useMemo(()=>su(e),[e]),o=l.useMemo(()=>lp(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 C=new Map,w=[];for(const I of n){const{connectionState:R="new",machineName:L}=cp(I,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),_=Pv(I),P=p.current.get(I.id);if(P&&P.ide===I&&P.sourceSignature===_&&P.connectionState===R&&P.machineName===L){C.set(I.id,P),w.push(...P.conversations);continue}const B=Oi(I,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),Y={ide:I,sourceSignature:_,connectionState:R,machineName:L,conversations:B};C.set(I.id,Y),w.push(...B)}p.current=C;const g=new Map,S=I=>{const R=Bv(I),L=u.current.get(I.tabKey);if(L&&L.signature===R)return g.set(I.tabKey,L),L.timestamp;const _={signature:R,timestamp:Sp(I)||(L==null?void 0:L.timestamp)||0};return g.set(I.tabKey,_),_.timestamp},N=[...w].sort((I,R)=>Cp(I,R,S));return u.current=g,N},[n,t,o]),h=l.useMemo(()=>{const C=Dv(m,r);return ao(i.current,C)?i.current:(i.current=C,C)},[m,r]),y=l.useMemo(()=>{const C=new Map,w=Array.from(new Set(h.map(g=>g.routeId)));for(const g of w){const S=ns(h,g);S&&C.set(g,S)}return C},[h]),x=l.useMemo(()=>{const C=new Map;for(const w of h){const g=y.get(w.routeId),S=w.streamSource==="native"&&g?g:w;for(const N of Vr({providerSessionId:w.providerSessionId,sessionId:w.sessionId,tabKey:w.tabKey}))C.set(N,S)}return C},[h,y]),f=l.useMemo(()=>$v(h,y),[h,y]),v=l.useCallback(C=>{if(C)return x.get(C)},[x]),k=l.useCallback(C=>{if(C)return f.get(C)},[f]),b=l.useMemo(()=>{const C=h.filter(w=>!Ms(w,a).surfaceHidden);return ao(c.current,C)?c.current:(c.current=C,C)},[h,a]),j=l.useMemo(()=>{const C=b.map(w=>w.tabKey);return ao(d.current,C)?d.current:(d.current=C,C)},[b]);return{chatIdes:n,conversations:h,visibleConversations:b,visibleTabKeys:j,resolveConversationBySessionId:v,resolveConversationByTarget:k}}function Ov({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 Hv({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){l.useEffect(()=>{ct.setIdes(e)},[e]),l.useEffect(()=>{ct.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=ct.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=Vu.on("status_event",o=>{ct.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",y=String(h).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),x=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(y);t(u,"resolve_action",{action:x?"approve":"reject",button:h,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(v=>console.error("[SW Action] approval failed:",v))};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 Wv="adhdev_dashboardLayout_v1",Kv="adhdev_dashboardDockview_v1",Uv="adhdev_dashboardDockviewHiddenRestore_v1",$r={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function zi(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function zv(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Ip(e){return`${Wv}:${e}`}function Gv(e){const t=Ip(e);return zi(t,null)}function Vv(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=Ip(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Ap(e){return`${Kv}:${e}`}function qv(e){const t=Ap(e);return zi(t,null)}function Yv(e,t){try{const r=Ap(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Mp(e){return`${Uv}:${e}`}function Jv(e){const t=Mp(e);return zi(t,{})}function Xv(e,t){try{const r=Mp(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Qv(){return{groupAssignments:[...$r.groupAssignments],focusedGroup:$r.focusedGroup,groupActiveTabIds:{...$r.groupActiveTabIds},groupTabOrders:{...$r.groupTabOrders},groupSizes:[...$r.groupSizes]}}function Zv(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function ew(){const[e]=l.useState(()=>zv(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),[y,x]=l.useState(!1),f=l.useCallback(()=>{if(y)return;const I=Gv(e)??Qv();r(new Map(I.groupAssignments)),a(I.focusedGroup),i(I.groupActiveTabIds),d(I.groupTabOrders),u(I.groupSizes),x(!0)},[y,e]);l.useEffect(()=>{y&&Vv(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[y,e,t,n,o,c,p]),l.useEffect(()=>{const I=window.matchMedia("(max-width: 767px)"),R=L=>h(L.matches);return I.addEventListener("change",R),()=>I.removeEventListener("change",R)},[]);const v=l.useCallback(I=>{r(I)},[]),k=l.useCallback(I=>{a(I)},[]),b=l.useCallback(I=>{i(I)},[]),j=l.useCallback(I=>{d(I)},[]),C=l.useCallback(I=>{u(I)},[]),w=l.useCallback(I=>{k(I)},[k]),g=l.useCallback((I,R)=>{i(L=>(L[I]??null)===(R??null)?L:{...L,[I]:R})},[]),S=l.useCallback((I,R)=>{d(L=>{const _=L[I];return Zv(_,R)?L:{...L,[I]:R}})},[]),N=l.useCallback((I,R)=>{const L=R.get(I)??0;return g(L,I),w(L),L},[w,g]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:v,focusedGroup:n,updateFocusedGroup:k,focusGroup:w,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:g,groupTabOrders:c,updateGroupTabOrders:j,setGroupTabOrder:S,groupSizes:p,updateGroupSizes:C,isMobile:m,hasHydratedStoredLayout:y,hydrateStoredLayout:f,focusConversationTab:N}}function tw(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=ka(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function sw({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 y=l.useRef(!1),x=l.useRef(!1),f=l.useRef(null),v=l.useRef(!1);l.useEffect(()=>{if(!e||y.current||t.length===0)return;if(!a){o();return}const k=r(e);k&&(i(k.tabKey,n),y.current=!0,x.current=!0,f.current!=null&&(window.clearTimeout(f.current),f.current=null),c(b=>{const j=new URLSearchParams(b);return j.delete("activeTab"),j},{replace:!0}))},[e,t,r,n,a,o,i,c]),l.useEffect(()=>{if(!(x.current||a)&&t.length!==0){if(!e){o(),x.current=!0;return}if(y.current){x.current=!0;return}if(f.current==null)return f.current=window.setTimeout(()=>{f.current=null,!(x.current||a)&&(o(),x.current=!0)},1500),()=>{f.current!=null&&(window.clearTimeout(f.current),f.current=null)}}},[e,t.length,a,o]),l.useEffect(()=>{if(!d){v.current=!1;return}if(!p||v.current||u)return;const k=m.find(b=>b.id===p.routeId);k&&(!k.chats||k.chats.length===0||tw(k.chats,p))&&(v.current=!0,h())},[d,p,u,m,h])}function oo(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=ka(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function _p({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 x=>{try{await e("standalone","launch_ide",{ideType:x,enableCdp:!0})}catch(f){console.error("Launch failed",f)}},[e]),m=l.useCallback(async(x,f)=>{try{const v=x||(t==null?void 0:t.daemonId)||"",k=await e(v,"switch_chat",{id:f,sessionId:f,...Os(t)}),b=k==null?void 0:k.result;if((k==null?void 0:k.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?nr(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?nr(a,`⚠️ Switch error: ${b}`):nr(a,"⚠️ Session switch failed")}catch(v){console.error("Switch failed",v),nr(a,`❌ Switch failed: ${v.message||"connection error"}`)}},[t,e,a]),h=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const x=Hs(t);await e(x,"new_chat",{...Os(t)}),ey(x,t.sessionId,ka(t)[0]),o(f=>({...f,[t.tabKey]:Date.now()}))}catch(x){console.error("New chat failed",x)}finally{c(!1)}}},[t,i,e,o]),y=l.useCallback(async()=>{var x,f;if(!(!t||d)){p(!0);try{const v=Hs(t),k=async()=>e(v,"list_chats",{forceExpand:!0,...Os(t)});let b=await k(),j=(b==null?void 0:b.chats)||((x=b==null?void 0:b.result)==null?void 0:x.chats);oo(j,t)&&(await new Promise(C=>setTimeout(C,450)),b=await k(),j=(b==null?void 0:b.chats)||((f=b==null?void 0:b.result)==null?void 0:f.chats)),b!=null&&b.success&&Array.isArray(j)&&(n(t.routeId,j),oo(j,t)&&!oo(r,t)&&nr(a,"⚠️ History dialog did not fully open — try once more"))}catch(v){console.error("Refresh history failed",v)}finally{p(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:m,handleNewChat:h,handleRefreshHistory:y}}function rw(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 nw(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Nc(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 Cn(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 Sc(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 aw(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 ow(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 Cc(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 Ic(e){return Array(e).fill(100/e)}function iw({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(()=>Cn(e,p),[e,p]),h=m.assignments,y=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),x=y>1,f=l.useCallback((w,g)=>{t(S=>{const N=new Map(Cn(S,p).assignments);return g===0?N.delete(w):N.set(w,g),N}),n(S=>({...S,[g]:w})),r(g)},[t,p,n,r]),v=l.useCallback(w=>{t(g=>{const S=Cn(g,p).assignments,N=new Map;for(const[I,R]of S)R!==w&&(R>w?N.set(I,R-1):N.set(I,R));return N}),i(g=>{if(g.length<=1)return[];const S=[...g];S.splice(w,1);const N=S.reduce((I,R)=>I+R,0);return N>0?S.map(I=>I/N*100):[]}),r(0)},[t,p,i,r]),k=l.useCallback((w,g)=>{g.preventDefault();const S=u.current;if(!S)return;const N=g.clientX,I=S.offsetWidth,R=o.length===y?[...o]:Ic(y),L=P=>{const Y=(P.clientX-N)/I*100,M=[...R];M[w]=Math.max(15,R[w]+Y),M[w+1]=Math.max(15,R[w+1]-Y),i(M)},_=()=>{document.removeEventListener("mousemove",L),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",L),document.addEventListener("mouseup",_)},[o,y,i]),b=l.useCallback((w,g,S)=>{if(y>=4)return;const N=S==="left"?g:g+1;t(I=>{const R=Cn(I,p).assignments,L=new Map;for(const _ of d){const P=R.get(_.tabKey)??0,B=P>=N?P+1:P;B>0&&L.set(_.tabKey,B)}return N>0&&L.set(w,N),L}),i(I=>{const R=I.length===y?[...I]:Ic(y),L=R[g]??100/y,_=Math.max(15,L/2),P=Math.max(15,L/2),B=[...R];B[g]=_,B.splice(N,0,P);const Y=B.reduce((M,H)=>M+H,0);return B.map(M=>M/Y*100)}),n(I=>{const R=Cc(I,N);return R[N]=w,R}),a(I=>{const R=Cc(I,N);return R[N]=[w],R}),r(N)},[y,t,p,d,i,n,a,r]);l.useEffect(()=>{rw(e,h)||t(h)},[e,h,t]),l.useEffect(()=>{const{mapping:w,usedGroups:g}=m;n(S=>{const N=Sc(S,w);return Nc(S,N)?S:N}),a(S=>{const N=Sc(S,w);return Nc(S,N)?S:N}),r(S=>{const N=c?0:aw(S,g,w);return S===N?S:N}),i(S=>{const N=c?[]:ow(S,g,m.groupCount);return nw(S,N)?S:N})},[m,c,n,a,r,i]);const j=l.useMemo(()=>{const w=Array.from({length:y},()=>[]);for(const g of d){const S=h.get(g.tabKey)??0,N=Math.min(S,y-1);w[N].push(g)}return w},[d,h,y]),C=l.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:h,numGroups:y,isSplitMode:x,groupedConvs:j,moveTabToGroup:f,closeGroup:v,handleResizeStart:k,splitTabRelative:b,clearAllSplits:C}}function io(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 lw(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 In(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Gi(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=io(t.channel)||io(e.updateChannel)||io(e.releaseChannel)||void 0,n=lw(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=In(t.targetVersion)||In(e.serverVersion)||void 0,o=In(t.minVersion)||void 0,i=In(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 ir(e,t=null){return Gi(e).targetVersion||t}function Tp(e){return Gi(e).channel||null}function Lp(e){const t=Gi(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 cw({ides:e,sendDaemonCommand:t}){const r="0.9.82",n=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:Hi(m,ir(m,r))).sort((m,h)=>Number(Jr(h,ir(h,r)))-Number(Jr(m,ir(m,r)))),[r,e]),a=l.useMemo(()=>n.some(m=>Jr(m,ir(m,r))),[r,n]),o=l.useMemo(()=>n.map(m=>ir(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 y,x;const h=e.find(f=>f.id===m);if(h){p(f=>({...f,[m]:"upgrading"}));try{const f=await t(m,"daemon_upgrade",Lp(h));(y=f==null?void 0:f.result)!=null&&y.upgraded||(x=f==null?void 0:f.result)!=null&&x.success?p(v=>({...v,[m]:"done"})):p(v=>({...v,[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 Rp=80;function Un(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function dw(e){return{...e,createdAt:Un(e.createdAt),updatedAt:Un(e.updatedAt,e.createdAt),lastEventAt:Un(e.lastEventAt,e.updatedAt||e.createdAt)}}function uw(e){const t=au(e);return t==="unknown:"?e.id:t}function pw(e){return[e.type,nu(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function mw(e,t=Rp){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=uw(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 hw(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||o!=null&&o.muted)continue;const i=ja(a,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=Un(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),p=pw({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(dw({id:p,dedupKey:p,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Su(a),preview:pg(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return mw(n)}function fw(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function xw(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Rp}=e,a=l.useMemo(()=>hw(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=l.useMemo(()=>fw(a),[a]);return{notifications:a,unreadCount:o}}function bw({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}}function Vi(...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 gw(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 qi(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=gw(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 yw(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 vw(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Yi(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=vw(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 Ac(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 Pp(e,t={}){const r=e==null?void 0:e.mcpConfig;if((r==null?void 0:r.mode)!=="manual")return null;const a=Ac(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"}).trim();return!a.includes(`
65
- `)&&!a.startsWith("{")?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:Ac(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function ww(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 an(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Dp(e){return Na(e)||e.tabKey||e.routeId||null}function $p(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=ns(e.conversations,n)||e.conversations.find(i=>i.routeId===n);if(o!=null&&o.tabKey)return o.tabKey}return t||r||n||null}function Ns(e){return String(e||"").trim()}function Ep(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ha(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function jw(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function kw(e,t){const r=Ns(e.providerSessionId),n=Ns(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Ns).filter(Boolean);return!!(r&&i.includes(r)||n&&i.includes(n))});return a?a.tabKey:n||r||null}function Nw(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=Ep(t.daemonId);if(n&&n!==e.machineId)return null;const a=Ns(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=Ns(e.resumeSessionId),i=Ns(e.launchedSessionId),c=Ns(t.providerSessionId),d=Ns(t.targetSessionId);if(o&&o!==c&&o!==d||i&&i!==c&&i!==d)return null;const p=ha(e.workspacePath);if(p){const u=ha(t.workspaceName);if(u&&!jw(u,p))return null}return kw(t,r)}function Mc(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Sw({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=ha(n.workspacePath),p=e.find(m=>{var v,k,b,j;if(!m||m.type==="adhdev-daemon"||Ep(m.daemonId||m.id)!==n.machineId||(sn(m)?"cli":cr(m)?"acp":"ide")!==n.kind)return!1;const x=String(m.agentType||m.type||"");if(n.providerType&&x!==n.providerType)return!1;if(n.resumeSessionId)return String(m.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const C=String(n.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(g=>String(g||"")).filter(Boolean).includes(C)}if(d){const C=ha(m.workspace||m.runtimeWorkspaceLabel);return C?C===d:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((j=(b=(k=(v=m.activeChat)==null?void 0:v.messages)==null?void 0:k.at)==null?void 0:b.call(k,-1))==null?void 0:j.timestamp)||0)>=n.startedAt-5e3});if(!p)return;const u=$p({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});u&&(i(),r(u))},[i,t,e,r,n]),l.useEffect(()=>ct.onStatusEvent(d=>{const p=o.current;if(!p)return;const u=Nw(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 Cw({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const i=_i(),{launchCli:c}=ga(),d=l.useCallback(async(v,k)=>Yi(e,v,k),[e]),p=l.useCallback(async(v,k)=>{if(!k.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(v,"workspace_add",{path:k.trim()});return b!=null&&b.success?{ok:!0}:{ok:!1,error:(b==null?void 0:b.error)||"Could not save workspace"}}catch(b){return{ok:!1,error:b instanceof Error?b.message:"Could not save workspace"}}},[e]),u=l.useCallback(async(v,k,b)=>{var j;try{const C={ideType:k,enableCdp:!0};(j=b==null?void 0:b.workspacePath)!=null&&j.trim()&&(C.workspace=b.workspacePath.trim());const w=await e(v,"launch_ide",C);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:v,kind:"ide",providerType:k,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(C){return{ok:!1,error:C instanceof Error?C.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(v,k,b,j)=>{var w,g,S,N;const C=Date.now();try{const I={cliType:b};(w=j==null?void 0:j.workspacePath)!=null&&w.trim()?I.dir=j.workspacePath.trim():j!=null&&j.workspaceId&&(I.workspaceId=j.workspaceId),(g=j==null?void 0:j.resumeSessionId)!=null&&g.trim()&&(I.resumeSessionId=j.resumeSessionId.trim()),Array.isArray(j==null?void 0:j.cliArgs)&&j.cliArgs.length>0&&(I.cliArgs=j.cliArgs),(S=j==null?void 0:j.initialModel)!=null&&S.trim()&&(I.initialModel=j.initialModel.trim()),(N=j==null?void 0:j.initialThinkingLevel)!=null&&N.trim()&&(I.initialThinkingLevel=j.initialThinkingLevel.trim());const R=await c(v,I),L=(R==null?void 0:R.result)||R,_=(L==null?void 0:L.sessionId)||(L==null?void 0:L.id);return R!=null&&R.success&&_?(t({machineId:v,kind:k,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,launchedSessionId:_,startedAt:C}),{ok:!0}):R!=null&&R.success?(t({machineId:v,kind:k,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:(R==null?void 0:R.error)||(L==null?void 0:L.error)||`Could not launch ${k.toUpperCase()} session`}}catch(I){return Mc(I)?(t({machineId:v,kind:k,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:I instanceof Error?I.message:`Could not launch ${k.toUpperCase()} session`}}},[c,e,t]),h=l.useCallback(async v=>{var k;if(i!=null&&i.listMeshes)return i.listMeshes(v);if(!v)return[];try{const b=await e(v,"list_meshes",{}),j=(b==null?void 0:b.result)??b;if((j==null?void 0:j.success)===!1)throw new Error((j==null?void 0:j.error)||"Could not load meshes");return(Array.isArray(j==null?void 0:j.meshes)?j.meshes:Array.isArray((k=j==null?void 0:j.result)==null?void 0:k.meshes)?j.result.meshes:[]).map(w=>{var g;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(((g=w.nodes[0])==null?void 0:g.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(b){throw console.error("List meshes failed",b),b}},[i,e]),y=l.useCallback(async(v,k,b,j)=>{var w,g;if(!k.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(v,k,b,j);const C=Date.now();try{const S={meshId:k.trim()};b.trim()&&(S.cliType=b.trim());const N=(w=j==null?void 0:j.initialModel)==null?void 0:w.trim(),I=(g=j==null?void 0:j.initialThinkingLevel)==null?void 0:g.trim();N&&(S.initialModel=N),I&&(S.initialThinkingLevel=I);const R=await e(v,"launch_mesh_coordinator",S),L=(R==null?void 0:R.result)??R;if((L==null?void 0:L.success)===!1||(R==null?void 0:R.success)===!1){const P=String((L==null?void 0:L.code)||(R==null?void 0:R.code)||""),B=ww((L==null?void 0:L.meshCoordinatorSetup)||(L==null?void 0:L.manualSetup)||(R==null?void 0:R.meshCoordinatorSetup)||(R==null?void 0:R.manualSetup));return{ok:!1,error:(L==null?void 0:L.error)||(R==null?void 0:R.error)||"Could not launch mesh coordinator",code:P||void 0,manualSetup:B}}const _=(L==null?void 0:L.sessionId)||(L==null?void 0:L.id);return _?r(_):t({machineId:v,kind:"cli",providerType:(L==null?void 0:L.cliType)||b.trim()||void 0,workspacePath:(L==null?void 0:L.workspace)||null,startedAt:C}),{ok:!0}}catch(S){return Mc(S)?(t({machineId:v,kind:"cli",providerType:b.trim()||void 0,startedAt:C}),{ok:!0}):{ok:!1,error:S instanceof Error?S.message:"Could not launch mesh coordinator"}}},[i,r,e,t]),x=l.useCallback(async(v,k)=>{if(!v||!k)return[];try{const b=await e(v,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),j=(b==null?void 0:b.result)??b;return Array.isArray(j==null?void 0:j.sessions)?j.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),f=l.useCallback(async v=>{await Np({conversation:n,mode:v,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:p,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineMeshes:h,handleLaunchMeshCoordinator:y,handleListMachineSavedSessions:x,setActiveCliViewMode:f}}function Iw(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 Aw(e,t,r=Date.now()){return!e||!Iw(t)?null:{tabKey:e,nonce:r}}function Mw({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 v,k;if(!e){if(c){const b=t.find(j=>j.tabKey===c);if(b)return b}return r[0]}const f=n[a];if(f){const b=t.find(j=>j.tabKey===f);if(b)return b}return((v=o[a])==null?void 0:v[0])||((k=o[0])==null?void 0:k[0])},[t,c,a,n,o,e,r]),h=l.useCallback(f=>{d(f)},[]),y=l.useCallback(f=>{d(f.tabKey),i(v=>{const k=new URLSearchParams(v),b=hg(f);return b?k.set("activeTab",b):k.delete("activeTab"),k},{replace:!0})},[i]),x=l.useCallback((f,v)=>{const k=Aw(f,v);k&&u(k)},[]);return{activeConv:m,openDesktopConversation:y,requestScrollToBottom:x,scrollToBottomRequest:p,setDesktopActiveTab:h}}function _w(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 Tw(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 Lw({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=Ms(e,r),m=Tw({tabKey:e.tabKey,historySessionId:Na(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:zs(e),liveState:u}),h=m.autoReadKey,y=_w({autoReadKey:h,shouldMarkSeen:m.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!m.shouldMarkSeen){y.shouldCancelPending&&p(),a.current=h;return}if(!y.shouldSchedule)return;y.shouldCancelPending&&p();const x=()=>{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 v=m.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:v,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=y.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(x,1500);const v=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=v,document.addEventListener("visibilitychange",v);return}const f=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(x,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 lo(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 Rw({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var q;const{launchCli:p}=ga(),[u,m]=l.useState(!1),[h,y]=l.useState([]),[x,f]=l.useState(()=>Dt()),[v,k]=l.useState(!1),[b,j]=l.useState(null),C=l.useRef(null),w=l.useMemo(()=>r||t||e,[e,r,t]),g=!!w&&lt(w)&&!it(w),S=l.useMemo(()=>{if(!w||!g)return null;const A=w.daemonId||w.routeId||"",$=ms(w),T=lo(w);return`${A}:${$}:${w.providerSessionId||""}:${T}`},[w,g]),N=l.useMemo(()=>!w||!g?"":lo(w),[w,g]),{isCreatingChat:I,isRefreshingHistory:R,handleSwitchSession:L,handleNewChat:_,handleRefreshHistory:P}=_p({sendDaemonCommand:a,activeConv:w,chats:(q=n.find(A=>A.id===(w==null?void 0:w.routeId)))==null?void 0:q.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),B=l.useCallback(()=>{m(!0)},[]),Y=l.useCallback(()=>{m(!1)},[]),M=l.useCallback(async()=>{if(!(!w||!g||v)){k(!0);try{const A=w.daemonId||w.routeId,$=ms(w),T=lo(w),F=await a(A,"list_saved_sessions",{agentType:$,providerType:$,kind:"cli",limit:50,...w.providerSessionId?{providerSessionId:w.providerSessionId}:{},...T?{workspace:T}:{}}),z=(F==null?void 0:F.result)??F;y(Array.isArray(z==null?void 0:z.sessions)?z.sessions:[])}catch(A){console.error("Refresh saved sessions failed",A),y([])}finally{k(!1)}}},[w,v,g,a]);l.useEffect(()=>{if(!u){C.current=null;return}if(!g){C.current=null,y([]),k(!1);return}!S||v||C.current!==S&&(C.current=S,M())},[M,u,v,g,S]);const H=l.useCallback(async A=>{if(!w||!g||!A.providerSessionId||!A.workspace)return;const $=w.daemonId||w.routeId,T=ms(w);try{j(A.providerSessionId);const F=await p($,{cliType:T,dir:A.workspace,resumeSessionId:A.providerSessionId,initialModel:du(A.summaryMetadata,"model",{preferShortValue:!0})||void 0}),z=(F==null?void 0:F.result)??F,U=typeof(z==null?void 0:z.sessionId)=="string"?z.sessionId:typeof(z==null?void 0:z.id)=="string"?z.id:"";U&&d(te=>{const Z=new URLSearchParams(te);return Z.set("activeTab",U),Z},{replace:!0}),Y()}catch(F){console.error("Resume saved session failed",F)}finally{j(null)}},[Y,w,g,a,d]);return{historyModalOpen:u,openHistoryModal:B,closeHistoryModal:Y,historyTargetConv:w,isSavedSessionHistoryTarget:g,isHistoryCreatingChat:I,isHistoryRefreshingHistory:R,handleHistorySwitchSession:L,handleHistoryNewChat:_,handleHistoryRefresh:P,savedHistorySessions:h,savedHistoryFilters:x,setSavedHistoryFilters:f,missingWorkspaceResumePath:N,isSavedHistoryLoading:v,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:M,handleResumeSavedHistorySession:H}}function Pw({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 k=c(n);return k&&!lt(k)&&!it(k)?k:null},[e,n,c]),y=l.useMemo(()=>{const k=d==null?void 0:d.routeId;if(!k)return null;const b=d!=null&&d.tabKey?o.find(j=>j.tabKey===d.tabKey):a?o.find(j=>j.tabKey===a):null;return(b==null?void 0:b.routeId)===k?b:ns(o,k)},[o,d,a]),x=l.useMemo(()=>{if(y)return i.find(k=>k.id===y.routeId)},[i,y]);l.useEffect(()=>{h&&(p({routeId:h.routeId,tabKey:zl(h)}),m(h),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,h]);const f=l.useCallback(k=>{k&&(p({routeId:k.routeId,tabKey:zl(k)}),m(k))},[]),v=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:y,remoteDialogIdeEntry:x,remoteDialogActiveConv:u,setRemoteDialogActiveConv:m,openRemoteDialog:f,closeRemoteDialog:v}}function Dw({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:y,openRemoteDialog:x,closeRemoteDialog:f}=Pw({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}),[v,k]=l.useState(!1),[b,j]=l.useState(null),C=l.useCallback(async S=>{const N=S||d;!N||!lt(N)&&!it(N)||(j(N),k(!0))},[d]),w=l.useCallback(()=>{k(!1),j(null)},[]),g=l.useCallback(async S=>{const N=b||d;if(!N||!lt(N)&&!it(N)){w();return}k(!1);try{const I=ms(N),R=N.routeId||N.daemonId||"";await p(R,"stop_cli",{cliType:I,targetSessionId:N.sessionId,mode:S,...Ia(N)})}catch(I){console.error("Stop CLI failed:",I)}finally{j(null)}},[d,w,b,p]);return{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:h,setRemoteDialogActiveConv:y,openRemoteDialog:x,closeRemoteDialog:f,cliStopDialogOpen:v,cliStopTargetConv:b,requestCliStop:C,cancelCliStop:w,confirmCliStop:g}}function co(e,t=!0){return(e??!0)&&t}const Ji=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:y,actionLogs:x,userName:f,scrollToBottomRequestNonce:v,isInputActive:k=!0,isVisible:b=!0}){const j=n,C=!n,w=co(b,j),g=co(b,C),S=co(b),N=wp(t),I=N.status||N.modalMessage||N.modalButtons?{...t,...N.status?{status:N.status}:{},...N.modalMessage!==void 0?{modalMessage:N.modalMessage}:{},...N.modalButtons!==void 0?{modalButtons:N.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(ru,{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(Vs,{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:j?"visible":"hidden",pointerEvents:j?"auto":"none"},children:s.jsx(Gy,{activeConv:I,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,isVisible:w,isInputActive:k&&w})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(Qo,{activeConv:I,ideEntry:a,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:y,actionLogs:x,userName:f,scrollToBottomRequestNonce:v,isInputActive:k&&g,isVisible:g})})]}):s.jsx(Qo,{activeConv:I,ideEntry:a,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:y,actionLogs:x,userName:f,scrollToBottomRequestNonce:v,isInputActive:k&&S,isVisible:S})]})},(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 $w({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var j,C,w;const i=cn(),c=_s(e),d=o?null:Nu(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=fr(e),y=mg(e),x=(j=e.settings)==null?void 0:j.meshNodeFor,f=e.meshQueueStats,v=((C=e.coordinator)==null?void 0:C.meshId)||((w=e.settings)==null?void 0:w.meshCoordinatorFor),k=l.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),b=l.useCallback(()=>{if(r){r();return}const g=Dp(e);g&&i(an(g))},[e,i,r]);return!p&&!u&&!m&&!d&&!x&&!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:b,title:y,children:[s.jsx(os,{size:12}),s.jsx("span",{children:y})]}):s.jsxs("span",{className:"conversation-meta-chip",title:y,children:[s.jsx(os,{size:12}),s.jsx("span",{children:y})]})),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(tn,{size:12}),s.jsx("span",{children:h})]}),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(tn,{size:12}),s.jsx("span",{children:h})]}),d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:k,title:d,children:[s.jsx(Is,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(Is,{size:12}),s.jsx("span",{children:d})]})),x&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Is,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),v&&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(jf,{size:12}),s.jsxs("span",{children:[f.pending," Pending"]})]})]})}function Ew({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:y,onOpenMeshGraph:x,onStopCli:f,cliViewMode:v,onSetCliViewMode:k,handleSendChat:b,handleForceSendChat:j,handleFocusAgent:C,handleModalButton:w,handleRelaunch:g}){var _,P;const S=l.useRef(null),N=lt(e)&&!t,I=N&&v==="terminal",R=!!e.daemonId&&!!((_=e.coordinator)!=null&&_.meshId||(P=e.settings)!=null&&P.meshCoordinatorFor),L=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 ${L} 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(bi,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:ft(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx($w,{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:[N&&v&&s.jsx(ep,{mode:v,onChange:k,compact:!0}),N&&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(wt,{size:14})}),R&&x&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(Yt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(e),type:"button",children:s.jsx(yi,{size:14})}),!t&&!N&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(e),type:"button",children:s.jsx(os,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(Ji,{activeConv:e,clearToken:0,isCliTerminal:I,ideEntry:n,terminalRef:S,handleModalButton:w,handleRelaunch:g,handleSendChat:b,handleForceSendChat:j,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:C,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const uo={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 Bw(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Bp(){const[e,t]=l.useState("unix"),[r,n]=l.useState("powershell"),[a,o]=l.useState(!1),i=e==="unix"?"unix":r;l.useEffect(()=>{t(Bw())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(uo[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:uo[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:uo[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 Fp({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:os},{key:"chats",label:"Chats",icon:Xs}];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 An({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 tr({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 Er({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 Fw({conversation:e,onCancel:t,onConfirm:r}){const n=ft(e);return s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] 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:t,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"card fade-in mobile-compact-dialog 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-bg-primary",children:[s.jsxs("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base md:text-lg font-extrabold",children:["Hide ",n,"?"]}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:"This only collapses the chat locally. You can restore it from Hidden tabs."})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:r,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Hide"}),s.jsx("button",{onClick:t,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function Mn({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:d,onToggleMute:p}){const u=t==="needs_attention"||t==="task_complete",m=t==="working",h=t==="earlier",y=t==="task_complete",{isReconnecting:x,isConnecting:f}=kr(e.conversation),v=ft(e.conversation),k=xr(e.conversation),b=Ju(e.conversation,{requiresAction:t==="needs_attention"}),j=u?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":h?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",C=u?"bg-accent-primary shadow-glow":m?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":h?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",w=h?"text-text-secondary":"text-text-primary",g=h?"text-text-muted":"text-text-secondary",S=h?"text-text-secondary opacity-80":"text-text-muted",N=h?"text-text-muted opacity-80":"text-text-muted",I=!m&&!y,R=qu(e.conversation),L="text-[color:var(--status-warning)]",_=P=>{if(!c)return;P.preventDefault(),P.stopPropagation();const B=c==null?void 0:c(e.conversation);Promise.resolve(B).catch(Y=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",Y)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${j}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[u||m?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 ${C}`,style:u?{color:"var(--accent-on-primary)"}:void 0,children:r(v)}),R&&i&&s.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:P=>{P.preventDefault(),P.stopPropagation(),i(e.conversation)},"aria-label":`Open mesh graph for ${v}`,title:"Open live repo mesh graph",children:s.jsx(Yt,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:_,type:"button",children:[s.jsx("div",{className:"flex items-center gap-2 pr-[124px]",children:s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${w}`,children:v})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${g}`,children:[s.jsx("span",{className:"truncate",children:k}),s.jsx(aa,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),x?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${L} animate-pulse`,children:"Reconnecting…"})]}):f?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):b==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:L,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${S}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[I&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${N}`,children:tu(e.timestamp)}),y&&s.jsx("span",{className:"rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),p&&s.jsx("button",{type:"button",className:`mobile-inbox-mute-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${d?"border-amber-500/60 bg-amber-500 text-white hover:bg-amber-600":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:P=>{P.preventDefault(),P.stopPropagation(),p()},"aria-label":d?`Unmute ${v}`:`Mute ${v}`,title:d?"Muted — notifications silenced. Tap to unmute.":"Mute notifications",children:d?s.jsx(Kd,{size:13}):s.jsx(jr,{size:13})}),a&&s.jsx("button",{type:"button",className:"mobile-inbox-hide-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:P=>{P.preventDefault(),P.stopPropagation(),a()},"aria-label":`Hide ${v}`,title:"Hide conversation",children:s.jsx(vi,{size:13})}),o&&s.jsx("button",{type:"button",className:"mobile-inbox-stop-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-status-error/30 bg-bg-primary/70 text-status-error transition-colors hover:border-status-error/60 hover:bg-status-error/10",onClick:P=>{P.preventDefault(),P.stopPropagation(),o()},"aria-label":`Stop ${v} session`,title:"Stop session (terminates the agent)",children:s.jsx(wt,{size:13})})]})]})},e.conversation.tabKey)}function _c({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 Ow({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:y,onStopCli:x,onOpenNewSession:f,onOpenMachine:v,onOpenSettings:k,onSectionChange:b,wsStatus:j="connected",isStandalone:C=!1,onCollectChatDebugBundle:w,isConversationMuted:g,onToggleMuteConversation:S}){const[N,I]=l.useState(null),R=j==="disconnected"||j==="reconnecting"||j==="offline"||j==="auth_failed",L=i.length>0,_=t.length>0||r.length>0||n.length>0||a.length>0,P=e==="machines"?"Machines":"Chats",B=C?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",Y=C?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",M=l.useCallback(async A=>{const $=Hs(A);if(!$)return;const T=Array.isArray(A.messages)?A.messages:[],F=_u({activeConv:A,visibleMessages:T,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:T.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),z=await p($,"get_chat_debug_bundle",{...Os(A),delivery:"daemon_file",frontendSnapshot:F}),U=Yr(z),te=Ru(U),Z=await Lu(te);Z==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ct.showToast(Tu(U,{locatorCopyStatus:Z}),Z==="failed"?"warning":"success")},[d,p]),H=w||M,q=l.useCallback(()=>{N&&(h==null||h(N),I(null))},[N,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 ${B}`,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:P}),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(jr,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:k,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(ya,{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] ${Y}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:R?s.jsx(Er,{icon:s.jsx(_c,{}),title:j==="offline"?"Network offline":j==="auth_failed"?"Session expired":"Reconnecting",subtitle:j==="offline"?"Waiting for network…":j==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):i.length===0?s.jsx(Er,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:C?"Waiting for your daemon":"Connect your machines",subtitle:C?"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:!C&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Bp,{})})}):s.jsx(tr,{children:i.map((A,$)=>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] ${$>0?"border-t border-border-subtle/70":""}`,onClick:()=>v(A.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(A.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:A.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:A.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[A.unread," new"]}):A.total>0?`${A.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:A.subtitle}),A.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[A.total," chat",A.total!==1?"s":"",A.unread>0?` · ${A.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},A.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(An,{title:"Needs attention",className:"mb-0"}),s.jsx(tr,{children:t.map((A,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Mn,{item:A,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:h?()=>I(A.conversation):void 0,onRequestStopCli:x?()=>x(A.conversation):void 0,onOpenMeshGraph:y,onCollectChatDebugBundle:H,isMuted:g==null?void 0:g(A.conversation),onToggleMute:S?()=>S(A.conversation):void 0})},A.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(An,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(tr,{children:r.map((A,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Mn,{item:A,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:h?()=>I(A.conversation):void 0,onRequestStopCli:x?()=>x(A.conversation):void 0,onOpenMeshGraph:y,onCollectChatDebugBundle:H,isMuted:g==null?void 0:g(A.conversation),onToggleMute:S?()=>S(A.conversation):void 0})},A.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(An,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(tr,{children:n.map((A,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Mn,{item:A,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:h?()=>I(A.conversation):void 0,onRequestStopCli:x?()=>x(A.conversation):void 0,onOpenMeshGraph:y,onCollectChatDebugBundle:H,isMuted:g==null?void 0:g(A.conversation),onToggleMute:S?()=>S(A.conversation):void 0})},A.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(An,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(tr,{children:a.map((A,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Mn,{item:A,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:h?()=>I(A.conversation):void 0,onRequestStopCli:x?()=>x(A.conversation):void 0,onOpenMeshGraph:y,onCollectChatDebugBundle:H,isMuted:g==null?void 0:g(A.conversation),onToggleMute:S?()=>S(A.conversation):void 0})},A.conversation.tabKey))}):_?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):R?s.jsx(Er,{icon:s.jsx(_c,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):L?s.jsx(Er,{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(Xs,{size:20})}),title:"No conversations yet",subtitle:tp,children:f&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:f,"aria-label":us,title:us,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:us})]})}):s.jsx(Er,{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(tr,{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"&&f&&_&&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:f,"aria-label":us,title:us,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"})]})}),N&&s.jsx(Fw,{conversation:N,onCancel:()=>I(null),onConfirm:q}),s.jsx(Fp,{section:e,onSectionChange:b})]})}function Hw(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 Op(e){const t=[e.workspace||"Workspace unknown"],r=qs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Hw(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Xi({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=yw(r),y=u.trim();return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] 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(wt,{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(bi,{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:x=>m(x.target.value),onKeyDown:x=>{x.key!=="Enter"||!y||a||(x.preventDefault(),d(y))},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:()=>{!y||a||d(y)},disabled:!y||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(x=>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(x.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(hr,{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:x.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:x.path})]})]},x.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(y||r),disabled:!y&&!r||a,children:i})]})]})})}function Hp({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:y,onModelChange:x,historyProviderNode:f,onConfirm:v,onCancel:k}){const b=n==null?void 0:n.find(j=>j.key===a);return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] 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:k,"aria-label":"Close launch confirmation",children:s.jsx(wt,{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:j=>o(j.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(j=>s.jsx("option",{value:j.key,children:j.label},j.key))}),(b==null?void 0:b.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:b.description})]}),f,r.map(j=>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:j.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:j.value})]},`${j.label}:${j.value}`)),h&&x&&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:y||"",onChange:j=>x(j.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:j=>m(j.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:k,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:v,disabled:d,children:[s.jsx(Wd,{size:14}),d?c:i]})]})]})})}function Tc(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Wp(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?"⭐ ":""}${Tc(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:Tc(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 Ww(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Kw(e){return[Ww(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Uw(e){return e.lastLaunchedAt?wa(e.lastLaunchedAt):""}function Kp(e){return{metaText:Kw(e),updatedLabel:Uw(e)}}function po(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function zw({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var Je,qe,je,at;const i=Sr(),[c,d]=l.useState(!1),p=(((Je=e.detectedIdes)==null?void 0:Je.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(Ie=>({id:Ie.id,path:Ie.path,label:Ie.label})),[e]),m=e.defaultWorkspaceId||null,[h,y]=l.useState(m||((qe=u[0])==null?void 0:qe.id)||""),[x,f]=l.useState(""),[v,k]=l.useState(""),[b,j]=l.useState([]),[C,w]=l.useState(!1),[g,S]=l.useState(""),[N,I]=l.useState(!1),[R,L]=l.useState(po(p,t.length,r.length)),_=l.useRef(null),[P,B]=l.useState(null),Y=l.useRef("__home__"),[M,H]=l.useState("__home__"),[q,A]=l.useState(""),[$,T]=l.useState(""),[F,z]=l.useState(""),[U,te]=l.useState([]),[Z,se]=l.useState(()=>Dt().textQuery),[G,O]=l.useState(()=>Dt().workspaceQuery),[V,pe]=l.useState(()=>Dt().modelQuery),[fe,de]=l.useState(()=>Dt().resumableOnly),[ke,ye]=l.useState(()=>Dt().sortMode),[we,he]=l.useState(!1),[K,E]=l.useState(!1),J=l.useRef(null),re=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const be=h==="__custom__"?x.trim():((je=u.find(Ie=>Ie.id===h))==null?void 0:je.path)||"",ue=h==="__custom__"&&!!be&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),D=h!=="__custom__"&&((at=u.find(Ie=>Ie.id===h))==null?void 0:at.path)||"",me=l.useMemo(()=>(e.recentLaunches||[]).map(Ie=>Ie.workspace),[e]),Se=l.useCallback(async Ie=>{w(!0),S("");try{const ot=await a(Ie);k(ot.path),f(ot.path),j(ot.directories)}catch(ot){S(ot instanceof Error?ot.message:"Could not load folder")}finally{w(!1)}},[a]),oe=l.useCallback(()=>{var ot;y("__custom__"),I(!0);const Ie=qi(e.platform,Vi(x.trim(),D,me,e.defaultWorkspacePath,(ot=u.find(nt=>nt.id===m))==null?void 0:ot.path,u.map(nt=>nt.path)));Se(Ie)},[x,m,Se,me,D,e.platform,u]),Q=l.useCallback(Ie=>{if(Ie!=null&&Ie.workspaceId){y(Ie.workspaceId),f("");return}if(Ie!=null&&Ie.workspacePath){y("__custom__"),f(Ie.workspacePath);return}y(""),f("")},[]),ve=l.useCallback(Ie=>{if(y(Ie),Ie==="__custom__"){oe();return}f("")},[oe]),Ne=l.useCallback(Ie=>{y("__custom__"),f(Ie)},[]),Le=l.useCallback((Ie,ot)=>{_.current=ot,Y.current=Ie.selectedWorkspaceKey||"__home__",H(Ie.selectedWorkspaceKey||"__home__"),A(Ie.initialArgs||""),T(Ie.initialModel||""),z(""),te([]);const nt=Ie.providerType?`${e.id}:${Ie.providerType}`:null;if(s0(re.current,nt)){const Qe=Dt();se(Qe.textQuery),O(Qe.workspaceQuery),pe(Qe.modelQuery),de(Qe.resumableOnly),ye(Qe.sortMode)}re.current=nt,B(Ie),Ie.providerType&&o&&(he(!0),o(Ie.providerType).then(Qe=>te(Qe||[])).catch(Qe=>console.warn("Failed to load saved sessions",Qe)).finally(()=>he(!1)))},[o,e.id]),We=l.useMemo(()=>sp(U,{textQuery:Z,workspaceQuery:G,modelQuery:V,resumableOnly:fe,sortMode:ke}),[V,fe,U,ke,Z,G]);l.useEffect(()=>{F&&(We.some(Ie=>Ie.providerSessionId===F)||z(""))},[We,F]);const le=l.useCallback(()=>{_.current&&(E(!0),_.current().finally(()=>{_.current=null,E(!1),B(null)}))},[]),Ee=l.useCallback(()=>{_.current=null,B(null)},[]),Be=l.useCallback(Ie=>{Y.current=Ie,H(Ie)},[]);return l.useEffect(()=>{var Ie;J.current!==e.id&&(J.current=e.id,y(m||((Ie=u[0])==null?void 0:Ie.id)||"__custom__"),f(""),k(""),j([]),S(""),I(!1),se(Dt().textQuery),O(Dt().workspaceQuery),pe(Dt().modelQuery),de(Dt().resumableOnly),ye(Dt().sortMode),re.current=null,L(po(p,t.length,r.length)))},[r.length,t.length,m,p,e.id,u]),l.useEffect(()=>{var Ie;h!=="__custom__"&&(h&&u.some(ot=>ot.id===h)||y(m||((Ie=u[0])==null?void 0:Ie.id)||"__custom__"))},[m,h,u]),l.useEffect(()=>{R==="ide"&&p||R==="cli"&&t.length>0||R==="acp"&&r.length>0||L(po(p,t.length,r.length))},[R,r.length,t.length,p]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:p,workspaceRows:u,defaultWorkspaceId:m,workspaceChoice:h,customWorkspacePath:x,browseCurrentPath:v,browseDirectories:b,browseBusy:C,browseError:g,browseDialogOpen:N,activeLauncherKind:R,launchConfirm:P,launchConfirmWorkspaceKeyRef:Y,launchConfirmWorkspaceKey:M,launchConfirmArgs:q,launchConfirmModel:$,launchConfirmResumeId:F,launchConfirmSavedSessions:U,launchConfirmTextFilter:Z,launchConfirmWorkspaceFilter:G,launchConfirmModelFilter:V,launchConfirmResumableOnly:fe,launchConfirmSortMode:ke,filteredLaunchConfirmSavedSessions:We,launchConfirmSessionsLoading:we,launchConfirmBusy:K,resolvedWorkspacePath:be,canCreateMissingWorkspace:ue,openBrowseDialog:oe,loadBrowsePath:Se,handleWorkspaceChoiceChange:ve,chooseCustomWorkspacePath:Ne,setCustomWorkspacePath:f,setBrowseDialogOpen:I,setActiveLauncherKind:L,openLaunchConfirm:Le,handleConfirmLaunch:le,closeLaunchConfirm:Ee,setWorkspaceSelectionFromOption:Q,setLaunchConfirmWorkspaceKeyAndSync:Be,setLaunchConfirmArgs:A,setLaunchConfirmModel:T,setLaunchConfirmResumeId:z,setLaunchConfirmTextFilter:se,setLaunchConfirmWorkspaceFilter:O,setLaunchConfirmModelFilter:pe,setLaunchConfirmResumableOnly:de,setLaunchConfirmSortMode:ye}}function Gw({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:y,onOpenRecent:x,onOpenMachineDetails:f,onMachineUpgrade:v,onLaunchDetectedIde:k,onAddWorkspace:b,onBrowseDirectory:j,onLaunchWorkspaceProvider:C,onListSavedSessions:w}){const g=M=>M==="ide"?"IDE":M==="cli"?"CLI":"ACP",S=r.slice(0,4),N=t.slice(0,3),I=zw({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:c,onBrowseDirectory:j,onListSavedSessions:w}),R=l.useMemo(()=>S.map(M=>{const{metaText:H,updatedLabel:q}=Kp(M);return{key:`recent-launch:${M.id}`,primary:M.label,secondary:H,updatedLabel:q,onClick:()=>{const{options:A,selectedKey:$}=Wp({machine:{workspaces:I.workspaceRows,defaultWorkspaceId:I.defaultWorkspaceId},currentWorkspacePath:M.workspace});I.openLaunchConfirm({title:M.kind==="ide"?ia("restart-ide",M.label):M.providerSessionId?rp(M.label):ia("start-fresh",M.label),description:M.kind==="ide"?la("restart-ide"):M.providerSessionId?np():la("start-fresh"),confirmLabel:M.kind==="ide"?ca("restart-ide"):M.providerSessionId?oa(!0):ca("start-fresh"),busyLabel:M.kind==="ide"?da("restart-ide"):M.providerSessionId?Bi(!0):da("start-fresh"),workspaceOptions:A,selectedWorkspaceKey:$,details:[{label:"Mode",value:g(M.kind)},...M.providerType?[{label:"Provider",value:M.providerType}]:[]]},async()=>{const T=A.find(F=>F.key===I.launchConfirmWorkspaceKeyRef.current);I.setWorkspaceSelectionFromOption(T),await x({...M,workspace:(T==null?void 0:T.workspacePath)??null})})}}}),[I,x,S]),L=l.useMemo(()=>N.map(M=>({key:`recent-chat:${M.conversation.tabKey}`,primary:ft(M.conversation),secondary:Ly(M.conversation,{timestampLabel:M.timestamp?tu(M.timestamp):null}),unread:M.unread,onClick:()=>y(M.conversation)})),[y,N]),_=I.showAllRecent?R:R.slice(0,4),P=R.length>0,B=L.length>0,Y=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 ${Y} 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(bi,{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:Jt(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:[B&&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:L.map(M=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${M.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:M.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:M.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:M.secondary})]},M.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(M=>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:M.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:M.primary}),M.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:M.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:M.secondary})]},M.key))}),R.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(M=>!M),children:I.showAllRecent?"Show fewer":`Show ${R.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:v,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(Xi,{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:M=>{I.loadBrowsePath(M)},onConfirm:M=>{I.chooseCustomWorkspacePath(M),I.setBrowseDialogOpen(!1)}}),I.launchConfirm&&s.jsx(Hp,{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?oa(!!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:Fi()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:I.launchConfirmTextFilter,onChange:M=>I.setLaunchConfirmTextFilter(M.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:M=>I.setLaunchConfirmWorkspaceFilter(M.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:M=>I.setLaunchConfirmModelFilter(M.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:M=>I.setLaunchConfirmSortMode(M.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:M=>I.setLaunchConfirmResumableOnly(M.target.checked),disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:I.launchConfirmResumeId,onChange:M=>I.setLaunchConfirmResumeId(M.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:a0()}),I.filteredLaunchConfirmSavedSessions.map(M=>s.jsxs("option",{value:M.providerSessionId,disabled:!M.canResume,children:[M.title||M.providerSessionId," ",M.canResume?"":"(workspace missing)"]},M.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 M=I.filteredLaunchConfirmSavedSessions.find(q=>q.providerSessionId===I.launchConfirmResumeId);if(!M)return null;const H=Op(M);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:H.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:H.providerSessionId}),s.jsx("div",{className:"mt-1",children:H.metaLine}),H.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:H.updatedLabel}),H.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:H.preview})]})})()]}),onConfirm:I.handleConfirmLaunch,onCancel:I.closeLaunchConfirm}),u&&s.jsx(Fp,{section:p,onSectionChange:h})]})}const Lc=8e3;function Vw(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,r=t&&typeof t=="object",n=r&&t.success===!1,a=r&&t.mirrorStale===!0;return!n&&!a?{confirmed:!0}:{confirmed:!1,reason:n&&typeof t.error=="string"?t.error:a?"the coordinator did not confirm the change":"command was rejected"}}function Up(e,t,r){const n=l.useRef(new Map),[,a]=l.useState(0),o=l.useCallback(()=>a(y=>y+1),[]);l.useEffect(()=>{const y=n.current;if(y.size===0)return;const x=Date.now();let f=!1;for(const[v,k]of y){const b=e.get(v),j=k.muted===void 0||(b?b.muted===k.muted:!1),C=k.hidden===void 0||(b?b.surfaceHidden===k.hidden:!1),w=x-k.at>Lc;(j&&C||w)&&(y.delete(v),f=!0)}f&&o()},[e,o]),l.useEffect(()=>{if(n.current.size===0)return;const y=setInterval(()=>{const x=n.current,f=Date.now();let v=!1;for(const[k,b]of x)f-b.at>Lc&&(x.delete(k),v=!0);v&&o(),x.size===0&&clearInterval(y)},1e3);return()=>clearInterval(y)});const i=l.useCallback((y,x)=>{const f=n.current.get(y);n.current.set(y,{...f,...x,at:Date.now()}),o()},[o]),c=l.useCallback(y=>{const x=y.sessionId,f=x?n.current.get(x):void 0;return(f==null?void 0:f.muted)!==void 0?f.muted:Ms(y,e).muted},[e]),d=l.useCallback(y=>{const x=y.sessionId,f=x?n.current.get(x):void 0;return(f==null?void 0:f.hidden)!==void 0?f.hidden:Ms(y,e).surfaceHidden},[e]),p=l.useCallback((y,x)=>{const f=_s(y),v=y.sessionId;!f||!v||(i(v,x),t(f,"set_conversation_prefs",{sessionId:v,...x,...Ia(y)}).then(k=>{const b=Vw(k);b.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",b.reason),n.current.delete(v),o(),r==null||r(`Couldn't update conversation — ${b.reason}`))}).catch(k=>{console.warn("[conversation-prefs] set_conversation_prefs failed",k),n.current.delete(v),o();const b=k instanceof Error?k.message:String(k??"the daemon is unreachable");r==null||r(`Couldn't update conversation — ${b}`)}))},[t,i,o,r]),u=l.useCallback(y=>{p(y,{muted:!c(y)})},[p,c]),m=l.useCallback((y,x)=>{p(y,{hidden:x})},[p]),h=l.useCallback(y=>{p(y,{hidden:!d(y)})},[p,d]);return{isMuted:c,isHidden:d,toggleMute:u,setHidden:m,toggleHidden:h}}function zn(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function qw(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:zn(e)}function Yw(e){var n,a,o;const t=((n=e.p2p)==null?void 0:n.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((a=e.p2p)!=null&&a.available)||!!((o=e.p2p)!=null&&o.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function Jw(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:qs(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=sn(n)?"cli":cr(n)?"acp":"ide",o=qs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||(sn(n)?n.cliName||n.type:cr(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:cr(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 Xw(e,t){const r=new Map;for(const n of t){const a=_s(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=Go(n),d=a.filter(m=>m.unread||m.requiresAction).length,p=Yw(n),u=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:Jt(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?Ry(i,Wu(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 Qw(e){return e==="chat"}function _n(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 Zw({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:y,setSelectedTabKey:x,setScreen:f,setSelectedMachineId:v,setSection:k,setMachineBackTarget:b,resetMachineAction:j}){const C=l.useRef(null),w=l.useCallback(g=>{if(!(g!=null&&g.sessionId))return;const S=Ms(g,i),N=Math.max(Date.now(),zs(g),S.lastUpdated||0);_n("mark_read:start",{tabKey:g.tabKey,sessionId:g.sessionId,displayPrimary:ft(g),inboxBucket:S.inboxBucket,unread:S.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:zs(g),readAt:N}),c(_s(g)||g.routeId,"mark_session_seen",{sessionId:g.sessionId,providerSessionId:g.providerSessionId,seenAt:N,completionMarker:S.completionMarker}).then(I=>{_n("mark_read:result",{tabKey:g.tabKey,sessionId:g.sessionId,result:I})}).catch(I=>{_n("mark_read:error",{tabKey:g.tabKey,sessionId:g.sessionId,error:I instanceof Error?I.message:String(I)})})},[i,c]);return l.useEffect(()=>{var S;if(!n){Qw(o)&&f("inbox"),x(((S=e[0])==null?void 0:S.tabKey)||null),C.current=null;return}if(o!=="chat"){C.current=null;return}const g=`${n.tabKey}:${n.sessionId||""}`;C.current!==g&&(C.current=g,w(n))},[e,w,o,n,f,x]),l.useEffect(()=>{if(!d)return;const g=e.find(S=>S.tabKey===d);g&&(x(g.tabKey),f("chat"),p==null||p())},[e,p,d,f,x]),l.useEffect(()=>{if(!u)return;const g=t.find(S=>S.id===u);g&&(v(g.id),j(),k("machines"),b("inbox"),f("machine"),m==null||m())},[t,m,u,j,b,f,k,v]),l.useEffect(()=>{h&&(k(h),f("inbox"),y==null||y())},[y,h,f,k]),l.useEffect(()=>{const g=r.filter(S=>S.inboxBucket==="task_complete"||S.unread);g.length!==0&&_n("inbox_state",{screen:o,selectedTabKey:a,items:g.map(S=>{const N=Ms(S.conversation,i);return{liveState:N,tabKey:S.conversation.tabKey,sessionId:S.conversation.sessionId,displayPrimary:ft(S.conversation),serverBucket:N.inboxBucket,computedBucket:S.inboxBucket,serverUnread:N.unread,computedUnread:S.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:zs(S.conversation)}})})},[r,i,o,a]),{markConversationRead:w}}function ej(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Rc(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function tj(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function sj({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const{launchCli:a}=ga(),[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(j,C,w)=>{var g;try{i("loading"),d(`Launching ${C}…`);const S={ideType:C,enableCdp:!0};(g=w==null?void 0:w.workspacePath)!=null&&g.trim()&&(S.workspace=w.workspacePath.trim()),await e(j,"launch_ide",S),i("done"),d(`${C} launch requested`)}catch(S){i("error"),d(S instanceof Error?S.message:"Launch IDE failed"),console.error("Launch IDE failed",S)}},[e]),y=l.useCallback(async(j,C,w)=>{if(C.trim())try{i("loading"),d(w!=null&&w.createIfMissing?"Creating folder…":"Saving workspace…");const g=await e(j,"workspace_add",{path:C.trim(),createIfMissing:(w==null?void 0:w.createIfMissing)===!0});if(g!=null&&g.success){i("done"),d(w!=null&&w.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((g==null?void 0:g.error)||"Could not save workspace")}catch(g){i("error"),d(g instanceof Error?g.message:"Could not save workspace")}},[e]),x=l.useCallback(async j=>{var C,w,g,S,N,I;try{i("loading"),d("Starting daemon upgrade…");const R=await e(j,"daemon_upgrade",{});if((C=R==null?void 0:R.result)!=null&&C.alreadyLatest){i("done"),d(`Already on v${((w=R==null?void 0:R.result)==null?void 0:w.version)||"latest"}.`);return}if((g=R==null?void 0:R.result)!=null&&g.upgraded||(S=R==null?void 0:R.result)!=null&&S.success){i("done"),d(`Upgrade to v${((N=R==null?void 0:R.result)==null?void 0:N.version)||"latest"} started. Daemon is restarting…`);return}i("error"),d(((I=R==null?void 0:R.result)==null?void 0:I.error)||"Upgrade failed")}catch(R){i("error"),d(R instanceof Error?R.message:"Upgrade failed")}},[e]),f=l.useCallback(async(j,C,w,g)=>{var I,R,L;const S=Date.now(),N={machineId:j,kind:C,providerType:w,workspaceId:(g==null?void 0:g.workspaceId)||null,workspacePath:(g==null?void 0:g.workspacePath)||null,resumeSessionId:(g==null?void 0:g.resumeSessionId)||null,startedAt:S};try{i("loading"),d(`Launching ${w}…`),u(N);const _={cliType:w};(I=g==null?void 0:g.workspacePath)!=null&&I.trim()?_.dir=g.workspacePath.trim():g!=null&&g.workspaceId&&(_.workspaceId=g.workspaceId),g!=null&&g.resumeSessionId&&(_.resumeSessionId=g.resumeSessionId),(R=g==null?void 0:g.args)!=null&&R.trim()&&(_.cliArgs=g.args.trim().split(/\s+/).filter(Boolean)),(L=g==null?void 0:g.model)!=null&&L.trim()&&(_.initialModel=g.model.trim());const P=await a(j,_),B=(P==null?void 0:P.result)||P,Y=(B==null?void 0:B.sessionId)||(B==null?void 0:B.id);if(P!=null&&P.success&&Y){u(null),i("done"),d(`${w} launched`),t(an(Y));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)||(B==null?void 0:B.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(_){if(tj(_)){i("loading"),d(`${w} launch requested — waiting for session…`);return}u(null),i("error"),d(_ instanceof Error?_.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),v=l.useCallback(async(j,C)=>{try{const w=await e(j,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),g=(w==null?void 0:w.result)??w;return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]}catch(w){return console.error("Failed to list saved sessions on mobile:",w),[]}},[e]),k=l.useCallback(async(j,C)=>Yi(e,j,C),[e]);l.useEffect(()=>{if(!p)return;const j=Rc(p.workspacePath),C=r.find(g=>{var _,P,B,Y;if(!g||g.type==="adhdev-daemon"||ej(g.daemonId||g.id)!==p.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==p.kind||String(g.agentType||g.type||"")!==p.providerType)return!1;const R=String(g.providerSessionId||"");if(p.resumeSessionId&&R)return R===p.resumeSessionId;if(j){const M=Rc(g.workspace||g.runtimeWorkspaceLabel);return M?M===j:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((Y=(B=(P=(_=g.activeChat)==null?void 0:_.messages)==null?void 0:P.at)==null?void 0:B.call(P,-1))==null?void 0:Y.timestamp)||0)>=p.startedAt-5e3});if(!C)return;const w=$p({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:n});w&&(u(null),i("done"),d(`${p.providerType} launched`),t(an(w)))},[n,r,t,p]),l.useEffect(()=>{if(!p)return;const j=window.setTimeout(()=>{u(C=>!C||C.startedAt!==p.startedAt?C:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(j)},[p]);const b=l.useCallback(async(j,C)=>{if(C.kind==="ide"&&C.providerType){await h(j,C.providerType,{workspacePath:C.workspace||null});return}(C.kind==="cli"||C.kind==="acp")&&C.providerType&&await f(j,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[h,f]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:h,handleAddWorkspace:y,handleMachineUpgrade:x,handleLaunchWorkspaceProvider:f,handleListSavedSessions:v,handleBrowseDirectory:k,handleOpenRecent:b}}function rj({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:p}){const u=l.useCallback(k=>{o(k.tabKey),i("chat"),n(k)},[n,i,o]),m=l.useCallback(k=>{const b=e.find(j=>j.routeId===k.routeId&&j.streamSource==="native");b&&(o(b.tabKey),i("chat"),n(b))},[e,n,i,o]),h=l.useCallback(()=>{n(t),i("inbox")},[n,t,i]),y=l.useCallback((k,b="inbox")=>{c(k),a(),d("machines"),p(b),i("machine")},[a,p,i,d,c]),x=l.useCallback(k=>{const b=_s(k);b&&y(b,"chat")},[y]),f=l.useCallback(()=>{a(),i(r)},[r,a,i]),v=l.useCallback(k=>{d(k),i("inbox")},[i,d]);return{openConversation:u,openNativeConversation:m,backFromConversation:h,openMachine:y,openConversationMachine:x,backFromMachine:f,changeMachineSection:v}}function yr(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function nj(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function aj({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:y,onOpenHistory:x,onOpenRemote:f,onStopCli:v,wsStatus:k,isConnected:b,onShowAllHiddenConversations:j,onHideConversation:C,onOpenMeshGraph:w,onOpenNewSession:g,liveSessionInboxState:S,setCliViewModeOverrides:N}){const[I,R]=l.useState(()=>{var Q;return((Q=e[0])==null?void 0:Q.tabKey)||null}),[L,_]=l.useState(()=>e[0]?"chat":"inbox"),[P,B]=l.useState("chats"),[Y,M]=l.useState(null),[H,q]=l.useState("inbox"),A=l.useRef([]),$=cn(),T="0.9.82",F=l.useMemo(()=>e.find(Q=>Q.tabKey===I)||e[0]||null,[e,I]),z=l.useMemo(()=>F?r.find(Q=>Q.id===F.routeId):void 0,[r,F]),U=l.useMemo(()=>!F||it(F)||!lt(F)?null:Nr(F),[F]),te=l.useMemo(()=>r.filter(Q=>Q.type==="adhdev-daemon").sort(Ii),[r]),Z=l.useMemo(()=>te.find(Q=>Q.id===Y)||null,[te,Y]),se=Aa({sendDaemonCommand:a,activeConv:F||void 0,setActionLogs:o,isStandalone:i}),G=sj({sendDaemonCommand:a,navigate:$,ides:r,conversations:e}),O=ly(e),V=l.useMemo(()=>e.map(Q=>{const ve=L==="chat"&&(F==null?void 0:F.tabKey)===Q.tabKey,Ne=ja(Q,S,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ve}),Le=zs(Q),We=Wu(Q),le=Yu(Q,We);return{conversation:Q,timestamp:Le,preview:le,unread:Ne.unread,requiresAction:Ne.requiresAction,isWorking:Ne.isWorking,inboxBucket:Ne.inboxBucket}}),[e,S,L,F,O]),{markConversationRead:pe}=Zw({conversations:e,machineEntries:te,items:V,selectedConversation:F,selectedTabKey:I,screen:L,liveSessionInboxState:S,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:y,setSelectedTabKey:R,setScreen:_,setSelectedMachineId:M,setSection:B,setMachineBackTarget:q,resetMachineAction:G.resetMachineAction}),fe=rj({conversations:e,selectedConversation:F,machineBackTarget:H,markConversationRead:pe,resetMachineAction:G.resetMachineAction,setSelectedTabKey:R,setScreen:_,setSelectedMachineId:M,setSection:B,setMachineBackTarget:q}),{isMuted:de,toggleMute:ke}=Up(S,a),ye=l.useMemo(()=>zn(V.filter(Q=>Q.requiresAction&&!de(Q.conversation))),[V,de]),we=l.useMemo(()=>zn(V.filter(Q=>Q.unread&&!Q.requiresAction&&!de(Q.conversation))),[V,de]),he=l.useMemo(()=>qw(V.filter(Q=>!Q.unread&&!Q.requiresAction&&Q.isWorking),A.current),[V]);l.useEffect(()=>{A.current=he.map(Q=>Q.conversation.tabKey)},[he]);const K=l.useMemo(()=>zn(V.filter(Q=>!Q.unread&&!Q.requiresAction&&!Q.isWorking)),[V]),E=l.useMemo(()=>Z?V.filter(Q=>_s(Q.conversation)===Z.id):[],[V,Z]),J=l.useMemo(()=>Jw(Z,r),[r,Z]),re=(Z==null?void 0:Z.version)||null,be=!!Z&&!!re&&!0&&re!==T,ue=l.useMemo(()=>(Z==null?void 0:Z.availableProviders)||[],[Z]),D=l.useMemo(()=>ue.filter(Q=>yr(Q,"cli")).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[ue]),me=l.useMemo(()=>ue.filter(Q=>yr(Q,"acp")).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[ue]),Se=l.useMemo(()=>Xw(te,V),[V,te]),oe=l.useCallback(async Q=>{Z&&await G.handleOpenRecent(Z.id,Q)},[G,Z]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:L==="chat"&&F?s.jsx(Ew,{selectedConversation:F,isAcp:it(F),isStandalone:i,selectedIdeEntry:z,actionLogs:n,userName:c,isSendingChat:se.isSendingChat,sendFeedbackMessage:se.sendFeedbackMessage,isFocusingAgent:se.isFocusingAgent,handleModalButton:se.handleModalButton,handleRelaunch:se.handleRelaunch,onBack:fe.backFromConversation,onOpenNativeConversation:fe.openNativeConversation,onOpenMachine:fe.openConversationMachine,onOpenHistory:x,onOpenRemote:f,onOpenMeshGraph:w,onStopCli:v,cliViewMode:U,onSetCliViewMode:async Q=>{await Np({conversation:F,mode:Q,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:N})},handleSendChat:se.handleSendChat,handleForceSendChat:se.handleForceSendChat,handleFocusAgent:se.handleFocusAgent}):L==="machine"&&Z?s.jsx(Gw,{selectedMachineEntry:Z,selectedMachineConversations:E,selectedMachineRecentLaunches:J,cliProviders:D,acpProviders:me,selectedMachineNeedsUpgrade:be,appVersion:T,machineAction:G.machineAction,isStandalone:i,section:P,showBottomNav:H==="inbox",onBack:fe.backFromMachine,onSectionChange:fe.changeMachineSection,onOpenConversation:fe.openConversation,onOpenRecent:oe,onOpenMachineDetails:()=>$(`/machines/${Z.id}`),onMachineUpgrade:()=>G.handleMachineUpgrade(Z.id),onLaunchDetectedIde:(Q,ve)=>G.handleLaunchDetectedIde(Z.id,Q,ve),onAddWorkspace:(Q,ve)=>G.handleAddWorkspace(Z.id,Q,ve),onBrowseDirectory:Q=>G.handleBrowseDirectory(Z.id,Q),onLaunchWorkspaceProvider:(Q,ve,Ne)=>G.handleLaunchWorkspaceProvider(Z.id,Q,ve,Ne),onListSavedSessions:Q=>G.handleListSavedSessions(Z.id,Q)}):s.jsx(Ow,{section:P,attentionItems:ye,unreadItems:we,workingItems:he,completedItems:K,hiddenConversations:t,machineCards:Se,getAvatarText:nj,actionLogs:n,sendDaemonCommand:a,onOpenConversation:fe.openConversation,onShowAllHidden:j,onHideConversation:C,onOpenMeshGraph:w,onStopCli:v,onOpenNewSession:g,onOpenMachine:fe.openMachine,onOpenSettings:()=>$("/settings"),onSectionChange:B,wsStatus:k,isConnected:b,isStandalone:i,isConversationMuted:de,onToggleMuteConversation:ke})})}function mo(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function oj({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(v=>{v.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),y=l.useCallback(v=>{if(!v.dataTransfer.types.includes("text/tab-key"))return;if(v.preventDefault(),!mo(t,r)){u("merge");return}const k=v.currentTarget.getBoundingClientRect(),b=v.clientX-k.left,j=k.width/3;b<j?u("split-left"):b>j*2?u("split-right"):u("merge")},[t,r]),x=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),u(null))},[]),f=l.useCallback(v=>{i.current=0,d(!1);const k=v.dataTransfer.getData("text/tab-key"),b=k?e.some(C=>C.tabKey===k):!1,j=p;if(u(null),o(),!!k){if(v.preventDefault(),j==="split-left"&&mo(t,r)){r==null||r(k,"split-left");return}if(j==="split-right"&&mo(t,r)){r==null||r(k,"split-right");return}if(b){a(k);return}n==null||n(k)}},[e,p,t,r,n,a,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:h,handleDragOver:y,handleDragLeave:x,handleDrop:f}}function ij(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 lj({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),y=l.useRef(n),x=l.useRef(a);l.useEffect(()=>{y.current=n},[n]),l.useEffect(()=>{x.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(S=>{const N=ij(S,e);return N.length===S.length&&N.every((I,R)=>I===S[R])?S:N})},[e]);const f=l.useMemo(()=>{const S=p??c;if(S.length===0)return e;const N=new Map(S.map((I,R)=>[I,R]));return[...e].sort((I,R)=>{const L=N.get(I.tabKey)??999,_=N.get(R.tabKey)??999;return L-_})},[e,p,c]);l.useEffect(()=>{var N,I;if(f.length===0){o!==null&&(i(null),(N=y.current)==null||N.call(y,null));return}if(o&&f.some(R=>R.tabKey===o))return;const S=f[0].tabKey;S!==o&&(i(S),(I=y.current)==null||I.call(y,S))},[f,o]);const v=l.useMemo(()=>f.find(S=>S.tabKey===o),[f,o]),k=l.useCallback(S=>{var N;i(S),(N=y.current)==null||N.call(y,S)},[]),b=l.useCallback((S,N,I)=>{d(R=>{var B;const L=R.filter(Y=>Y!==S),_=L.indexOf(N);if(_<0)return R;const P=I==="left"?_:_+1;return L.splice(P,0,S),(B=x.current)==null||B.call(x,L),L}),u(null)},[]),j=l.useCallback((S,N,I)=>{const L=(c.length>0?c:e.map(B=>B.tabKey)).filter(B=>B!==S),_=L.indexOf(N);if(_<0)return;const P=I==="left"?_:_+1;L.splice(P,0,S),m.current=L,u(L)},[c,e]),C=l.useCallback(()=>{var N;const S=m.current;S&&(d(S),(N=x.current)==null||N.call(x,S))},[]),w=l.useCallback(()=>{m.current=null,u(null)},[]),g=l.useCallback(S=>{d(N=>{var R;const I=N.filter(L=>L!==S);return I.push(S),(R=x.current)==null||R.call(x,I),I})},[]);return{activeTabId:o,activeConv:v,sortedConversations:f,previewOrderRef:m,draggingTabRef:h,selectTab:k,handleTabReorder:b,updatePreviewOrder:j,commitPreviewOrder:C,clearPreviewOrder:w,moveTabToEnd:g,setDraggingTabKey:S=>{h.current=S}}}function cj({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 Qi({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?tp: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:us,"aria-label":us,children:[s.jsx(ji,{size:14}),s.jsx("span",{children:us})]})}),i&&s.jsx(Bp,{}),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 zp="adhdev-tab-shortcuts";function Gp(){try{return JSON.parse(localStorage.getItem(zp)||"{}")}catch{return{}}}function Vp({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>Gp()),[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(zp,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 y=p(h);if(!y)return;const x={...o};for(const[f,v]of Object.entries(x))v===y&&delete x[f];x[c]=y,u(x),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[y,x]of Object.entries(o))if(t.includes(y)&&p(h)===x){h.preventDefault(),r(),n(y);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 ho=e=>{e.preventDefault()},dj=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:y,onClearPreviewOrder:x,onDragStateReset:f,onDragTabKeyChange:v,onReceiveTab:k,onOpenContextMenu:b,longPressTimer:j,isGroupActive:C}){const w=kr(t),g=w.isGenerating?"agent-tab-generating":w.isWaiting?"agent-tab-waiting":"",S=w.isReconnecting,N=_y(t),I=Ty(t),R=qu(t),L=l.useCallback($=>{c.current=t.tabKey,v(t.tabKey),$.dataTransfer.setData("text/tab-key",t.tabKey),$.dataTransfer.effectAllowed="move"},[t.tabKey,c,v]),_=l.useCallback(()=>{c.current=null,v(null),y(),x(),f()},[c,v,y,x,f]),P=l.useCallback($=>{const T=c.current;if(!(!T||T===t.tabKey)&&$.dataTransfer.types.includes("text/tab-key")){$.preventDefault(),$.stopPropagation();const F=$.currentTarget.getBoundingClientRect(),z=$.clientX<F.left+F.width/2?"left":"right";m(T,t.tabKey,z)}},[t.tabKey,c,m]),B=l.useCallback($=>{$.preventDefault(),$.stopPropagation();const T=$.dataTransfer.getData("text/tab-key");if(T&&T!==t.tabKey){const F=$.currentTarget.getBoundingClientRect(),z=$.clientX<F.left+F.width/2?"left":"right";i.includes(T)?h(T,t.tabKey,z):k&&k(T)}x()},[t.tabKey,i,h,k,x]),Y=l.useCallback($=>{$.stopPropagation(),d(),p(t.tabKey),u(t)},[t,u,d,p]),M=l.useCallback($=>{$.preventDefault(),b($.clientX,$.clientY,t.tabKey)},[t.tabKey,b]),H=l.useCallback($=>{const T=$.touches[0];j.current=setTimeout(()=>{b(T.clientX,T.clientY,t.tabKey)},600)},[t.tabKey,j,b]),q=l.useCallback(()=>{j.current&&clearTimeout(j.current)},[j]),A=["adhdev-dockview-tab",g,r&&"is-active",C&&"is-group-active",S&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:A,draggable:!0,onDragStart:L,onDragEnd:_,onDragOver:P,onDrop:B,onClick:Y,onContextMenu:M,onTouchStart:H,onTouchEnd:q,onTouchMove:q,style:{position:"relative",cursor:"pointer",opacity:n?.4:void 0},children:[R&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-badge pointer-events-none absolute top-0.5 right-0.5 text-text-muted",title:"Mesh chat","aria-label":"Mesh chat",children:s.jsx(Yt,{size:11})}),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:"▲"}):S?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:"○"})}),N.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:I,"aria-label":I||N.join(" · "),children:N.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:ft(t),children:ft(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[S?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Ws(t)}):w.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Ws(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:Ws(t)}),s.jsx(aa,{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 uj({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:y,onReceiveTab:x,onHideTab:f,isGroupActive:v,allowTabShortcuts:k=!0}){const[b,j]=l.useState(null),C=l.useRef(null),w=l.useRef(null),g=l.useMemo(()=>e.map(P=>P.tabKey),[e]);dn("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:S,tabShortcuts:N,shortcutListening:I,setShortcutListening:R,saveShortcuts:L}=Vp({enabled:k,sortedTabKeys:e.map(P=>P.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!b)return;const P=B=>{const Y=document.querySelector("[data-pane-context-menu]");Y&&Y.contains(B.target)||j(null)};return window.addEventListener("mousedown",P,!0),()=>window.removeEventListener("mousedown",P,!0)},[b]),l.useEffect(()=>{const P=w.current;if(!P)return;const B=Y=>{Math.abs(Y.deltaY)<=Math.abs(Y.deltaX)||(Y.preventDefault(),P.scrollLeft+=Y.deltaY)};return P.addEventListener("wheel",B,{passive:!1}),()=>P.removeEventListener("wheel",B)},[]);const _=l.useCallback((P,B,Y)=>{j({x:P,y:B,tabKey:Y})},[]);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(dj,{conv:P,isActive:t===P.tabKey,isDraggedTab:a.current===P.tabKey,isTaskCompleteUnread:n.has(P.tabKey),shortcut:k?N[P.tabKey]:void 0,conversationKeys:g,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:y,onReceiveTab:x,onOpenContextMenu:_,longPressTimer:C,isGroupActive:v},P.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),b&&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:b.x,top:b.y},children:[k&&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:ho,onClick:P=>{P.stopPropagation(),R(b.tabKey),j(null)},children:["⌨ ",N[b.tabKey]?`Change shortcut (${N[b.tabKey]})`:"Set shortcut"]}),N[b.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:ho,onClick:()=>{const P={...N};delete P[b.tabKey],L(P),j(null)},children:"✕ Remove shortcut"})]}),f&&s.jsxs(s.Fragment,{children:[k&&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:ho,onClick:()=>{f(b.tabKey),j(null)},children:"🚫 Hide from Dashboard"})]})]}),k&&I&&s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>R(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. ",S?"⌘+1":"Ctrl+1",", ",S?"⌥+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 pj({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:y,onReceiveTab:x,style:f,onActiveTabChange:v,initialActiveTabId:k,initialTabOrder:b,onTabOrderChange:j,onHideTab:C,isFocused:w,allowTabShortcuts:g=!0,onOpenNewSession:S,liveSessionInboxState:N}){const{sendCommand:I}=xt(),R=l.useRef(null),{activeTabId:L,activeConv:_,sortedConversations:P,draggingTabRef:B,selectTab:Y,handleTabReorder:M,updatePreviewOrder:H,commitPreviewOrder:q,clearPreviewOrder:A,moveTabToEnd:$,setDraggingTabKey:T}=lj({conversations:e,initialActiveTabId:k,initialTabOrder:b,onActiveTabChange:v,onTabOrderChange:j}),F=Aa({sendDaemonCommand:a,activeConv:_,setActionLogs:o,isStandalone:i}),{dragOver:z,dropAction:U,resetDragState:te,handleDragEnter:Z,handleDragOver:se,handleDragLeave:G,handleDrop:O}=oj({conversations:e,numGroups:h,onMoveTab:y,onReceiveTab:x,onOwnTabDrop:$,onClearPreviewOrder:A}),V=_&&!it(_)&&Nr(_)==="terminal",pe=l.useMemo(()=>_?t.find(ye=>ye.id===_.routeId):void 0,[t,_]),fe=l.useMemo(()=>_?n.filter(ye=>ye.routeId===_.tabKey):[],[n,_]),de=l.useMemo(()=>new Set(P.filter(ye=>yx(ye,N,{isOpenConversation:ye.tabKey===L})).map(ye=>ye.tabKey)),[L,N,P]);dn("PaneGroup",{groupIndex:p,conversationCount:e.length,activeTabId:L,dragOver:z});const ke=l.useCallback(ye=>{ye.streamSource==="agent-stream"&&ye.agentType&&I(ye.routeId,Mu(),{agentType:ye.agentType,...ye.sessionId&&{targetSessionId:ye.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:z?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(uj,{conversations:P,activeTabId:L,groupIndex:p,numGroups:h,unreadTabKeys:de,draggingTabRef:B,onFocus:u,onSelectTab:Y,onConversationActivated:ke,onPreviewReorder:H,onReorderTab:M,onCommitPreviewOrder:q,onClearPreviewOrder:A,onDragStateReset:te,onDragTabKeyChange:T,onMoveTab:y,onReceiveTab:x,onHideTab:C,isGroupActive:w??!1,allowTabShortcuts:g}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:Z,onDragOver:se,onDragLeave:G,onDrop:O,children:[z&&s.jsx(cj,{dropAction:U,canSplit:!!(h<4&&y)}),_?s.jsx(Ji,{activeConv:_,clearToken:r[_.tabKey]||0,isCliTerminal:!!V,ideEntry:pe,terminalRef:R,handleModalButton:F.handleModalButton,handleRelaunch:F.handleRelaunch,handleSendChat:F.handleSendChat,handleForceSendChat:F.handleForceSendChat,isSendingChat:F.isSendingChat,sendFeedbackMessage:F.sendFeedbackMessage,handleFocusAgent:F.handleFocusAgent,isFocusingAgent:F.isFocusingAgent,actionLogs:fe,userName:d,isInputActive:!m||!!w}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Qi,{conversationsCount:e.length,isSplitMode:m,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:S})})]})]})}function mj({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:y,focusGroup:x,moveTabToGroup:f,splitTabRelative:v,closeGroup:k,handleResizeStart:b,groupActiveTabIds:j,setGroupActiveTab:C,groupTabOrders:w,setGroupTabOrder:g,toggleHiddenTab:S,onOpenNewSession:N,allowTabShortcuts:I=!0,liveSessionInboxState:R}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((L,_)=>{const P=t&&n.length===r?`${n[_]}%`:void 0;return s.jsxs(It.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:B=>b(_-1,B),onDoubleClick:()=>k(_),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(pj,{style:t?{flexBasis:P??`${100/r}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:L,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,userName:h,groupIndex:_,isFocused:t&&y===_,onFocus:()=>x(_),isSplitMode:t,numGroups:r,onMoveTab:(B,Y)=>{Y==="left"&&_>0?f(B,_-1):Y==="right"&&_<r-1?f(B,_+1):Y==="split-left"&&r<4?v(B,_,"left"):Y==="split-right"&&r<4&&v(B,_,"right")},onReceiveTab:B=>f(B,_),onActiveTabChange:B=>C(_,B),initialActiveTabId:j[_],initialTabOrder:w[_],onTabOrderChange:B=>g(_,B),onHideTab:S,onOpenNewSession:N,allowTabShortcuts:I,liveSessionInboxState:R})]},_)})})}const qp="adhdev-dashboard-action-shortcuts",hj=1200,fj=[["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 xj(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function ut(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 Yp(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:ut("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:ut("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:ut("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:ut("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:ut("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:ut("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:ut("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:ut("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:ut("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:ut("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:ut("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:ut("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:ut("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:ut("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:ut("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:ut("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:ut("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:ut("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:ut("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:ut("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:ut("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:ut("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:ut("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:ut("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:ut("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:ut("toggleCliView",e)}]}function oi(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function fa(e){const t=Object.fromEntries(Yp(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(qp)||"{}"),n={...t,...r};for(const[a,o]of fj)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function Jp(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function bj({enabled:e=!0,onTrigger:t}){const r=xj(),[n,a]=l.useState(()=>fa(r)),[o,i]=l.useState(null),[c,d]=l.useState([]),p=l.useRef({parts:[],timer:null}),u=l.useCallback(f=>{const v=[];return f.metaKey&&v.push(r?"⌘":"Meta"),f.ctrlKey&&v.push("Ctrl"),f.altKey&&v.push(r?"⌥":"Alt"),f.shiftKey&&f.key.length!==1&&v.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(v.push(Jp(f.key)),v.join("+"))},[r]),m=l.useCallback(f=>{a(f);try{localStorage.setItem(qp,JSON.stringify(f))}catch{}},[]);l.useEffect(()=>{const f=fa(r),v=Object.entries(n),k=Object.entries(f);v.length===k.length&&v.every(([b,j])=>f[b]===j)||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}},[]),y=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},hj))},[]);l.useEffect(()=>{if(!o)return;const f=v=>{if(v.preventDefault(),v.stopPropagation(),v.key==="Escape"){i(null),d([]);return}const k=u(v);if(!k)return;const j=!(v.metaKey||v.ctrlKey||v.altKey)&&/^[A-Z0-9]$/.test(k);if(c.length===0&&j){d([k]);return}const w=[...c,k].slice(0,2).join(" "),g={...n};for(const[S,N]of Object.entries(g))N===w&&delete g[S];g[o]=w,m(g),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=v=>{if(v.defaultPrevented)return;const k=u(v);if(!k)return;const b=v.metaKey||v.ctrlKey||v.altKey;if(oi(v.target))return;const j=p.current.parts,C=b?[k]:[...j.slice(-1),k].slice(-2),w=C.join(" "),g=C[C.length-1],S=Object.entries(n).filter(([,_])=>!!_),N=S.find(([,_])=>_===w);if(N){v.preventDefault(),h(),t(N[0]);return}if(S.some(([,_])=>_.startsWith(`${w} `))){v.preventDefault(),p.current.parts=C,y();return}const R=S.find(([,_])=>_===g);if(R){v.preventDefault(),h(),t(R[0]);return}if(S.some(([,_])=>_.startsWith(`${g} `))){v.preventDefault(),p.current.parts=[g],y();return}h()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[n,y,e,u,t,h,o]),l.useEffect(()=>()=>h(),[h]);const x=l.useMemo(()=>Yp(r),[r]);return{isMac:r,actionDefinitions:x,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:m}}function gj({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 Xp(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Pc({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!Xp(n):!0}function yj({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:Xp(r)}const Qp=1e3,vj=4;function Dc(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function $c(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function wj({detachDelayMs:e=Qp,stillnessThresholdPx:t=vj,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},y=()=>{m(),o=null,i=null,c=null,d=null,u=!1},x=()=>{!o||!c||!d||u||p!=null||(p=n(()=>{p=null,!(!o||!c||!d||u)&&Dc(d,i)&&($c(c,d,t)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},f=k=>{if(!(!o||u)){if(!Dc(k,i)){d={clientX:k.clientX,clientY:k.clientY},h();return}(!c||$c(c,k,t))&&(m(),c={clientX:k.clientX,clientY:k.clientY}),d={clientX:k.clientX,clientY:k.clientY},x()}},v=k=>{!o||u||(k&&(d={clientX:k.clientX,clientY:k.clientY}),h())};return{startDrag:k=>{m(),o=k.panelId,i=k.selfPanelBounds??null,c=null,d={clientX:k.clientX,clientY:k.clientY},u=!1},markSelfPanel:f,markNonSelfPanel:v,markNoDropTarget:v,markDockTarget:v,endDrag:y,isDragging:()=>o!=null,hasDetached:()=>u,dispose:y}}function jj(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Gn(e){return ft(e)||e.tabKey}function kj(e){return`remote:${e}`}function Zt(e){return e.startsWith("remote:")}function Ec(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function fo(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 xo(e,t){e.classList.remove(Do.className,$o.className),e.classList.add(t==="light"?Do.className:$o.className)}function Bc(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 Nj(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:Gn(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 Fc(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!==Gn(a)&&o.api.setTitle(Gn(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:Gn(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 Oc(e,t,r){var d,p;const n=r?kj(r):null;for(const u of[...e.panels])Zt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=ns(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),i=Qu(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 Zp({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?bt.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=bt.onStatus)==null?void 0:u.call(bt,(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?bt.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?bt.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 em=l.createContext(null);function Ta(){const e=l.useContext(em);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Sj(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 Cj({params:e}){var d;const t=Ta(),r=l.useMemo(()=>ns([...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}=Zp({doId:a,targetSessionId:r?Au(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(Qd,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot: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 Ij(){const e=Ta();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Qi,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Aj(e){var b,j;Sj(e);const t=Ta(),r=l.useCallback(C=>{"button"in C&&C.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(C=>py(C),[]),i=l.useCallback(()=>uy(a),[a]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const C=ns([...t.conversationsByTabKey.values()],e.params.routeId),w=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,g=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${w?" is-active":""}${g?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(C==null?void 0:C.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:C!=null&&C.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:C.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=((j=e.api.group.activePanel)==null?void 0:j.id)===e.api.id,u=e.api.isGroupActive,m=ja(d,t.liveSessionInboxState,{isOpenConversation:p}),h=m.isReconnecting,y=m.isConnecting,x=m.isGenerating||c,f=m.isWaiting,v=m.unread,k=t.tabShortcuts[d.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${u?" is-group-active":""}${h?" is-reconnecting":""}`,title:ft(d),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:C=>{var w;C.preventDefault(),r(C),t.openTabContextMenu({x:C.clientX,y:C.clientY,tabKey:d.tabKey,sourceDocument:((w=C.target)==null?void 0:w.ownerDocument)??document})},children:[v&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:x?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:"○"}):y?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:ft(d)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:h?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Ws(d)}):y?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Ws(d)}):s.jsx("span",{children:Ws(d)})})]}),k&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:k,children:k})]})}function Tn(e){return e.isActive}function Hc(e){return e.isVisible}function Mj(e){e.preventDefault()}function _j({params:e,api:t}){var y;const r=Ta(),n=l.useRef(null),[a,o]=l.useState(()=>Tn(t)),[i,c]=l.useState(()=>Hc(t)),d=r.conversationsByTabKey.get(e.tabKey),p=Aa({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});l.useEffect(()=>{o(Tn(t)),c(Hc(t));const x=[t.onDidActiveChange(f=>o(f.isActive)),t.onDidActiveGroupChange(f=>{if(!Tn(t)&&!f.isActive){o(!1);return}o(Tn(t))}),t.onDidVisibilityChange(f=>c(f.isVisible))];return()=>{for(const f of x)f.dispose()}},[t]);const u=l.useMemo(()=>d?r.ides.find(x=>x.id===d.routeId):void 0,[r.ides,d]),m=l.useMemo(()=>d?r.actionLogs.filter(x=>x.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(Qi,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const h=!it(d)&&Nr(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(Ji,{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:((y=r.scrollToBottomRequest)==null?void 0:y.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:i})})}function Tj({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:y,onOpenNewSession:x,onRequestScrollToBottom:f,requestedActiveTabKey:v,requestedRemoteIdeId:k,onRequestedActiveTabConsumed:b,scrollToBottomRequest:j,liveSessionInboxState:C,layoutProfile:w}){var nt,Qe,Lt;const{theme:g}=Ts(),{sendCommand:S}=xt(),N=l.useRef(null),I=l.useRef(null),R=l.useRef(null),L=l.useRef(!1),_=l.useRef(!1),P=l.useRef(!1),B=l.useRef(null),Y=l.useRef([]),[M,H]=l.useState(null),[q,A]=l.useState(0),$=l.useRef(typeof window>"u"?{}:Jv(w)),T=l.useMemo(()=>new Map(e.map(X=>[X.tabKey,X])),[e]),F=l.useMemo(()=>{const X=N.current;return X?X.groups.some(ee=>{try{const ne=ee.model.location.type;return ne!=="floating"&&ne!=="popout"?!1:ee.panels.some(ie=>T.has(ie.id))}catch{return!1}}):!1},[T,q,e]),z=l.useCallback(()=>{var X;(X=N.current)==null||X.focus()},[]),U=l.useCallback((X,ee)=>{f==null||f(X,ee)},[f]),te=l.useCallback(X=>{const ee=document,ne=X.document;for(const Ce of ee.querySelectorAll('link[rel="stylesheet"]')){const Re=ne.createElement("link");Re.rel="stylesheet",Re.href=Ce.href,Ce.crossOrigin&&(Re.crossOrigin=Ce.crossOrigin),ne.head.appendChild(Re)}for(const Ce of ee.querySelectorAll("style")){const Re=ne.createElement("style");Re.textContent=Ce.textContent,ne.head.appendChild(Re)}const ie=[];for(const Ce of ee.styleSheets)try{for(const Re of Ce.cssRules)Re instanceof CSSStyleRule&&(Re.selectorText===":root"||Re.selectorText==="html")&&ie.push(Re.cssText)}catch{}if(ie.length>0){const Ce=ne.createElement("style");Ce.textContent=ie.join(`
66
- `),ne.head.appendChild(Ce)}const xe=ee.documentElement.getAttribute("data-theme");xe&&ne.documentElement.setAttribute("data-theme",xe),ne.documentElement.style.colorScheme=xe==="light"?"light":"dark",ne.body.className=ee.body.className;const Ae=ee.documentElement.getAttribute("style");Ae&&ne.documentElement.setAttribute("style",Ae);const De=ne.getElementById("dv-popout-window");De instanceof HTMLElement&&(De.classList.add("adhdev-dockview"),xo(De,g))},[g]),Z=l.useCallback(()=>{var ee;const X=N.current;if(X)for(const ne of X.groups)try{const ie=(ee=ne.element)==null?void 0:ee.ownerDocument;if(!ie||ie===document)continue;const xe=ie.getElementById("dv-popout-window");xe instanceof HTMLElement&&(xe.classList.add("adhdev-dockview"),xo(xe,g));const Ae=document.documentElement.getAttribute("data-theme");Ae&&ie.documentElement.setAttribute("data-theme",Ae),ie.documentElement.style.colorScheme=Ae==="light"?"light":"dark",ie.body.className=document.body.className;const De=document.documentElement.getAttribute("style");De?ie.documentElement.setAttribute("style",De):ie.documentElement.removeAttribute("style")}catch{}},[g]),se=l.useCallback(X=>{const ee=N.current;if(!ee)return;const ne=ee.getPanel(X);ne&&ee.addPopoutGroup(ne,{popoutUrl:"/popout.html",onDidOpen:({window:ie})=>{te(ie),we();const xe=T.get(X);ie.document.title=xe?`${ft(xe)} — ADHDev`:"ADHDev — Popout"}})},[T,te]),G=l.useCallback(X=>{const ee=N.current,ne=ee==null?void 0:ee.getPanel(X);if(!ee||!ne)return;const ie=ee.groups.filter(xe=>{var Ae;try{return((Ae=xe.element)==null?void 0:Ae.ownerDocument)===document}catch{return!0}});ie.length>0?ne.api.moveTo({group:ie[0],position:"center"}):ne.api.moveTo({position:"center"}),ne.api.setActive()},[]),O=l.useCallback(X=>{var ie;const ee=N.current;if(!ee)return!1;const ne=ee.getPanel(X);if(!ne)return!1;try{return((ie=ne.group.element)==null?void 0:ie.ownerDocument)!==document}catch{return!1}},[]),V=l.useCallback(X=>{O(X)&&G(X),u(X)},[O,G,u]),pe=l.useCallback(X=>{const ee=N.current,ne=ee==null?void 0:ee.getPanel(X);!ee||!ne||ee.addFloatingGroup(ne,{width:600,height:500})},[]),fe=l.useCallback(X=>{var ne;const ee=(ne=N.current)==null?void 0:ne.getPanel(X);if(!ee)return!1;try{return ee.group.model.location.type==="floating"}catch{return!1}},[]),de=l.useCallback(()=>{var ee,ne;const X=(ne=(ee=N.current)==null?void 0:ee.activePanel)==null?void 0:ne.id;return!X||Zt(X)?null:T.has(X)?X:null},[T]),ke=l.useCallback(X=>{const ee=N.current,ne=ee==null?void 0:ee.getPanel(X);if(!ee||!ne)return;const ie=ee.groups.filter(xe=>{try{return xe.model.location.type==="grid"}catch{return!0}});ie.length>0?ne.api.moveTo({group:ie[0],position:"center"}):ne.api.moveTo({position:"center"}),ne.api.setActive()},[]),ye=l.useCallback(()=>{var Ae;const X=N.current;if(!X)return;const ne=X.groups.filter(De=>{var Ce;try{return((Ce=De.element)==null?void 0:Ce.ownerDocument)===document&&De.model.location.type==="grid"}catch{return!1}})[0]||null,ie=[...X.panels];for(const De of ie){const Ce=(Ae=De.group.element)==null?void 0:Ae.ownerDocument,Re=De.group.model.location.type;Ce===document&&Re==="grid"||(ne&&ne.id!==De.group.id?De.api.moveTo({group:ne,position:"center"}):De.api.moveTo({position:"center"}))}const xe=X.activePanel;xe&&(xe.group.model.openPanel(xe),xe.api.setActive()),fo(document)},[]),we=l.useCallback(()=>{var ee,ne;const X=N.current;if(X)for(const ie of X.groups){const xe=(ee=ie.element)==null?void 0:ee.ownerDocument;if(!xe||xe===document)continue;const Ae=xe.getElementById("dv-popout-window");if(!(Ae instanceof HTMLElement))continue;let De=null,Ce=xe.title||"ADHDev",Re="Popout workspace";const He=ie.activePanel;if(He)if(De=He.id,Zt(He.id)){const ce=((ne=He.params)==null?void 0:ne.routeId)||He.id.slice(7),ge=ns([...T.values()],ce);Ce=Qu(ge),Re=ge!=null&&ge.machineName?`Remote view · ${ge.machineName}`:"Remote view"}else{const ce=T.get(He.id);Ce=ce?ft(ce):He.title||He.id,Re=ce?Ws(ce):"Dockview panel"}xe.title=`${Ce} — ADHDev`;const Xe=Array.from(xe.querySelectorAll("#adhdev-popout-header"));for(const ce of Xe)ce.remove();const Oe=xe.createElement("div");Oe.id="adhdev-popout-header",xe.body.appendChild(Oe),Oe.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(";")),Oe.innerHTML=`
67
- <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
68
- <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
69
- <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Ec(Ce)}</div>
70
- <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Ec(Re)}</div>
71
- </div>
72
- <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
73
- <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>
74
- <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>
75
- </div>
76
- `,Ae.style.top="52px",Ae.style.height="calc(100% - 52px)";const Ue=Oe.querySelector("[data-adhdev-popout-focus]");Ue&&(Ue.onclick=()=>{window.focus()});const ae=Oe.querySelector("[data-adhdev-popout-dock]");ae&&(ae.disabled=!De,ae.style.opacity=De?"1":"0.5",ae.style.cursor=De?"pointer":"default",ae.onclick=()=>{var ce;De&&G(De),(ce=xe.defaultView)==null||ce.focus()})}},[T,G]),he=l.useCallback(X=>{var ie;const ee=N.current,ne=ee==null?void 0:ee.getPanel(X);if(!(!ee||!ne)){ne.group.model.openPanel(ne),ne.api.setActive(),U(X,"dockview-shortcut");try{const xe=ne.group.model.location;xe.type==="popout"?xe.getWindow().focus():fo((ie=ne.group.element)==null?void 0:ie.ownerDocument)}catch{}}},[U]),K=l.useCallback(X=>{const ee=N.current,ne=ee==null?void 0:ee.activePanel,ie=(ee==null?void 0:ee.activeGroup)||(ne==null?void 0:ne.group);if(!ee||!ne||!ie)return;const xe=ie.panels||[];if(xe.length<=1)return;const Ae=xe.findIndex(Re=>Re.id===ne.id);if(Ae<0)return;const De=(Ae+X+xe.length)%xe.length,Ce=xe[De];Ce&&(Ce.group.model.openPanel(Ce),Ce.api.setActive(),Zt(Ce.id)||U(Ce.id,"dockview-shortcut"))},[U]),E=l.useCallback(X=>{var Ue;const ee=N.current,ne=(ee==null?void 0:ee.activeGroup)||((Ue=ee==null?void 0:ee.activePanel)==null?void 0:Ue.group);if(!ee||!ne)return;const ie=ee.groups||[],xe=ie.find(ae=>ae.id===ne.id);if(!xe)return;const Ae=xe.element.getBoundingClientRect(),De=Ae.left+Ae.width/2,Ce=Ae.top+Ae.height/2,Re=(ae,ce,ge,$e)=>Math.max(0,Math.min(ce,$e)-Math.max(ae,ge)),He=ae=>{const ce=ae.element.getBoundingClientRect(),ge=ce.left+ce.width/2,$e=ce.top+ce.height/2;let Fe=0,Ye=0,Ze=0,rt=!1;if(X==="left"?(rt=ge<De,Fe=Math.max(0,Ae.left-ce.right),Ye=Math.abs($e-Ce),Ze=Re(Ae.top,Ae.bottom,ce.top,ce.bottom)):X==="right"?(rt=ge>De,Fe=Math.max(0,ce.left-Ae.right),Ye=Math.abs($e-Ce),Ze=Re(Ae.top,Ae.bottom,ce.top,ce.bottom)):X==="above"?(rt=$e<Ce,Fe=Math.max(0,Ae.top-ce.bottom),Ye=Math.abs(ge-De),Ze=Re(Ae.left,Ae.right,ce.left,ce.right)):(rt=$e>Ce,Fe=Math.max(0,ce.top-Ae.bottom),Ye=Math.abs(ge-De),Ze=Re(Ae.left,Ae.right,ce.left,ce.right)),!rt)return Number.POSITIVE_INFINITY;const Ge=Ze>0?0:120;return Fe*3+Ye+Ge};let Xe=null,Oe=Number.POSITIVE_INFINITY;for(const ae of ie){if(ae.id===xe.id)continue;const ce=He(ae);Number.isFinite(ce)&&(ce>=Oe||(Oe=ce,Xe=ae))}return Xe||void 0},[]),J=l.useCallback(X=>{var ie;const ee=E(X);if(!ee)return;const ne=ee.activePanel||ee.panels[0];ne&&(ee.model.openPanel(ne),ne.api.setActive(),Zt(ne.id)||U(ne.id,"dockview-focus"),fo((ie=ee.element)==null?void 0:ie.ownerDocument))},[E,U]),re=l.useCallback((X,ee)=>{const ne=N.current,ie=ne==null?void 0:ne.activePanel,xe=(ne==null?void 0:ne.activeGroup)||(ie==null?void 0:ie.group);if(!ne||!ie||!xe)return;let Ae=E(X);!Ae&&(ee!=null&&ee.createGroupIfMissing)&&(Ae=ne.addGroup({referenceGroup:xe,direction:X})),Ae&&(ie.api.moveTo({group:Ae,position:"center"}),ie.group.model.openPanel(ie),ie.api.setActive(),Zt(ie.id)||U(ie.id,ee!=null&&ee.createGroupIfMissing?"dockview-split":"dockview-move"))},[E,U]),{isMac:be,tabShortcuts:ue,shortcutListening:D,setShortcutListening:me,saveShortcuts:Se}=Vp({sortedTabKeys:e.map(X=>X.tabKey),onFocus:z,onSelectTab:he}),oe=l.useCallback(()=>{var ne;const X=N.current;if(!X)return;const ee=X.activePanel;if(ee){if(Zt(ee.id)){const ie=((ne=ee.params)==null?void 0:ne.routeId)||ee.id.slice(7),xe=ns(e,ie);xe!=null&&xe.tabKey&&me(xe.tabKey);return}T.has(ee.id)&&me(ee.id)}},[T,he,me,e]),Q=l.useCallback(X=>{const ee=[];return X.metaKey&&ee.push(be?"⌘":"Meta"),X.ctrlKey&&ee.push("Ctrl"),X.altKey&&ee.push(be?"⌥":"Alt"),X.shiftKey&&X.key.length!==1&&ee.push(be?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(X.key)?null:(ee.push(Jp(X.key)),ee.join("+"))},[be]),ve=l.useCallback(X=>{var ee,ne;switch(X){case"splitActiveTabRight":re("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":re("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const ie=de();ie&&pe(ie);return}case"popoutActiveTab":{const ie=de();ie&&se(ie);return}case"dockActiveTab":{const ie=de();if(!ie)return;O(ie)?G(ie):fe(ie)&&ke(ie);return}case"focusLeftPane":J("left");return;case"focusRightPane":J("right");return;case"focusUpPane":J("above");return;case"focusDownPane":J("below");return;case"moveActiveTabToLeftPane":re("left");return;case"moveActiveTabToRightPane":re("right");return;case"moveActiveTabToUpPane":re("above");return;case"moveActiveTabToDownPane":re("below");return;case"selectPreviousGroupTab":K(-1);return;case"selectNextGroupTab":K(1);return;case"setActiveTabShortcut":oe();return;case"hideCurrentTab":{const ie=(ne=(ee=N.current)==null?void 0:ee.activePanel)==null?void 0:ne.id;ie&&!Zt(ie)&&V(ie);return}default:return}},[K,ke,J,pe,de,V,fe,O,G,re,se,oe]);l.useEffect(()=>{if(!M)return;const X=M.sourceDocument,ee=X.defaultView??window,ne=ie=>{const xe=X.querySelector("[data-dockview-tab-context-menu]");xe&&xe.contains(ie.target)||H(null)};return ee.addEventListener("mousedown",ne,!0),ee!==window&&window.addEventListener("mousedown",()=>H(null),!0),()=>{ee.removeEventListener("mousedown",ne,!0),ee!==window&&window.removeEventListener("mousedown",()=>H(null),!0)}},[M]);const Ne=l.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:T,hasDetachedConversationPanels:F,ides:r,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:x,liveSessionInboxState:C,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:V,userName:p,scrollToBottomRequest:j,tabShortcuts:ue,openTabContextMenu:({x:X,y:ee,tabKey:ne,sourceDocument:ie})=>H({x:X,y:ee,tabKey:ne,sourceDocument:ie??document}),popoutTab:se,moveTabBackToMain:G,isTabInPopout:O,floatTab:pe,isTabFloating:fe}),[n,t,T,F,r,i,c,x,C,a,o,V,p,j,ue,se,G,O,pe,fe]),Le=M?gj({isTabInPopout:O(M.tabKey),isTabFloating:fe(M.tabKey),tabShortcut:ue[M.tabKey],actionShortcuts:m}):[],We=l.useCallback(X=>{var ie;const ee=N.current;if((((ie=ee==null?void 0:ee.activePanel)==null?void 0:ie.id)??null)===X.id){X.group.model.openPanel(X);return}X.group.model.openPanel(X),X.api.setActive()},[]),le=l.useCallback((X,ee="requested-tab")=>{if(!X)return!1;const ne=N.current;if(!ne)return!1;const ie=ne.getPanel(X);return ie?(We(ie),U(X,ee),b==null||b(),!0):!1},[We,b,U]),Ee=l.useCallback(()=>{if(P.current)return!1;const X=le(B.current,"stored-layout-restore");return X&&(P.current=!0),X},[le]),Be=l.useCallback(()=>{var ee;const X=N.current;X&&Yv(w,{activeTabId:((ee=X.activePanel)==null?void 0:ee.id)??null,layout:X.toJSON()})},[w]),Je=l.useCallback(()=>{Xv(w,$.current)},[w]),qe=l.useCallback(X=>{var ie,xe,Ae,De;const ee=N.current;if(!ee)return{kind:"grid"};const ne=ee.toJSON();for(const Ce of ne.floatingGroups||[])if((xe=(ie=Ce.data)==null?void 0:ie.views)!=null&&xe.includes(X)&&Ce.position)return{kind:"floating",position:Ce.position};for(const Ce of ne.popoutGroups||[])if((De=(Ae=Ce.data)==null?void 0:Ae.views)!=null&&De.includes(X))return{kind:"popout",position:Ce.position,popoutUrl:Ce.url};return{kind:"grid"}},[]),je=l.useCallback(X=>{const ee=N.current;if(!ee)return;const ne=ee.getPanel(X),ie=$.current[X];if(!ne||!ie||ie.kind==="grid")return;if(ne.group.model.location.type===ie.kind){delete $.current[X],Je();return}if(ie.kind==="floating"){ee.addFloatingGroup(ne,{x:ie.position.left??24,y:ie.position.top??24,width:ie.position.width,height:ie.position.height}),delete $.current[X],Je();return}delete $.current[X],Je()},[Je]);l.useEffect(()=>(h==null||h({setShortcutForActiveTab:oe,restoreHiddenTabToSavedLocation:je,activateConversationTab:he,resetAllPanelsToMain:ye,activatePreviousTabInGroup:()=>K(-1),activateNextTabInGroup:()=>K(1),floatActiveTab:()=>{const X=de();X&&pe(X)},popoutActiveTab:()=>{const X=de();X&&se(X)},dockActiveTab:()=>{const X=de();X&&(O(X)?G(X):fe(X)&&ke(X))},splitActiveTabRight:()=>re("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>re("below",{createGroupIfMissing:!0}),focusLeftPane:()=>J("left"),focusRightPane:()=>J("right"),focusUpPane:()=>J("above"),focusDownPane:()=>J("below"),moveActiveTabToLeftPane:()=>re("left"),moveActiveTabToRightPane:()=>re("right"),moveActiveTabToUpPane:()=>re("above"),moveActiveTabToDownPane:()=>re("below")}),()=>h==null?void 0:h(null)),[K,ke,pe,J,de,fe,O,re,G,se,h,ye,je,he,oe]),l.useEffect(()=>()=>{var X;(X=R.current)==null||X.call(R),R.current=null},[]);const at=l.useCallback(X=>{var ne,ie;N.current=X.api,(ne=R.current)==null||ne.call(R),R.current=null;const ee=qv(w);if(B.current=(ee==null?void 0:ee.activeTabId)??null,ee!=null&&ee.layout&&X.api.fromJSON(ee.layout,{reuseExistingPanels:!1}),_.current=Pc({hasStoredLayout:!!(ee!=null&&ee.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),_.current||(Fc(X.api,e),Oc(X.api,e,k)),X.api.totalPanels===0&&e.length>0){const xe=Nj(X.api,e,v);if(xe){const Ae=X.api.getPanel(xe);Ae&&We(Ae)}}else!_.current&&!le(v)&&Ee();if(L.current=!0,X.api.onDidActivePanelChange(xe=>{var De;if(B.current=(xe==null?void 0:xe.id)??null,P.current=!0,we(),xe&&Zt(xe.id)){const Ce=((De=xe.params)==null?void 0:De.routeId)||xe.id.slice(7),Re=ns(e,Ce);y((Re==null?void 0:Re.tabKey)??null),Be();return}if(y((xe==null?void 0:xe.id)??null),Be(),!xe)return;const Ae=T.get(xe.id);(Ae==null?void 0:Ae.streamSource)==="agent-stream"&&Ae.agentType&&S(Ae.routeId,Mu(),{agentType:Ae.agentType,...Ae.sessionId&&{targetSessionId:Ae.sessionId}}).catch(()=>{})}),X.api.onDidLayoutChange(()=>{Be(),we(),A(xe=>xe+1)}),jj()){const xe=Oe=>({clientX:Oe.clientX,clientY:Oe.clientY}),Ae=Oe=>{const Ue=Oe==null?void 0:Oe.getBoundingClientRect();return Ue?{left:Ue.left,right:Ue.right,top:Ue.top,bottom:Ue.bottom}:null},De=Oe=>{var ae;const Ue=(ae=I.current)==null?void 0:ae.getBoundingClientRect();return Ue?Oe.clientX<Ue.left||Oe.clientX>Ue.right||Oe.clientY<Ue.top||Oe.clientY>Ue.bottom:!1},Ce=wj({detachDelayMs:Qp,onDetach:({panelId:Oe,clientX:Ue,clientY:ae})=>{var Ze,rt;const ce=X.api.getPanel(Oe);if(!ce)return;try{if(ce.group.model.location.type!=="grid")return}catch{return}const ge=(Ze=I.current)==null?void 0:Ze.getBoundingClientRect(),$e=(rt=ce.group.element)==null?void 0:rt.getBoundingClientRect(),Fe=Math.round(Math.min(Math.max(($e==null?void 0:$e.width)??600,360),720)),Ye=Math.round(Math.min(Math.max(($e==null?void 0:$e.height)??500,260),640));X.api.addFloatingGroup(ce,{x:ge?Math.max(0,Ue-ge.left-32):void 0,y:ge?Math.max(0,ae-ge.top-18):void 0,width:Fe,height:Ye}),ce.api.setActive(),Be(),we(),A(Ge=>Ge+1)}}),Re=[X.api.onWillDragPanel(Oe=>{if(!(Oe.nativeEvent.defaultPrevented||Oe.nativeEvent.shiftKey)){try{if(Oe.panel.group.model.location.type!=="grid")return}catch{return}Ce.startDrag({panelId:Oe.panel.id,selfPanelBounds:Ae(Oe.panel.group.element),...xe(Oe.nativeEvent)})}}),X.api.onWillShowOverlay(Oe=>{if(Ce.hasDetached()){Oe.preventDefault();return}Ce.markDockTarget(xe(Oe.nativeEvent))}),X.api.onWillDrop(Oe=>{if(Ce.hasDetached()){Oe.preventDefault(),Ce.endDrag();return}Ce.markDockTarget(xe(Oe.nativeEvent))}),X.api.onDidDrop(()=>Ce.endDrag()),X.api.onUnhandledDragOverEvent(Oe=>{Ce.isDragging()&&Ce.markSelfPanel(xe(Oe.nativeEvent))})],He=Oe=>{if(!Ce.isDragging())return;const Ue=xe(Oe);De(Ue)&&Ce.markNonSelfPanel(Ue)},Xe=()=>Ce.endDrag();window.addEventListener("dragover",He,!0),window.addEventListener("drop",Xe,!0),window.addEventListener("dragend",Xe,!0),R.current=()=>{Ce.dispose();for(const Oe of Re)Oe.dispose();window.removeEventListener("dragover",He,!0),window.removeEventListener("drop",Xe,!0),window.removeEventListener("dragend",Xe,!0)}}X.api.onDidAddGroup(xe=>{requestAnimationFrame(()=>{var Ae,De;try{const Ce=(Ae=xe.element)==null?void 0:Ae.ownerDocument;if(!Ce||Ce===document)return;(De=Ce.getElementById("dv-popout-window"))==null||De.classList.add("adhdev-dockview");const Re=document.documentElement.getAttribute("data-theme");Re&&Ce.documentElement.setAttribute("data-theme",Re),Ce.body.className=document.body.className;const He=document.documentElement.getAttribute("style");He&&Ce.documentElement.setAttribute("style",He)}catch{}we(),A(Ce=>Ce+1)})}),y(((ie=X.api.activePanel)==null?void 0:ie.id)??null)},[We,le,T,r,d,w,y,Be,v,k,S,we,e]);l.useLayoutEffect(()=>{const X=N.current;if(!X||!L.current||_.current&&Pc({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;_.current&&(_.current=!1);const ee=Y.current,ne=new Set(ee),ie=e.map(Xe=>Xe.tabKey),xe=new Set(ie),Ae=yj({previousVisibleConversationCount:ee.length,visibleConversationCount:e.length,ides:r});let De=!1;for(const Xe of ee)xe.has(Xe)||Ae||($.current[Xe]=qe(Xe),De=!0);De&&Je(),Ae||(Fc(X,e),Oc(X,e,k));const Ce=ie.filter(Xe=>!ne.has(Xe));let Re=!1;for(const Xe of Ce){const Oe=X.getPanel(Xe),Ue=$.current[Xe];if(!Oe||!Ue||Ue.kind==="grid")continue;if(Oe.group.model.location.type===Ue.kind){delete $.current[Xe],Re=!0;continue}if(Ue.kind==="floating"){X.addFloatingGroup(Oe,{x:Ue.position.left??24,y:Ue.position.top??24,width:Ue.position.width,height:Ue.position.height}),delete $.current[Xe],Re=!0;continue}}if(Re&&Je(),Y.current=ie,v&&le(v))return;!X.activePanel&&X.panels[0]&&We(X.panels[0]),!!(X.activePanel&&X.getPanel(X.activePanel.id))||Ee()},[We,le,Ee,r,d,Je,qe,v,k,e]),l.useEffect(()=>{L.current&&le(v)},[le,v]),l.useEffect(()=>{const X=ne=>{const ie=ne.target;if(!ie)return;const xe=ie.querySelector("[data-tab-key]")||ie.closest("[data-tab-key]");if(xe){const Ae=xe.getAttribute("data-tab-key");if(Ae&&ne.dataTransfer){const De=ie.closest(".dv-tab")||xe.closest(".dv-tab")||xe;ne.dataTransfer.effectAllowed="move",ne.dataTransfer.setData("text/tab-key",Ae),De instanceof HTMLElement&&ne.dataTransfer.setDragImage(De,Math.max(12,Math.round(De.clientWidth/2)),Math.max(10,Math.round(De.clientHeight/2)))}}};window.addEventListener("dragstart",X);const ee=Bc(N.current);for(const ne of ee)ne.addEventListener("dragstart",X);return()=>{window.removeEventListener("dragstart",X);for(const ne of ee)ne.removeEventListener("dragstart",X)}},[q]),l.useEffect(()=>{var ee;const X=(ee=I.current)==null?void 0:ee.querySelector(".adhdev-dockview");X instanceof HTMLElement&&xo(X,g),Z(),we()},[we,Z,g]),l.useEffect(()=>{we()},[we]),l.useEffect(()=>{const X=ee=>{if(ee.defaultPrevented||D)return;const ne=Q(ee);if(!ne)return;const ie=ee.metaKey||ee.ctrlKey||ee.altKey;oi(ee.target)&&!ie||fa(be).setActiveTabShortcut!==ne||(ee.preventDefault(),ee.stopPropagation(),oe())};return window.addEventListener("keydown",X,!0),()=>window.removeEventListener("keydown",X,!0)},[Q,be,D,oe]),l.useEffect(()=>{const X=I.current;if(!X)return;const ee=ne=>{var Ce,Re;if(!ne.isTrusted)return;const ie=(Re=(Ce=ne.target)==null?void 0:Ce.closest)==null?void 0:Re.call(Ce,".dv-scrollable");if(!ie)return;ne.preventDefault(),ne.stopPropagation();const xe=Math.abs(ne.deltaX),Ae=Math.abs(ne.deltaY),De=xe>Ae?ne.deltaX:ne.deltaY;ie.dispatchEvent(new WheelEvent("wheel",{deltaY:De,deltaMode:ne.deltaMode,bubbles:!1,cancelable:!0}))};return X.addEventListener("wheel",ee,{passive:!1,capture:!0}),()=>X.removeEventListener("wheel",ee,{capture:!0})},[]),l.useEffect(()=>{const X=Bc(N.current);if(X.length===0)return;const ee=X.map(ne=>{let ie=[],xe=null;const Ae=()=>{xe!=null&&ne.clearTimeout(xe),xe=null,ie=[]},De=()=>{xe!=null&&ne.clearTimeout(xe),xe=ne.setTimeout(()=>{xe=null,ie=[]},1200)},Ce=He=>{if(!He.ctrlKey&&!He.metaKey&&!He.altKey)return;const Xe=Q(He);if(!Xe)return;const Oe=Gp();for(const[Ue,ae]of Object.entries(Oe))if(e.some(ce=>ce.tabKey===Ue)&&ae===Xe){He.preventDefault(),he(Ue);return}},Re=He=>{if(He.defaultPrevented||D)return;const Xe=Q(He);if(!Xe)return;const Oe=He.metaKey||He.ctrlKey||He.altKey;if(oi(He.target))return;const Ue=fa(be),ae=Object.entries(Ue).filter(([Ge,Nt])=>!!Nt&&(Ge==="splitActiveTabRight"||Ge==="splitActiveTabDown"||Ge==="floatActiveTab"||Ge==="popoutActiveTab"||Ge==="dockActiveTab"||Ge==="focusLeftPane"||Ge==="focusRightPane"||Ge==="focusUpPane"||Ge==="focusDownPane"||Ge==="moveActiveTabToLeftPane"||Ge==="moveActiveTabToRightPane"||Ge==="moveActiveTabToUpPane"||Ge==="moveActiveTabToDownPane"||Ge==="selectPreviousGroupTab"||Ge==="selectNextGroupTab"||Ge==="setActiveTabShortcut"||Ge==="hideCurrentTab")),ce=Oe?[Xe]:[...ie.slice(-1),Xe].slice(-2),ge=ce.join(" "),$e=ce[ce.length-1],Fe=ae.find(([,Ge])=>Ge===ge);if(Fe){He.preventDefault(),Ae(),ve(Fe[0]);return}if(ae.some(([,Ge])=>Ge.startsWith(`${ge} `))){He.preventDefault(),ie=ce,De();return}const Ze=ae.find(([,Ge])=>Ge===$e);if(Ze){He.preventDefault(),Ae(),ve(Ze[0]);return}if(ae.some(([,Ge])=>Ge.startsWith(`${$e} `))){He.preventDefault(),ie=[$e],De();return}Ae()};return ne.addEventListener("keydown",Ce),ne.addEventListener("keydown",Re),()=>{Ae(),ne.removeEventListener("keydown",Ce),ne.removeEventListener("keydown",Re)}});return()=>{for(const ne of ee)ne()}},[Q,be,q,he,D,ve,e]);const Ie=g==="light"?Do:$o,ot=((Lt=(Qe=(nt=N.current)==null?void 0:nt.activePanel)==null?void 0:Qe.group.element)==null?void 0:Lt.ownerDocument)??document;return s.jsxs(em.Provider,{value:Ne,children:[s.jsx("div",{ref:I,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(mh,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:_j,remote:Cj},defaultTabComponent:Aj,watermarkComponent:Ij,onReady:at,singleTabMode:"default",tabAnimation:"smooth",theme:Ie,popoutUrl:"/popout.html"})}),M&&ur.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[var(--z-popover)] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:M.x,top:M.y},children:Le.map(X=>{if(X.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},X.id);let ee=s.jsx(Ef,{size:13,className:"shrink-0 opacity-70"}),ne=()=>{};switch(X.id){case"dockInWindow":case"dockBackToGrid":ee=s.jsx(Ff,{size:13,className:"shrink-0 opacity-70"}),ne=()=>{ke(M.tabKey),H(null)};break;case"moveBackToMain":ee=s.jsx($f,{size:13,className:"shrink-0 opacity-70"}),ne=()=>{G(M.tabKey),H(null)};break;case"floatAsPanel":ee=s.jsx(Bf,{size:13,className:"shrink-0 opacity-70"}),ne=()=>{pe(M.tabKey),H(null)};break;case"openInNewWindow":ee=s.jsx(Df,{size:13,className:"shrink-0 opacity-70"}),ne=()=>{se(M.tabKey),H(null)};break;case"setShortcut":ne=ie=>{ie.stopPropagation(),me(M.tabKey),H(null)};break;case"removeShortcut":ee=s.jsx(wt,{size:13,className:"shrink-0 opacity-70"}),ne=()=>{const ie={...ue};delete ie[M.tabKey],Se(ie),H(null)};break;case"hideTab":ee=s.jsx(vi,{size:13,className:"shrink-0 opacity-70"}),ne=()=>{V(M.tabKey),H(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 ${X.tone==="muted"?"text-text-muted":""}`,onMouseDown:Mj,onClick:ne,children:[ee,s.jsx("span",{className:"flex-1 min-w-0",children:X.label}),X.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:X.shortcut}):null]},X.id)})}),M.sourceDocument.body),D&&ur.createPortal(s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>me(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:X=>X.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. ",be?"⌘+1":"Ctrl+1",", ",be?"⌥+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"})]})}),ot.body)]})}const tm="adhdev-recent-launch-args-v1",Lj=8;function Rj(e){return String(e||"").trim().replace(/\s+/g," ")}function sm(e,t){return`${e.trim()}::${t.trim()}`}function rm(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(tm)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function Pj(e){if(!(typeof window>"u"))try{window.localStorage.setItem(tm,JSON.stringify(e))}catch{}}function Dj(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=rm().byKey[sm(r,n)])==null?void 0:o.items)||[]}function $j(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=Rj(r);if(!n||!a||!o)return;const i=rm(),c=sm(n,a),d=((u=i.byKey[c])==null?void 0:u.items)||[],p=[o,...d.filter(m=>m!==o)].slice(0,Lj);i.byKey[c]={items:p},Pj(i)}function Ej(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Ur({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 Bj({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 Fj({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:i,onOpenHistory:c,onClearSelection:d}){const p=o?Op(o):null,u=Bj({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Ur,{title:"Saved history",description:Fi(),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:c0()})]}),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 nm({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}const bo={cli:"CLI",ide:"IDE",acp:"ACP"};function Oj({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:bo.cli,enabled:r},{id:"ide",label:bo.ide,enabled:n},{id:"acp",label:bo.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 go(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>yr(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>yr(a,"acp"))?"acp":null}function Ln(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Hj({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:p}){var zt,is;const u=Sr(),m=l.useMemo(()=>[...e].sort(Ii),[e]),[h,y]=l.useState(((zt=m[0])==null?void 0:zt.id)||""),x=l.useMemo(()=>m.find(W=>W.id===h)||m[0],[h,m]),f=l.useMemo(()=>((x==null?void 0:x.workspaces)||[]).map(W=>({id:W.id,path:W.path,label:W.label})),[x]),v=(x==null?void 0:x.defaultWorkspaceId)||null,[k,b]=l.useState("workspace"),[j,C]=l.useState(""),[w,g]=l.useState(""),[S,N]=l.useState([]),[I,R]=l.useState(""),[L,_]=l.useState(!1),[P,B]=l.useState(null),[Y,M]=l.useState(""),[H,q]=l.useState(go(m[0])),[A,$]=l.useState(""),[T,F]=l.useState(""),[z,U]=l.useState(""),[te,Z]=l.useState(""),[se,G]=l.useState(!1),[O,V]=l.useState([]),[pe,fe]=l.useState(""),[de,ke]=l.useState([]),[ye,we]=l.useState(!1),[he,K]=l.useState(!1),[E,J]=l.useState(""),[re,be]=l.useState(!1),[ue,D]=l.useState(()=>Dt()),[me,Se]=l.useState(null),[oe,Q]=l.useState(!1),[ve,Ne]=l.useState(""),[Le,We]=l.useState(null),[le,Ee]=l.useState(!1),[Be,Je]=l.useState(""),[qe,je]=l.useState([]),[at,Ie]=l.useState(!1),[ot,nt]=l.useState(""),[Qe,Lt]=l.useState(!1),X=l.useRef(null),ee=l.useRef(0);l.useEffect(()=>{var W;!h&&((W=m[0])!=null&&W.id)&&y(m[0].id)},[h,m]),l.useEffect(()=>{!x||!(!x.workspaces||!x.availableProviders||!x.detectedIdes||!x.recentLaunches)||u(x.id,{minFreshMs:3e4}).catch(()=>{})},[u,x]);const ne=l.useCallback(W=>{W&&u(W,{minFreshMs:3e4}).catch(()=>{})},[u]),ie=l.useMemo(()=>((x==null?void 0:x.availableProviders)||[]).filter(W=>yr(W,"cli")),[x]),xe=l.useMemo(()=>((x==null?void 0:x.availableProviders)||[]).filter(W=>yr(W,"acp")),[x]),Ae=l.useMemo(()=>((x==null?void 0:x.detectedIdes)||[]).map(W=>({id:W.type,label:W.name||W.type,meta:W.running?"Detected locally":"Available to open"})),[x]),De=l.useMemo(()=>H==="cli"?ie.map(W=>({id:W.type,label:W.displayName||W.type,meta:""})):H==="acp"?xe.map(W=>({id:W.type,label:W.displayName||W.type,meta:""})):Ae,[xe,H,ie,Ae]),Ce=l.useMemo(()=>S.find(W=>W.id===I)||null,[S,I]),Re=l.useMemo(()=>ie.find(W=>W.type===A)||null,[ie,A]),He=l.useMemo(()=>[...ie,...xe].find(W=>W.type===A),[ie,xe,A]),Xe=l.useMemo(()=>w0(He?[He]:[],He==null?void 0:He.type),[He]),Oe=l.useMemo(()=>{const W=j0(He?[He]:[],He==null?void 0:He.type);return W.length?W:["low","medium","high"]},[He]),Ue=l.useMemo(()=>Pp(Re==null?void 0:Re.meshCoordinator,{meshId:(Ce==null?void 0:Ce.id)||"",workspace:(Ce==null?void 0:Ce.workspace)||""}),[Re,Ce]),ae=Le||Ue,ce=l.useCallback(async W=>{_(!0),M("");try{const Me=await c(W);N(Me),R(Pe=>{var dt;return Me.some(Et=>Et.id===Pe)?Pe:((dt=Me[0])==null?void 0:dt.id)||""}),B(W)}catch(Me){N([]),R(""),B(W),M(Me instanceof Error?Me.message:"Could not load meshes")}finally{_(!1)}},[c]);l.useEffect(()=>{var Me;if(!x)return;if(X.current!==x.id){X.current=x.id,b("workspace"),C(v||((Me=f[0])==null?void 0:Me.id)||"__home__"),g(""),N([]),R(""),B(null),M(""),q(go(x)),$(""),F(""),U(""),Z(""),G(!1),fe(""),ke([]),K(!1),J(""),D(Dt()),Ne(""),We(null);return}C(Pe=>{var dt;return Pe==="__custom__"||Pe==="__home__"||f.some(Et=>Et.id===Pe)?Pe:v||((dt=f[0])==null?void 0:dt.id)||"__home__"}),q(Pe=>Pe==="ide"&&Ae.length>0||Pe==="cli"&&ie.length>0||Pe==="acp"&&xe.length>0?Pe:go(x))},[xe.length,ie.length,v,Ae.length,x,f]),l.useEffect(()=>{!x||k!=="mesh"||P===x.id||L||ce(x.id)},[ce,P,L,x,k]),l.useEffect(()=>{k==="mesh"&&H!=="cli"&&ie.length>0&&q("cli")},[H,ie.length,k]),l.useEffect(()=>{var W;H&&(De.some(Me=>Me.id===A)||$(((W=De[0])==null?void 0:W.id)||""))},[H,De,A]),l.useEffect(()=>{We(null)},[x==null?void 0:x.id,I,A,k]),l.useEffect(()=>{U(""),Z(""),G(!1)},[A]);const ge=l.useCallback(async(W,Me)=>{const Pe=ee.current+1;return ee.current=Pe,we(!0),J(""),p(W,Me).then(dt=>{ee.current===Pe&&ke(dt)}).catch(dt=>{ee.current===Pe&&(ke([]),J(dt instanceof Error?dt.message:"Could not load saved sessions"))}).finally(()=>{ee.current===Pe&&(we(!1),K(!0))})},[p]),$e=l.useCallback((W,Me)=>{V(Dj(W,Me))},[]);l.useEffect(()=>{ee.current+=1,fe(""),D(Dt()),!x||!A||H==="ide"?V([]):$e(x.id,A),K(!1),ke([]),J(""),we(!1)},[H,$e,ge,x,A]),l.useEffect(()=>{if(!pe)return;const W=de.find(Me=>Me.providerSessionId===pe);W!=null&&W.canResume||fe("")},[de,pe]);const Fe=j==="__custom__"?w.trim():j==="__home__"?"":((is=f.find(W=>W.id===j))==null?void 0:is.path)||"",Ye=l.useMemo(()=>x?t.filter(W=>W.id!==x.id&&W.daemonId===x.id).map(W=>W.workspace):[],[t,x]),Ze=l.useMemo(()=>((x==null?void 0:x.recentLaunches)||[]).map(W=>W.workspace),[x]),rt=l.useCallback(W=>{const Me=String(W.workspace||"").trim();if(!Me)return;const Pe=f.find(dt=>Ln(dt.path)===Ln(Me));if(Pe){C(Pe.id),g("");return}C("__custom__"),g(Me)},[f]),Ge=l.useCallback(W=>{const Me=String(W.workspace||"").trim();if(!Me)return{workspaceId:null,workspacePath:null};const Pe=f.find(dt=>Ln(dt.path)===Ln(Me));return Pe?{workspaceId:Pe.id,workspacePath:null}:{workspaceId:null,workspacePath:Me}},[f]),Nt=l.useMemo(()=>de.find(W=>W.providerSessionId===pe)||null,[de,pe]),Xt=l.useMemo(()=>{var Me;if(H!=="cli"||!x||!A)return null;const W=((Me=ie.find(Pe=>Pe.type===A))==null?void 0:Me.displayName)||A;return{routeId:x.id,daemonId:x.id,providerSessionId:pe||void 0,transport:"pty",mode:"chat",agentName:W,agentType:A,status:"idle",title:W,messages:[],ideType:A,workspaceName:Fe,workspacePath:Fe,displayPrimary:W,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${x.id}:${A}`,machineName:Jt(x,{fallbackId:x.id})}},[H,ie,Fe,x,pe,A]),Ht=l.useCallback(()=>{var Me;if(!x)return;C("__custom__"),Ee(!0),nt("");const W=qi(x.platform,Vi(w.trim(),Fe,Ye,Ze,x.defaultWorkspacePath,(Me=f.find(Pe=>Pe.id===v))==null?void 0:Me.path,f.map(Pe=>Pe.path)));Ie(!0),n(x.id,W).then(Pe=>{Je(Pe.path),g(Pe.path),je(Pe.directories)}).catch(Pe=>{nt(Pe instanceof Error?Pe.message:"Could not load folder")}).finally(()=>Ie(!1))},[w,v,Ze,Ye,n,Fe,x,f]),Te=l.useCallback(W=>{x&&(Ie(!0),nt(""),n(x.id,W).then(Me=>{Je(Me.path),g(Me.path),je(Me.directories)}).catch(Me=>{nt(Me instanceof Error?Me.message:"Could not load folder")}).finally(()=>Ie(!1)))},[n,x]),Ve=l.useCallback(async()=>{if(!x||!Fe)return;Lt(!0),Ne("");const W=await a(x.id,Fe);if(Lt(!1),!W.ok){Ne(W.error||"Could not save workspace");return}Ne("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,Fe,x]),Rt=l.useCallback(async()=>{if(!x)return;if(k==="mesh"){if(!I||!A)return;Q(!0),Ne(""),We(null);const Pe=await d(x.id,I,A,{initialModel:z.trim()?z.trim():null,initialThinkingLevel:te.trim()?te.trim():null});if(Q(!1),!Pe.ok){if(Pe.code==="mesh_coordinator_manual_mcp_setup_required"&&Pe.manualSetup){We(Pe.manualSetup),Ne("Manual MCP setup required before this provider can act as mesh coordinator.");return}Ne(Pe.error||"Could not start mesh coordinator");return}r();return}if(!H||!A)return;Q(!0),Ne("");const W=T.trim()?T.trim().split(/\s+/).filter(Boolean):[],Me=H==="ide"?await o(x.id,A,{workspacePath:Fe||null}):await i(x.id,H,A,{workspaceId:j!=="__home__"&&j!=="__custom__"?j:null,workspacePath:j==="__custom__"&&Fe||null,resumeSessionId:H==="cli"&&pe?pe:null,cliArgs:W,initialModel:z.trim()?z.trim():null,initialThinkingLevel:te.trim()?te.trim():null});if(Q(!1),!Me.ok){Ne(Me.error||"Could not start session");return}H!=="ide"&&T.trim()&&($j(x.id,A,T),$e(x.id,A)),r()},[H,T,z,te,$e,r,o,d,i,Fe,x,I,pe,A,j,k]),jt=k==="mesh"?"Start mesh coordinator":H?o0(H,H==="cli"&&!!pe):"Start",Kt=k==="mesh"?"Starting coordinator…":H?i0(H,H==="cli"&&!!pe):"Starting…",Ut=m.length>5;return x?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] 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.jsx("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("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(wt,{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(Ur,{title:"Machine",children:Ut?s.jsx("select",{"aria-label":"Machine",value:x.id,onChange:W=>y(W.target.value),onFocus:()=>m.forEach(W=>ne(W.id)),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(W=>s.jsx("option",{value:W.id,children:Jt(W,{fallbackId:W.id})},W.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:m.map(W=>{const Me=Jt(W,{fallbackId:W.id}),Pe=x.id===W.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${Me}`,"aria-pressed":Pe,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${Pe?"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:()=>y(W.id),onMouseEnter:()=>ne(W.id),onFocus:()=>ne(W.id),disabled:oe,title:Me,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${W.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:Me})]},W.id)})})}),s.jsxs(Ur,{title:"Workspace",action:k==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ht,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(W=>s.jsxs("button",{type:"button",role:"radio","aria-checked":k===W.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${k===W.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:()=>{b(W.id),Ne(""),W.id==="mesh"&&x&&P!==x.id&&!L&&ce(x.id)},disabled:oe,children:[s.jsx("div",{className:"text-sm font-semibold",children:W.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:W.desc})]},W.id))}),k==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:j,onChange:W=>{const Me=W.target.value;C(Me),Me==="__custom__"?Ht():Ne("")},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(W=>s.jsxs("option",{value:W.id,children:[W.id===v?"⭐ ":"",iu(W.path,W.label)||W.path]},W.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:j==="__home__"?"Launch without a workspace.":Fe||"Select a workspace folder."}),j==="__custom__"&&Fe&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ht,disabled:oe,children:[s.jsx(hr,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ve,disabled:oe||Qe,children:Qe?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[L&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!L&&Y&&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:Y}),!L&&!Y&&S.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."}),S.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:S.map(W=>s.jsxs("button",{type:"button",role:"radio","aria-checked":I===W.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${I===W.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>R(W.id),disabled:oe,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:W.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[W.repoIdentity||"Repo mesh",typeof W.nodesCount=="number"?` · ${W.nodesCount} node${W.nodesCount===1?"":"s"}`:""]}),W.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",W.workspace]})]},W.id))})]})]}),s.jsx(Oj,{workspaceMode:k,activeKind:H,cliEnabled:ie.length>0,ideEnabled:Ae.length>0,acpEnabled:xe.length>0,busy:oe,onSelect:q}),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:H==="ide"?"Choose IDE":H==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[De.map(W=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${A===W.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(W.id),disabled:oe,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:W.label}),W.meta&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:W.meta})]},W.id)),De.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."})]})]}),k==="mesh"&&ae&&s.jsx(nm,{setup:ae,providerName:(Re==null?void 0:Re.displayName)||(Re==null?void 0:Re.name)||A}),k!=="mesh"&&H!=="ide"&&s.jsxs(Ur,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:T,onChange:W=>F(W.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}),O.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:O.map(W=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>F(W),disabled:oe,title:W,children:W},W))})]}),(k==="mesh"&&!!A||k!=="mesh"&&H!=="ide")&&s.jsx(Ur,{title:"Model & thinking (optional)",children:s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Model"}),Xe.length>0&&!se?s.jsxs("select",{value:Xe.includes(z)?z:"",onChange:W=>{W.target.value==="__custom__"?(G(!0),U("")):U(W.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:[s.jsx("option",{value:"",children:"(provider default)"}),Xe.map(W=>s.jsx("option",{value:W,children:W},W)),s.jsx("option",{value:"__custom__",children:"Custom…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:z,onChange:W=>U(W.target.value),placeholder:"Type a model name",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:oe,autoFocus:se}),Xe.length>0&&s.jsx("button",{type:"button",className:"self-start text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{G(!1),U("")},disabled:oe,children:"← Back to model list"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Thinking level"}),s.jsxs("select",{value:te,onChange:W=>Z(W.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:[s.jsx("option",{value:"",children:"(provider default)"}),Oe.map(W=>s.jsx("option",{value:W,children:W},W))]})]})]})}),k!=="mesh"&&H==="cli"&&s.jsx(Fj,{busy:oe,savedSessionsLoading:ye,savedSessionsError:E,selectedSession:Nt,onRefresh:()=>{!x||!A||ge(x.id,A)},onOpenHistory:()=>{!x||!A||(be(!0),Ej({hasLoadedInitialResults:he,isLoading:ye})&&ge(x.id,A))},onClearSelection:()=>fe("")}),ve&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ve.includes("saved")||ve.includes("requested")||ve.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:ve})]}),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:Rt,disabled:oe||(k==="mesh"?!I||!A||H!=="cli"||L:!H||!A||j==="__custom__"&&!Fe),children:[s.jsx(Wd,{size:14}),oe?Kt:jt]})]})]})}),le&&s.jsx(Xi,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:Be,directories:qe,busy:at,error:ot,onClose:()=>Ee(!1),onNavigate:Te,onConfirm:W=>{g(W),Je(W),C("__custom__"),Ee(!1)}}),re&&Xt&&s.jsx(ap,{activeConv:Xt,ides:[],isCreatingChat:!1,isRefreshingHistory:ye,savedSessions:de,isSavedSessionsLoading:ye,isResumingSavedSessionId:me,savedHistoryFilters:ue,missingWorkspaceResumePath:Fe||null,onSavedHistoryFiltersChange:D,onClose:()=>be(!1),onNewChat:()=>{fe(""),be(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!x||!A||ge(x.id,A)},onResumeSavedSession:W=>{if(!x||!A||me||!W.canResume)return;const Me=Ge(W);fe(W.providerSessionId),rt(W),Se(W.providerSessionId),be(!1),Q(!0),Ne(""),i(x.id,"cli",A,{workspaceId:Me.workspaceId,workspacePath:Me.workspacePath,resumeSessionId:W.providerSessionId}).then(Pe=>{if(!Pe.ok){Ne(Pe.error||"Could not resume session");return}r()}).finally(()=>{Q(!1),Se(Pe=>Pe===W.providerSessionId?null:Pe)})}})]}):null}function am(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 Zi(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=am(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 el(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function om(e){var t;return!el(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 Rn(e){return[...new Set(e.filter(t=>!!t))]}function Wj(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?Rn([t==null?void 0:t.id,...n.map(i=>i.id)]):a.length>0?Rn(a.map(i=>i.id)):o.length>0?Rn(o.map(i=>i.id)):Rn(e.nodes.map(i=>i.id))}function im(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 Kj(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${im(e)}::${n}x${a}`}const Uj={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"},zj={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"},Gj={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"},Vj={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 Ls(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-[var(--z-modal-backdrop)] 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=>zj[t],actionButton:t=>Vj[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-[var(--z-modal-backdrop)] 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=>Uj[t],actionButton:t=>Gj[t]}}const vr={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,layerGap:220,nodeGap:82,edgeLabelBuffer:180,placeholderTopOffset:0},hn={worktreeCardWidth:188,submoduleCardWidth:188,minWorktreeCardHeight:88,minSubmoduleCardHeight:88,maxEstimatedCardHeight:178,layerGap:160,nodeGap:52,edgeLabelBuffer:120},qj={maxWidth:180};function Yj(e){return e==="TB"?"DOWN":"RIGHT"}function tl(e,t){return{"elk.algorithm":"layered","elk.direction":Yj(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 Jj=tl(vr,"LR");tl(hn,"LR");function Xj(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 Qj=new hh;function on(e,t=!1){const r=t?hn:vr;return e.type==="submoduleNode"?r.submoduleCardWidth:r.worktreeCardWidth}function Vn(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=am(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 lm(e,t=!1){const r=t?hn:vr,n=on(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(Zj(e)/o),c=Pn(e.label,a,2),d=Pn(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,a,2),p=Pn(Vn(e),a+(t?1:4),t?2:3),u=Zi(e),m=om(e)?el(e):null,h=t?0:Pn(m,Math.max(24,Math.floor(n/8)),4),y=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),x=e.type==="submoduleNode"?r.minSubmoduleCardHeight:r.minWorktreeCardHeight;return Math.min(r.maxEstimatedCardHeight,Math.max(x,Math.ceil(y)))}function Pn(e,t,r){const n=(e||"").trim();return n?Math.max(1,Math.min(r,Math.ceil(n.length/t))):0}function Zj(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 ek(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 tk(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function sk(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 rk(e,t,r){return{id:e.id,x:t,y:r,width:on(e),height:lm(e)}}function nk(e,t){return{id:`${e.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:t.repoIdentity,branch:e.branch,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:null,locality:"unknown",connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null,health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],nextStepHint:"Waiting for worktree nodes to report live mesh status.",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{nodeId:`${e.id}__placeholder`,machineLabel:"",workspace:t.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}}function cm(e){const t=[...e.nodes].sort(ek),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,nk(r,e)]}function ak(e,t=Jj,r=!1,n="LR"){const a=cm(e),o=new Set(a.map(d=>d.id)),i=a.map(d=>({id:d.id,width:on(d,r),height:lm(d,r)})),c=e.edges.filter(d=>o.has(d.source)&&o.has(d.target)).sort(tk).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 ok(e,t=!1){const r=[...new Set(e.map(a=>Math.round(a.x)))].sort((a,o)=>a-o),n=t?hn.layerGap:vr.layerGap;return r.length<2?n:Math.min(...r.slice(1).map((a,o)=>a-r[o]))}async function dm(e,t=!1,r="LR",n){var x,f;const o=tl(t?hn:vr,r),i=cm(e),c=new Map(i.map(v=>[v.id,v])),d=ak(e,o,t,r);if(n&&n.size>0)for(const v of d.children??[]){const k=n.get(v.id);k&&k>0&&(v.height=k)}const p=await Qj.layout(d),u=(p.children??[]).map(v=>{const k=c.get(v.id);return k?sk(k,Math.round(v.x??0),Math.round(v.y??vr.placeholderTopOffset),!v.id.endsWith("__placeholder")):null}).filter(Boolean),m=new Map(i.map((v,k)=>[v.id,k]));u.sort((v,k)=>(m.get(v.id)??0)-(m.get(k.id)??0));const h=u.map(v=>rk(v.graphNode,v.position.x,v.position.y)),y=new Map;for(const v of p.edges??[]){const k=v.sections;if(!k||k.length===0)continue;const b=k[0],j=(x=v.sources)==null?void 0:x[0],C=(f=v.targets)==null?void 0:f[0];if(!j||!C)continue;const w=[];w.push({x:Math.round(b.startPoint.x),y:Math.round(b.startPoint.y)});for(const g of b.bendPoints??[])w.push({x:Math.round(g.x),y:Math.round(g.y)});w.push({x:Math.round(b.endPoint.x),y:Math.round(b.endPoint.y)}),y.set(v.id,{id:v.id,source:j,target:C,points:w})}return{nodes:u,bounds:h,edgeRoutes:y,columnGap:ok(h,t),layoutOptions:{...o}}}function ik(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 um(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function lk(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(ik),...e.edges.map(um)].join("::")}function ck(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(um)].join("::")}const dk=5*60*1e3;function pm(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function mm(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function uk(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"||pm(e)||mm(e)?"remote":"unknown"}function pk(e){const t=e.connection;if(!t)return{connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null};const r=t.rttMs,n=typeof r=="number"&&Number.isFinite(r)&&r>=0?r:null;return{connectionTransport:t.transport??null,connectionState:t.state??null,connectionReason:typeof t.reason=="string"&&t.reason.trim()?t.reason.trim():null,connectionReported:t.reported===!0,connectionRttMs:n}}function hm(e){const t=e.connectionTransport;if(t==="direct"||t==="relay"||t==="local")return t;const r=e.connectionState;return r==="connecting"?"connecting":r==="disconnected"?"disconnected":r==="failed"?"failed":r==="closed"?"closed":null}function mk(e){if(e.connectionTransport==="local"||e.connectionState==="self")return null;const t=hm(e);return!t||t==="local"||typeof e.connectionRttMs!="number"||!Number.isFinite(e.connectionRttMs)?null:`${Math.round(e.connectionRttMs)}ms`}function hk(e){return Ti(e)}function fm(e){var t;return hk(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function xm(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function fk(e){return e.activeSessionDetails&&e.activeSessionDetails.length>0?e.activeSessionDetails:(e.activeSessions??[]).map(t=>({sessionId:t,workspace:e.workspace,isCached:!0}))}function bm(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function gm(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function sl(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function xk(e){return sl(e)?"degraded":gm(e)?"dirty":"online"}function bk(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function Wc(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 yo(e){return e.length===0?"unknown":e.reduce((t,r)=>Wc(r)>Wc(t)?r:t)}function gk(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"],y=h.indexOf(u[0]),x=h.indexOf(m[0]);return y!==-1||x!==-1?y===-1?1:x===-1?-1:y-x: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 yk(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 Kc(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 vk(e){return e.reduce((t,r)=>Kc(r.status)>Kc(t.status)?r:t)}function wk(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 jk(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 kk(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 Uc(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 xm(t)??0}function Nk(e){return e.length===0?null:e.reduce((t,r)=>{const n=Uc(t.status),a=Uc(r.status);return a!==n?a<n?r:t:zc(r)>zc(t)?r:t})}function Sk(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 Ck(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 Ik(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 Ak(e,t){if(fm(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=bm(a)||gm(a),i=!!(a!=null&&a.hasConflicts)||sl(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 Mk(e,t){const r=Ak(e,t);return r?{...r,defaultBranch:r.defaultBranch??t}:null}function _k(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function Tk(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(fm(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>dk&&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 ym(e){const t=yu(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??gk(t.nodes),a=xm(t.refreshedAt),o=new Set(t.nodes.flatMap(M=>{var H;return(((H=M.git)==null?void 0:H.submodules)??[]).map(q=>q.path)})),i=[],c=[],d=jk(t),p=new Map,u=Sk(kk(t));for(const M of t.nodes){const H=M.git,q=(H==null?void 0:H.branch)??null,A=xk(H),$=bm(H)||A==="dirty",T=yk(M,n),F=Mk(M,n),z=Tk({nodeStatus:M,expectedSubmodulePaths:o,refreshedAtMs:a}),U=typeof M.clonedFromNodeId=="string"?M.clonedFromNodeId:null,te=fk(M),Z=Nk(u.get(M.nodeId)??[]),se=pk(M),G={id:M.nodeId,type:T.length>0?"orphanNode":"worktreeNode",label:M.machineLabel||M.nodeId.slice(0,8),workspace:M.workspace,branch:q,upstream:(H==null?void 0:H.upstream)??null,upstreamStatus:(H==null?void 0:H.upstreamStatus)??null,daemonId:pm(M),machineId:mm(M),machineLabel:M.machineLabel||null,locality:uk(M),connectionTransport:se.connectionTransport,connectionState:se.connectionState,connectionReason:se.connectionReason,connectionReported:se.connectionReported,connectionRttMs:se.connectionRttMs,health:yo([M.health,A]),ahead:(H==null?void 0:H.ahead)??0,behind:(H==null?void 0:H.behind)??0,dirty:$,dirtyFiles:bk(H),hasConflicts:(H==null?void 0:H.hasConflicts)??!1,activeSessionCount:te.length,activeSessions:te.map(O=>O.sessionId),sessionDetails:te,providers:M.providers??[],isOrphan:T.length>0,orphanReasons:T,error:M.error,nextStepHint:z.snapshotWarnings[0]??T[0]??(F==null?void 0:F.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:U,worktreeBranch:M.worktreeBranch??null,submodulePath:null,submoduleCommit:(H==null?void 0:H.headCommit)??null,outOfSync:sl(H),snapshotCompleteness:z.snapshotCompleteness,snapshotWarnings:z.snapshotWarnings,branchConvergence:F,refineJobStatus:(Z==null?void 0:Z.status)??null,refineJobId:(Z==null?void 0:Z.jobId)??null,refineJobBranch:(Z==null?void 0:Z.branch)??null,refineJobInto:(Z==null?void 0:Z.into)??null,source:M};if(i.push(G),q){const O=p.get(q)??[];O.push(G.id),p.set(q,O)}for(const O of(H==null?void 0:H.submodules)??[]){const V=`${G.id}::submodule::${O.path}`,pe=O.path.split("/").filter(Boolean).pop()||O.path;i.push({id:V,type:"submoduleNode",label:pe,workspace:O.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:G.daemonId,machineId:G.machineId,machineLabel:G.machineLabel,locality:G.locality,connectionTransport:G.connectionTransport,connectionState:G.connectionState,connectionReason:G.connectionReason,connectionReported:G.connectionReported,connectionRttMs:G.connectionRttMs,health:_k(O),ahead:0,behind:0,dirty:O.dirty,dirtyFiles:O.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],error:O.error,nextStepHint:O.error||(O.outOfSync?`${O.path} is out of sync with the parent checkout`:O.dirty?`${O.path} has local changes`:`${O.path} is in sync with the parent checkout`),parentNodeId:G.id,submodulePath:O.path,submoduleCommit:O.commit,outOfSync:O.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:G.id,parentWorkspace:M.workspace,submodule:O}}),c.push({id:`${G.id}--${V}`,source:G.id,target:V,type:"submoduleLink",label:O.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const m=n?`__branch_${n}`:null;if(m&&n){const H=(p.get(n)??[]).map(U=>i.find(te=>te.id===U)).filter(Boolean),q=H.map(U=>U.branchConvergence).filter(Boolean),A=wk(t),$=H.length>0&&H.every(U=>Ck(U,n)),T=(A==null?void 0:A.length)===0&&$?Ik(n,H):q.length>0?vk(q):null,F=(A==null?void 0:A.length)===0&&$?0:q.filter(U=>U.needsConvergence).length,z={id:m,type:"defaultBranchNode",label:n,workspace:t.repoIdentity,branch:n,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:"default branch",locality:"unknown",connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null,health:yo(H.map(U=>U.health)),ahead:0,behind:0,dirty:H.some(U=>U.dirty),dirtyFiles:H.reduce((U,te)=>U+te.dirtyFiles,0),hasConflicts:H.some(U=>U.hasConflicts),activeSessionCount:H.reduce((U,te)=>U+te.activeSessionCount,0),activeSessions:H.flatMap(U=>U.activeSessions),sessionDetails:H.flatMap(U=>U.sessionDetails),providers:[...new Set(H.flatMap(U=>U.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:F>0?`${F} workspace(s) on ${n} still need follow-up`:H.length>0?`${H.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:T,source:{nodeId:m,machineLabel:n,workspace:t.repoIdentity,health:yo(H.map(U=>U.health)),providers:[],activeSessions:[],activeSessionDetails:[]}};i.push(z);for(const U of i)if(!(U.id===m||U.type==="submoduleNode")){if(U.branch===n){c.push({id:`${m}--${U.id}`,source:m,target:U.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(U.branch){c.push({id:`${m}--${U.id}`,source:m,target:U.id,type:U.isOrphan?"orphanLink":"parentBranch",label:U.branch,direction:"undirected"});continue}U.isOrphan&&c.push({id:`${m}--${U.id}`,source:m,target:U.id,type:"orphanLink",label:"detached",direction:"undirected"})}}const h=new Set(i.map(M=>M.id)),y=new Set;for(const M of i){if(!M.clonedFromNodeId||M.type==="submoduleNode"||!h.has(M.clonedFromNodeId))continue;const H=`clone_${M.clonedFromNodeId}--${M.id}`;if(y.has(H))continue;y.add(H);const q=M.worktreeBranch??M.branch??void 0;c.push({id:H,source:M.clonedFromNodeId,target:M.id,type:"cloneLink",label:q?`cloned · ${q}`:"cloned",direction:"directed"})}const x=i.filter(M=>M.type!=="defaultBranchNode"),f=x.filter(M=>M.isOrphan).length,v=x.filter(M=>M.hasConflicts).length,k=x.filter(M=>M.health==="offline").length,b=x.filter(M=>M.type==="submoduleNode"&&M.outOfSync).length,j=x.filter(M=>{var H;return M.type!=="submoduleNode"&&((H=M.branchConvergence)==null?void 0:H.needsConvergence)}).length,C=x.filter(M=>{var H;return((H=M.branchConvergence)==null?void 0:H.status)==="blocked_review"}).length,w=x.filter(M=>{var H;return((H=M.branchConvergence)==null?void 0:H.status)==="pushed_feature_branch_needs_merge"}).length,g=x.filter(M=>{var H;return((H=M.branchConvergence)==null?void 0:H.status)==="cleanup_candidate"}).length,S=x.filter(M=>{var H;return((H=M.branchConvergence)==null?void 0:H.status)==="not_mergeable"}).length,N=x.filter(M=>M.snapshotWarnings.length>0).length,I=x.filter(M=>M.snapshotCompleteness==="pending_git").length,R=x.filter(M=>M.snapshotCompleteness==="missing_git").length,L=x.filter(M=>M.snapshotCompleteness==="missing_submodule_report").length,_=x.filter(M=>M.snapshotCompleteness==="stale").length,P=x.filter(M=>M.refineJobStatus==="running"||M.refineJobStatus==="accepted").length,B=x.filter(M=>M.refineJobStatus==="failed").length,Y=[I>0?`${I} node(s) are still waiting for a live peer git snapshot`:null,R>0?`${R} node(s) have no visible peer git snapshot`:null,L>0?`${L} 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 j>0&&d.push(`${j} workspace(s) still need follow-up before the mesh is converged`),f>0&&d.push(`${f} workspace(s) need attention before safe coordination`),C>0&&d.push(`${C} 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`),g>0&&d.push(`${g} worktree workspace(s) are ready for refine / cleanup`),S>0&&d.push(`${S} workspace(s) have local changes or conflicts blocking convergence`),v>0&&d.push(`${v} workspace(s) report merge conflicts`),k>0&&d.push(`${k} node(s) are currently offline`),b>0&&d.push(`${b} submodule(s) are out of sync with their parent checkout`),d.push(...Y),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:x.length,onlineNodes:x.filter(M=>M.health==="online").length,dirtyNodes:x.filter(M=>M.dirty).length,orphanNodes:f,errorNodes:x.filter(M=>!!M.error||M.outOfSync).length,offlineNodes:k,followUpNodes:j,blockedReviewNodes:C,mergeReadyNodes:w,cleanupCandidateNodes:g,notMergeableNodes:S,incompleteSnapshotNodes:N,pendingGitSnapshotNodes:I,missingGitSnapshotNodes:R,missingSubmoduleSnapshotNodes:L,staleGitSnapshotNodes:_,activeRefineNodes:P,failedRefineNodes:B,totalActiveSessions:x.reduce((M,H)=>M+H.activeSessionCount,0)},warnings:d,snapshotWarnings:Y}}function Lk(e){return!e.nodes.some(t=>t.snapshotCompleteness==="pending_git"||t.snapshotCompleteness==="missing_git"||t.snapshotCompleteness==="missing_submodule_report")}const Rk=7,Pk=640,rl=l.createContext(Ls("dark")),vm=l.createContext(!1),wm=l.createContext("LR"),jm={overflowWrap:"anywhere",wordBreak:"break-word"},Dk={...jm,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},$k={...jm,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function km(e){return e.activeSessionCount>0}function Ek(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function Gc(e,t,r){const n=km(e),a=Ek(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=Zi(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 Ct(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 Vc(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 qc(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 Bk(e){return e.replace(/_/g," ")}function ls(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 Fk(e){var t;return((t=e.sessionDetails)==null?void 0:t.some(r=>ls(r)==="generating"))??!1}function vo(e,t){const r=ls(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":Ct("health",t)}function Ok(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function Yc(e){const t=Ok(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 wo(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 Hk(e){if(e.sessionDetails.length===0)return null;const t=e.sessionDetails.filter(o=>ls(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 Jc(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function Wk(e){return e.locality==="remote"?"meta":"health"}function Kk({data:e,selected:t}){const r=l.useContext(rl),n=l.useContext(vm),a=l.useContext(wm),o=e.graphNode,i=o.type==="defaultBranchNode",c=o.type==="submoduleNode",d=om(o),p=i?"default branch anchor":c?o.submodulePath||"submodule checkout":[o.machineLabel,Jc(o.locality)].filter(Boolean).join(" · ")||o.workspace,u=o.submoduleCommit?o.submoduleCommit.slice(0,7):null,m=!c&&!i&&o.connectionState!=="self",h=m?hm(o):null,y=h==="local"?null:h,x=m?mk(o):null,f=Zi(o),v=el(o),k=km(o),b=o.sessionDetails,j=o.sessionDetails,C=Hk(o),w=o.sessionDetails.map(S=>{const N=ls(S),I=S.providerType||"provider unknown",R=Br(S),L=S.startedAt||S.createdAt||null,_=S.statusNote?` · ${S.statusNote}`:"";return`Session: ${S.sessionId} · ${I} · ${N} · ${R} · ${Yc(L)}${_}`});if(n)return s.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${Gc(o,t,r.isDark)}`,style:{width:on(o,!0)},title:[o.label,o.branch?`Branch: ${o.branch}`:null,o.machineLabel?`Machine: ${o.machineLabel}`:null,o.workspace?`Workspace: ${o.workspace}`:null,f?`Status: ${f.label}`:null,Vn(o),...w].filter(Boolean).join(`
77
- `),children:[s.jsx(xn,{type:"target",position:a==="TB"?js.Top:js.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:[k&&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:qc(o.health)},"aria-hidden":!0})]})]}),o.health==="unknown"&&!f&&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 ${Ct("health",r.isDark)}`,children:s.jsx("span",{className:"truncate",children:"Connecting..."})}),f&&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] ${Vc(f.tone,r.isDark)}`,title:f.label,children:s.jsx("span",{className:"truncate",children:f.label})}),!f&&o.branch&&!c&&o.health!=="unknown"&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[10px] ${Ct("meta",r.isDark)} rounded-full border px-2 py-0.5 inline-block`,title:o.branch,children:o.branch}),C&&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:w.join(`
78
- `),children:C}),j.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:j.map(S=>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: ${S.sessionId}`,S.providerType?`Provider: ${S.providerType}`:null,`Status: ${ls(S)}`,`Role: ${Br(S)}`].filter(Boolean).join(`
79
- `),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:S.providerType||"provider unknown"}),s.jsx("span",{className:`shrink-0 rounded-full border px-1 py-0 text-[8px] font-semibold uppercase tracking-[0.1em] ${vo(S,r.isDark)}`,children:ls(S)})]}),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:wo(S.sessionId)}),s.jsx("span",{className:"shrink-0",children:Br(S)})]})]},S.sessionId))}),s.jsx(xn,{type:"source",position:a==="TB"?js.Bottom:js.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]});const g=[o.label,p,f?`Status: ${f.label}`:null,Vn(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&&v?`Note: ${v}`:null,...w].filter(Boolean).join(`
80
- `);return s.jsxs("div",{className:`rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all ${Gc(o,t,r.isDark)}${Fk(o)?" mesh-node-generating":""}`,style:{width:on(o)},title:g,children:[s.jsx(xn,{type:"target",position:a==="TB"?js.Top:js.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:[k&&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:qc(o.health)},"aria-hidden":!0})]})]}),f?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] ${Vc(f.tone,r.isDark)}`,title:f.label,children:s.jsx("span",{className:"truncate",children:f.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] ${Ct("meta",r.isDark)}`,title:o.branch,children:s.jsx("span",{className:"truncate",children:o.branch})}):null,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] 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:w.join(`
81
- `),children:s.jsx("span",{className:"truncate",children:C})}),j.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:j.map(S=>{const N=Br(S);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: ${S.sessionId}`,S.providerType?`Provider: ${S.providerType}`:null,`Status: ${ls(S)}`,`Role: ${N}`].filter(Boolean).join(`
82
- `),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:S.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] ${vo(S,r.isDark)}`,children:ls(S)})]}),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:wo(S.sessionId)}),s.jsx("span",{children:N})]})]},S.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 ${Ct("health",r.isDark)}`,children:"connecting..."}):s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${Ct("health",r.isDark)}`,children:Bk(o.health)}),c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("submodule",r.isDark)}`,children:"submodule"}),!i&&o.health==="unknown"&&!o.locality&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${Ct("health",r.isDark)}`,children:"..."}),!i&&(o.health!=="unknown"||o.locality)&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct(Wk(o),r.isDark)}`,children:Jc(o.locality)}),y&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("meta",r.isDark)}`,title:y==="relay"?"P2P link relayed through TURN (slower path)":`P2P transport: ${y}`,children:y}),x&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("meta",r.isDark)}`,title:"P2P round-trip latency",children:x}),u&&c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("meta",r.isDark)}`,children:u}),o.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("dirty",r.isDark)}`,children:c?"local changes":`${o.dirtyFiles} dirty`}),o.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("conflict",r.isDark)}`,children:"out of sync"}),o.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("conflict",r.isDark)}`,children:"conflicts"}),!c&&o.upstream&&o.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("orphan",r.isDark)}`,children:"upstream unverified"}),o.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("orphan",r.isDark)}`,children:"needs follow-up"}),!c&&o.refineJobStatus==="completed"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("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:Dk,children:Vn(o)}),b.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:b.map(S=>{const N=S.startedAt||S.createdAt||null,I=Br(S);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: ${S.sessionId}`,S.providerType?`Provider: ${S.providerType}`:null,`Status: ${ls(S)}`,`Role: ${I}`,N?`Started: ${N}`:"Started: not reported",S.statusNote?`Note: ${S.statusNote}`:null].filter(Boolean).join(`
83
- `),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:wo(S.sessionId)}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${vo(S,r.isDark)}`,children:ls(S)})]}),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:S.providerType||"provider unknown"}),s.jsx("span",{children:I}),s.jsx("span",{children:Yc(N)})]}),S.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${r.textMuted}`,children:S.statusNote})]},S.sessionId)})})]}),d&&v&&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:$k,children:v})]}),s.jsx(xn,{type:"source",position:a==="TB"?js.Bottom:js.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const Uk={meshNode:Kk},zk=8;function Gk(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=zk,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],y=Math.sign(m.x-u.x),x=Math.sign(m.y-u.y),f=Math.sign(h.x-m.x),v=Math.sign(h.y-m.y),k=Math.hypot(m.x-u.x,m.y-u.y),b=Math.hypot(h.x-m.x,h.y-m.y),j=Math.min(t,k/2,b/2);if(j<1||y===f&&x===v){r.push(`L ${m.x},${m.y}`);continue}const C=m.x-y*j,w=m.y-x*j,g=m.x+f*j,S=m.y+v*j;r.push(`L ${C},${w}`),r.push(`Q ${m.x},${m.y} ${g},${S}`)}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 Vk(e){const t=e.data.routePoints;if(t&&t.length>=2){const o=Gk(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=Ih(r):n.type==="worktreeLink"||n.type==="submoduleLink"||n.type==="cloneLink"?a=Sh(r):a=Ch(r),[a[0],a[1],a[2]]}function qk(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 Yk(e){const t=l.useContext(rl),r=e.data.graphEdge,[n,a,o]=Vk(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(vh,{id:e.id,path:n,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(wh,{children:s.jsx("div",{className:qk(r,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${a}px, ${o}px)`,pointerEvents:"none",maxWidth:qj.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const Jk={meshEdge:Yk};async function Xk(e,t,r,n,a){const o=await dm(e,r,n,a);return Nm(e,o,t,r)}async function Qk(e,t=Ls("dark"),r=!1,n="LR"){const a=await dm(e,r,n);return Nm(e,a,t,r)}function Nm(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=t1(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:Nh.ArrowClosed,width:p.type==="submoduleLink"?16:18,height:p.type==="submoduleLink"?16:18,color:Qc(p)}:void 0,style:{stroke:Qc(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 Zk=3,e1=2;function Xc(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 t1(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<Zk){for(const o of n)t.add(o.id);continue}const a=[...n].sort((o,i)=>{const c=Xc(i)-Xc(o);return c!==0?c:o.id.localeCompare(i.id)});for(const o of a.slice(0,e1))t.add(o.id)}return t}function Qc(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 s1(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 r1(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 n1({data:e,viewportKey:t}){const r=jh(),n=kh(),a=l.useRef(null),o=l.useMemo(()=>im(e),[e]),i=l.useMemo(()=>Wj(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 a1=12;function o1(e){return e>=16?"min-h-[720px]":e>=10?"min-h-[580px]":"min-h-[460px]"}function i1({data:e,selectedNodeId:t=null,directionPref:r,onNodeClick:n,onEdgeClick:a,onNodeHoverChange:o,onEdgeHoverChange:i}){const{theme:c}=Ts(),d=l.useMemo(()=>Ls(c),[c]),p=l.useMemo(()=>lk(e),[e]),u=l.useMemo(()=>ck(e),[e]),m=l.useRef(null),[h,y]=l.useState({width:0,height:0}),x=h.width>0&&h.width<Pk,f=e.nodes.length>=Rk||x,[v]=l.useState("LR"),k=r??v,b=l.useMemo(()=>r==="LR"||r==="TB"?r:x?"TB":k==="auto"?Xj(e):k,[k,r,p,e,x]),j=e.nodes.length>=a1,[C,w]=l.useState({nodes:[],edges:[]}),g=l.useMemo(()=>`${Kj(e,h.width,h.height)}::${b}`,[p,e,h.height,h.width,b]);l.useEffect(()=>{let N=!1;return Qk(e,d,f,b).then(I=>{if(N)return;w(I);const R=requestAnimationFrame(()=>{if(N)return;const L=m.current;if(!L)return;const _=new Map;for(const P of I.nodes){const B=L.querySelector(`.react-flow__node[data-id="${CSS.escape(P.id)}"]`);B&&B.offsetHeight>0&&_.set(P.id,B.offsetHeight)}_.size!==0&&Xk(e,d,f,b,_).then(P=>{N||w(P)})});return()=>cancelAnimationFrame(R)}),()=>{N=!0}},[e,u,d,f,b]);const S=l.useMemo(()=>C.nodes.map(N=>({...N,selected:N.id===t})),[C.nodes,t]);return l.useEffect(()=>{const N=m.current;if(!N)return;const I=()=>{const L=Math.max(0,Math.round(N.clientWidth)),_=Math.max(0,Math.round(N.clientHeight));y(P=>P.width===L&&P.height===_?P:{width:L,height:_})};I();const R=typeof ResizeObserver=="function"?new ResizeObserver(()=>I()):null;return R==null||R.observe(N),window.addEventListener("resize",I),()=>{R==null||R.disconnect(),window.removeEventListener("resize",I)}},[]),s.jsx(rl.Provider,{value:d,children:s.jsx(vm.Provider,{value:f,children:s.jsx(wm.Provider,{value:b,children:s.jsxs("div",{ref:m,className:`${d.graphShellClass} ${o1(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(fh,{nodes:S,edges:C.edges,nodeTypes:Uk,edgeTypes:Jk,minZoom:x?.3:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(N,I)=>n==null?void 0:n(I.data.graphNode),onEdgeClick:(N,I)=>{var L;const R=(L=I.data)==null?void 0:L.graphEdge;R&&(a==null||a(R))},onNodeMouseEnter:(N,I)=>o==null?void 0:o(I.data.graphNode),onNodeMouseLeave:()=>o==null?void 0:o(null),onEdgeMouseEnter:(N,I)=>{var R;return i==null?void 0:i(((R=I.data)==null?void 0:R.graphEdge)??null)},onEdgeMouseLeave:()=>i==null?void 0:i(null),className:"h-full w-full",colorMode:d.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(n1,{data:e,viewportKey:g}),s.jsx(xh,{className:d.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),j&&s.jsx(bh,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:s1,nodeClassName:r1,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(gh,{variant:yh.Dots,gap:18,size:1.2,color:d.graphBackgroundDotColor})]})})]})})})})}const l1="You are one independent member of a multi-agent cross-verification quorum";function c1(e){var n,a;const t=(e??"").trim();if(!t)return"";if(!t.startsWith(l1))return t;const r=(a=(n=t.match(/\n## Question\n([\s\S]*?)(?:\n## |$)/))==null?void 0:n[1])==null?void 0:a.trim().replace(/\s+/g," ");return r?`MAGI cross-verify — ${r}`:"MAGI cross-verification task"}function d1(e){return`${e.state??""} ${e.chatStatus??""} ${e.lifecycle??""}`.toLowerCase()}function u1(e){if(!Array.isArray(e))return[];const t=[];for(const r of e){const n=r.activeSessionDetails;if(Array.isArray(n))for(const a of n)a!=null&&a.sessionId&&d1(a).includes("approval")&&t.push({nodeId:r.nodeId,sessionId:a.sessionId,providerType:a.providerType,machineLabel:r.machineLabel||r.nodeId,detail:a.statusNote??a.title??null})}return t}function p1({approvals:e,nodes:t,onResolve:r,hideWhenEmpty:n=!0}){const a=l.useMemo(()=>e??u1(t),[e,t]),[o,i]=l.useState({});if(n&&a.length===0)return null;const c=(d,p)=>{o[d.sessionId]||(i(u=>({...u,[d.sessionId]:p})),Promise.resolve(r(d.nodeId,d.sessionId,p)).finally(()=>{i(u=>{const m={...u};return delete m[d.sessionId],m})}))};return s.jsxs("div",{className:"rounded-lg border p-3",style:{borderColor:"color-mix(in srgb, var(--status-warning) 40%, transparent)",background:"color-mix(in srgb, var(--status-warning) 8%, transparent)"},children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2 font-black text-xs",style:{color:"var(--status-warning)"},children:[s.jsx(Vs,{size:14}),"PENDING APPROVALS",s.jsxs("span",{className:"opacity-70 font-semibold",children:["(",a.length,")"]})]}),a.length===0?s.jsx("div",{className:"text-[11px] opacity-70",children:"No sessions are awaiting an approval decision."}):s.jsx("ul",{className:"flex flex-col gap-2",children:a.map(d=>{const p=o[d.sessionId]??null,u=p!==null;return s.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-md px-2.5 py-2",style:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)"},children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"text-xs font-semibold truncate",children:[d.machineLabel||d.nodeId,d.providerType&&s.jsx("span",{className:"ml-2 opacity-60 font-normal",children:d.providerType})]}),s.jsx("div",{className:"text-[10px] opacity-60 truncate",children:d.detail?d.detail.replace(/[\n\r]+/g," ").slice(0,120):`session ${d.sessionId}`})]}),s.jsxs("div",{className:"flex gap-2 shrink-0",children:[s.jsx("button",{onClick:()=>c(d,"approve"),disabled:u,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 font-extrabold ${u?"cursor-not-allowed opacity-60":"cursor-pointer"}`,style:{color:"var(--status-warning)",background:"var(--surface-primary)"},children:p==="approve"?"⏳ ...":"Approve"}),s.jsx("button",{onClick:()=>c(d,"reject"),disabled:u,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 font-semibold text-white bg-red-500/30 ${u?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:p==="reject"?"⏳ ...":"Reject"})]})]},`${d.nodeId}:${d.sessionId}`)})})]})}const m1=5,h1=40,f1={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function La(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function Sm(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 Cm(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 x1(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 Im(e){switch(e){case"active":return"emerald";case"paused":return"amber";case"completed":return"sky";case"abandoned":return"rose";default:return"muted"}}function b1(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 Am(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 Zc(e){switch(e){case"assigned":return 0;case"pending":return 1;case"completed":case"failed":case"cancelled":return 2;default:return 3}}function as(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 ed(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 nl(e){return e.replace(/[_-]+/g," ")}function Mm(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 _m(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 g1({status:e,daemonId:t=null,meshId:r=null,sendDaemonCommand:n=null}){var C,w,g,S;const{theme:a}=Ts(),o=l.useMemo(()=>Ls(a),[a]),i=((C=e.queue)==null?void 0:C.summary)??null,c=((w=e.queue)==null?void 0:w.tasks)??[],d=((g=e.ledger)==null?void 0:g.summary)??f1,p=((S=e.ledger)==null?void 0:S.entries)??[],u=e.missions??[],m=u.filter(N=>N.status==="active"||N.status==="paused"),h=u.filter(N=>N.status==="completed"||N.status==="abandoned"),y=e.asyncRefineJobs??[],[x,f]=l.useState(null),v=l.useCallback(()=>f(null),[]),k=l.useCallback(async(N,I,R)=>{!t||!n||await n(t,"mesh_approve",{meshId:r??void 0,node_id:N,session_id:I,action:R})},[t,r,n]),b=l.useCallback(N=>{if(!N)return"";const I=e.nodes.find(R=>R.nodeId===N);return(I==null?void 0:I.machineLabel)||N},[e.nodes]),j=l.useMemo(()=>{const N=[];for(const I of e.nodes){const R=I.activeSessionDetails&&I.activeSessionDetails.length>0?I.activeSessionDetails:(I.activeSessions??[]).map(L=>({sessionId:L,workspace:I.workspace,isCached:!0}));for(const L of R)N.push({node:I,session:L})}return N},[e.nodes]);return s.jsxs("div",{className:"flex flex-col gap-3 pb-2",children:[s.jsx(p1,{nodes:e.nodes,onResolve:k}),s.jsx(I1,{meshTheme:o,liveMissions:m,historyMissions:h,hasMissionField:Array.isArray(e.missions),onSelect:N=>f({kind:"mission",mission:N})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(A1,{meshTheme:o,ledgerSummary:d,entries:p,resolveNodeLabel:b,onSelect:N=>f({kind:"ledger",entry:N})}),s.jsx(M1,{meshTheme:o,queueSummary:i,tasks:c,onSelect:N=>f({kind:"queue",task:N})})]}),s.jsx(T1,{meshTheme:o,nodes:e.nodes}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(L1,{meshTheme:o,entries:j,onSelect:(N,I)=>f({kind:"session",node:N,session:I})}),s.jsx(R1,{meshTheme:o,jobs:y})]}),x&&s.jsx(v1,{meshTheme:o,detail:x,onClose:v,daemonId:t,meshId:r??e.meshId??null,sendDaemonCommand:n,resolveNodeLabel:b})]})}function Ys({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 Ot({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 gt({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 fn({meshTheme:e,children:t}){return s.jsx("div",{className:`text-xs ${e.textMuted}`,children:t})}function Ra({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 Pa({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 Da(e,t=m1){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 ht({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 y1(e){switch(e.kind){case"mission":return{kicker:"Mission",title:e.mission.title};case"ledger":return{kicker:"Ledger entry",title:nl(e.entry.kind)};case"queue":return{kicker:"Queue task",title:e.task.id};case"session":return{kicker:"Session",title:La(e.session.sessionId)}}}function v1({meshTheme:e,detail:t,onClose:r,daemonId:n,meshId:a,sendDaemonCommand:o,resolveNodeLabel:i}){l.useEffect(()=>{const h=y=>{y.key==="Escape"&&r()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[r]);const c=e.isDark,{kicker:d,title:p}=y1(t),u=c?"bg-[#030617]/[0.92]":"bg-[rgba(15,23,42,0.82)]",m=c?"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-[var(--z-modal)] flex items-stretch justify-center p-0 md:items-center md:p-4 ${u}`,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 ${m} md:h-auto md:max-h-[88dvh] md:max-w-[min(640px,calc(100vw-32px))] md:rounded-2xl`,onClick:h=>h.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 ${c?"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:d}),s.jsx("div",{className:`mt-0.5 break-all text-sm font-semibold ${e.textPrimary}`,children:p})]}),s.jsx("button",{type:"button",onClick:r,"aria-label":"Close detail",className:c?"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(k1,{meshTheme:e,mission:t.mission,daemonId:n,meshId:a,sendDaemonCommand:o}),t.kind==="ledger"&&s.jsx(N1,{meshTheme:e,entry:t.entry,resolveNodeLabel:i}),t.kind==="queue"&&s.jsx(S1,{meshTheme:e,task:t.task}),t.kind==="session"&&s.jsx(C1,{meshTheme:e,node:t.node,session:t.session})]})]})})}const w1=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function j1(e){const t=w1(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function k1({meshTheme:e,mission:t,daemonId:r,meshId:n,sendDaemonCommand:a}){var C;const o=t.tasks,i="goal"in t&&typeof t.goal=="string"&&t.goal?t.goal:"goalPreview"in t?t.goalPreview:"",c="goalTruncated"in t?t.goalTruncated===!0:!1,[d,p]=l.useState(null),[u,m]=l.useState(!1),[h,y]=l.useState(null),x=c&&!d&&!!r&&!!a,f=l.useCallback(async()=>{if(!(!r||!a)){m(!0),y(null);try{const w=await a(r,"mesh_status",{meshId:n??void 0,verbose:!0}),g=j1(w),N=(Array.isArray(g==null?void 0:g.missions)?g.missions:[]).find(R=>(R==null?void 0:R.id)===t.id),I=typeof(N==null?void 0:N.goal)=="string"&&N.goal?N.goal:null;I?p(I):y("Full goal unavailable")}catch(w){y(w instanceof Error?w.message:"Failed to fetch full mission goal")}finally{m(!1)}}},[r,n,a,t.id]),v=d??i,k=c&&!d,b=t.stats??null,j=((C=b==null?void 0:b.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(Ot,{meshTheme:e,label:t.status,tone:Im(t.status)}),s.jsx(Ot,{meshTheme:e,label:`${o.total} tasks`,tone:"muted"})]}),v&&s.jsxs("div",{className:`max-h-64 overflow-y-auto whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:[v,k&&!x&&s.jsx("span",{className:e.textMuted,children:" … (truncated)"})]}),h&&s.jsx("div",{className:"text-[11px] text-amber-400",children:h}),x&&s.jsx("button",{type:"button",className:"self-start text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:f,disabled:u,children:u?"Loading…":"Show full goal"}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5 sm:grid-cols-6",children:[s.jsx(gt,{meshTheme:e,label:"Completed",value:o.completed,tone:"emerald"}),s.jsx(gt,{meshTheme:e,label:"Assigned",value:o.assigned,tone:o.assigned>0?"sky":void 0}),s.jsx(gt,{meshTheme:e,label:"Pending",value:o.pending}),s.jsx(gt,{meshTheme:e,label:"Failed",value:o.failed,tone:o.failed>0?"rose":void 0}),s.jsx(gt,{meshTheme:e,label:"Blocked",value:o.blocked,tone:o.blocked>0?"amber":void 0}),s.jsx(gt,{meshTheme:e,label:"Cancelled",value:o.cancelled,tone:"muted"})]}),b&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(gt,{meshTheme:e,label:"Wall clock",value:ed(b.wallClockMs)??"—"}),s.jsx(gt,{meshTheme:e,label:"Total runtime",value:ed(b.totalDurationMs)??"—"}),s.jsx(gt,{meshTheme:e,label:"Retries",value:b.retries,tone:b.retries>0?"amber":void 0})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ht,{meshTheme:e,label:"Mission id",value:t.id}),s.jsx(ht,{meshTheme:e,label:"Created",value:as(t.createdAt)??t.createdAt}),s.jsx(ht,{meshTheme:e,label:"Updated",value:as(t.updatedAt)??t.updatedAt}),o.lastActivityAt&&s.jsx(ht,{meshTheme:e,label:"Last task activity",value:as(o.lastActivityAt)??o.lastActivityAt}),j>0&&b&&s.jsx(ht,{meshTheme:e,label:"Incomplete evidence",value:s.jsxs("details",{children:[s.jsxs("summary",{className:"cursor-pointer select-none",children:[j," task",j===1?"":"s"]}),s.jsx("div",{className:"mt-1 flex flex-col gap-0.5 break-all",children:b.incompleteTaskIds.map(w=>s.jsx("span",{className:`font-mono text-[10px] ${e.textMuted}`,children:w},w))})]})})]})]})}function N1({meshTheme:e,entry:t,resolveNodeLabel:r}){const n=_m(t.payload);let a="";try{a=JSON.stringify(t.payload??{},null,2)}catch{a=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(Ot,{meshTheme:e,label:nl(t.kind),tone:Mm(t.kind)})}),n&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:n}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ht,{meshTheme:e,label:"Entry id",value:t.id}),s.jsx(ht,{meshTheme:e,label:"When",value:as(t.timestamp)??t.timestamp}),t.nodeId&&s.jsx(ht,{meshTheme:e,label:"Node",value:r(t.nodeId)}),t.sessionId&&s.jsx(ht,{meshTheme:e,label:"Session",value:La(t.sessionId)}),t.providerType&&s.jsx(ht,{meshTheme:e,label:"Provider",value:t.providerType})]}),a&&a!=="{}"&&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:a})]})]})}function S1({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(Ot,{meshTheme:e,label:t.status,tone:Am(t.status)}),(t.requeueCount??0)>0&&s.jsx(Ot,{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(ht,{meshTheme:e,label:"Task id",value:t.id}),s.jsx(ht,{meshTheme:e,label:"Created",value:as(t.createdAt)??t.createdAt}),s.jsx(ht,{meshTheme:e,label:"Updated",value:as(t.updatedAt)??t.updatedAt}),(t.assignedNodeId||t.targetNodeId)&&s.jsx(ht,{meshTheme:e,label:"Node",value:t.assignedNodeId||t.targetNodeId}),(t.assignedSessionId||t.targetSessionId)&&s.jsx(ht,{meshTheme:e,label:"Session",value:La(t.assignedSessionId||t.targetSessionId)}),t.cancelReason&&s.jsx(ht,{meshTheme:e,label:"Cancel reason",value:t.cancelReason}),t.requeueReason&&s.jsx(ht,{meshTheme:e,label:"Requeue reason",value:t.requeueReason}),t.autoLaunch&&s.jsx(ht,{meshTheme:e,label:"Auto launch",value:`${t.autoLaunch.status}${t.autoLaunch.reason?` · ${t.autoLaunch.reason}`:""}`})]})]})}function C1({meshTheme:e,node:t,session:r}){var a,o;const n=Sm(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(Ot,{meshTheme:e,label:n,tone:Cm(n)}),s.jsx(Ot,{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(ht,{meshTheme:e,label:"Session id",value:r.sessionId}),s.jsx(ht,{meshTheme:e,label:"Node",value:t.machineLabel}),s.jsx(ht,{meshTheme:e,label:"Workspace",value:r.workspace||t.workspace}),(((a=t.git)==null?void 0:a.branch)??t.worktreeBranch)&&s.jsx(ht,{meshTheme:e,label:"Branch",value:((o=t.git)==null?void 0:o.branch)??t.worktreeBranch}),typeof r.role=="string"&&r.role&&s.jsx(ht,{meshTheme:e,label:"Role",value:r.role}),(r.startedAt||r.createdAt)&&s.jsx(ht,{meshTheme:e,label:"Started",value:as(r.startedAt||r.createdAt)??(r.startedAt||r.createdAt)})]})]})}function td({meshTheme:e,mission:t,onSelect:r}){const n=t.tasks,a=as(n.lastActivityAt);return s.jsxs(Ra,{meshTheme:e,onClick:r,children:[s.jsx(Ot,{meshTheme:e,label:t.status,tone:Im(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 I1({meshTheme:e,liveMissions:t,historyMissions:r,hasMissionField:n,onSelect:a}){const[o,i]=l.useState(!1),c=e.isDark,d=Da(t);return s.jsxs(Ys,{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(td,{meshTheme:e,mission:p,onSelect:()=>a(p)},p.id)),s.jsx(Pa,{meshTheme:e,expanded:d.expanded,hiddenCount:d.hiddenCount,onToggle:d.toggle})]}):s.jsx(fn,{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(td,{meshTheme:e,mission:p,onSelect:()=>a(p)},p.id))})]})]})}function A1({meshTheme:e,ledgerSummary:t,entries:r,resolveNodeLabel:n,onSelect:a}){const o=as(t.lastActivityAt),i=l.useMemo(()=>[...r].reverse(),[r]),c=Da(i);return s.jsxs(Ys,{meshTheme:e,title:"Ledger",children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(gt,{meshTheme:e,label:"Dispatched",value:t.taskDispatched}),s.jsx(gt,{meshTheme:e,label:"Completed",value:t.taskCompleted,tone:"emerald"}),s.jsx(gt,{meshTheme:e,label:"Failed",value:t.taskFailed,tone:t.taskFailed>0?"rose":void 0}),s.jsx(gt,{meshTheme:e,label:"Stalled",value:t.taskStalled,tone:t.taskStalled>0?"amber":void 0}),s.jsx(gt,{meshTheme:e,label:"Sessions",value:t.sessionLaunched}),s.jsx(gt,{meshTheme:e,label:"Checkpoints",value:t.checkpointCreated})]}),i.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:[c.visible.map(d=>{const p=_m(d.payload);return s.jsxs(Ra,{meshTheme:e,onClick:()=>a(d),children:[s.jsx(Ot,{meshTheme:e,label:nl(d.kind),tone:Mm(d.kind)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:d.nodeId||void 0,children:p||n(d.nodeId)||d.sessionId||"—"}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:as(d.timestamp)??""})]},d.id)}),s.jsx(Pa,{meshTheme:e,expanded:c.expanded,hiddenCount:c.hiddenCount,onToggle:c.toggle})]})]}),(t.recentFailures>0||o&&i.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",{}),o&&i.length===0&&s.jsx("span",{children:o})]})]})}function M1({meshTheme:e,queueSummary:t,tasks:r,onSelect:n}){const a=l.useMemo(()=>[...r].sort((i,c)=>{const d=Zc(i.status)-Zc(c.status);return d!==0?d:(c.updatedAt||"").localeCompare(i.updatedAt||"")}).slice(0,h1),[r]),o=Da(a);return t?s.jsxs(Ys,{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(gt,{meshTheme:e,label:"Pending",value:t.pending}),s.jsx(gt,{meshTheme:e,label:"Assigned",value:t.assigned,tone:t.assigned>0?"sky":void 0}),s.jsx(gt,{meshTheme:e,label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(gt,{meshTheme:e,label:"Completed",value:t.completed,tone:"emerald"}),s.jsx(gt,{meshTheme:e,label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0}),s.jsx(gt,{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(Ra,{meshTheme:e,onClick:()=>n(i),children:[s.jsx(Ot,{meshTheme:e,label:i.status,tone:Am(i.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:i.message||void 0,children:c1(i.message)||i.id}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:as(i.updatedAt)??""})]},i.id)),s.jsx(Pa,{meshTheme:e,expanded:o.expanded,hiddenCount:o.hiddenCount,onToggle:o.toggle})]})]})]}):s.jsx(Ys,{meshTheme:e,title:"Queue",children:s.jsx(fn,{meshTheme:e,children:"No queue activity."})})}function _1(e){return e.autoFastForwardEligible||e.suggestedAction==="auto_fast_forward"?{label:"fast-forward",tone:"sky"}:e.launchBlockedReason?{label:"blocked",tone:"rose"}:null}function T1({meshTheme:e,nodes:t}){const r=e.isDark;return s.jsx(Ys,{meshTheme:e,title:"Nodes",count:t.length,children:t.length===0?s.jsx(fn,{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=_1(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(Ot,{meshTheme:e,label:n.health,tone:b1(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:x1(n)}),a>0&&s.jsxs("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:[a," session",a>1?"s":""]}),typeof n.daemonBuildVersion=="string"&&n.daemonBuildVersion&&s.jsxs("span",{className:`shrink-0 font-mono text-[10px] ${e.textMuted}`,title:"Daemon build version reported by this node",children:["v",n.daemonBuildVersion]}),o&&s.jsx(Ot,{meshTheme:e,label:o.label,tone:o.tone})]},n.nodeId)})})})}function L1({meshTheme:e,entries:t,onSelect:r}){const n=Da(t);return s.jsx(Ys,{meshTheme:e,title:"Active sessions",count:t.length||void 0,children:t.length===0?s.jsx(fn,{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=Sm(o);return s.jsxs(Ra,{meshTheme:e,onClick:()=>r(a,o),children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:La(o.sessionId)}),s.jsx("span",{className:`shrink-0 ${e.textMuted}`,children:o.providerType||"?"}),s.jsx(Ot,{meshTheme:e,label:i,tone:Cm(i)})]},o.sessionId)}),s.jsx(Pa,{meshTheme:e,expanded:n.expanded,hiddenCount:n.hiddenCount,onToggle:n.toggle})]})})}function R1({meshTheme:e,jobs:t}){const r=e.isDark,n=t.filter(a=>a.status==="failed").length;return s.jsx(Ys,{meshTheme:e,title:"Refine jobs",count:t.length||void 0,action:n>0?s.jsx(Ot,{meshTheme:e,label:`${n} failed`,tone:"rose"}):void 0,children:t.length===0?s.jsx(fn,{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 P1=[{term:"Node",summary:"A workspace participating in the mesh — a repo checkout or an isolated git worktree.",details:["Base node vs worktree clone node — a clone isolates parallel work without conflicts.","Shows health (online/offline) alongside git state (branch · ahead/behind · dirty).","Multiple nodes can share the same daemon."]},{term:"P2P connection",summary:"How the selected coordinator reaches each remote node over WebRTC.",details:["direct — a direct host/STUN path; lowest latency.","relay — TURN-relayed; works through restrictive networks but is slower.","disconnected / failed — no live P2P link from the coordinator right now.","P2P connectivity is shown as transport and RTT chips on each node card (and in the node detail panel), not as a graph edge."]},{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:"MAGI",summary:"Cross-verification: several independent AI agents answer the same question in parallel.",details:["Confidence comes from independence — different AIs on different machines fail in different ways.","When the agents disagree, the disagreement itself flags what to double-check.","Run via mesh_magi_review; the synthesis weighs agreement against source coupling."]},{term:"MAGI panel",summary:"A saved, reusable team of (machine × AI) members you invoke by name across investigations.",details:["Each member is one provider (AI) optionally pinned to a node (machine), with a replica count.","independent — spans ≥2 providers AND ≥2 machines, so agreement adds real confidence.","coupled — collapses to one AI or one machine; repeated members repeat the same mistakes.","Managed machine-locally from the Panels tab; defined in ~/.adhdev/meshes.json."]},{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 D1({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(vf,{size:15})})}function $1({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(wt,{size:14})})]}),s.jsx("dl",{className:"grid gap-3 sm:grid-cols-2",children:P1.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 Zs=l.createContext(Ls("dark"));function Ke({label:e,tone:t="default",className:r,title:n}){const a=l.useContext(Zs);return s.jsx("span",{title:n,className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${a.badge(t)}${r?` ${r}`:""}`,children:e})}function St({label:e,value:t}){const r=l.useContext(Zs);return s.jsxs("div",{className:r.rowClass,children:[s.jsx("span",{className:r.rowLabelClass,children:e}),s.jsx("span",{className:r.rowValueClass,children:t})]})}const E1={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function Tm(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 jo(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 qn(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 B1(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function F1(e){return e.startedAt||e.createdAt||null}function O1(e){const t=F1(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 Lm(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function H1(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 W1(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 K1(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=[];t.branch&&n.push(t.branch),t.upstream&&t.upstreamStatus!=="fresh"&&n.push("upstream unverified"),t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&n.push(`↑${t.ahead??0}/↓${t.behind??0}`),r>0&&n.push(`${r} dirty`);const a=(t.submodules??[]).filter(i=>i.dirty),o=(t.submodules??[]).filter(i=>i.outOfSync||i.error);return a.length>0&&n.push(`${a.length} submodule dirty`),o.length>0&&n.push(`${o.length} submodule drift`),t.hasConflicts&&n.push("conflicts"),n.join(" · ")||"Clean"}const U1={first_eligible:"In order",least_loaded:"Spread",round_robin:"Spread (round-robin)",priority_only:"Spread (priority)"};function z1(e){if(e.startsWith("max_provider_parallel_reached:"))return`provider cap reached (${e.slice(30)})`;switch(e){case"global_max_parallel_tasks_reached":return"global parallel cap reached";case"node_has_active_assignment":return"already running a write task";default:return e.replace(/_/g," ")}}function G1(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 V1(e){return e.assignedNodeId||e.targetNodeId||null}function ii(e){return e?e.slice(0,7):null}function q1(e,t){var o,i,c;const r=ii((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?[ii(a.commit),a.message].filter(Boolean).join(" · "):null}function Y1(e,t){const r=q1(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function J1(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 X1(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 Q1(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":W1(e.connection)}function Z1(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 sd(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 eN(e){return e.direction==="directed"?"directed":"undirected"}function tN(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function sN(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,y,x,f,v,k,b,j,C,w,g,S,N,I,R,L;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)??"",((y=o.git)==null?void 0:y.behind)??"",((x=o.git)==null?void 0:x.headCommit)??"",((f=o.git)==null?void 0:f.staged)??"",((v=o.git)==null?void 0:v.modified)??"",((k=o.git)==null?void 0:k.untracked)??"",((b=o.git)==null?void 0:b.deleted)??"",((j=o.git)==null?void 0:j.renamed)??"",(C=o.git)!=null&&C.hasConflicts?1:0,((w=o.git)==null?void 0:w.lastCheckedAt)??"",((g=o.activeSessions)==null?void 0:g.join(","))??"",((S=o.activeSessionDetails)==null?void 0:S.length)??"",((N=o.activeSessionDetails)==null?void 0:N.map(_=>[_.sessionId,_.providerType??"",_.state??"",_.chatStatus??"",_.lifecycle??"",_.role??"",_.isSelfCoordinator?1:0,_.statusNote??"",_.startedAt??"",_.createdAt??""].join("/")).join(","))??"",((I=o.providers)==null?void 0:I.join(","))??"",((R=o.providerPriority)==null?void 0:R.join(","))??"",o.error??"",(((L=o.git)==null?void 0:L.submodules)??[]).map(_=>[_.path,_.commit,_.dirty?1:0,_.outOfSync?1:0,_.error??""].join("/")).join(",")].join("|")})].join("::")}function rN(e){return e.nodes.length===0?!1:e.nodes.every(t=>t.health==="unknown"&&(!t.connection||t.connection.state==="unknown"))}function nN({scheduling:e}){const t=l.useContext(Zs);if(!e)return s.jsx("div",{className:`${t.cardClass} rounded-2xl p-4 text-[12px] ${t.textSecondary}`,children:"Scheduling runtime not reported by this daemon (older build). Update the coordinator daemon to surface distribution, parallel caps, and per-node load."});const r=e.globalWriteCapReached?"warn":"good";return s.jsxs("div",{className:`${t.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${t.textPrimary}`,children:"Scheduling"}),s.jsx(Ke,{label:U1[e.strategy]??e.strategy,tone:"info"}),s.jsx(Ke,{label:`write ${e.activeWriteAssigned}/${e.maxParallelTasks}`,tone:r,title:"Active write (non-readonly) assigned tasks vs the global parallel cap"}),s.jsx(Ke,{label:`readonly ${e.activeReadonlyAssigned}/${e.maxReadonlyParallelTasks}`,tone:e.globalReadonlyCapReached?"warn":"default",title:"Active read-only diagnosis tasks vs their (2× write) cap"})]}),s.jsx("p",{className:`mt-2 text-[11px] ${t.textSecondary}`,children:"Distribution only governs how untargeted work is spread across eligible nodes. Per-node load, priority, and provider caps are below."})]})}function aN({scheduling:e}){return e?s.jsxs(s.Fragment,{children:[s.jsx(Ke,{label:`load ${e.load}`,tone:e.load>0?"info":"default",title:"Active assigned tasks on this node"}),typeof e.schedulingPriority=="number"&&e.schedulingPriority!==0&&s.jsx(Ke,{label:`priority ${e.schedulingPriority}`,tone:"default",title:"Soft scheduling priority (higher = preferred)"}),(e.providerRoles??[]).map(t=>s.jsx(Ke,{label:`${t.providerType} ${t.activeAssigned}${typeof t.maxParallel=="number"?`/${t.maxParallel}`:""}`,tone:t.capReached?"warn":"default",title:"Per-(node, provider) active assignments vs declared maxParallel cap"},t.providerType)),e.capReached&&(e.capReasons??[]).map(t=>s.jsx(Ke,{label:z1(t),tone:"warn",title:"Why this node cannot currently claim a new write task"},t))]}):null}function oN({node:e}){var u,m,h,y;const t=l.useContext(Zs),r=((u=e.activeSessionDetails)==null?void 0:u.length)??((m=e.activeSessions)==null?void 0:m.length)??0,n=ii((h=e.git)==null?void 0:h.headCommit),a=e.isLocalWorktree===!0,o=e.worktreeBootstrap,i=e.staleDaemonBuild,c=e.providerVersions&&typeof e.providerVersions=="object"?e.providerVersions:void 0,d=c?Object.entries(c).filter(([,x])=>typeof x=="string"&&x):[],p=typeof e.daemonBuildVersion=="string"&&e.daemonBuildVersion?e.daemonBuildVersion:void 0;return s.jsxs("div",{className:`rounded-xl border p-3 ${t.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${t.textPrimary}`,children:e.machineLabel||e.nodeId}),s.jsx(Ke,{label:e.health,tone:Tm(e.health)}),a&&s.jsx(Ke,{label:"worktree",tone:"info",title:e.worktreeBranch?`Worktree branch ${e.worktreeBranch}`:"Local worktree node"}),(o==null?void 0:o.status)&&o.status!=="ready"&&s.jsx(Ke,{label:`bootstrap ${o.status}`,tone:"warn",title:"Worktree bootstrap is still in progress"}),((y=e.connection)==null?void 0:y.state)&&e.connection.state!=="self"&&s.jsx(Ke,{label:e.connection.state,tone:e.connection.state==="connected"?"good":"warn",title:"Mesh peer connection state"}),r>0&&s.jsx(Ke,{label:`${r} session${r===1?"":"s"}`,tone:"default"}),e.autoFastForwardEligible&&s.jsx(Ke,{label:"fast-forward ready",tone:"info",title:"Clean, behind upstream — safe for fast-forward"}),!!i&&s.jsx(Ke,{label:"stale build",tone:"warn",title:"Live daemon was built behind workspace HEAD — merged fixes may not be live"}),p&&s.jsx(Ke,{label:`build ${p}`,tone:"default",title:"Daemon build version reported by this node"}),s.jsx(aN,{scheduling:e.scheduling})]}),d.length>0&&s.jsx("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:d.map(([x,f])=>s.jsx(Ke,{label:`${x}@${f}`,tone:"info",title:"Detected provider version on this node"},x))}),s.jsxs("div",{className:`mt-1.5 text-[11px] ${t.textSecondary}`,children:[K1(e),n?s.jsxs("span",{className:"ml-2 font-mono opacity-70",children:["@",n]}):null]})]})}function iN({status:e}){const t=l.useContext(Zs),r=e.meshProtocolMetrics,n=Array.isArray(e.providerVersionSkew)?e.providerVersionSkew:[];return!r&&n.length===0?null:s.jsxs("div",{className:`${t.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${t.textPrimary}`,children:"Protocol & provider versions"}),r&&s.jsx(Ke,{label:`v2 ${Math.round(r.v2Ratio*100)}% (${r.v2}/${r.total})`,tone:r.total>0&&r.v2===r.total?"good":"info",title:"Share of pending coordinator events carrying a mesh-protocol-v2 envelope in this drain"}),n.length>0&&s.jsx(Ke,{label:`${n.length} provider skew`,tone:"warn",title:"Providers running different versions across nodes"})]}),r&&Object.keys(r.scopes).length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:Object.entries(r.scopes).map(([a,o])=>s.jsx(Ke,{label:`${a}: ${o}`,tone:"default",title:"v2 event scope breakdown"},a))}),n.length>0&&s.jsx("div",{className:"mt-2 flex flex-col gap-1.5",children:n.map(a=>s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx("span",{className:`text-[11px] font-semibold ${t.textPrimary}`,children:a.provider}),a.versions.map(o=>s.jsx(Ke,{label:`${o.version} · ${o.nodeIds.length} node${o.nodeIds.length===1?"":"s"}`,tone:"default",title:o.nodeIds.join(", ")},o.version))]},a.provider))}),e.providerVersionSkewWarning&&s.jsx("p",{className:`mt-2 text-[11px] ${t.textSecondary}`,children:e.providerVersionSkewWarning})]})}function lN({canonicalStatus:e}){const t=l.useContext(Zs);return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsx(nN,{scheduling:e.scheduling}),s.jsx(iN,{status:e}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("span",{className:`px-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${t.textSecondary}`,children:"Nodes — runtime"}),e.nodes.length===0?s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${t.textSecondary} ${t.isDark?"border-white/10":"border-slate-200"}`,children:"No nodes reporting runtime yet."}):e.nodes.map(r=>s.jsx(oN,{node:r},r.nodeId))]})]})}function cN({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(g=>g.status==="failed"||g.status==="cancelled").slice(0,5):[],u=e.asyncRefineJobs,m=(u==null?void 0:u.filter(g=>g.status==="running"||g.status==="accepted"))??[],h=(u==null?void 0:u.filter(g=>g.status==="failed"))??[],y=e.staleDirectWorkSummary,x=y&&y.count>0;if(!c&&!d&&e.nodes.length===0&&!n&&m.length===0&&h.length===0&&!x&&o.length===0)return null;const f=a.isDark,v=`border-t ${f?"border-white/8":"border-slate-200"}`,k=`group w-full rounded-lg border text-xs ${f?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,b=`flex cursor-pointer list-none items-center gap-1.5 px-2.5 py-1.5 [&::-webkit-details-marker]:hidden ${a.textSecondary}`;function j({label:g,value:S,tone:N}){const I=N==="rose"?f?"text-rose-300":"text-rose-600":N==="sky"?f?"text-sky-300":"text-sky-600":N==="amber"?f?"text-amber-300":"text-amber-600":N==="emerald"?f?"text-emerald-300":"text-emerald-600":N==="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:S}),s.jsx("span",{className:`mt-0.5 text-[9px] uppercase tracking-wide ${a.textMuted}`,children:g})]})}const C=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(j,{label:"Pending",value:t.pending}),s.jsx(j,{label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(j,{label:"Done",value:t.completed,tone:"emerald"}),s.jsx(j,{label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0})]}):s.jsxs(s.Fragment,{children:[s.jsx(j,{label:"Done",value:r.taskCompleted,tone:"emerald"}),s.jsx(j,{label:"Failed",value:r.taskFailed,tone:r.taskFailed>0?"rose":void 0}),s.jsx(j,{label:"Sessions",value:r.sessionLaunched}),s.jsx(j,{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(j,{label:"Ledger done",value:r.taskCompleted,tone:"emerald"}),s.jsx(j,{label:"Sessions",value:r.sessionLaunched}),s.jsx(j,{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 ${v}`,children:s.jsx("div",{className:"flex flex-col gap-1",children:e.nodes.map(g=>{var _;const S=((_=g.connection)==null?void 0:_.state)??"unknown",N=S==="unknown"||S==="connecting",L=N?"bg-amber-400":S==="failed"||S==="closed"||S==="disconnected"?f?"bg-rose-400":"bg-rose-500":S==="connected"||S==="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 ${L}`}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${a.textSecondary}`,title:g.workspace,children:g.machineLabel}),s.jsx("span",{className:`shrink-0 font-mono text-[10px] ${a.textMuted}`,children:N?"…":S})]},g.nodeId)})})}),u&&u.length>0&&s.jsx("div",{className:`pt-2.5 ${v}`,children:s.jsxs("details",{className:k,children:[s.jsxs("summary",{className:b,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(g=>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:[g.branch??g.jobId.slice(0,14),g.into?` → ${g.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${g.status==="failed"?f?"text-rose-300":"text-rose-600":g.status==="running"||g.status==="accepted"?f?"text-sky-300":"text-sky-600":f?"text-emerald-300":"text-emerald-600"}`,children:g.status})]},g.jobId))})]})}),p.length>0&&s.jsx("div",{className:u&&u.length>0?"":`pt-2.5 ${v}`,children:s.jsxs("details",{className:k,children:[s.jsxs("summary",{className:b,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(g=>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:g.id.slice(0,10)}),g.message&&s.jsx("span",{className:`flex-1 truncate ${f?"text-slate-300":"text-slate-700"}`,children:g.message.slice(0,55)})]}),g.cancelReason&&s.jsx("div",{className:`truncate text-[10px] ${a.textMuted}`,children:g.cancelReason.slice(0,55)})]},g.id))})]})}),x&&s.jsxs("div",{className:`flex items-center justify-between pt-2.5 ${v}`,children:[s.jsx("span",{className:a.textMuted,children:"Stale work"}),s.jsx("span",{className:`tabular-nums ${f?"text-amber-300":"text-amber-600"}`,children:y.count})]}),o.length>0&&s.jsx("div",{className:`pt-2.5 ${v}`,children:s.jsxs("details",{className:k,children:[s.jsxs("summary",{className:b,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(g=>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:g.session.sessionId,children:Lm(g.session.sessionId)}),s.jsx("span",{className:`shrink-0 ${a.textMuted}`,children:g.session.providerType||"?"}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${a.textMuted}`,children:qn(g.session)})]},g.session.sessionId))})]})})]});return i?C: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"})]}),C]})}const dN={merged_to_main:"Merged to main",pushed_feature_branch_needs_merge:"Needs merge",blocked_review:"Blocked — needs review",cleanup_candidate:"Ready to clean up",not_mergeable:"Not mergeable"};function Rm({meshTheme:e,activeTab:t,onActiveTabChange:r,helpOpen:n,onHelpOpenChange:a}){const o=i=>i?e.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 ${e.textSecondary} border border-transparent hover:bg-white/[0.04]`;return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:`inline-flex w-fit items-center gap-1 rounded-xl border p-1 ${e.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":t==="overview",className:o(t==="overview"),onClick:()=>r("overview"),children:"Overview"}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="status",className:o(t==="status"),onClick:()=>r("status"),children:"Status"}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="graph",className:o(t==="graph"),onClick:()=>r("graph"),children:"Graph"})]}),s.jsx(D1,{meshTheme:e,open:n,onToggle:()=>a(!n)})]})}function uN({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null,bootstrapFallback:a,activeTab:o,onActiveTabChange:i,helpOpen:c,onHelpOpenChange:d,hideControls:p=!1}){var Ne,Le,We;const{theme:u}=Ts(),m=l.useMemo(()=>Ls(u),[u]),h=l.useMemo(()=>yu(e),[e]),y=a??rN(h),x=l.useMemo(()=>sN(h),[h]),f=l.useMemo(()=>ym(h),[x]),[v,k]=l.useState("overview"),[b,j]=l.useState(!1),C=o??v,w=c??b,g=l.useCallback(le=>{i?i(le):k(le)},[i]),S=l.useCallback(le=>{d?d(le):j(le)},[d]),[N,I]=l.useState(!1);l.useEffect(()=>{C==="graph"&&I(!0)},[C]);const[R,L]=l.useState(null),[_,P]=l.useState(null),[B,Y]=l.useState(null),[M,H]=l.useState({}),[q,A]=l.useState(null),[$,T]=l.useState(null),F=l.useMemo(()=>new Map(h.nodes.map(le=>[le.nodeId,le])),[h.nodes]),z=l.useMemo(()=>new Map(f.nodes.map(le=>[le.id,le])),[f.nodes]),U=((Ne=h.queue)==null?void 0:Ne.summary)??null,te=((Le=h.ledger)==null?void 0:Le.summary)??E1,Z=l.useMemo(()=>G1(h),[h]),se=l.useMemo(()=>{const le=new Map;for(const Ee of Z){const Be=qn(Ee.session);le.set(Be,(le.get(Be)??0)+1)}return[...le.entries()].sort((Ee,Be)=>Be[1]-Ee[1])},[Z]);l.useEffect(()=>{R&&(z.has(R)||(L(null),Y(le=>!le||"nodeId"in le&&le.nodeId===R?null:le)))},[z,R]);const G=R?F.get(R)??null:null,O=tN(f,R),V=(B==null?void 0:B.kind)==="edge"&&_?f.edges.find(le=>le.id===_)??null:null,pe=V?f.nodes.find(le=>le.id===V.source)??null:null,fe=V?f.nodes.find(le=>le.id===V.target)??null:null;l.useEffect(()=>{var le,Ee,Be;if(R)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:h.meshId,selectedNodeId:R,canonicalNode:Kb(G),graphNode:O?{id:O.id,branch:O.branch,upstream:O.upstream,headCommit:O.submoduleCommit,submoduleCount:((Ee=(le=G==null?void 0:G.git)==null?void 0:le.submodules)==null?void 0:Ee.length)??0,snapshotCompleteness:O.snapshotCompleteness,snapshotWarnings:O.snapshotWarnings,branchConvergence:((Be=O.branchConvergence)==null?void 0:Be.status)??null}:null})}catch{}},[h.meshId,O,R,G]);const de=(B==null?void 0:B.kind)==="session"?Z.find(le=>le.nodeId===B.nodeId&&le.session.sessionId===B.sessionId)??null:null,ke=l.useMemo(()=>Z.filter(le=>le.nodeId===R),[R,Z]),ye=X1({coordinatorDaemonId:r,selectedNodeStatus:G,selectedSessionEntry:de}),we=(ye==null?void 0:ye.workspace)??null,he=we?M[we]??null:null,K=Y1(G,(he==null?void 0:he.entries)??[]),E=(O==null?void 0:O.daemonId)??(G==null?void 0:G.daemonId)??r??null,J=!!(O&&n&&E&&O.type!=="submoduleNode"&&O.behind>0&&O.ahead===0&&O.dirtyFiles===0&&!O.dirty&&!O.hasConflicts&&O.upstreamStatus==="fresh"),re=l.useCallback(()=>{L(null),P(null),Y(null),A(null)},[]);l.useEffect(()=>{A(null)},[R]);const be=l.useCallback(async()=>{if(!O||!E||!n||!J)return;T(O.id),A(null);const le=(G==null?void 0:G.workspace)??O.workspace??"";try{const Ee=await n(E,"fast_forward_mesh_node",{meshId:h.meshId,nodeId:O.id,workspace:le,updateSubmodules:!0,dryRun:!0,execute:!1}),Be=(Ee==null?void 0:Ee.result)??Ee;if(A({phase:"dry_run",code:typeof(Be==null?void 0:Be.code)=="string"?Be.code:void 0,error:typeof(Be==null?void 0:Be.operationError)=="string"?Be.operationError:null,executed:(Be==null?void 0:Be.executed)===!0}),!(Be!=null&&Be.success)||Be.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${O.label}?`))return;const qe=await n(E,"fast_forward_mesh_node",{meshId:h.meshId,nodeId:O.id,workspace:le,updateSubmodules:!0,dryRun:!1,execute:!0}),je=(qe==null?void 0:qe.result)??qe;A({phase:"execute",code:typeof(je==null?void 0:je.code)=="string"?je.code:void 0,error:typeof(je==null?void 0:je.operationError)=="string"?je.operationError:null,executed:(je==null?void 0:je.executed)===!0})}catch(Ee){A({phase:"dry_run",error:Ee instanceof Error?Ee.message:"fast-forward failed"})}finally{T(null)}},[J,h.meshId,O,E,n]);l.useEffect(()=>{if(!O&&!V)return;const le=Ee=>{Ee.key==="Escape"&&re()};return window.addEventListener("keydown",le),()=>window.removeEventListener("keydown",le)},[re,V,O]),l.useEffect(()=>{if(!ye||!n)return;const{daemonId:le,workspace:Ee}=ye,Be=M[Ee];if(Be!=null&&Be.loading||Be&&(Be.entries.length>0||Be.error))return;let Je=!1;return H(qe=>{var je;return{...qe,[Ee]:{loading:!0,error:null,entries:((je=qe[Ee])==null?void 0:je.entries)??[]}}}),n(le,"git_log",{workspace:Ee,limit:5}).then(qe=>{Je||H(je=>({...je,[Ee]:{loading:!1,error:null,entries:J1(qe)}}))}).catch(qe=>{Je||H(je=>({...je,[Ee]:{loading:!1,error:qe instanceof Error?qe.message:"git_log failed",entries:[]}}))}),()=>{Je=!0}},[M,ye,n]);const ue=[...f.warnings??[],...h.nodes.filter(le=>le.machineStatus&&le.machineStatus!=="online").map(le=>`${le.machineLabel}: ${le.machineStatus}`)],D=f.stats.incompleteSnapshotNodes>0,me=f.stats.followUpNodes>0?`${f.stats.followUpNodes} need follow-up`:D?"mesh visibility incomplete":"mesh converged",Se=f.stats.followUpNodes>0?"danger":D?"warn":"good",[oe,Q]=l.useState("LR"),ve=le=>le?m.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":m.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";return s.jsx(Zs.Provider,{value:m,children:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[!p&&s.jsx("div",{className:"shrink-0 flex items-center justify-end",children:s.jsx(Rm,{meshTheme:m,activeTab:C,onActiveTabChange:g,helpOpen:w,onHelpOpenChange:S})}),w&&s.jsx($1,{meshTheme:m,onClose:()=>S(!1)}),s.jsx("div",{className:`${C==="overview"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-3 overflow-y-auto`,children:C==="overview"&&s.jsx(g1,{status:h,daemonId:r,meshId:h.meshId,sendDaemonCommand:n})}),s.jsx("div",{className:`${C==="status"?"flex":"hidden"} min-h-0 flex-1 flex-col overflow-y-auto`,children:C==="status"&&s.jsx(lN,{canonicalStatus:h})}),s.jsx("div",{className:`${C==="graph"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-4`,children:s.jsxs("div",{className:`${m.cardClass} relative flex min-h-0 flex-1 flex-col rounded-[28px]`,style:{minHeight:480},children:[s.jsxs("div",{className:`relative z-30 max-h-[42dvh] overflow-y-auto sm:max-h-none 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 ${m.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-nowrap overflow-x-auto sm:flex-wrap sm:overflow-visible gap-2 text-xs ${m.textSecondary}`,children:[s.jsx(Ke,{label:me,tone:Se,className:"shrink-0"}),f.stats.blockedReviewNodes>0&&s.jsx(Ke,{label:`${f.stats.blockedReviewNodes} blocked`,title:`${f.stats.blockedReviewNodes} blocked review`,tone:"danger",className:"shrink-0"}),f.stats.notMergeableNodes>0&&s.jsx(Ke,{label:`${f.stats.notMergeableNodes} not mergeable`,tone:"danger",className:"shrink-0"}),f.stats.mergeReadyNodes>0&&s.jsx(Ke,{label:`${f.stats.mergeReadyNodes} need merge`,tone:"warn",className:"shrink-0"}),f.stats.cleanupCandidateNodes>0&&s.jsx(Ke,{label:`${f.stats.cleanupCandidateNodes} cleanup`,title:`${f.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info",className:"shrink-0"}),f.stats.offlineNodes>0&&s.jsx(Ke,{label:`${f.stats.offlineNodes} offline`,tone:"danger",className:"shrink-0"}),f.stats.incompleteSnapshotNodes>0&&s.jsx(Ke,{label:`${f.stats.incompleteSnapshotNodes} incomplete`,title:`${f.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn",className:"shrink-0"}),f.stats.missingGitSnapshotNodes>0&&s.jsx(Ke,{label:`${f.stats.missingGitSnapshotNodes} no-git`,title:`${f.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn",className:"shrink-0"}),f.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Ke,{label:`${f.stats.missingSubmoduleSnapshotNodes} no-submod`,title:`${f.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn",className:"shrink-0"}),f.stats.staleGitSnapshotNodes>0&&s.jsx(Ke,{label:`${f.stats.staleGitSnapshotNodes} stale`,title:`${f.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn",className:"shrink-0"}),((U==null?void 0:U.active)??0)>0&&s.jsx(Ke,{label:`${(U==null?void 0:U.active)??0} active queue`,tone:"info",className:"shrink-0 hidden sm:inline-flex"}),s.jsx(Ke,{label:`${f.stats.totalNodes} nodes`,tone:"default",className:"shrink-0 hidden sm:inline-flex"}),f.stats.totalActiveSessions>0&&s.jsx(Ke,{label:`${f.stats.totalActiveSessions} attached chats`,tone:"info",className:"shrink-0 hidden sm:inline-flex"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[s.jsxs("div",{className:m.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:()=>Q("auto"),className:ve(oe==="auto"),title:"Auto-detect direction",children:"Auto"}),s.jsx("button",{type:"button",onClick:()=>Q("LR"),className:ve(oe==="LR"),title:"Left to right",children:"LR"}),s.jsx("button",{type:"button",onClick:()=>Q("TB"),className:ve(oe==="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 ${m.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 ${m.textSecondary} [&::-webkit-details-marker]:hidden`,children:(()=>{var Be;const le=((Be=h.asyncRefineJobs)==null?void 0:Be.filter(Je=>Je.status==="failed").length)??0,Ee=te.recentFailures;return le>0?s.jsxs("span",{className:m.isDark?"text-rose-300":"text-rose-600",children:[le," refine failed"]}):Ee>0?s.jsxs("span",{className:m.isDark?"text-amber-300":"text-amber-600",children:[Ee," 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 ${m.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsx(cN,{canonicalStatus:h,queueSummary:U,ledgerSummary:te,isBootstrapMode:y,meshTheme:m,sessionEntries:Z,inlineMode:!0})})]})}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${m.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 ${m.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 ${m.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(Ke,{label:`${f.stats.dirtyNodes} dirty`,tone:f.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Ke,{label:`${f.stats.orphanNodes} orphan`,tone:f.stats.orphanNodes>0?"warn":"good"}),s.jsx(Ke,{label:`${te.recentFailures} recent failures`,tone:te.recentFailures>0?"danger":"good"}),se.length===0?s.jsx(Ke,{label:"no session metadata"}):se.slice(0,2).map(([le,Ee])=>s.jsx(Ke,{label:`${Ee} ${le}`,tone:jo(le)},le))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ke,{label:"Anchor = default branch",tone:"info"}),s.jsx(Ke,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Ke,{label:"Submodule link = child checkout",tone:"warn"})]}),ue.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:ue.map(le=>s.jsx("span",{className:m.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:le},le))}),s.jsx("div",{className:`text-xs ${m.textMuted}`,children:"Click a node or edge to pin its drill-down details in the side panel. Click it again to close."})]})})]})})]})]}),y&&f.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 ${m.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 ${m.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:N?f.nodes.length>0?s.jsx(i1,{data:f,selectedNodeId:R,directionPref:oe,onNodeClick:le=>{if((B==null?void 0:B.kind)==="node"&&R===le.id){re();return}P(null),L(le.id),Y({kind:"node",nodeId:le.id})},onEdgeClick:le=>{if((B==null?void 0:B.kind)==="edge"&&_===le.id){re();return}L(null),P(le.id),Y({kind:"edge",edgeId:le.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…"})}),O&&(B==null?void 0:B.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 ${m.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 ${m.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 ${m.textPrimary}`,children:O.label}),s.jsx("div",{className:`mt-0.5 font-mono text-[11px] ${m.textMuted}`,children:O.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[O.behind>0&&s.jsx("button",{type:"button",onClick:()=>{be()},disabled:!J||$===O.id,className:m.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:$===O.id?"Checking":"Heal"}),s.jsx("button",{type:"button",onClick:re,"aria-label":"Close detail panel",className:m.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 le=(G==null?void 0:G.health)??O.health;return le==="unknown"?s.jsx(Ke,{label:"connecting...",tone:"default"}):s.jsx(Ke,{label:le,tone:Tm(le)})})(),O.branch&&s.jsx(Ke,{label:O.branch,tone:"default"}),O.ahead>0&&s.jsx(Ke,{label:`ahead ${O.ahead}`,tone:"warn"}),O.behind>0&&s.jsx(Ke,{label:`behind ${O.behind}`,tone:"warn"}),O.dirtyFiles>0&&s.jsx(Ke,{label:`${O.dirtyFiles} dirty`,tone:"warn"}),(G==null?void 0:G.connection)&&G.connection.state!=="unknown"&&s.jsx(Ke,{label:Q1(G),tone:H1(G.connection)}),((We=G==null?void 0:G.connection)==null?void 0:We.state)==="unknown"&&s.jsx(Ke,{label:"mesh connecting...",tone:"warn"}),ke.length>0&&s.jsx(Ke,{label:`${ke.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[O.machineLabel&&s.jsx(St,{label:"Machine",value:O.machineLabel}),O.locality&&O.locality!=="unknown"&&s.jsx(St,{label:"Locality",value:O.locality}),s.jsx(St,{label:"Workspace",value:(G==null?void 0:G.workspace)??O.workspace}),K&&s.jsx(St,{label:"HEAD",value:K}),(O.dirtyFiles>0||O.ahead>0||O.behind>0)&&s.jsx(St,{label:"Dirty/ahead/behind",value:`${O.dirtyFiles}/${O.ahead}/${O.behind}`}),ke.length>0&&s.jsx(St,{label:"Sessions",value:String(ke.length)}),O.upstream&&s.jsx(St,{label:"Upstream",value:O.upstream}),(()=>{var Ee;const le=((Ee=G==null?void 0:G.connection)==null?void 0:Ee.source)??Z1(O);return le&&le!=="unknown"?s.jsx(St,{label:"Source",value:String(le)}):null})(),(()=>{var Ee;const le=(Ee=G==null?void 0:G.connection)==null?void 0:Ee.transport;return le&&le!=="unknown"?s.jsx(St,{label:"Transport",value:le}):null})(),(()=>{const le=O.machineId??(G==null?void 0:G.machineId);return le?s.jsx(St,{label:"Machine id",value:le}):null})(),(()=>{const le=O.daemonId??(G==null?void 0:G.daemonId);return le?s.jsx(St,{label:"Daemon id",value:le}):null})()]}),ke.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${m.textMuted}`,children:"Active Sessions"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:ke.map(le=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${m.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 ${m.textMuted}`,title:le.session.sessionId,children:Lm(le.session.sessionId)}),s.jsx(Ke,{label:qn(le.session),tone:jo(qn(le.session))})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 ${m.textMuted}`,children:[s.jsx("span",{className:"truncate",children:le.session.providerType||"provider unknown"}),s.jsx("span",{children:B1(le.session)}),s.jsx("span",{children:O1(le.session)})]}),le.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${m.textMuted}`,children:le.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${m.textMuted}`,title:le.session.workspace||le.workspace,children:[(le.session.workspace||le.workspace).slice(0,38),le.branch?` · ${le.branch}`:""]})]},le.session.sessionId))})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${m.textMuted}`,children:"Ledger (mesh-wide)"}),s.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[s.jsx(St,{label:"Completed",value:String(te.taskCompleted)}),s.jsx(St,{label:"Failed",value:s.jsx("span",{className:te.taskFailed>0?m.isDark?"text-rose-300":"text-rose-600":"",children:te.taskFailed})}),s.jsx(St,{label:"Launched",value:String(te.sessionLaunched)}),s.jsx(St,{label:"Recent failures",value:s.jsx("span",{className:te.recentFailures>0?m.isDark?"text-amber-300":"text-amber-600":"",children:te.recentFailures})})]})]}),(()=>{var Be,Je;const le=((Be=h.queue)==null?void 0:Be.tasks)??((Je=h.queue)==null?void 0:Je.items)??null;if(!Array.isArray(le)||le.length===0)return null;const Ee=le.filter(qe=>V1(qe)===R).slice(0,3);return Ee.length===0?null:s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${m.textMuted}`,children:"Queue tasks"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:Ee.map(qe=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${m.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 ${m.textMuted}`,children:qe.id.slice(0,12)}),s.jsx(Ke,{label:qe.status??"unknown",tone:jo(qe.status)})]}),qe.message&&s.jsx("div",{className:`mt-0.5 truncate ${m.textMuted}`,children:qe.message.slice(0,48)})]},qe.id))})]})})(),O.snapshotWarnings.length>0&&s.jsxs("div",{className:m.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:O.snapshotWarnings[0]})]}),O.branchConvergence&&(O.branchConvergence.reason||O.branchConvergence.nextStep)&&s.jsxs("div",{className:m.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.jsxs("div",{className:"font-medium",children:["Follow-up — ",dN[O.branchConvergence.status]??O.branchConvergence.status]}),O.branchConvergence.reason&&s.jsx("div",{className:"mt-1",children:O.branchConvergence.reason}),O.branchConvergence.nextStep&&s.jsx("div",{className:`${O.branchConvergence.reason?"mt-1.5 pt-1.5 border-t border-sky-400/20":"mt-1"}`,children:O.branchConvergence.nextStep})]}),q&&s.jsxs("div",{className:m.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:q.phase==="execute"?"Heal result":"Heal preview"}),s.jsx("div",{className:"mt-1",children:q.code??q.error??"No result code returned."})]})]}),V&&(B==null?void 0:B.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 ${m.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 ${m.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 ${m.textPrimary}`,children:V.label||sd(V)}),s.jsx("div",{className:`mt-0.5 break-all font-mono text-[11px] ${m.textMuted}`,children:V.id})]}),s.jsx("button",{type:"button",onClick:re,"aria-label":"Close detail panel",className:m.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(Ke,{label:sd(V),tone:"default"}),s.jsx(Ke,{label:eN(V),tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(St,{label:"From",value:(pe==null?void 0:pe.label)??V.source}),s.jsx(St,{label:"To",value:(fe==null?void 0:fe.label)??V.target}),s.jsx(St,{label:"Label",value:V.label??"none"})]})]})]})]})})]})})}function vt(e){return typeof e=="string"?e.trim():""}function li(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function al(...e){const t=new Set;for(const r of e){const n=vt(r);n&&t.add(n)}return[...t]}function pN(e,t){var m,h;const r=li(e==null?void 0:e.settings),n=vt((m=e==null?void 0:e.coordinator)==null?void 0:m.meshId)||vt(r.meshCoordinatorFor),a=vt(r.meshNodeFor),o=!!n||!!a,i=n===t||a===t;if(o&&!i)return null;const c=li(e==null?void 0:e.activeChat),d=al(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?vt((h=e==null?void 0:e.coordinator)==null?void 0:h.role)||"coordinator":a===t?vt(r.meshNodeRole)||"worker":vt(e==null?void 0:e.role)||vt(r.meshNodeRole)||void 0;return{sessionId:p,aliases:d,meshId:t,nodeId:i&&vt(r.meshNodeId)||null,providerType:vt(e==null?void 0:e.providerType)||void 0,state:vt(e==null?void 0:e.status)||void 0,chatStatus:vt(c.status)||void 0,lifecycle:vt(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:vt(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:vt(e==null?void 0:e.runtimeRecoveryState)||void 0,...u?{role:u}:{},...i?{isSelfCoordinator:n===t}:{},workspace:vt(e==null?void 0:e.workspace)||null}}function Pm(e,t){var n;return t?(Array.isArray((n=e.status)==null?void 0:n.sessions)?e.status.sessions:[]).map(a=>pN(a,t)).filter(a=>a!==null):[]}function xa(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function mN(e,t){const r=new Set(xa(t));return xa(e).some(n=>r.has(n))}function hN(e,t){const r=t.filter(a=>!!a);return r.length===0?e:[...e.filter(a=>!r.some(o=>mN(a,o))),...r]}function fN(e,t){if(t.length===0)return e;const r=new Map;for(const i of t)for(const c of xa(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 y=al(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),x=y[0]||"";if(!x)continue;const f=y.map(v=>r.get(v)).find(Boolean);f&&(n=!0),p.set(x,f?{...h,sessionId:x,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:x})}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(xa(h).some(v=>p.has(v)))continue;const x=h.nodeId!=null&&h.nodeId===i.nodeId,f=h.isSelfCoordinator&&!h.nodeId&&u;!x&&!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 xN(e,t){const n=Pm(e,t).map(a=>{var d;const o=(Array.isArray((d=e.status)==null?void 0:d.sessions)?e.status.sessions:[]).find(p=>vt(p==null?void 0:p.id)===a.sessionId),i=li(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??"",vt(i.status)||vt(i.kind)||vt(i.type),a.nodeId??"",a.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(a=>!!a).sort();return n.length>0?n.join(`
84
- `):null}function Dm({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 y=new Set;if(t&&y.add(t),r)for(const x of r)x&&y.add(x);return[...y].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 y=p.map(x=>rs.subscribe({sendData:a},x,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${x}`,params:{includeSessions:!0}},f=>{if(f.topic!=="daemon.metadata")return;const v=xN(f,n);if(v===(d.current.get(x)??null))return;d.current.set(x,v);const k=Pm(f,n);c(b=>{const j=new Map(b);return j.set(x,k),j})}));return()=>{for(const x of y)x()}},[u,n,a]);const m=l.useMemo(()=>{const y=[];for(const x of i.values())y.push(...x);return y},[i]),h=l.useMemo(()=>hN(m,o),[o,m]);return l.useMemo(()=>e?fN(e,h):null,[h,e])}const rd=[1500,4e3,9e3];function bN(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 gN(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>{var r;return bN(t)?!1:t.gitProbePending||((r=t.connection)==null?void 0:r.state)==="connecting"?!0:t.machineStatus==="online"||t.launchReady===!0})}function yN(e){return!Number.isInteger(e)||e<0?rd[0]:rd[e]??null}const ko=new Map;function vN(e,t){return!e||!t?null:`${e}::${t}`}function wN(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:al(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 $m({activeConv:e,sendDaemonCommand:t,onClose:r}){var te,Z,se,G,O,V;const n=((te=e.coordinator)==null?void 0:te.meshId)??(typeof((Z=e.settings)==null?void 0:Z.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),a=e.daemonId??null,o=vN(a,n),i=o?ko.get(o)??null:null,c=_i(),{sendData:d}=xt(),{theme:p}=Ts(),u=l.useMemo(()=>Ls(p),[p]),[m,h]=l.useState("overview"),[y,x]=l.useState(!1),f=l.useMemo(()=>wN(e,n),[e.agentType,(se=e.coordinator)==null?void 0:se.meshId,e.sessionId,(G=e.settings)==null?void 0:G.meshCoordinatorFor,(O=e.settings)==null?void 0:O.meshNodeFor,(V=e.settings)==null?void 0:V.meshNodeId,e.status,e.workspacePath,n]),[v,k]=l.useState(i),[b,j]=l.useState(!1),[C,w]=l.useState(!1),[g,S]=l.useState(!1),[N,I]=l.useState(null),[R,L]=l.useState((i==null?void 0:i.refreshedAt)??null),_=l.useRef(i!==null),P=l.useRef(!1),B=l.useRef(!1),Y=l.useRef(!0),M=l.useRef(0),H=l.useRef(null);l.useEffect(()=>{_.current=v!==null},[v]);const q=l.useCallback(()=>{H.current!==null&&(clearTimeout(H.current),H.current=null)},[]);l.useEffect(()=>{q(),M.current=0;const pe=o?ko.get(o)??null:null;k(pe),L((pe==null?void 0:pe.refreshedAt)??null),_.current=pe!==null,B.current=!1,w(!1),I(null)},[o,q]);const A=l.useCallback(async(pe=!1,fe=!1)=>{if(!a||!n){I("This coordinator does not expose a live mesh id."),k(null);return}if(P.current){pe&&(B.current=!0);return}fe||(q(),M.current=0),P.current=!0;const de=!_.current;j(de),w(pe&&_.current),I(null);try{const ke=c!=null&&c.loadMeshStatus?await c.loadMeshStatus(a,n,{refresh:pe,retryProfile:fe?"interactive":"settled"}):await t(a,"mesh_status",{meshId:n,refresh:pe}),ye=Li(ke);if(!ye){I("mesh_status returned an unexpected payload.");return}if(o&&ko.set(o,ye),k(ye),_.current=!0,L(ye.refreshedAt||new Date().toISOString()),gN(ye.nodes)){const we=yN(M.current);we!==null&&Y.current&&(M.current+=1,H.current=setTimeout(()=>{Y.current&&A(!0,!0)},we))}else M.current=0}catch(ke){I(ke instanceof Error?ke.message:"Failed to load live mesh status")}finally{P.current=!1,j(!1),w(!1),B.current&&Y.current&&(B.current=!1,window.setTimeout(()=>{Y.current&&A(!0)},0))}},[o,q,a,n,c,t]);l.useEffect(()=>(Y.current=!0,M.current=0,(async()=>(await A(!1,!0),Y.current&&H.current===null&&!P.current&&A(!0,!0)))(),()=>{Y.current=!1,q()}),[A,q]),l.useEffect(()=>{const pe=fe=>{fe.key==="Escape"&&r()};return window.addEventListener("keydown",pe),()=>window.removeEventListener("keydown",pe)},[r]);const $=(v==null?void 0:v.meshName)||n||"Repo Mesh",T=l.useMemo(()=>f?[f]:[],[f]),F=Dm({status:v,daemonId:a,meshId:n,sendData:d,extraLiveSessions:T}),z=R?new Date(R).toLocaleTimeString():null,U=l.useMemo(()=>b?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[b]);return s.jsx("div",{className:u.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:u.dialogShellClass,onClick:pe=>pe.stopPropagation(),children:[s.jsxs("div",{className:`relative ${u.dialogHeaderClass}`,children:[s.jsx("button",{type:"button",onClick:r,className:`absolute right-4 top-[calc(16px+env(safe-area-inset-top,0px))] z-10 md:right-5 md:top-1/2 md:-translate-y-1/2 ${u.dialogCloseButtonClass}`,"aria-label":"Close mesh graph",children:s.jsx(wt,{size:16})}),s.jsx("div",{className:"min-w-0 flex-1 pr-12 md:pr-0",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(Yt,{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:$}),s.jsx("span",{className:u.dialogKickerClass,children:"Mesh observability"}),s.jsx("button",{type:"button",onClick:()=>S(pe=>!pe),"aria-expanded":g,"aria-label":g?"Hide mesh details":"Show mesh details",className:"btn btn-secondary btn-sm rounded-lg px-1.5 py-1 md:hidden",title:g?"Hide mesh details":"Show mesh details",children:s.jsx(gi,{size:14})})]}),s.jsxs("p",{className:`${u.dialogSubtitleClass} ${g?"block":"hidden"} md:block`,children:[ft(e),e.workspaceName?` · ${e.workspaceName}`:"",v!=null&&v.repoIdentity?` · ${v.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end md:pr-12",children:[s.jsx(Rm,{meshTheme:u,activeTab:m,onActiveTabChange:h,helpOpen:y,onHelpOpenChange:x}),z&&s.jsx("span",{className:`${u.dialogRefreshedChipClass} ${g?"inline-flex":"hidden"} md:inline-flex`,children:`Refreshed ${z}`}),!C&&v&&s.jsx("span",{className:`${u.dialogRefreshedChipClass} ${g?"inline-flex":"hidden"} md:inline-flex`,children:d&&!N?"Live daemon metadata":"Metadata subscription unavailable"}),s.jsx("button",{type:"button",onClick:()=>{A(!0)},disabled:b||C,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:b||C?"Refreshing…":"Refresh"})]})]}),N&&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:N}),s.jsx("div",{className:u.dialogBodyClass,children:F?s.jsx(uN,{status:F,emptyMessage:U,daemonId:a,sendDaemonCommand:t,activeTab:m,onActiveTabChange:h,helpOpen:y,onHelpOpenChange:x,hideControls:!0}):s.jsx("div",{className:u.dialogEmptyClass,children:U})})]})})}function jN(e,t){const{sendCommand:r}=xt(),[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=kN(n);return{remoteUrl:n,githubUrl:c,loading:o}}function kN(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 Em=5e3;function NN(e){return`git:${e}`}function SN({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Em}){return{type:"subscribe",topic:"workspace.git",key:NN(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function ol(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Js(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 CN(e){const t=ol(e);return(t==null?void 0:t.success)===!1?{status:null,error:Js(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Js(t,"Git status response did not include status")}}function IN(e){const t=ol(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Js(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Js(t,"Git diff summary response did not include diffSummary")}}function No(e){return e===void 0||typeof e=="boolean"}function AN(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&No(t.binary)&&No(t.truncated)&&No(t.staged)}function MN(e){const t=ol(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Js(t,"Git file diff request failed")}:AN(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Js(t,"Git file diff response did not include a valid diff object")}}function _N({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Em}){const{sendCommand:o,sendData:i}=xt(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[p,u]=l.useState(null),[m,h]=l.useState(null),[y,x]=l.useState(!1),[f,v]=l.useState(null),k=l.useCallback(async()=>{if(!(!d||!e||!c)){x(!0),v(null);try{const j=CN(await o(e,"git_status",{workspace:c}));if(j.error){u(null),h(null),v(j.error);return}if(u(j.status),!n){h(null);return}const C=IN(await o(e,"git_diff_summary",{workspace:c}));if(C.error){h(null),v(C.error);return}h(C.diffSummary)}catch(j){v(Js(j,"Git status request failed"))}finally{x(!1)}}},[d,e,n,o,c]),b=l.useMemo(()=>c?SN({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return l.useEffect(()=>{if(!d||!e||!c||!b){u(null),h(null),x(!1),v(null);return}const j=i?rs.subscribe({sendData:i},e,b,C=>{var w,g;C.workspace===c&&(u(C.status),h(C.diffSummary??null),v(((w=C.status)==null?void 0:w.error)||((g=C.diffSummary)==null?void 0:g.error)||null),x(!1))},{retryIntervalMs:1e3}):null;return k(),()=>{j==null||j()}},[d,e,k,b,i,c]),{status:p,diffSummary:m,loading:y,error:f,refresh:k}}const TN={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},LN={added:"text-status-online",modified:"text-orange-400",deleted:"text-status-error",renamed:"text-accent-primary",copied:"text-accent-primary",untracked:"text-text-muted",conflict:"text-status-error font-bold"};function nd(e){return e.split("/").pop()??e}function RN(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function PN({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=TN[o.status]??"?",d=LN[o.status]??"text-text-muted",p=RN(o.path),u=nd(o.path),m=o.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-status-online 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:["← ",nd(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-status-online",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-status-error",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 DN(e,t){let r="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?r="bg-status-online/10 text-status-online":e.startsWith("-")&&!e.startsWith("---")?r="bg-status-error/10 text-status-error":e.startsWith("@@")?r="text-accent-primary":(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 $N({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-status-error ${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(`
85
- `);return s.jsxs("div",{ref:i,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((d,p)=>DN(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 EN(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(`
86
- `)}function Bm({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=xt(),{status:a,diffSummary:o,loading:i,error:c,refresh:d}=_N({daemonId:e,workspace:t,includeDiffSummary:!0}),[p,u]=l.useState(null),[m,h]=l.useState(null),[y,x]=l.useState(""),[f,v]=l.useState(!1),[k,b]=l.useState(!1),[j,C]=l.useState(null),[w,g]=l.useState(null),{githubUrl:S}=jN(e,t),N=l.useCallback(async B=>{if(!((p==null?void 0:p.path)===B.path&&!p.loading)){u({path:B.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const Y=await n(e,"git_diff_file",{workspace:t,path:B.path,staged:B.staged}),M=MN(Y);if(M.error||!M.diff){u({path:B.path,diff:"",binary:!1,truncated:!1,loading:!1,error:M.error??"Failed to load diff"});return}u({path:B.path,diff:M.diff.diff,binary:M.diff.binary??!1,truncated:M.diff.truncated??!1,loading:!1,error:null})}catch(Y){const M=Y instanceof Error?Y.message:"Failed to load diff";u({path:B.path,diff:"",binary:!1,truncated:!1,loading:!1,error:M})}}},[e,n,p,t]),I=l.useCallback(B=>{x(""),v(!1),C(null),g(null),h(B)},[]),R=l.useCallback(()=>{h(null),C(null),b(!1)},[]),L=l.useCallback(async()=>{var B,Y,M;if(m){b(!0),C(null);try{let H;m==="checkpoint"?H=await n(e,"git_checkpoint",{workspace:t,message:y,includeUntracked:f}):m==="stash"?H=await n(e,"git_stash_push",{workspace:t,message:y,includeUntracked:f}):m==="stash_pop"?H=await n(e,"git_stash_pop",{workspace:t}):m==="checkout_files"&&p&&(H=await n(e,"git_checkout_files",{workspace:t,paths:[p.path]}));const q=(H==null?void 0:H.result)??H;if((q==null?void 0:q.success)===!1||q!=null&&q.error){C((q==null?void 0:q.error)??"Action failed"),b(!1);return}m==="checkpoint"?g(`Checkpoint created: ${((Y=(B=q==null?void 0:q.checkpoint)==null?void 0:B.commit)==null?void 0:Y.slice(0,7))??"done"}`):m==="stash"?g(`Stashed as ${((M=q==null?void 0:q.stash)==null?void 0:M.stashRef)??"stash@{0}"}`):m==="stash_pop"?g("Stash restored"):(g("File reverted"),u(null)),h(null),await d()}catch(H){C(H instanceof Error?H.message:"Action failed")}finally{b(!1)}}},[m,n,e,t,y,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:B=>{B.target===B.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}),S&&s.jsx("a",{href:`${S}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-accent-primary 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(wt,{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-status-online",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-status-error",children:[a.deleted," deleted"]}),a.stashCount>0&&s.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&s.jsx("span",{className:"font-bold text-status-error",children:"conflicts"}),P===0&&!a.error&&s.jsx("span",{className:"text-status-online",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-status-online",children:[" +",o.totalInsertions]}),o.totalDeletions>0&&s.jsxs("span",{className:"text-status-error",children:[" -",o.totalDeletions]})]})]}),c&&s.jsx("div",{className:"shrink-0 border-b border-border/50 bg-status-error/10 px-4 py-2 text-xs text-status-error",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(PN,{files:o.files,truncated:o.truncated,selectedPath:(p==null?void 0:p.path)??null,onFileClick:N}),!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($N,{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-status-online/10 px-4 py-2 text-xs text-status-online flex items-center justify-between",children:[s.jsx("span",{children:w}),s.jsx("button",{onClick:()=>g(null),className:"ml-2 text-status-online 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 B=EN((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(B),g("Copied to clipboard"),setTimeout(()=>g(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:y,onChange:B=>x(B.target.value),maxLength:200,placeholder:"Message (required)",className:"rounded border border-border bg-surface-secondary 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:B=>v(B.target.checked)}),"Include untracked files"]})]}),j&&s.jsx("p",{className:"text-xs text-status-error",children:j}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:R,disabled:k,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:L,disabled:k||(m==="checkpoint"||m==="stash")&&!y.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:k?"Working…":"Confirm"})]})]})})]})})}function BN({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),[y,x]=l.useState("quickstart"),[f,v]=l.useState("workspace"),k=l.useMemo(()=>!t&&!e,[t,e]),b=l.useCallback(N=>{a(N),N&&i(!1)},[]),j=l.useCallback(N=>{i(N),N&&a(!1)},[]),C=l.useCallback(()=>{x(r===0?"quickstart":"shortcuts"),v("workspace"),d(!0),a(!1),i(!1)},[r]),w=l.useCallback(()=>{d(!1)},[]),g=l.useCallback(()=>{u(!0)},[]),S=l.useCallback(()=>{u(!1)},[]);return l.useEffect(()=>{if(!k){h(!1);return}h(!0);const N=window.setTimeout(()=>{h(!1)},1e4);return()=>window.clearTimeout(N)},[k]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:p,guideNudgeVisible:m,guideTab:y,shortcutSection:f,isDesktopDashboard:k,setGuideTab:x,setShortcutSection:v,handleInboxOpenChange:b,handleHiddenOpenChange:j,handleOpenShortcutHelp:C,closeShortcutHelp:w,openNewSession:g,closeNewSession:S}}function FN(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 ON(e){return e instanceof Error?e.message:String(e||"")}function HN(e){const t=ON(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function WN({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:y,sendDaemonCommand:x,setActionLogs:f,setCliViewModeOverrides:v,isStandalone:k,initialDataLoaded:b,userName:j,requestedMobileTabKey:C,onRequestedMobileTabConsumed:w,requestedMachineId:g,onRequestedMachineConsumed:S,requestedMobileSection:N,onRequestedMobileSectionConsumed:I,containerRef:R,isSplitMode:L,numGroups:_,groupSizes:P,groupedConvs:B,clearedTabs:Y,focusedGroup:M,focusGroup:H,moveTabToGroup:q,splitTabRelative:A,closeGroup:$,handleResizeStart:T,groupActiveTabIds:F,setGroupActiveTab:z,groupTabOrders:U,setGroupTabOrder:te,toggleHiddenTab:Z,visibleConversations:se,requestedDesktopTabKey:G,onRequestedDesktopTabConsumed:O,onDesktopActiveTabChange:V,onRequestScrollToBottom:pe,onHideConversation:fe,onShowHiddenConversation:de,onShowAllHiddenConversations:ke,scrollToBottomRequest:ye,machineEntries:we,layoutProfile:he,onBrowseMachineDirectory:K,onSaveMachineWorkspace:E,onLaunchMachineIde:J,onLaunchMachineProvider:re,onListMachineMeshes:be,onLaunchMeshCoordinator:ue,onListMachineSavedSessions:D,notifications:me,notificationUnreadCount:Se,liveSessionInboxState:oe,onMarkNotificationRead:Q,onMarkNotificationUnread:ve,onDeleteNotification:Ne}){const Le=It.useRef(null),{inboxOpen:We,hiddenOpen:le,shortcutHelpOpen:Ee,newSessionOpen:Be,guideNudgeVisible:Je,guideTab:qe,shortcutSection:je,isDesktopDashboard:at,setGuideTab:Ie,setShortcutSection:ot,handleInboxOpenChange:nt,handleHiddenOpenChange:Qe,handleOpenShortcutHelp:Lt,closeShortcutHelp:X,openNewSession:ee,closeNewSession:ne}=BN({isMobile:t,showMobileChatMode:e,visibleConversationCount:se.length}),[ie,xe]=It.useState(null),[Ae,De]=It.useState(null),Ce=It.useCallback((Te,Ve)=>{xe({daemonId:Te,workspace:Ve})},[]),Re=It.useCallback(Te=>{De(Te)},[]),He=It.useCallback(Te=>{var Ve;ur.flushSync(()=>{de(Te)}),(Ve=Le.current)==null||Ve.restoreHiddenTabToSavedLocation(Te.tabKey)},[de]),Xe=It.useCallback(Te=>{var Rt;const Ve=u.find(jt=>Uo(jt,Te))||m.find(jt=>Uo(jt,Te));Ve&&(m.some(jt=>jt.tabKey===Ve.tabKey)&&He(Ve),V(Ve.tabKey),(Rt=Le.current)==null||Rt.activateConversationTab(Ve.tabKey),pe(Ve.tabKey,"notification-open")),Q(Te.id),nt(!1)},[He,m,u,V,Q,pe]),Oe=It.useCallback(()=>{var Ve;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Ve=Le.current)==null||Ve.resetAllPanelsToMain(),Qe(!1))},[Qe]),Ue=It.useCallback(async Te=>{var Ut;if(!r)return;const Ve=(Ut=r.modalButtons)==null?void 0:Ut[Te];if(!Ve)return;const Rt=Hs(r);if(!Rt)return;const jt=Ve.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Kt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(jt);try{await x(Rt,"resolve_action",{button:Ve,action:Kt?"approve":"reject",buttonIndex:Te,...Os(r)})}catch(zt){HN(zt)||console.error("[Shortcut approval] Failed:",zt)}},[r,x]),{isMac:ae,actionDefinitions:ce,actionShortcuts:ge,shortcutListening:$e,shortcutListeningDraft:Fe,setShortcutListening:Ye,setShortcutListeningDraft:Ze,saveShortcuts:rt}=bj({enabled:at&&!Ee,onTrigger:Te=>{var Ve,Rt,jt,Kt,Ut,zt,is,W,Me,Pe,dt,Et,Rs,Mt,vs,ws;if(Te==="openShortcutHelp"){Lt();return}if(Te==="openNewSession"){ee();return}if(Te==="hideCurrentTab"){r&&fe(r);return}if(Te==="toggleHiddenTabs"){Qe(!le);return}if(Te==="openHistoryForActiveTab"){r&&!it(r)&&o(r);return}if(Te==="openRemoteForActiveTab"){r&&!lt(r)&&!it(r)&&i(r);return}if(Te==="splitActiveTabRight"){(Ve=Le.current)==null||Ve.splitActiveTabRight();return}if(Te==="splitActiveTabDown"){(Rt=Le.current)==null||Rt.splitActiveTabDown();return}if(Te==="floatActiveTab"){(jt=Le.current)==null||jt.floatActiveTab();return}if(Te==="popoutActiveTab"){(Kt=Le.current)==null||Kt.popoutActiveTab();return}if(Te==="dockActiveTab"){(Ut=Le.current)==null||Ut.dockActiveTab();return}if(Te==="focusLeftPane"){(zt=Le.current)==null||zt.focusLeftPane();return}if(Te==="focusRightPane"){(is=Le.current)==null||is.focusRightPane();return}if(Te==="focusUpPane"){(W=Le.current)==null||W.focusUpPane();return}if(Te==="focusDownPane"){(Me=Le.current)==null||Me.focusDownPane();return}if(Te==="moveActiveTabToLeftPane"){(Pe=Le.current)==null||Pe.moveActiveTabToLeftPane();return}if(Te==="moveActiveTabToRightPane"){(dt=Le.current)==null||dt.moveActiveTabToRightPane();return}if(Te==="moveActiveTabToUpPane"){(Et=Le.current)==null||Et.moveActiveTabToUpPane();return}if(Te==="moveActiveTabToDownPane"){(Rs=Le.current)==null||Rs.moveActiveTabToDownPane();return}if(Te==="triggerPrimaryApprovalAction"){Ue(0);return}if(Te==="triggerSecondaryApprovalAction"){Ue(1);return}if(Te==="triggerTertiaryApprovalAction"){Ue(2);return}if(Te==="setActiveTabShortcut"){(Mt=Le.current)==null||Mt.setShortcutForActiveTab();return}if(Te==="selectPreviousGroupTab"){(vs=Le.current)==null||vs.activatePreviousTabInGroup();return}if(Te==="selectNextGroupTab"){(ws=Le.current)==null||ws.activateNextTabInGroup();return}!r||!lt(r)||it(r)||Te==="toggleCliView"&&p(d==="chat"?"terminal":"chat")}}),Ge=It.useCallback(()=>{X(),Ye(null),Ze([])},[X,Ye,Ze]),Nt=It.useMemo(()=>je==="all"?ce:ce.filter(Te=>FN(Te)===je),[ce,je]),Xt=It.useCallback(()=>{const Te=Object.fromEntries(ce.map(Ve=>[Ve.id,""]));rt(Te)},[ce,rt]),Ht=It.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const Te=Object.fromEntries(ce.map(Ve=>[Ve.id,Ve.defaultShortcut]));rt(Te)},[ce,rt]);return It.useEffect(()=>{const Te=Ve=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Ve.metaKey&&Ve.key.toLowerCase()==="w":Ve.ctrlKey&&Ve.key.toLowerCase()==="w")&&(Ve.preventDefault(),r&&fe&&fe(r))};return window.addEventListener("keydown",Te),()=>window.removeEventListener("keydown",Te)},[r,fe]),It.useEffect(()=>{if(!Ee||$e)return;const Te=Ve=>{Ve.key==="Escape"&&(Ve.preventDefault(),Ge())};return window.addEventListener("keydown",Te,!0),()=>window.removeEventListener("keydown",Te,!0)},[Ge,Ee,$e]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(t0,{activeConv:r,wsStatus:n,isConnected:a,conversations:se,hiddenConversations:m,onOpenHistory:o,onHideConversation:fe,onShowConversation:He,onShowAllHidden:ke,onResetPanelsToMain:Oe,notifications:me,notificationUnreadCount:Se,onOpenNotification:Xe,onMarkNotificationRead:Q,onMarkNotificationUnread:ve,onDeleteNotification:Ne,inboxOpen:We,onInboxOpenChange:nt,hiddenOpen:le,onHiddenOpenChange:Qe,onOpenNewSession:t?void 0:ee,onOpenDashboardGuide:Lt,guideNudgeVisible:Je,actionShortcuts:ge,onOpenRemote:()=>{!r||lt(r)||it(r)||i(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:p,onOpenGitDialog:Ce,onOpenMeshGraph:Re}),e?s.jsx(aj,{conversations:u,hiddenConversations:m,ides:h,actionLogs:y,sendDaemonCommand:x,setActionLogs:f,setCliViewModeOverrides:v,isStandalone:k,userName:j,requestedActiveTabKey:C,onRequestedActiveTabConsumed:w,requestedMachineId:g,onRequestedMachineConsumed:S,requestedMobileSection:N,onRequestedMobileSectionConsumed:I,onOpenHistory:o,onOpenRemote:i,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:ke,onHideConversation:fe,onOpenMeshGraph:Re,onOpenNewSession:ee,liveSessionInboxState:oe}):t?s.jsx(mj,{containerRef:R,isSplitMode:L,numGroups:_,groupSizes:P,groupedConvs:B,clearedTabs:Y,ides:h,actionLogs:y,sendDaemonCommand:x,setActionLogs:f,isStandalone:k,hasRegisteredMachines:we.length>0,userName:j,focusedGroup:M,focusGroup:H,moveTabToGroup:q,splitTabRelative:A,closeGroup:$,handleResizeStart:T,groupActiveTabIds:F,setGroupActiveTab:z,groupTabOrders:U,setGroupTabOrder:te,toggleHiddenTab:Z,onOpenNewSession:ee,allowTabShortcuts:!1,liveSessionInboxState:oe}):s.jsx(Tj,{visibleConversations:se,clearedTabs:Y,ides:h,actionLogs:y,sendDaemonCommand:x,setActionLogs:f,isStandalone:k,hasRegisteredMachines:we.length>0,initialDataLoaded:b,userName:j,toggleHiddenTab:Z,actionShortcuts:ge,registerActionHandlers:Te=>{Le.current=Te},onActiveTabChange:V,requestedActiveTabKey:G,onRequestedActiveTabConsumed:O,onRequestScrollToBottom:pe,scrollToBottomRequest:ye,onOpenNewSession:ee,liveSessionInboxState:oe,layoutProfile:he}),Be&&s.jsx(Hj,{machines:we,ides:h,onClose:ne,onBrowseDirectory:K,onSaveWorkspace:E,onLaunchIde:J,onLaunchProvider:re,onListMeshes:be,onLaunchMeshCoordinator:ue,onListSavedSessions:D}),Ae&&s.jsx($m,{activeConv:Ae,sendDaemonCommand:x,onClose:()=>De(null)}),ie&&s.jsx(Bm,{daemonId:ie.daemonId,workspace:ie.workspace,onClose:()=>xe(null)}),Ee&&s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:Ge,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:Te=>Te.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:Ge,"aria-label":"Close dashboard guide",children:s.jsx(wt,{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(Te=>s.jsx("button",{type:"button",className:`btn btn-sm ${qe===Te.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ie(Te.id),children:Te.label},Te.id))}),qe==="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 ",ae?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),qe==="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."]})]})]})]}),qe==="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(Te=>s.jsx("button",{type:"button",className:`btn btn-sm ${je===Te.id?"btn-primary":"btn-secondary"}`,onClick:()=>ot(Te.id),children:Te.label},Te.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Xt,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:Ht,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Nt.map(Te=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${$e===Te.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:Te.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Te.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:Te.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-surface-secondary border border-border-subtle min-w-[72px] text-center",children:$e===Te.id?Fe.length>0?`${Fe.join(" ")} ...`:"Listening...":ge[Te.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Ye(Te.id),Ze([])},children:$e===Te.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Ve={...ge};Ve[Te.id]="",rt(Ve)},children:"Disable"})]})]})},Te.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",ae?"⌘⇧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 KN=[{icon:"🦦",title:"Welcome to ADHDev",desc:"Drive any local CLI coding agent — Claude Code, Codex, Gemini — straight from your browser or phone. The agents keep running on your machine; you control them from the web.",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:"Watch and steer, live",desc:"Follow each agent's session in real time and steer it as it works — switch sessions, take screenshots, and (for IDE sessions) view and control the screen over a P2P connection.",visual:"🖱️"},{icon:"🕸️",title:"Orchestrate your agents",desc:"Repo Mesh (Cloud Pro) lets one coordinator hand work to agents across many machines — parallel git worktrees, automatic branch convergence, and cross-checking the same repo from several angles.",visual:"🕸️"}],UN={icon:"🚀",title:"Get started",desc:"Run this on any machine you want to drive, then sign in — the daemon pairs itself to your dashboard automatically.",code:"curl -fsSL https://adhf.dev/install | sh"},zN={icon:"🚀",title:"You're all set",desc:"This dashboard is already connected to your local daemon. Start a session from the Dashboard tab, or add more providers under Burrow → Providers.",visual:"✅"};function GN({onClose:e,standalone:t=!1}){const[r,n]=l.useState(0),a=[...KN,t?zN:UN],o=a[r],i=r===a.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:"var(--z-modal)",background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:c=>{c.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(wt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:a.map((c,d)=>s.jsx("div",{style:{width:d===r?24:8,height:8,borderRadius:4,background:d===r?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},d))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:o.visual||o.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:o.icon})," ",o.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:o.desc}),o.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:"$"}),o.code]}),i&&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:()=>i?e():n(c=>c+1),className:"btn btn-primary",children:i?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
87
- @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
88
- @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
89
- `})]})}function VN({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 qN({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,i]=l.useState(()=>a||"native"),c=l.useMemo(()=>lp(t),[t]),d=l.useMemo(()=>e?Oi(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?ns(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(v=>v.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]),y=l.useMemo(()=>u.map(f=>({tabKey:f.tabKey,title:Xu(f)||n,status:f.status})),[u,n]),x=l.useCallback(f=>{if(f)return d.find(v=>Uo(v,{sessionId:f,routeId:f,tabKey:f,providerSessionId:f}))},[d]);return{activeChatTab:o,setActiveChatTab:i,activeConv:h,conversations:d,extensionTabs:y,hasExtensions:y.length>0,resolveConversationByTarget:x}}function YN({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,y]=l.useState("split"),[x,f]=l.useState(()=>As(e)?"native":e.tabKey),v=l.useRef(null),k=l.useMemo(()=>t||r.find(H=>H.id===e.routeId),[e.routeId,t,r]),b=l.useMemo(()=>Tt((k==null?void 0:k.type)||""),[k==null?void 0:k.type]),{conversations:j,extensionTabs:C,hasExtensions:w}=qN({ideData:k,allIdes:r,connectionStates:n,ideName:b||"IDE",preferredTabKey:As(e)?void 0:e.tabKey}),g=l.useMemo(()=>k?ns(j,k.id):null,[k,j]);l.useEffect(()=>{const H=v.current,q={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(v.current=q,!(H&&H.routeId===q.routeId&&H.tabKey===q.tabKey&&H.streamSource===q.streamSource)){if(As(e)){f("native");return}f(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),l.useEffect(()=>{if(x==="native"){if(j.some(H=>H.streamSource==="native"))return;(g==null?void 0:g.streamSource)==="agent-stream"&&f(g.tabKey);return}if(!j.some(H=>H.tabKey===x)){if((g==null?void 0:g.streamSource)==="agent-stream"){f(g.tabKey);return}f("native")}},[j,x,g]);const S=l.useMemo(()=>x==="native"?j.find(H=>H.streamSource==="native")||e:j.find(H=>H.tabKey===x)||e,[e,j,x]),N=wp(S),I=l.useMemo(()=>N.status||N.modalMessage||N.modalButtons?{...S,...N.status?{status:N.status}:{},...N.modalMessage!==void 0?{modalMessage:N.modalMessage}:{},...N.modalButtons!==void 0?{modalButtons:N.modalButtons}:{}}:S,[S,N]),R=Qs(I),L=Aa({sendDaemonCommand:o,activeConv:I,setActionLogs:i,isStandalone:c}),{connScreenshot:_,screenshotUsage:P,handleRemoteAction:B}=Zp({doId:R,targetSessionId:Au(I),connState:I.connectionState||"new",viewMode:h}),Y=l.useMemo(()=>a.filter(H=>H.routeId===I.tabKey),[a,I.tabKey]);l.useEffect(()=>{u==null||u(I)},[I,u]),l.useEffect(()=>{const H=q=>{q.key==="Escape"&&m()};return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[m]);const M=l.useCallback(H=>{H.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-center justify-center p-0 md:p-3 bg-black/60 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:M,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(os,{size:16})}),s.jsx("span",{className:"truncate",children:Ri(S)||"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(H=>{const q=h===H;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${q?"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:()=>y(H),title:H==="split"?"Split view":"Remote only",children:H==="split"?s.jsx(Nf,{size:15}):s.jsx(os,{size:15})},H)})}),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(S),title:"Chat History",children:[s.jsx(yi,{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(VN,{hasExtensions:w,ideName:b||"IDE",activeChatTab:x,extensionTabs:C,onSelectTab:f}),s.jsx(ru,{activeConv:I,onModalButton:L.handleModalButton}),s.jsx(Qo,{activeConv:I,ideEntry:k,showMetaChips:!1,handleSendChat:L.handleSendChat,handleForceSendChat:L.handleForceSendChat,isSendingChat:L.isSendingChat,sendFeedbackMessage:L.sendFeedbackMessage,handleFocusAgent:L.handleFocusAgent,isFocusingAgent:L.isFocusingAgent,actionLogs:Y,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${h==="split"?"order-1 md:order-2":""}`,children:s.jsx(Qd,{addLog:()=>{},connState:I.connectionState||"new",connScreenshot:_,screenshotUsage:P,transportType:I.transport,onAction:B})})]})]})})}function JN({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=Dy(e);return s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] 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 mobile-compact-dialog 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-bg-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 XN({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o,interactivePrompt:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(Jy,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(ap,{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(YN,{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&&(lt(r.targetConv)||it(r.targetConv))&&s.jsx(JN,{activeConv:r.targetConv,canSaveAndStop:lt(r.targetConv)&&!it(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(op,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),s.jsx(eu,{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(GN,{onClose:o.onClose,standalone:o.standalone})]})}function QN({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(va,{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=Jt(i,{fallbackId:i.id}),d=n[i.id],p=i.version||i.daemonVersion||"unknown",u=i.versionUpdateRequired===!0,h=Tp(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(wt,{size:16})})]})}function ZN(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function eS(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 tS(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>eS(t)).map(t=>t.id)}}function sS(){var pl,ml,hl,fl;const{sendCommand:e}=xt(),t=Sr(),r=vp(),n=hi(),a=cn(),[o,i]=Ah(),c=o.get("activeTab"),d=((pl=n.state)==null?void 0:pl.openRemoteForTabKey)||null,p=((ml=n.state)==null?void 0:ml.openMachineId)||null,u=((hl=n.state)==null?void 0:hl.mobileSection)||null,m=Gu(),h=m.ides||[],y=m.initialLoaded??!0,{updateRouteChats:x,setToasts:f}=m,[v,k]=l.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),b=m.toasts||[],j=m.wsStatus||"connected",C=m.isConnected??!0,w=m.connectionStates||{},g=m.showReconnected||!1,{layoutProfile:S,groupAssignments:N,updateGroupAssignments:I,focusedGroup:R,updateFocusedGroup:L,focusGroup:_,groupActiveTabIds:P,updateGroupActiveTabIds:B,setGroupActiveTab:Y,groupTabOrders:M,updateGroupTabOrders:H,setGroupTabOrder:q,groupSizes:A,updateGroupSizes:$,isMobile:T,hasHydratedStoredLayout:F,hydrateStoredLayout:z,focusConversationTab:U}=ew(),[te,Z]=l.useState(()=>Ui());l.useEffect(()=>lv(Z),[]);const se=l.useMemo(()=>ZN({isMobile:T,mobileViewMode:te}),[T,te]),[G,O]=l.useState([]),[V,pe]=l.useState({}),[fe,de]=l.useState({});dn("Dashboard",{ideCount:h.length,toastCount:b.length,focusedGroup:R,groupCount:Object.keys(N).length,actionLogCount:G.length});const ke=l.useMemo(()=>h.filter(st=>st.type==="adhdev-daemon").sort(Ii),[h]),we=!!ke[0];l.useEffect(()=>{const{metadataDaemonIds:st,runtimeDaemonIds:Bt}=tS(ke);for(const Ir of st)t(Ir,{minFreshMs:3e4}).catch(()=>{});for(const Ir of Bt)r(Ir,{minFreshMs:3e4}).catch(()=>{})},[t,r,ke]);const he=l.useMemo(()=>Cv(h,V),[h,V]),{conversations:K,visibleConversations:E,visibleTabKeys:J,resolveConversationBySessionId:re,resolveConversationByTarget:be}=Fv({ides:he,connectionStates:w,clearedTabs:fe}),ue=l.useMemo(()=>new Map(K.map(st=>[st.tabKey,st])),[K]);iy(E,se);const D=l.useMemo(()=>su(h),[h]),me=Up(D,e,l.useCallback(st=>nr(f,`⚠️ ${st}`),[f])),{notifications:Se,unreadCount:oe}=xw({conversations:K,liveSessionInboxState:D}),{handleMarkDashboardNotificationRead:Q,handleMarkDashboardNotificationUnread:ve,handleDeleteDashboardNotification:Ne}=bw({notifications:Se,sendDaemonCommand:e}),{containerRef:Le,normalizedGroupAssignments:We,numGroups:le,isSplitMode:Ee,groupedConvs:Be,moveTabToGroup:Je,closeGroup:qe,handleResizeStart:je,splitTabRelative:at}=iw({groupAssignments:N,updateGroupAssignments:I,updateFocusedGroup:L,updateGroupActiveTabIds:B,updateGroupTabOrders:H,groupSizes:A,updateGroupSizes:$,isMobile:T,visibleConversations:E,visibleTabKeys:J}),{activeConv:Ie,openDesktopConversation:ot,requestScrollToBottom:nt,scrollToBottomRequest:Qe,setDesktopActiveTab:Lt}=Mw({isMobile:T,conversations:K,visibleConversations:E,groupActiveTabIds:P,focusedGroup:R,groupedConvs:Be,setSearchParams:i});Lw({activeConv:Ie,isMobile:T,liveSessionInboxState:D,sendDaemonCommand:e});const{requestedDesktopTabKey:X,requestedMobileTabKey:ee,consumeRequestedActiveTab:ne}=Ov({isMobile:T,urlActiveTab:c,resolveConversationBySessionId:re,setSearchParams:i}),{remoteDialogConv:ie,remoteDialogIdeEntry:xe,remoteDialogActiveConv:Ae,setRemoteDialogActiveConv:De,openRemoteDialog:Ce,closeRemoteDialog:Re,cliStopDialogOpen:He,cliStopTargetConv:Xe,requestCliStop:Oe,cancelCliStop:Ue,confirmCliStop:ae}=Dw({isMobile:T,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:X,conversations:K,ides:h,resolveConversationByTarget:be,activeConv:Ie,sendDaemonCommand:e}),{historyModalOpen:ce,openHistoryModal:ge,closeHistoryModal:$e,historyTargetConv:Fe,isSavedSessionHistoryTarget:Ye,isHistoryCreatingChat:Ze,isHistoryRefreshingHistory:rt,handleHistorySwitchSession:Ge,handleHistoryNewChat:Nt,handleHistoryRefresh:Xt,savedHistorySessions:Ht,savedHistoryFilters:Te,setSavedHistoryFilters:Ve,missingWorkspaceResumePath:Rt,isSavedHistoryLoading:jt,resumingSavedHistorySessionId:Kt,handleRefreshSavedHistory:Ut,handleResumeSavedHistorySession:zt}=Rw({activeConv:Ie,remoteDialogConv:ie,remoteDialogActiveConv:Ae,ides:h,sendDaemonCommand:e,updateRouteChats:x,setToasts:f,setClearedTabs:de,setSearchParams:i}),is=l.useMemo(()=>E,[E]),W=T&&te==="chat",Me=l.useMemo(()=>K.filter(st=>Ms(st,D).surfaceHidden),[K,D]),Pe=l.useCallback(st=>{const Bt=new URLSearchParams(o);Bt.set("activeTab",st),i(Bt,{replace:!0})},[o,i]),{trackPendingLaunch:dt}=Sw({ides:h,conversations:K,onOpenSession:Pe}),{handleBrowseMachineDirectory:Et,handleSaveMachineWorkspace:Rs,handleLaunchMachineIde:Mt,handleLaunchMachineProvider:vs,handleListMachineMeshes:ws,handleLaunchMeshCoordinator:Cr,handleListMachineSavedSessions:Ba,setActiveCliViewMode:fs}=Cw({sendDaemonCommand:e,trackPendingLaunch:dt,onOpenSession:Pe,activeConv:Ie,ides:h,setCliViewModeOverrides:pe});Av({visibleConversations:E,clearedTabs:fe,setClearedTabs:de,setActionLogs:O,isConversationMuted:me.isMuted}),Hv({ides:h,sendDaemonCommand:e,setToasts:f,resolveConversationByTarget:be});const Vm=jp(),{isRefreshingHistory:qm,handleRefreshHistory:Ym}=_p({sendDaemonCommand:e,activeConv:Ie,chats:(fl=h.find(st=>st.id===(Ie==null?void 0:Ie.routeId)))==null?void 0:fl.chats,updateRouteChats:x,setToasts:f,setClearedTabs:de});sw({urlActiveTab:T&&!W?c:null,conversations:K,resolveConversationBySessionId:re,normalizedGroupAssignments:We,hasHydratedStoredLayout:T&&!W?F:!0,hydrateStoredLayout:T&&!W?z:()=>{},focusConversationTab:U,setSearchParams:i,historyModalOpen:ce,activeConv:Ie,isRefreshingHistory:qm,ides:h,handleRefreshHistory:Ym});const Jm=l.useMemo(()=>!Ie||!lt(Ie)||it(Ie)?null:Nr(Ie),[Ie]),{versionMismatchDaemons:Xm,hasRequiredVersionDaemons:dl,targetVersion:Qm,versionBannerDismissed:Zm,setVersionBannerDismissed:eh,upgradingDaemons:th,handleBannerUpgrade:sh}=cw({ides:h,sendDaemonCommand:e}),ul=l.useCallback(st=>{me.setHidden(st,!1),ot(st)},[ot,me]),rh=l.useCallback(()=>{for(const st of Me)me.setHidden(st,!1)},[Me,me]),nh=l.useCallback(st=>{me.setHidden(st,!0)},[me]),ah=l.useCallback(st=>{me.toggleHidden(st)},[me]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[(!Zm||dl)&&s.jsx(QN,{daemons:Xm,targetVersion:Qm,required:dl,upgradingDaemons:th,onUpgrade:sh,onDismiss:()=>eh(!0)}),s.jsx(WN,{showMobileChatMode:W,isMobile:T,activeConv:Ie,wsStatus:j,isConnected:C,onOpenHistory:st=>{st&&De(st),ge()},onOpenRemote:Ce,onStopCli:Oe,activeCliViewMode:Jm,onSetActiveCliViewMode:fs,mobileChatConversations:is,ides:h,actionLogs:G,sendDaemonCommand:e,setActionLogs:O,setCliViewModeOverrides:pe,isStandalone:we,initialDataLoaded:y,userName:m.userName,requestedMobileTabKey:ee,onRequestedMobileTabConsumed:ne,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:Le,isSplitMode:Ee,numGroups:le,groupSizes:A,groupedConvs:Be,clearedTabs:fe,focusedGroup:R,focusGroup:_,moveTabToGroup:Je,splitTabRelative:at,closeGroup:qe,handleResizeStart:je,groupActiveTabIds:P,setGroupActiveTab:Y,groupTabOrders:M,setGroupTabOrder:q,toggleHiddenTab:st=>{const Bt=ue.get(st);Bt&&ah(Bt)},visibleConversations:E,hiddenConversations:Me,requestedDesktopTabKey:X,onRequestedDesktopTabConsumed:ne,onDesktopActiveTabChange:Lt,onRequestScrollToBottom:nt,onHideConversation:nh,onShowHiddenConversation:ul,onShowAllHiddenConversations:rh,scrollToBottomRequest:Qe,machineEntries:ke,layoutProfile:S,onBrowseMachineDirectory:Et,onSaveMachineWorkspace:Rs,onLaunchMachineIde:Mt,onLaunchMachineProvider:vs,onListMachineMeshes:ws,onLaunchMeshCoordinator:Cr,onListMachineSavedSessions:Ba,notifications:Se,notificationUnreadCount:oe,liveSessionInboxState:D,onMarkNotificationRead:Q,onMarkNotificationUnread:ve,onDeleteNotification:Ne}),s.jsx("style",{children:`
90
- body { overflow: hidden; overscroll-behavior: none; }
91
- `}),s.jsx(XN,{historyModal:{open:ce,targetConv:Fe,ides:h,isCreatingChat:Ze,isRefreshingHistory:Ye?!1:rt,savedSessions:Ht,savedHistoryFilters:Te,missingWorkspaceResumePath:Rt||null,onSavedHistoryFiltersChange:Ve,isSavedSessionsLoading:jt,isResumingSavedSessionId:Kt,onClose:$e,onNewChat:Nt,onSwitchSession:Ge,onRefreshHistory:Ye?Ut:Xt,onResumeSavedSession:zt},remoteDialog:{conversation:ie,ideEntry:xe,ides:h,connectionStates:w,actionLogs:G,sendDaemonCommand:e,setActionLogs:O,isStandalone:we,userName:m.userName,onOpenHistory:st=>{st&&De(st),ge()},onConversationChange:De,onClose:Re},cliStopDialog:{open:He,targetConv:Xe,onCancel:Ue,onStopNow:async()=>{await ae("hard")},onSaveAndStop:async()=>{await ae("save")}},connectionBanner:{wsStatus:j,showReconnected:g,loginUrl:m.connectionLoginUrl,onReconnect:m.retryServerConnection},toastOverlay:{toasts:b,onDismiss:st=>f(Bt=>Bt.filter(Ir=>Ir.id!==st)),onClick:st=>{if(st.targetKey){const Bt=be(st.targetKey);Bt&&(U(Bt.tabKey,We),ul(Bt),nt(Bt.tabKey,"toast-open"))}}},onboarding:{open:v,standalone:we,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}k(!1)}},interactivePrompt:Vm})]})}function rS({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const{launchCli:o}=ga(),[i,c]=l.useState([]),[d,p]=l.useState(null),[u,m]=l.useState(null),[h,y]=l.useState(!1),[x,f]=l.useState(null),[v,k]=l.useState(!1),[b,j]=l.useState(""),C=l.useRef(null),w=l.useCallback($=>{C.current=$},[]),g=l.useCallback(($,T,F=!1)=>{c(z=>[...z.slice(-100),{timestamp:Date.now(),level:$,message:T}]),setTimeout(()=>{var z;return(z=a.current)==null?void 0:z.scrollIntoView({behavior:"smooth"})},100),F&&ct.showToast(T,$==="error"||$==="warn"?"warning":"success")},[a]),S=l.useCallback($=>{const T=$ instanceof Error?$.message:String($||"");return T.includes("P2P command timeout")||T.includes("P2P not connected")||T.includes("P2P not available")},[]),N=l.useCallback(async($,T)=>{var F;if(!e||d)return!1;p($),g("info",`Launching ${Tt($)}${T!=null&&T.workspace?` in ${T.workspace}`:""}...`);try{const z={ideType:$,enableCdp:!0};(F=T==null?void 0:T.workspace)!=null&&F.trim()?z.workspace=T.workspace.trim():T!=null&&T.useDefaultWorkspace&&(z.useDefaultWorkspace=!0);const U=await r(e,"launch_ide",z);return g(U!=null&&U.success?"info":"error",U!=null&&U.success?`${Tt($)} launched`:`Failed: ${U==null?void 0:U.error}`,!0),!!(U!=null&&U.success)}catch(z){return g("error",`Launch error: ${z.message}`,!0),!1}finally{p(null)}},[e,d,g,r]),I=l.useCallback(async $=>{if(!e)return{success:!1};const{cliType:T,dir:F,workspaceId:z,useDefaultWorkspace:U,useHome:te,argsStr:Z,model:se,resumeSessionId:G}=$;if(!T)return g("warn","Select a CLI or ACP provider first",!0),{success:!1};const O=Z?Z.split(/\s+/).filter(Boolean):void 0,V=(F==null?void 0:F.trim())||(z?"(saved id)":U?"(default workspace)":te?"(home)":"");g("info",`Launching ${T}${V?` in ${V}`:""}${se?` (model: ${se})`:""}...`),m(T);try{const pe={cliType:T,cliArgs:O,initialModel:se||void 0};F!=null&&F.trim()?pe.dir=F.trim():z?pe.workspaceId=z:U?pe.useDefaultWorkspace=!0:te&&(pe.useHome=!0),G&&(pe.resumeSessionId=G);const fe=await o(e,pe),de=(fe==null?void 0:fe.result)||fe;return fe!=null&&fe.success?(g("info",`${T} launched`,!0),(de==null?void 0:de.launchSource)==="home"?g("info","📂 Running in home directory (explicit choice)"):(de==null?void 0:de.launchSource)==="defaultWorkspace"&&g("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:de==null?void 0:de.sessionId}):(g("error",`Failed: ${(fe==null?void 0:fe.error)||(de==null?void 0:de.error)}`,!0),(fe==null?void 0:fe.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&f({cliType:T,argsStr:Z,model:se}),{success:!1,sessionId:de==null?void 0:de.sessionId})}catch(pe){return S(pe)?(g("warn",`${T} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(g("error",`Launch error: ${pe.message}`,!0),{success:!1})}finally{m(null)}},[e,g,S,r]),R=l.useCallback(async($,T,F,z)=>e?$?T.trim()?I({cliType:$,dir:T,argsStr:F,model:z}):(f({cliType:$,argsStr:F,model:z}),{success:!1}):(g("warn","Select a provider",!0),{success:!1}):{success:!1},[e,g,I]),L=l.useCallback(async($,T,F)=>{if(e&&window.confirm(`Stop ${$}?
92
- This will terminate the process.`))try{const z=await r(e,"stop_cli",{cliType:$,dir:T,targetSessionId:F});z!=null&&z.success?g("info",`${$} stopped`,!0):g("error",`Stop failed: ${(z==null?void 0:z.error)||"Unknown error"}`,!0)}catch(z){g("error",`Stop failed: ${z.message}`,!0)}},[e,g,r]),_=l.useCallback(async $=>{try{await r($.daemonId,"restart_ide",{ideType:$.type}),g("info",`${Tt($.type)} restart initiated`,!0)}catch(T){g("error",`Restart failed: ${T.message}`,!0)}},[g,r]),P=l.useCallback(async $=>{if(window.confirm(`Stop ${Tt($.type)}?
93
- This will disconnect CDP and optionally kill the process.`))try{const T=await r($.daemonId,"stop_ide",{ideType:$.type,killProcess:!0});T!=null&&T.success?g("info",`${Tt($.type)} stopped`,!0):g("error",`Stop failed: ${(T==null?void 0:T.error)||"Unknown error"}`,!0)}catch(T){g("error",`Stop failed: ${T.message}`,!0)}},[g,r]),B=l.useCallback(async()=>{if(e)try{const $=await r(e,"detect_ides",{});g("info",`Found ${(($==null?void 0:$.result)||[]).length} IDE(s)`,!0)}catch($){g("error",`Detection failed: ${$.message}`,!0)}},[e,g,r]),Y=l.useCallback(async $=>{if(!e||!$.trim())return!1;y(!0);try{const T=await r(e,"workspace_add",{path:$.trim()});return T!=null&&T.success?(g("info",`Workspace added: ${$.trim()}`),!0):(g("error",(T==null?void 0:T.error)||"workspace_add failed"),!1)}catch(T){return g("error",T.message),!1}finally{y(!1)}},[e,g,r]),M=l.useCallback(async $=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){y(!0);try{const T=await r(e,"workspace_remove",{id:$});T!=null&&T.success?g("info","Workspace removed",!0):g("error",(T==null?void 0:T.error)||"workspace_remove failed",!0)}catch(T){g("error",T.message,!0)}finally{y(!1)}}},[e,g,r]),H=l.useCallback(async $=>{var T;if(e){y(!0);try{const F=await r(e,"workspace_set_default",$===null?{clear:!0}:{id:$});if(F!=null&&F.success){g("info",$?"Default workspace updated":"Default workspace cleared",!0);const z=typeof F.defaultWorkspacePath=="string"?F.defaultWorkspacePath:"";z&&((T=C.current)==null||T.call(C,z))}else g("error",(F==null?void 0:F.error)||"workspace_set_default failed",!0)}catch(F){g("error",F.message,!0)}finally{y(!1)}}},[e,g,r]),q=l.useCallback(async $=>{var F;if(!e||!$.trim())return;const T=$.trim();y(!0);try{const z=await r(e,"workspace_set_default",{path:T});z!=null&&z.success?(g("info","Default workspace set from history"),(F=C.current)==null||F.call(C,T)):g("error",(z==null?void 0:z.error)||"Could not set default (path missing on disk?)")}catch(z){g("error",z.message)}finally{y(!1)}},[e,g,r]),A=l.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:b}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:b})}catch($){g("warn",`Live nickname updated, but account sync failed: ${$.message}`)}g("info",`Nickname set to "${b||"(cleared)"}"`),k(!1)}catch($){g("error",`Failed: ${$.message}`)}},[e,b,t,g,n,r]);return{logs:i,launchingIde:d,launchingAgentType:u,workspaceBusy:h,launchPick:x,setLaunchPick:f,editingNickname:v,setEditingNickname:k,nicknameInput:b,setNicknameInput:j,addLog:g,handleLaunchIde:N,runLaunchCliCore:I,handleLaunchCli:R,handleStopCli:L,handleRestartIde:_,handleStopIde:P,handleDetectIdes:B,handleWorkspaceAdd:Y,handleWorkspaceRemove:M,handleWorkspaceSetDefault:H,handleWorkspaceResumePath:q,handleSaveNickname:A,setOnDefaultWorkspaceChanged:w}}function nS({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(gn,{icon:s.jsx(Hd,{size:16}),label:"Uptime",value:typeof e.uptime=="number"?Bx(e.uptime):"Waiting…"}),s.jsx(gn,{icon:s.jsx(os,{size:16}),label:"IDEs",value:`${t.length}`}),s.jsx(gn,{icon:s.jsx(wi,{size:16}),label:"CLIs",value:`${r.length}`}),s.jsx(gn,{icon:s.jsx(Cf,{size:16}),label:"ACPs",value:`${n.length}`})]}),s.jsxs(ys,{padding:"lg",className:"mb-5",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(_l,{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(_l,{value:i,max:100,label:"Memory",color:"#3b82f6",detail:a?`${Va(e.totalMem-o)} / ${Va(e.totalMem)}${e.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Va(e.totalMem)} total`})]})]})]})}function aS(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 oS(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 So(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 ad(e){if(!e||typeof e!="object")return null;if(So(e))return e;const t=e,r=t.result;return So(r)?r:So(t.sourceConfig)?t.sourceConfig:null}function iS(e){const t=e.trim();return t||null}function lS({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var w;const o=t.filter(g=>g.category==="ide"),[i,c]=l.useState(((w=o[0])==null?void 0:w.type)||""),[d,p]=l.useState(""),[u,m]=l.useState(""),[h,y]=l.useState(!1),[x,f]=l.useState(""),[v,k]=l.useState(!1),b=g=>{const S=g.toLowerCase().replace(/[^a-z0-9-]/g,"");p(S),(!u||u===j(d))&&m(j(S))},j=g=>g.split("-").map(S=>S.charAt(0).toUpperCase()+S.slice(1)).join(" "),C=async()=>{if(!(!d||!u||!i)){y(!0),f("");try{const g=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:i});g!=null&&g.success||g!=null&&g.created?(k(!0),a==null||a(d)):f((g==null?void 0:g.error)||"Failed to create provider")}catch(g){f((g==null?void 0:g.message)||"Connection failed")}y(!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:g=>g.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:v?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(g=>s.jsxs("button",{onClick:()=>c(g.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:i===g.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:i===g.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:g.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:i===g.type?"#a78bfa":"var(--text-secondary)"},children:g.displayName})]},g.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:g=>b(g.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:g=>m(g.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"})]}),x&&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:x})]})}),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:v?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:C,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 od={"user-custom":"Custom",trusted:"Official","trusted-with-scripts":"Official · runs JS","external-safe":"External · spec-only","external-untrusted":"⚠ External · untrusted JS"},cS={"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 dS({trust:e,sourceName:t,description:r}){const n=t&&(e==="external-safe"||e==="external-untrusted")?`${od[e]} · ${t}`:od[e];return s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded border whitespace-nowrap ${cS[e]}`,title:r,children:n})}function uS(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 pS={detected:"Detected",not_detected:"Not detected",enabled_unchecked:"Enabled (unchecked)",disabled:"Disabled"},id={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"},mS={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 ld(e){if(!e)return"—";const t=e.ok?"OK":"Failed",r=e.message||e.path||e.command||"";return r?`${t} — ${r}`:t}function hS(e){return e==="cli"||e==="acp"}function fS({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=hS(e.category);return s.jsxs(ys,{padding:"none",children:[s.jsxs("button",{onClick:()=>d(y=>!y),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 ${mS[e.category]??"border-border-subtle text-text-muted"}`,children:e.category.toUpperCase()}),(t==null?void 0:t.trust)&&s.jsx(dS,{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 ${id[m]??id.disabled}`,children:pS[m]??m}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[h&&s.jsx("button",{onClick:y=>{y.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 y=t==null?void 0:t.links;if(!y)return null;const x=Object.entries(y).map(([f,v])=>({k:f,href:uS(v)})).filter(f=>f.href!==null);return x.length===0?null:s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Links:"})," ",x.map(({k:f,href:v})=>s.jsx("a",{href:v,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:"})," ",ld(t==null?void 0:t.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Verification:"})," ",ld(t==null?void 0:t.lastVerification)]})]}),e.schema.length>0&&s.jsx("div",{className:"flex flex-col gap-1.5",children:e.schema.map(y=>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:[y.label||y.key,r===`${e.type}.${y.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving…"})]}),y.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:y.description})]}),s.jsx("div",{className:"shrink-0",children:y.type==="boolean"?s.jsx("button",{onClick:()=>void n(e.type,y.key,!(e.values[y.key]??y.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:e.values[y.key]??y.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[y.key]??y.default?21:3}})}):y.type==="number"?s.jsx("input",{type:"number",value:Number(e.values[y.key]??y.default??0)||0,min:y.min,max:y.max,onChange:x=>{const f=parseInt(x.target.value)||0;y.min!==void 0&&f<y.min||y.max!==void 0&&f>y.max||n(e.type,y.key,f)},className:"machine-input w-20 text-center text-[11px]"}):y.type==="select"&&y.options?s.jsx("select",{value:String(e.values[y.key]??y.default??""),onChange:x=>void n(e.type,y.key,x.target.value),className:"machine-input text-[11px]",children:y.options.map(x=>s.jsx("option",{value:x,children:x},x))}):s.jsx("input",{type:"text",defaultValue:String(e.values[y.key]??y.default??""),onBlur:x=>void n(e.type,y.key,x.target.value),className:"machine-input w-[180px] text-[11px]"})})]},y.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 Dn(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function xS({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),[y,x]=l.useState(""),[f,v]=l.useState("main"),[k,b]=l.useState(""),[j,C]=l.useState(!1),[w,g]=l.useState(null),[S,N]=l.useState(null),I=l.useCallback(async()=>{if(e){d(!0),u(null);try{const P=Dn(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 R=async()=>{if(y.trim()){C(!0),u(null);try{const P=Dn(await t(e,"add_provider_source",{url:y.trim(),ref:f.trim()||"main",...k.trim()?{name:k.trim()}:{}}));P!=null&&P.success?(h(!1),x(""),v("main"),b(""),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{C(!1)}}},L=async P=>{if(confirm(`Remove provider source ${P}? This deletes the cloned manifests and clears any active-source entries that pointed here.`)){g(P),u(null);try{const B=Dn(await t(e,"remove_provider_source",{name:P}));B!=null&&B.success?(await I(),r==null||r()):u((B==null?void 0:B.error)||"Failed to remove source")}catch(B){u((B==null?void 0:B.message)||String(B))}finally{g(null)}}},_=async(P,B)=>{N(`${P}:${B}`),u(null);try{const Y=Dn(await t(e,"set_active_provider_source",{type:P,sourceName:B}));Y!=null&&Y.success?(await I(),r==null||r()):u((Y==null?void 0:Y.error)||"Failed to set active source")}catch(Y){u((Y==null?void 0:Y.message)||String(Y))}finally{N(null)}};return s.jsxs(ys,{padding:"none",className:"px-4.5 py-3.5",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 L(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(([B,Y])=>s.jsxs("span",{className:"mr-3",children:[s.jsxs("span",{className:"text-text-secondary",children:[B,":"]})," ",Y.length]},B))})]},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(B=>s.jsxs("button",{type:"button",onClick:()=>void _(P.type,B),disabled:S===`${P.type}:${B}`,className:`text-[10px] px-2 py-0.5 rounded border ${P.active===B?"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===B?"Active":`Switch active to ${B}`,children:[P.active===B?"● ":"",B]},B))})]},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:y,onChange:P=>x(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=>v(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:k,onChange:P=>b(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 R(),disabled:j||!y.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:j?"Cloning…":"Clone + register"})]})]})]})}function bS({machineId:e,providers:t,sendDaemonCommand:r}){var H;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),[y,x]=l.useState(!1),[f,v]=l.useState(!1),[k,b]=l.useState(null),[j,C]=l.useState("normal"),[w,g]=l.useState(""),[S,N]=l.useState(!1),I=l.useCallback(async()=>{if(e)try{const q=await r(e,"get_provider_source_config",{}),A=ad(q);A&&(b(A),C(A.sourceMode),g(A.explicitProviderDir||""))}catch{}},[e,r]),R=l.useCallback(async()=>{if(e){i(!0);try{const q=await r(e,"get_provider_settings",{}),A=aS(q);if(A){const $=oS(A,t,{filterSchema:T=>T.filter(F=>F.key!=="enabled")});$.sort((T,F)=>T.category.localeCompare(F.category)||T.displayName.localeCompare(F.displayName)),a($)}}catch{}i(!1)}},[e,t,r]);l.useEffect(()=>{n.length===0&&R(),k||I()},[]);const L=async(q,A,$)=>{d(`${q}.${A}`),a(T=>T.map(F=>F.type===q?{...F,values:{...F.values,[A]:$}}:F));try{const T=await r(e,"set_provider_setting",{providerType:q,key:A,value:$});T!=null&&T.success||R()}catch{R()}d(null)},_=async(q,A)=>{await L(q,"enabled",A),await R()},P=async q=>{d(`${q}.detect`);try{await r(e,"detect_provider",{providerType:q})}finally{await R(),d(null)}},B=async q=>{await L(q,"executablePath",""),await L(q,"executableArgs",""),await R()},Y=async()=>{N(!0);try{const q=await r(e,"set_provider_source_config",{providerSourceMode:j,providerDir:iS(w)}),A=ad(q);A?(b(A),C(A.sourceMode),g(A.explicitProviderDir||"")):await I(),await R()}catch{await I()}N(!1)},M=n.filter(q=>p==="all"||q.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(q=>s.jsx("button",{onClick:()=>u(q),className:`machine-btn text-[10px] px-2 py-0.5 ${p===q?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:q.toUpperCase()},q))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>x(q=>!q),className:`machine-btn text-[10px] ${y?"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:R,disabled:o,className:"machine-btn text-[10px]",children:[o?"⏳":"↻"," Refresh"]}),s.jsx("button",{onClick:()=>v(q=>!q),className:"machine-btn text-[10px]",title:"Show source configuration (advanced)",children:"⚙ Advanced"})]})]}),y&&s.jsx(xS,{machineId:e,sendDaemonCommand:r,onChange:()=>{R()}}),f&&s.jsxs(ys,{padding:"none",className:"px-4.5 py-3.5",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:j,onChange:q=>C(q.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:q=>g(q.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void Y(),disabled:S,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:S?"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:"})," ",(k==null?void 0:k.userDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Upstream root:"})," ",(k==null?void 0:k.upstreamDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Provider roots:"})," ",((H=k==null?void 0:k.providerRoots)==null?void 0:H.join(" → "))||"—"]})]})]}),o&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings…"}):M.length===0?s.jsx(ys,{padding:"none",className:"px-4.5 py-8 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:M.map(q=>s.jsx(fS,{prov:q,providerInfo:t.find(A=>A.type===q.type),savingKey:c,onSetSetting:L,onEnableToggle:_,onDetect:P,onResetCommand:B},q.type))}),m&&s.jsx(lS,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>h(!1),onCreated:()=>{h(!1),R()}})]})}const gS=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function yS({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function vS(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function wS(e){return e.trim().toLowerCase()}function $a(e,t){const r=wS(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function il(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function wr(e,t=220){const r=il(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function jS(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 kS(e,t){return e.filter(r=>$a([r.level,r.message],t))}function cd(e){return`${e.timestamp}:${e.level}:${e.message}`}function NS(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const i of e.entries)n.set(cd(i),i);for(const i of t.entries)n.set(cd(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 SS(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 CS(e,t){return e.split(`
94
- `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>$a([r],t))}function IS(e,t){return e.filter(r=>$a([r.level,r.category,r.stage,r.interactionId,il(r.payload)],t))}function AS(e,t){return e.filter(r=>$a([r.kind,r.topic,r.interactionId,il(r.payload)],t))}function dd(e){return e==="warn"||e==="error"}function MS({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){return{all:e.length+t.length+r.length+n.length,info:e.filter(a=>a.level!=="debug").length+r.filter(a=>a.level!=="debug").length+n.length,issues:e.filter(a=>dd(a.level)).length+r.filter(a=>dd(a.level)).length}}function _S({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(`
95
- `)):t.length>0&&a.push(["[daemon logs]",...t].join(`
96
- `)),r.length>0&&a.push(["[trace]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${wr(o.payload,500)}`.trim())].join(`
97
- `)),n.length>0&&a.push(["[browser events]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${wr(o.payload,500)}`.trim())].join(`
98
- `)),a.join(`
99
-
100
- `)}function TS({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,y]=l.useState(null),[x,f]=l.useState(!0),[v,k]=l.useState("info"),[b,j]=l.useState("all"),[C,w]=l.useState(!0),[g,S]=l.useState(!0),[N,I]=l.useState(""),[R,L]=l.useState(""),[_,P]=l.useState(0),B=l.useRef(0),Y=l.useRef(0),M=l.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),H=l.useRef([]),q=l.useCallback(()=>{const te={entries:[],kind:"empty",rawText:"",lastTs:0};M.current=te,B.current=0,n([]),c(""),o("empty"),w(!0)},[]),A=l.useCallback(()=>{H.current=[],Y.current=0,p([]),S(!0)},[]),$=l.useCallback(te=>{te!==v&&(q(),k(te))},[v,q]),T=l.useCallback(te=>{j(Z=>Z===te?Z:te)},[]),F=l.useCallback(()=>{q(),A(),m([]),y(null),I(""),L(""),pr.clear()},[q,A]),z=l.useCallback(()=>{P(te=>te+1)},[]),U=l.useCallback(async()=>{if(!e)return;const te=B.current,Z=Y.current,[se,G]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:v,since:te}),t(e,"get_debug_trace",yS({count:120,since:Z,category:b}))]);if(se.status==="fulfilled"){const O=se.value,V=(O==null?void 0:O.result)||O,pe=jS(V),fe=NS(M.current,pe,300);M.current=fe,B.current=fe.lastTs,w(!1),I((O==null?void 0:O.success)===!1?String((O==null?void 0:O.error)||"Could not load daemon logs"):""),o(fe.kind),c(fe.rawText),n(fe.entries)}else w(!1),I(se.reason instanceof Error?se.reason.message:"Could not load daemon logs");if(G.status==="fulfilled"){const O=G.value,V=(O==null?void 0:O.result)||O;if((O==null?void 0:O.success)===!1)L(String((O==null?void 0:O.error)||"Could not load daemon trace"));else if(Array.isArray(V==null?void 0:V.trace)){const pe=V.trace,fe=SS(H.current,pe,120),de=pe.reduce((ke,ye)=>Math.max(ke,Number(ye.ts||0)),Z);H.current=fe,de>Z&&(Y.current=de),L(""),p(fe)}else L("");S(!1)}else S(!1),L(G.reason instanceof Error?G.reason.message:"Could not load daemon trace");m(pr.list({limit:120})),y(Date.now())},[v,e,t,b]);return l.useEffect(()=>{A()},[A,b]),l.useEffect(()=>{if(!e||(U(),!x))return;const te=setInterval(()=>{U()},3e3);return()=>clearInterval(te)},[x,U,e,_]),{daemonLogs:r,daemonLogKind:a,daemonRawText:i,debugTrace:d,webEvents:u,lastUpdatedAt:h,autoRefresh:x,logLevel:v,traceCategory:b,daemonLoading:C,traceLoading:g,daemonFetchError:N,traceFetchError:R,setAutoRefresh:f,setLogLevel:$,setTraceCategory:T,refresh:z,clear:F}}function LS({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 ud(e){return e==="warn"||e==="error"}function RS(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 PS(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 pd(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function DS(e){const t=wr(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function $S(e){const t=wr(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function ES({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:$S(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:DS(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:PS(o,i),severity:RS(o),message:o,raw:o})}),a.sort((o,i)=>o.ts!==i.ts?o.ts-i.ts:pd(o.source)-pd(i.source))}function BS(e){return`${e.source}:${e.severity}:${e.message}`}function FS(e){const t=e.filter(n=>ud(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!ud(n.severity))continue;const a=BS(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 OS(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function md(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${OS(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function HS({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
101
- `)),a.push(["[source status]",...r.map(i=>`${i.label}: ${i.status} - ${i.detail}`)].join(`
102
- `)),t.latestIssue&&a.push(["[latest issue]",md(t.latestIssue)].join(`
103
- `)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(i=>`${i.count}x ${i.severity.toUpperCase()} ${i.source} ${i.message}`)].join(`
104
- `));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(md):["No diagnostic events captured."]].join(`
105
- `)),a.join(`
106
-
107
- `)}function WS(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function KS(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function US({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=vS(n,o),y=kS(e,c),x=CS(t,c),f=IS(h,c),v=AS(a,c),k=WS(y,i),b=i==="all"?x:[],j=KS(f,i),C=i==="issues"?[]:v,w=MS({daemonLogs:y,daemonRawLines:x,trace:f,webEvents:v}),g=ES({daemonLogs:k,daemonRawLines:b,trace:j,webEvents:C}),S=FS(g),N=LS({daemonLoading:d,traceLoading:p,daemonFetchError:u,traceFetchError:m,daemonLogKind:r,daemonLogsCount:y.length,daemonRawLineCount:x.length,traceCount:f.length,webEventCount:v.length});return{filteredDaemonLogs:y,filteredDaemonRawLines:x,filteredTraceEntries:f,filteredWebEvents:v,visibleDaemonLogs:k,visibleDaemonRawLines:b,visibleTraceEntries:j,visibleWebEvents:C,quickFilterCounts:w,diagnosticEvents:g,diagnosticsSummary:S,sourceStates:N}}function zS(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Fm(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function ci(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 Co(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 ll(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function GS({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${ci(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Fm(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:ll(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 VS({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 qS({logLevel:e,traceCategory:t,onLogLevelChange:r,onTraceCategoryChange:n}){return s.jsx(ys,{padding:"sm",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:gS.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 YS({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 ${Co(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 ${Co(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:[ll(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:Fm(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 ${Co(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: ",zS(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 JS({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()," · ",ll(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function XS({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(GS,{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 ${ci(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 ${ci(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:wr(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:wr(u.payload,360)||"No payload"})]},u.id))]})]})]})}function QS({machineId:e,sendDaemonCommand:t}){const r=TS({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(()=>US({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 x=u.current?"smooth":"instant";setTimeout(()=>{var f;(f=p.current)==null||f.scrollIntoView({behavior:x}),u.current=!0},50)}},[m.diagnosticEvents.length,r.autoRefresh]);const h=l.useCallback(async()=>{var f;const x=_S({daemonLogs:m.visibleDaemonLogs,daemonRawLines:m.visibleDaemonRawLines,trace:m.visibleTraceEntries,webEvents:m.visibleWebEvents});if(!x.trim()){ct.showToast("No visible logs to copy.","info");return}try{await((f=navigator.clipboard)==null?void 0:f.writeText(x)),ct.showToast("Copied visible logs to clipboard.","success")}catch(v){ct.showToast(v instanceof Error?v.message:"Could not copy visible logs","warning")}},[m.visibleDaemonLogs,m.visibleDaemonRawLines,m.visibleTraceEntries,m.visibleWebEvents]),y=l.useCallback(async()=>{var f;const x=HS({events:m.diagnosticEvents,summary:m.diagnosticsSummary,sources:m.sourceStates});try{await((f=navigator.clipboard)==null?void 0:f.writeText(x)),ct.showToast("Copied diagnostic bundle to clipboard.","success")}catch(v){ct.showToast(v instanceof Error?v.message:"Could not copy diagnostic bundle","warning")}},[m.diagnosticEvents,m.diagnosticsSummary,m.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(VS,{quickFilter:n,quickFilterCounts:m.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:()=>{y()},onCopyVisible:()=>{h()},onToggleAutoRefresh:()=>r.setAutoRefresh(x=>!x),onRefresh:r.refresh,onClear:r.clear}),s.jsx(qS,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(YS,{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(JS,{patterns:m.diagnosticsSummary.repeatedPatterns}),s.jsx(XS,{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 ZS(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 Om(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 eC(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=Om((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 tC(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Io(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 Ao(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Mo(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function hd(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 sC(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function rC(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-bg-glass text-text-muted"}}function nC(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 aC({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=l.useState(""),[o,i]=l.useState(null),[c,d]=l.useState(!1),p=gv(e,{enabled:!!e,includeSessions:!0,limit:Xl,intervalMs:Pg}),u=p.diagnostics,m=p.loading,h=p.applyDiagnostics,y=l.useMemo(()=>ZS({diagnostics:u,loading:m,refreshing:c,error:n}),[u,m,c,n]),x=l.useMemo(()=>new Map(t.map(L=>[L.sessionId||L.id,L])),[t]),f=l.useCallback(async()=>{if(e){d(!0);try{const L=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Xl}),_=Ao(L);if(!(_!=null&&_.success))throw new Error((_==null?void 0:_.error)||"Could not load hosted runtime diagnostics");h(_.diagnostics||_.result||null),a("")}catch(L){const _=L instanceof Error?L.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 v=l.useCallback(async(L,_)=>{const P=`${L}:${_.sessionId}`;if(!(L==="session_host_stop_session"&&!window.confirm(`Stop ${_.displayName}?
108
- This will terminate the hosted runtime.`))){i(P);try{const B=await r(e,L,{sessionId:_.sessionId}),Y=Ao(B);if(!(Y!=null&&Y.success))throw new Error((Y==null?void 0:Y.error)||"Session host action failed");const M=L==="session_host_resume_session"?"resumed":L==="session_host_restart_session"?"restarted":"stopped";ct.showToast(`Session host ${M}: ${_.displayName}`,"success"),await f()}catch(B){const Y=B instanceof Error?B.message:"Session host action failed";ct.showToast(Y,"warning"),a(Y)}finally{i(B=>B===P?null:B)}}},[e,f,r]),k=l.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
109
- 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=Ao(_);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const B=P.result||{},Y=Array.isArray(B.prunedSessionIds)?B.prunedSessionIds.length:0,M=typeof B.duplicateGroupCount=="number"?B.duplicateGroupCount:0;ct.showToast(`Pruned ${Y} duplicate runtime(s) across ${M} group(s)`,"success"),await f()}catch(_){const P=_ instanceof Error?_.message:"Duplicate prune failed";ct.showToast(P,"warning"),a(P)}finally{i(_=>_==="session_host_prune_duplicate_sessions"?null:_)}}},[e,f,r]),b=l.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((L,_)=>(_.lastActivityAt||0)-(L.lastActivityAt||0)),[u==null?void 0:u.sessions]),j=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)||[]}:eC(b),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,b]),C=j.liveRuntimes,w=j.recoverySnapshots,g=j.inactiveRecords,S=l.useMemo(()=>nC(C),[C]),N=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(L=>L.level==="warn"||L.level==="error")||null,[u==null?void 0:u.recentLogs]),R=(L,_)=>{var T;const P=o===`session_host_resume_session:${L.sessionId}`,B=o===`session_host_restart_session:${L.sessionId}`,Y=o===`session_host_stop_session:${L.sessionId}`,M=Om(L.meta),H=x.get(L.sessionId),q=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,A=_==="recovery"?"Recover":"Resume",$=tC(_);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:L.displayName||(H==null?void 0:H.cliName)||L.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${rC(L.lifecycle)}`,children:L.lifecycle}),M&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:M})]}),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:L.workspaceLabel||(H==null?void 0:H.runtimeWorkspaceLabel)||L.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:L.runtimeKey}),L.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",L.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((T=L.writeOwner)==null?void 0:T.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:sC(L.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(Ed,{size:11})," ",q]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",hd(L.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",$]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[_==="recovery"&&(L.lifecycle==="interrupted"||L.lifecycle==="failed"||L.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{v("session_host_resume_session",L)},children:P?`${A}ing…`:A}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{v("session_host_restart_session",L)},children:B?"Restarting…":"Restart"}),_==="live"&&(L.lifecycle==="running"||L.lifecycle==="starting"||L.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:()=>{v("session_host_stop_session",L)},children:Y?"Stopping…":"Stop"})]})]})},L.sessionId)};return s.jsxs(ys,{padding:"lg",className:"mb-5",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(Is,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:l0()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[S>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{k()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${S})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${y.toneClass}`,children:y.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{f()},disabled:m||c,children:[s.jsx(va,{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(Vs,{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:hd(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Mo(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(Vs,{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:[Mo(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(wi,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Io("live")}),C.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:C.map(L=>R(L,"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(Is,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Io("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(L=>R(L,"recovery"))})]}),g.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:Io("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:g.map(L=>R(L,"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"}),N.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:N.map(L=>{var P;const _=b.find(B=>B.sessionId===L.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=x.get(L.sessionId))==null?void 0:P.cliName)||L.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[L.action,L.lifecycle?` · ${L.lifecycle}`:"",L.detail?` · ${L.detail}`:"",L.error?` · ${L.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${L.success===!1?"text-red-300":"text-text-secondary"}`,children:Mo(L.timestamp)})]},`${L.sessionId}:${L.timestamp}:${L.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 oC({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] 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 iC(e,t){const r=Tp(e),n=ir(e,t),a=Hi(e,n),o=Jr(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 _o({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 To({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-border-subtle bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function lC({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=iC(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(_o,{icon:s.jsx(Xs,{size:13}),children:"Current Chats"}),s.jsx(To,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(m=>{const h=ni(m);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass 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:ft(m)}),h>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:wa(h)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:xr(m)})]},m.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(_o,{icon:s.jsx(Hd,{size:13}),children:"Recent Launches"}),s.jsx(To,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(m=>{const{metaText:h,updatedLabel:y}=Kp(m);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass 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}),y&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:y})]}),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(_o,{icon:s.jsx(Vs,{size:13}),children:"Daemon Update"}),s.jsx(To,{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(va,{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 cC({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),[y,x]=l.useState(""),[f,v]=l.useState([]),[k,b]=l.useState(!1),[j,C]=l.useState(""),w=l.useCallback(async S=>{b(!0),C("");try{const N=await Yi(i,e,S);x(N.path),v(N.directories)}catch(N){C(N instanceof Error?N.message:"Could not load folder")}finally{b(!1)}},[e,i]),g=l.useCallback(()=>{h(!0);const S=[...r.map(I=>I.workspace),...n.map(I=>I.workspace),...a.map(I=>I.workspace)],N=qi(t.platform,Vi(S,t.defaultWorkspacePath,(t.workspaces||[]).map(I=>I.path)));w(N)},[a,n,r,w,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(ys,{padding:"lg",className:"mb-4",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(hr,{size:14})," Workspaces"]}),s.jsx("button",{type:"button",className:"btn bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick:g,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(S=>{const N=S.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 ${N?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:N?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void u(N?null:S.id),className:`text-base leading-none shrink-0 transition-colors ${N?"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:iu(S.path,S.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:S.path,children:S.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void p(S.id),children:"Remove"})]},S.id)})})]}),m&&s.jsx(Xi,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:y,directories:f,busy:k,error:j,confirmLabel:"Add workspace",onClose:()=>h(!1),onNavigate:S=>{w(S)},onConfirm:S=>{(async()=>{if(!S)return;await d(S)&&h(!1)})()}})]})}function dC({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-border-subtle 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(cC,{machineId:t,machine:e,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function uC({onNicknameSynced:e}={}){var ke,ye,we,he,K,E,J,re,be,ue;const{id:t}=Mh(),r=cn(),n=hi(),{sendCommand:a}=xt(),o=Sr(),i=vp(),c=Gu(),d=c.ides||[],p=c.initialLoaded??!0,u=d.find(D=>D.id===t&&D.type==="adhdev-daemon"),m=d.some(D=>D.type==="adhdev-daemon"),h=t?(ke=c.connectionRetryStatuses)==null?void 0:ke[t]:void 0,y=!!(h!=null&&h.blocked),[x,f]=l.useState("workspace"),[v,k]=l.useState(null);l.useCallback((D,me)=>{k({daemonId:D,workspace:me})},[]);const[,b]=l.useState("ide"),j=l.useRef(null),[C,w]=l.useState(null),g=l.useRef("__home__"),[S,N]=l.useState("__home__"),[I,R]=l.useState(!1),L=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||x!=="overview")return;const D=u.machine;(typeof(D==null?void 0:D.cpus)!="number"||typeof(D==null?void 0:D.totalMem)!="number"||typeof(D==null?void 0:D.arch)!="string"||typeof(D==null?void 0:D.release)!="string")&&i(t,{minFreshMs:3e4}).catch(()=>{})},[x,i,u,t]),bv(t&&x==="overview"?[t]:[],{enabled:x==="overview",intervalMs:Tg});const _=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},P=rS({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:L});l.useEffect(()=>ct.onToast(me=>{c.setToasts(oe=>{if(oe.some(Ne=>Ne.message===me.message&&me.timestamp-Ne.timestamp<3e3))return oe;const ve={id:me.id,message:me.message,type:me.type,timestamp:me.timestamp,targetKey:me.targetKey,actions:me.actions};return[...oe.slice(-4),ve]});const Se=me.duration||5e3;setTimeout(()=>c.setToasts(oe=>oe.filter(Q=>Q.id!==me.id)),Se)}),[c]);const B=(u==null?void 0:u.availableProviders)||[],Y={};for(const D of B)Y[D.type]=D.icon;const M=u?{id:u.id,hostname:lu(u,{fallbackId:u.id}),platform:((ye=u.machine)==null?void 0:ye.platform)||"unknown",arch:((we=u.machine)==null?void 0:we.arch)||"",cpus:((he=u.machine)==null?void 0:he.cpus)||0,totalMem:((K=u.machine)==null?void 0:K.totalMem)||0,freeMem:(E=u.machine)==null?void 0:E.freeMem,availableMem:(J=u.machine)==null?void 0:J.availableMem,loadavg:(re=u.machine)==null?void 0:re.loadavg,uptime:(be=u.machine)==null?void 0:be.uptime,release:((ue=u.machine)==null?void 0:ue.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,H=d.filter(D=>D.daemonId===t&&D.type!=="adhdev-daemon").filter(D=>!sn(D)&&!cr(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,version:D.version||"",instanceId:D.instanceId||"",status:D.status,workspace:D.workspace||null,terminals:D.terminals||0,aiAgents:Gx(D.aiAgents||(D.agents||[]).map(me=>({id:me.name,name:me.name,status:me.status,version:me.version}))),activeChat:D.activeChat||null,chats:D.chats||[],childSessions:D.childSessions||[],cdpConnected:D.cdpConnected||!1,daemonId:t,lastMessageAt:D.lastMessageAt})),q=d.filter(D=>D.daemonId===t&&sn(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,cliName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,mode:D.mode,runtimeKey:D.runtimeKey,runtimeDisplayName:D.runtimeDisplayName,runtimeWorkspaceLabel:D.runtimeWorkspaceLabel,runtimeWriteOwner:D.runtimeWriteOwner||null,runtimeAttachedClients:D.runtimeAttachedClients||[],daemonId:t,lastMessageAt:D.lastMessageAt})),A=d.filter(D=>D.daemonId===t&&cr(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,acpName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,daemonId:t,lastMessageAt:D.lastMessageAt})),$=u?Jt(u,{fallbackId:t}):"",T="workspace",F=n.state,z=F==null?void 0:F.initialMachineTab,U=F==null?void 0:F.initialWorkspaceCategory;F==null||F.initialWorkspaceId,F==null||F.initialWorkspacePath;const te=z==="ides"||z==="clis"||z==="acps"?"workspace":z||T,Z=z==="ides"?"ide":z==="clis"?"cli":z==="acps"?"acp":U,se=[...H.map(D=>{var me;return{id:`ide:${D.type}:${D.workspace||""}`,label:((me=D.activeChat)==null?void 0:me.title)||D.type,kind:"ide",providerType:D.type,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:D.lastMessageAt||0}}),...q.map(D=>{var me;return{id:`cli:${D.type}:${D.workspace||""}`,label:((me=D.activeChat)==null?void 0:me.title)||D.cliName,kind:"cli",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:D.lastMessageAt||0}}),...A.map(D=>{var me;return{id:`acp:${D.type}:${D.workspace||""}`,label:((me=D.activeChat)==null?void 0:me.title)||D.acpName,kind:"acp",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:qs(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:D.lastMessageAt||0}})].sort((D,me)=>(me.lastLaunchedAt||0)-(D.lastLaunchedAt||0)),G=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(D=>({id:D.id,label:D.title||D.providerName||D.providerType,kind:D.kind,providerType:D.providerType,providerSessionId:D.providerSessionId,subtitle:qs(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace,summaryMetadata:D.summaryMetadata,lastLaunchedAt:D.lastLaunchedAt})):se,O=l.useMemo(()=>{var me;const D=((me=c.connectionStates)==null?void 0:me[t||""])||void 0;return d.filter(Se=>Se.daemonId===t&&Se.type!=="adhdev-daemon").flatMap(Se=>Oi(Se,{connectionStates:t&&D?{[t]:D}:void 0,defaultConnectionState:D})).filter(Se=>!(Se.transport==="pty"&&Se.mode==="terminal")).sort((Se,oe)=>ni(oe)-ni(Se))},[d,c.connectionStates,t]),V=l.useCallback(D=>{const me=Dp(D);me&&r(an(me))},[r]),pe=l.useCallback(()=>{j.current&&(R(!0),j.current().finally(()=>{j.current=null,R(!1),w(null)}))},[]),fe=l.useCallback(D=>{if(!M)return;const{options:me,selectedKey:Se}=Wp({machine:M,currentWorkspacePath:D.workspace}),oe=async()=>{b(D.kind),f("workspace")};j.current=async()=>{const Q=me.find(Le=>Le.key===g.current),ve=(Q==null?void 0:Q.workspacePath)??null,Ne=(Q==null?void 0:Q.workspaceId)??null;if(D.kind==="ide"&&D.providerType){await P.handleLaunchIde(D.providerType,ve?{workspace:ve}:void 0);return}if((D.kind==="cli"||D.kind==="acp")&&D.providerType){await P.runLaunchCliCore({cliType:D.providerType,dir:Ne?void 0:ve||"",workspaceId:Ne||void 0,model:D.kind==="acp"&&du(D.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:D.providerSessionId});return}await oe()},g.current=Se,N(Se),w({title:D.kind==="ide"?ia("restart-ide",D.label):D.providerSessionId?rp(D.label):ia("start-fresh",D.label),description:D.kind==="ide"?la("restart-ide"):D.providerSessionId?np():la("start-fresh"),confirmLabel:D.kind==="ide"?ca("restart-ide"):D.providerSessionId?oa(!0):ca("start-fresh"),busyLabel:D.kind==="ide"?da("restart-ide"):D.providerSessionId?Bi(!0):da("start-fresh"),workspaceOptions:me,details:[{label:"Mode",value:D.kind.toUpperCase()},...D.providerType?[{label:"Provider",value:D.providerType}]:[]]})},[P,M]);if(l.useEffect(()=>{f(te)},[T,te,t]),l.useEffect(()=>{Z&&b(Z)},[Z,t]),!M)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 de=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(os,{size:14})," Workspace"]}),count:H.length+q.length+A.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Is,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ya,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(kf,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Fd,{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:D=>P.setNicknameInput(D.target.value),onKeyDown:D=>{D.key==="Enter"&&P.handleSaveNickname(),D.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(M.machineNickname||"")},title:"Click to set nickname",children:$}),y?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:[M.platform," · ",M.arch]}),s.jsxs("span",{children:[M.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),M.p2p.available&&s.jsxs("span",{children:["P2P ",M.p2p.state==="connected"?"connected":M.p2p.state]}),M.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:M.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:de.map(D=>s.jsxs("button",{onClick:()=>f(D.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${x===D.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[D.label,D.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${x===D.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:D.count})]},D.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:[x==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(lC,{machineEntry:u,providers:B,recentLaunches:G,currentConversations:O,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",Lp(u))}catch{}},onOpenRecent:fe,onOpenConversation:V}),s.jsx(dC,{machine:M,machineId:t,ideSessions:H,cliSessions:q,acpSessions:A,actions:P,sendDaemonCommand:a})]}),x==="providers"&&s.jsx(bS,{machineId:t,providers:B,sendDaemonCommand:a}),x==="overview"&&s.jsx(nS,{machine:M,ideSessions:H,cliSessions:q,acpSessions:A}),x==="session-host"&&s.jsx(aC,{machineId:t,cliSessions:q,sendDaemonCommand:a}),x==="logs"&&s.jsx(QS,{machineId:t,sendDaemonCommand:a})]})})}),P.launchPick&&M&&s.jsx(oC,{machine:M,launchPick:P.launchPick,actions:P}),C&&s.jsx(Hp,{title:C.title,description:C.description,details:C.details,workspaceOptions:C.workspaceOptions,selectedWorkspaceKey:S,onWorkspaceChange:D=>{g.current=D,N(D)},confirmLabel:C.confirmLabel,busyLabel:C.busyLabel,busy:I,onConfirm:pe,onCancel:()=>{j.current=null,w(null)}}),v&&s.jsx(Bm,{daemonId:v.daemonId,workspace:v.workspace,onClose:()=>k(null)}),s.jsx(op,{toasts:c.toasts||[],onDismiss:D=>c.setToasts(me=>me.filter(Se=>Se.id!==D)),onClickToast:D=>{D.targetKey&&r(an(D.targetKey))}}),s.jsx("style",{children:`
110
- @keyframes toast-in {
111
- from { opacity: 0; transform: translateX(40px); }
112
- to { opacity: 1; transform: translateX(0); }
113
- }
114
- `})]})}function pC({daemonIds:e,meshId:t,sendData:r,onRevisionAdvance:n}){const a=l.useRef(new Map),o=l.useRef(n);o.current=n;const i=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{a.current=new Map},[i,t]),l.useEffect(()=>{if(!t||!r)return;const c=[...new Set(e.filter(Boolean))];if(c.length===0)return;const d=c.map(p=>rs.subscribe({sendData:r},p,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${p}`,params:{includeSessions:!0}},u=>{if(u.topic!=="daemon.metadata")return;const m=u.meshStateRevisions;if(!m)return;const h=m[t]??m["*"];if(typeof h!="number")return;const y=a.current.get(p);a.current.set(p,h),y!==void 0&&h>y&&o.current()}));return()=>{for(const p of d)p()}},[i,t,r])}const mC={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},Hm=l.createContext(null);function hC(){const e=l.useContext(Hm);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function fC({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 xC({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 bC({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 gC({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 yC({status:e}){const r={online:{color:"#22c55e",label:"Online"},dirty:{color:"#f59e0b",label:"Dirty",title:"Workspace has uncommitted changes"},offline:{color:"#6b7280",label:"Offline"},degraded:{color:"#ef4444",label:"Degraded",title:"P2P connection to this node is down or timed out — often transient. Wait and retry, or re-establish the node's connection."},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`},title:r.title,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:r.color}}),r.label]})}function vC(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function wC({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:y,newMeshDaemonId:x,onNewMeshDaemonIdChange:f,newMeshWorkspace:v,onNewMeshWorkspaceChange:k,createPickerWorkspaces:b,onSelectMesh:j,onCreate:C,onCancelCreate:w}){return s.jsxs(mn,{icon:s.jsx(Yt,{}),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(Ft,{variant:"error",onDismiss:n,className:"mb-4",children:r}),i&&s.jsxs(mt,{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(yt,{label:"Create on machine",hint:"Mesh setup is stored by the selected daemon.",children:s.jsx("select",{className:"input w-full",value:x,onChange:g=>f(g.target.value),disabled:!a.length,children:a.length===0?s.jsx("option",{value:"",children:"No connected daemon"}):a.map(g=>s.jsx("option",{value:g.id,children:vC(g)},g.id))})}),o.createDaemonPicker&&s.jsx(yt,{label:"Workspace",hint:"Choose from workspaces registered by the selected daemon.",children:s.jsx("select",{className:"input w-full",value:v,onChange:g=>k(g.target.value),disabled:!x||!b.length,children:x?b.length===0?s.jsx("option",{value:"",children:"No registered workspaces"}):b.map(g=>s.jsx("option",{value:g.path,children:g.label?`${g.label} · ${g.path}`:g.path},g.id||g.path)):s.jsx("option",{value:"",children:"Select a machine first"})})}),s.jsx(yt,{label:"Name",children:s.jsx(ss,{value:d,onChange:g=>p(g.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(yt,{label:"Repo remote URL (optional)",hint:"Provide a remote URL OR a stable identity.",children:s.jsx(ss,{value:h,onChange:g=>y(g.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(yt,{label:"Repo identity (optional)",hint:"Provide a remote URL OR a stable identity.",children:s.jsx(ss,{value:u,onChange:g=>m(g.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:C,disabled:!d.trim()||!h.trim()&&!u.trim()||o.createDaemonPicker&&(!x||!v),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(_a,{icon:s.jsx(Yt,{}),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(g=>{var S;return s.jsx("button",{type:"button",onClick:()=>j(g.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(Yt,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:g.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:g.repoIdentity||g.repo_identity||"No repo identity"}),(g.defaultBranch||g.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(xC,{size:11}),g.defaultBranch||g.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(g.createdAt||g.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((S=g.nodes)==null?void 0:S.length)??g.nodeCount??0," node(s)"]})]})]})},g.id)})})]})}const jC=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],kC=[{kind:"rca",label:"Root-cause analysis",hint:"rca"},{kind:"design",label:"Design / approach review",hint:"design"},{kind:"claim_audit",label:"Verify specific claims",hint:"claim_audit"},{kind:"freeform",label:"Freeform review",hint:"freeform"}];function NC(){return{nodeId:"",provider:"",model:"",n:""}}function fd(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function SC(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function CC(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r],a=n.provider.trim();if(!a)return{error:`Slot ${r+1}: provider is required`};const o=n.nodeId.trim(),i=n.model.trim(),c=n.n.trim();let d;if(c){const p=Number(c);if(!Number.isFinite(p)||p<1)return{error:`Slot ${r+1}: replica count must be ≥ 1`};d=Math.floor(p)}t.push({provider:a,...o?{nodeId:o}:{},...i?{model:i}:{},...d!==void 0?{n:d}:{}})}return t.length===0?{error:"A kind binding needs at least one slot"}:{slots:t}}function IC({status:e,daemonId:t,sendDaemonCommand:r,availableProviders:n}){const{theme:a}=Ts(),o=l.useMemo(()=>Ls(a),[a]),i=l.useMemo(()=>up(n),[n]),[c,d]=l.useState({}),[p,u]=l.useState(!1),[m,h]=l.useState(null),[y,x]=l.useState({}),[f,v]=l.useState(null),k=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(A=>({nodeId:A.nodeId,machineLabel:A.machineLabel,providers:A.providers,providerPriority:A.providerPriority})),[e==null?void 0:e.nodes]),b=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(A=>A.nodeId),[e==null?void 0:e.nodes]),j=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(A=>[A.nodeId,A.machineLabel||A.nodeId])),[e==null?void 0:e.nodes]),C=l.useMemo(()=>{const A={};for(const $ of k)A[$.nodeId]=fd($);return A},[k]),w=l.useMemo(()=>{const A=[...new Set(k.flatMap(fd).filter(Boolean))];return[...new Set([...A,...jC])].sort()},[k]),g=!!t&&!!r,S=A=>A&&typeof A=="object"&&"result"in A?A.result:A,N=l.useCallback(async()=>{if(!(!t||!r)){u(!0),h(null);try{const A=await r(t,"magi_kind_panel_list",{}),$=S(A);if(($==null?void 0:$.success)===!1)throw new Error($.error||"Failed to load kind panels");d($!=null&&$.kindPanels&&typeof $.kindPanels=="object"?$.kindPanels:{}),x({})}catch(A){h((A==null?void 0:A.message)||"Failed to load kind panels")}finally{u(!1)}}},[t,r]);l.useEffect(()=>{N()},[N]);const I=l.useCallback(A=>{if(y[A])return y[A];const $=c[A];return $?$.map(SC):[]},[y,c]),R=(A,$)=>{x(T=>({...T,[A]:$}))},L=(A,$,T)=>{const F=I(A);R(A,F.map((z,U)=>U===$?{...z,...T}:z))},_=A=>{R(A,[...I(A),NC()])},P=(A,$)=>{R(A,I(A).filter((T,F)=>F!==$))},B=l.useCallback(async A=>{if(!t||!r)return;const $=CC(I(A));if("error"in $){h(`${A}: ${$.error}`);return}v(A),h(null);try{const T=await r(t,"magi_kind_panel_set",{kind:A,slots:$.slots}),F=S(T);if((F==null?void 0:F.success)===!1)throw new Error(F.error||"Failed to save kind binding");await N()}catch(T){h((T==null?void 0:T.message)||"Failed to save kind binding")}finally{v(null)}},[t,r,I,N]),Y=l.useCallback(async A=>{if(!(!t||!r)&&confirm(`Remove the MAGI panel binding for "${A}"?`)){v(A),h(null);try{const $=await r(t,"magi_kind_panel_remove",{kind:A}),T=S($);if((T==null?void 0:T.success)===!1)throw new Error(T.error||"Failed to remove kind binding");await N()}catch($){h(($==null?void 0:$.message)||"Failed to remove kind binding")}finally{v(null)}}},[t,r,N]),M=`w-full rounded-lg border px-2.5 py-1.5 text-xs ${o.isDark?"border-white/10 bg-slate-950/40 text-slate-100 placeholder:text-slate-500":"border-slate-300 bg-white text-slate-900 placeholder:text-slate-400"}`,H="btn btn-primary btn-sm",q="btn btn-secondary btn-sm";return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("p",{className:`text-[12px] ${o.textSecondary}`,children:"Pick which agents review each task type. Add one row per agent."}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:q,onClick:()=>void N(),disabled:p||!g,children:p?"Loading…":"Refresh"})})]}),!g&&s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${o.textSecondary} ${o.isDark?"border-white/10":"border-slate-200"}`,children:"Connect to a coordinator daemon to manage kind → panel bindings."}),m&&s.jsx("div",{className:"rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-[12px] text-rose-300",children:m}),s.jsx("div",{className:"flex flex-col gap-3",children:kC.map(({kind:A,label:$,hint:T})=>{const F=I(A),z=!!c[A],U=f===A;return s.jsxs("div",{className:`${o.cardClass} rounded-2xl p-4 flex flex-col gap-3`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[13px] font-semibold ${o.textPrimary}`,children:$}),s.jsx("span",{className:`font-mono text-[10px] ${o.textMuted}`,children:T}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${z?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:z?`${c[A].length} agent${c[A].length===1?"":"s"}`:"off"})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[F.length===0&&s.jsx("div",{className:`rounded-xl border p-2.5 text-[11px] ${o.textSecondary} ${o.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:"No agents yet — add one to enable this review type."}),F.map((te,Z)=>{const se=te.nodeId?C[te.nodeId]??[]:[],G=te.nodeId&&se.length?se:w;return s.jsxs("div",{className:`rounded-xl border p-2.5 grid grid-cols-1 sm:grid-cols-[1fr_1fr_1fr_auto_auto] gap-x-2 gap-y-1 items-start ${o.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${o.textSecondary}`,children:"Machine"}),s.jsxs("select",{className:M,value:te.nodeId,onChange:O=>L(A,Z,{nodeId:O.target.value}),title:"Which machine runs this agent. Leave on “any” to let the coordinator route by tags.",children:[s.jsx("option",{value:"",children:"Any machine"}),b.map(O=>s.jsx("option",{value:O,children:j[O]??O},O)),te.nodeId&&!b.includes(te.nodeId)&&s.jsxs("option",{value:te.nodeId,children:[j[te.nodeId]??te.nodeId," (offline)"]})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${o.textSecondary}`,children:"Provider *"}),s.jsxs("select",{className:M,value:te.provider,onChange:O=>L(A,Z,{provider:O.target.value}),title:"The AI agent this slot runs.",children:[s.jsx("option",{value:"",children:"Select provider…"}),G.map(O=>s.jsx("option",{value:O,children:O},O)),te.provider&&!G.includes(te.provider)&&s.jsx("option",{value:te.provider,children:te.provider})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${o.textSecondary}`,children:"Model"}),(()=>{var pe;const O=(te.provider?(pe=i.get(te.provider))==null?void 0:pe.models:void 0)??[],V=!!te.model&&O.length>0&&!O.includes(te.model);return O.length>0&&!V?s.jsxs("select",{className:M,value:O.includes(te.model)?te.model:"",title:"Optional model override (best-effort). Blank uses the provider default.",onChange:fe=>L(A,Z,{model:fe.target.value==="__custom__"?" ":fe.target.value}),children:[s.jsx("option",{value:"",children:"default"}),O.map(fe=>s.jsx("option",{value:fe,children:fe},fe)),s.jsx("option",{value:"__custom__",children:"Custom…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:M,value:te.model.trim(),placeholder:"default",title:"Optional model override (best-effort). Blank uses the provider default.",onChange:fe=>L(A,Z,{model:fe.target.value})}),O.length>0&&s.jsx("button",{type:"button",className:`self-start bg-transparent border-none cursor-pointer p-0 text-[10px] ${o.textSecondary} hover:underline`,onClick:()=>L(A,Z,{model:""}),children:"← Back to model list"})]})})()]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${o.textSecondary}`,children:"Copies"}),s.jsx("input",{className:`${M} sm:w-16`,value:te.n,placeholder:"1",inputMode:"numeric",title:"How many parallel copies of this agent to run. Blank = 1.",onChange:O=>L(A,Z,{n:O.target.value})})]}),s.jsx("button",{type:"button",className:`${q} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>P(A,Z),"aria-label":"Remove agent",title:"Remove agent",children:"✕"})]},Z)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:q,onClick:()=>_(A),disabled:!g,children:"+ Add agent"})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:H,onClick:()=>void B(A),disabled:U||!g,children:U?"Saving…":"Save"}),s.jsx("button",{type:"button",className:q,onClick:()=>void Y(A),disabled:U||!g||!z,title:z?"Clear this kind binding":"Nothing to remove — this kind is unconfigured",children:"Remove binding"})]})]},A)})})]})}function AC({daemonId:e,meshId:t,cliType:r,sendCommand:n}){const[a,o]=l.useState(!1),[i,c]=l.useState(!1),[d,p]=l.useState(null),[u,m]=l.useState(null),[h,y]=l.useState(null),x=l.useCallback(async()=>{if(!e||!t){p("Connect a daemon to preview the default.");return}c(!0),p(null);try{const v=await n(e,"coordinator_prompt_preview",{meshId:t,cliType:r}),k=v!=null&&v.result&&typeof v.result=="object"?v.result:v;if(!(k!=null&&k.success)){p((k==null?void 0:k.error)||"Failed to render the default prompt");return}m(typeof k.prompt=="string"?k.prompt:""),y(typeof k.bytes=="number"?k.bytes:null)}catch(v){p((v==null?void 0:v.message)||String(v))}finally{c(!1)}},[e,t,r,n]),f=l.useCallback(()=>{const v=!a;o(v),v&&u===null&&!i&&x()},[a,u,i,x]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:f,className:"inline-flex items-center gap-1 text-[12px] text-accent-primary bg-transparent border-none cursor-pointer p-0",children:[s.jsx("span",{className:`transition-transform ${a?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),a?"Hide the default prompt":"View the default prompt",s.jsxs("span",{className:"text-text-muted",children:["(",r,")"]})]}),a&&s.jsxs("div",{className:"mt-2",children:[i&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Rendering…"}),d&&s.jsxs("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:[d,s.jsx("button",{type:"button",onClick:()=>void x(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:"Retry"})]}),!i&&!d&&u!==null&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between text-[11px] text-text-muted",children:[s.jsx("span",{children:"This is what a coordinator session gets when Override is empty."}),h!==null&&s.jsxs("span",{children:[(h/1024).toFixed(1)," KB"]})]}),s.jsx("textarea",{readOnly:!0,value:u,rows:14,className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-secondary font-mono",onFocus:v=>v.currentTarget.select()})]})]})]})}const MC=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function _C(e){const t=MC(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function TC(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function LC(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const RC=["active","paused","completed","abandoned"];function xd(e){return(e.status||"active").toLowerCase()}const PC=8;function DC({status:e,daemonId:t,meshId:r,sendCommand:n}){const a=l.useMemo(()=>TC(e),[e]),[o,i]=l.useState({}),[c,d]=l.useState({}),[p,u]=l.useState(!1),[m,h]=l.useState(null),[y,x]=l.useState("active"),[f,v]=l.useState(!1),k=l.useMemo(()=>{const N={};for(const I of a){const R=xd(I);N[R]=(N[R]||0)+1}return N},[a]),b=l.useMemo(()=>y==="all"?a:a.filter(N=>xd(N)===y),[a,y]),j=f?b:b.slice(0,PC),C=b.length-j.length,w=!!t&&a.length>0,g=l.useCallback(async()=>{if(t){u(!0),h(null);try{const N=await n(t,"mesh_status",{meshId:r,verbose:!0}),I=_C(N),R=Array.isArray(I==null?void 0:I.missions)?I.missions:[],L={};for(const _ of R)_.id&&typeof _.goal=="string"&&_.goal&&(L[_.id]=_.goal);i(_=>({..._,...L}))}catch(N){h(N instanceof Error?N.message:"Failed to fetch full mission goals")}finally{u(!1)}}},[t,r,n]),S=l.useCallback(N=>{d(I=>({...I,[N]:!I[N]})),!c[N]&&!o[N]&&g()},[c,o,g]);return a.length===0?null:s.jsxs(mt,{title:"Missions",description:"Active and historical missions reported by the coordinator. Expand a goal to fetch its full text on demand.",children:[m&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400",children:m}),s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[RC.filter(N=>(k[N]||0)>0).map(N=>s.jsxs("button",{type:"button",onClick:()=>{x(N),v(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] capitalize transition-colors ${y===N?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:[N," ",k[N]]},N)),s.jsxs("button",{type:"button",onClick:()=>{x("all"),v(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] transition-colors ${y==="all"?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:["All ",a.length]})]}),b.length===0&&s.jsxs("div",{className:"text-[12px] text-text-muted",children:["No ",y," missions."]}),s.jsx("div",{className:"flex flex-col gap-2",children:j.map(N=>{var Y;const I=c[N.id]===!0,R=o[N.id],L=LC(N),_=I&&R?R:L.text,P=I&&!R&&L.truncated,B=((Y=N.tasks)==null?void 0:Y.total)??0;return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 px-3 py-2.5",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-text-primary",title:N.title,children:N.title||N.id}),N.status&&s.jsx("span",{className:"shrink-0 rounded-full border border-border-subtle px-2 py-0.5 text-[10px] uppercase tracking-wide text-text-muted",children:N.status}),B>0&&s.jsxs("span",{className:"shrink-0 text-[11px] text-text-muted",children:[B," task",B===1?"":"s"]})]}),_&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${I?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[_,P&&s.jsx("span",{className:"text-text-muted",children:" … (full goal unavailable)"})]}),(L.truncated||R)&&w&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>S(N.id),disabled:p,children:I?"Show less":p&&!R?"Loading…":"Show full goal"})]},N.id)})}),C>0&&s.jsxs("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>v(!0),children:["Show ",C," more"]})]})}const $C=["","low","medium","high"],EC={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function bd(e){return{provider:e.provider||"",model:e.model||"",thinkingLevel:e.thinkingLevel||"",difficulty:Array.isArray(e.difficulty)?e.difficulty:[],capability:Array.isArray(e.capability)?e.capability:[],maxParallel:e.maxParallel!=null?String(e.maxParallel):""}}function gd(e){const t=e.provider.trim();if(!t)return null;const r=e.model.trim(),n=e.thinkingLevel.trim()||void 0,a=Number(e.maxParallel),o=Number.isFinite(a)&&a>0?Math.floor(a):void 0;return{provider:t,...r?{model:r}:{},...n?{thinkingLevel:n}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...o!==void 0?{maxParallel:o}:{}}}function BC(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const Ds="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function FC({slots:e,availableProviders:t,saving:r,onSave:n}){const[a,o]=l.useState(()=>e.map(bd)),i=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{o(e.map(bd))},[i]);const c=l.useMemo(()=>[...new Set(t.map(k=>k.type).filter(Boolean))],[t]),d=l.useMemo(()=>up(t),[t]),p=l.useMemo(()=>{const k=a.map(gd).filter(Boolean);return JSON.stringify(k)!==JSON.stringify(e)},[a,e]),u=(k,b)=>o(j=>j.map((C,w)=>w===k?{...C,...b}:C)),m=(k,b)=>o(j=>j.map((C,w)=>{var N;if(w!==k)return C;const g=((N=d.get(b))==null?void 0:N.models)??[],S=!C.model||g.length===0||g.includes(C.model);return{...C,provider:b,...S?{}:{model:""}}})),h=k=>o(b=>b.filter((j,C)=>C!==k)),y=()=>o(k=>[...k,BC()]),x=(k,b)=>o(j=>{const C=k+b;if(C<0||C>=j.length)return j;const w=[...j];return[w[k],w[C]]=[w[C],w[k]],w}),f=(k,b)=>o(j=>j.map((C,w)=>{if(w!==k)return C;const g=C.difficulty.includes(b);return{...C,difficulty:g?C.difficulty.filter(S=>S!==b):[...C.difficulty,b]}})),v=()=>n(a.map(gd).filter(Boolean));return s.jsxs("div",{className:"flex flex-col gap-2",onClick:k=>k.stopPropagation(),children:[a.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"No capability slots set — that's fine. This node still runs tasks using its provider priority order (below). Slots are optional fine-tuning: add one to route specific task difficulties or capabilities to a specific tool."}),a.map((k,b)=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-2.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[s.jsxs("span",{className:"text-[11px] font-semibold text-text-muted",children:["#",b+1]}),s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:b===0,onClick:()=>x(b,-1),title:"Move up",children:"↑"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:b===a.length-1,onClick:()=>x(b,1),title:"Move down",children:"↓"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-status-error/30 text-status-error hover:bg-status-error/10",onClick:()=>h(b),"aria-label":`Remove slot ${b+1}`,children:s.jsx(wt,{size:12})})]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Provider"}),c.length>0?s.jsxs("select",{className:Ds,value:k.provider,onChange:j=>m(b,j.target.value),children:[s.jsx("option",{value:"",children:"(select)"}),c.map(j=>s.jsx("option",{value:j,children:j},j)),k.provider&&!c.includes(k.provider)&&s.jsx("option",{value:k.provider,children:k.provider})]}):s.jsx("input",{className:Ds,value:k.provider,placeholder:"claude-cli",onChange:j=>u(b,{provider:j.target.value})})]}),(()=>{var S;const j=d.get(k.provider),C=(j==null?void 0:j.models)??[],w=(S=j==null?void 0:j.thinking)!=null&&S.length?["",...j.thinking]:$C,g=!!k.model&&C.length>0&&!C.includes(k.model);return s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Model"}),C.length>0&&!g?s.jsxs("select",{className:Ds,value:C.includes(k.model)?k.model:"",onChange:N=>u(b,{model:N.target.value==="__custom__"?" ":N.target.value}),children:[s.jsx("option",{value:"",children:"(provider default)"}),C.map(N=>s.jsx("option",{value:N,children:N},N)),s.jsx("option",{value:"__custom__",children:"Custom…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:Ds,value:k.model.trim(),placeholder:k.provider?`${k.provider} model`:"model",onChange:N=>u(b,{model:N.target.value})}),C.length>0&&s.jsx("button",{type:"button",className:"self-start bg-transparent border-none cursor-pointer p-0 text-[10px] text-text-muted hover:underline",onClick:()=>u(b,{model:""}),children:"← Back to model list"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Thinking"}),s.jsx("select",{className:Ds,value:k.thinkingLevel,onChange:N=>u(b,{thinkingLevel:N.target.value}),children:w.map(N=>s.jsx("option",{value:N,children:N||"(default)"},N||"_default"))})]})]})})()]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Difficulty (blank = all)"}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:Rx.map(j=>{const C=k.difficulty.includes(j);return s.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${C?"border-accent-primary/60 bg-accent-primary/15 text-accent-primary":"border-border-subtle bg-bg-primary/60 text-text-muted hover:text-text-primary"}`,onClick:()=>f(b,j),children:EC[j]},j)})})]}),s.jsxs("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Capability tags (comma-separated)"}),s.jsx("input",{className:Ds,value:k.capability.join(", "),placeholder:"worktree, os=darwin",onChange:j=>u(b,{capability:j.target.value.split(",").map(C=>C.trim()).filter(Boolean)})})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Max parallel (per slot)"}),s.jsx("input",{type:"number",inputMode:"numeric",min:1,className:Ds,value:k.maxParallel,placeholder:"unlimited",onChange:j=>u(b,{maxParallel:j.target.value})})]})]})]},b)),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1",onClick:y,children:[s.jsx(ji,{size:13})," Add slot"]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:v,disabled:!!r||!p,children:r?"Saving…":"Save slots"})]})]})}function OC(e){const t=new Map;for(const r of e)r!=null&&r.id&&t.set(r.id,br(r.availableProviders||[]));return t}function HC(e,t){const r=String(e.daemon_id||e.daemonId||"");return r&&t.has(r)?t.get(r):!r&&t.size===1?[...t.values()][0]:[]}function WC(e){var d,p,u;const t=e,r=[],n=Array.isArray(t.capabilities)?t.capabilities:[];for(const m of n){const h=typeof m=="string"?m.trim():"";h&&r.push({tag:h,custom:!0})}const a=(((d=t.userOverrides)==null?void 0:d.platform)||t.reportedPlatform||"").toString().trim(),o=(((p=t.userOverrides)==null?void 0:p.arch)||t.reportedArch||"").toString().trim();a&&r.push({tag:`os=${a}`,custom:!1}),o&&r.push({tag:`arch=${o}`,custom:!1});const i=Array.isArray((u=t.policy)==null?void 0:u.providerPriority)?String(t.policy.providerPriority[0]||"").trim():"";i&&r.push({tag:`provider=${i}`,custom:!1});const c=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";return t.isLocalWorktree===!0&&c&&r.push({tag:`worktree=${c}`,custom:!1}),r}function KC(e){const t=e.capabilities;return Array.isArray(t)?t.map(r=>typeof r=="string"?r.trim():"").filter(Boolean):[]}const UC=["os=","arch=","provider=","worktree=","converge="];function zC({node:e,saving:t,onSave:r}){const n=l.useMemo(()=>WC(e).filter(x=>!x.custom),[e]),a=l.useMemo(()=>KC(e),[e]),[o,i]=l.useState(a),[c,d]=l.useState(""),p=JSON.stringify(o)!==JSON.stringify(a),m=(x=>{const f=x.trim();return f?/\s/.test(f)?"Tags cannot contain spaces.":UC.some(v=>f.toLowerCase().startsWith(v))?"That prefix is auto-derived — pick a different tag.":o.includes(f)?"Already added.":null:null})(c);function h(){const x=c.trim();!x||m||(i(f=>[...f,x]),d(""))}function y(x){i(f=>f.filter(v=>v!==x))}return s.jsxs("div",{className:"mt-2",onClick:x=>x.stopPropagation(),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wide text-text-muted mr-1",children:"Routing tags"}),n.map(x=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 font-mono text-[10px] text-text-muted",title:"Auto-derived — can't be edited",children:x.tag},x.tag)),o.map(x=>s.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 font-mono text-[10px] text-accent-primary",title:"Custom tag",children:[x,s.jsx("button",{type:"button",className:"text-accent-primary/70 hover:text-accent-primary bg-transparent border-none cursor-pointer p-0 leading-none",onClick:()=>y(x),disabled:t,"aria-label":`Remove ${x}`,children:"×"})]},x))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:c,onChange:x=>d(x.target.value),onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),h())},placeholder:"add a custom tag (e.g. test-runner)",disabled:t,className:"min-w-[12rem] flex-1 px-2 py-1 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:h,disabled:t||!c.trim()||!!m,children:"Add"}),p&&s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>r(o),disabled:t,children:t?"Saving…":"Save tags"})]}),m&&s.jsx("div",{className:"mt-1 text-[11px] text-amber-400",children:m}),o.length===0&&n.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"No routing tags — tasks can run here without matching any specific capability. Tags are optional."})]})}function GC(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function VC(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 qC(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 YC(e){const t=qC(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"No provider detected on this node — task launch is blocked until a provider is selected or installed. (Empty capability slots alone do not block launch; this means no provider was found.)"}}function JC(e){return e.isLocalWorktree===!0}function XC(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 yd(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function QC(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 ZC({nodes:e,meshQueue:t,activeDaemon:r,daemons:n,selectedMeshId:a,userName:o,features:i,coordinatorDaemonId:c,availableCliProviders:d,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:h,nodeSystemPromptDrafts:y,onNodeSystemPromptDraftChange:x,savingNodeSystemPromptId:f,onSaveNodeSystemPrompt:v,selectedNodeId:k,onSelectNode:b,showAddNode:j,onShowAddNode:C,onCancelAddNode:w,nodeWorkspace:g,onNodeWorkspaceChange:S,nodeProviderPriority:N,onNodeProviderPriorityChange:I,nodeDaemonId:R,onNodeDaemonIdChange:L,nodeCustomPath:_,onNodeCustomPathChange:P,nodePickerWorkspaces:B,nodePickerProviders:Y,attachableDaemons:M,onAddNode:H,onRemoveNode:q}){const A=l.useMemo(()=>OC(n),[n]),$=l.useMemo(()=>e.filter(T=>!JC(T)),[e]);return s.jsxs(mt,{title:i.addNodeDaemonPicker?`Nodes & Providers (${$.length})`:"Nodes & Providers",description:i.addNodeDaemonPicker?"Workspaces in this mesh and their preferred AI tools. Setup inventory only — live graph/git/session truth is owned by the Mesh Host status above.":"Workspaces participating in this mesh and their preferred AI tools.",children:[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:[M.length," available"]})]}),n.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:"No connected machine daemons are currently available."}):M.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:M.map(T=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${T.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{L(T.id),S(""),P(!1),I(nn(br(T.availableProviders||[]))),C()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate",children:yd(T)}),T.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:T.id}),s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted",children:[(T.workspaces||[]).length," workspace(s) detected"]})]},T.id))})]}),!j&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:C,children:[s.jsx(gC,{size:13})," ",i.addNodeDaemonPicker?"Attach machine":"Add node"]}),j&&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(),L(""),P(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(wt,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(yt,{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:R,onChange:T=>{var F;L(T.target.value),S(""),P(!1),I(nn(br(((F=n.find(z=>z.id===T.target.value))==null?void 0:F.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:"Select a machine..."}),n.map(T=>s.jsx("option",{value:T.id,children:yd(T)},T.id))]})}),(i.addNodeDaemonPicker?R:!0)&&s.jsx(yt,{label:"Workspace Path",children:i.addNodeDaemonPicker&&!_&&B.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:B.map(T=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${g===T.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:()=>S(T.path),children:[s.jsx("span",{className:"font-medium block truncate",children:T.label||T.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:T.path})]},T.id||T.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{P(!0),S("")},children:"Or enter a custom path →"})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(ss,{value:g,onChange:T=>S(T.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:T=>{T.key==="Enter"&&H()}}),B.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),S("")},children:"← Pick from saved workspaces"})]}):(()=>{var z;const T=Array.isArray(r==null?void 0:r.workspaces)?r.workspaces:[],F=`mesh-add-node-workspaces-${a||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(ss,{value:g,onChange:U=>S(U.target.value),placeholder:((z=T[0])==null?void 0:z.path)||"/Users/dev/projects/myapp",list:T.length>0?F:void 0,autoFocus:!0}),T.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:F,children:T.map(U=>s.jsx("option",{value:U.path,children:U.label||U.path},U.id||U.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:T.slice(0,6).map(U=>s.jsx("button",{type:"button",onClick:()=>S(U.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:U.path,children:U.label||U.path.split("/").filter(Boolean).pop()||U.path},U.id||U.path))})]})]})})()})}),s.jsx(yt,{label:"Preferred AI tools (in order)",hint:"Order used when launching without an explicit provider.",children:s.jsx(C0,{value:N,availableProviders:i.addNodeDaemonPicker?Y:d,onChange:I})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:H,disabled:!g.trim()||i.addNodeDaemonPicker&&!R,className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>{w(),L(""),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."}),$.length===0?s.jsx(_a,{icon:s.jsx(hr,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:$.map(T=>{var se;const F=YC(T),z=GC(T,t),U=XC(T,r),te=k===T.id,Z=T.status||T.machine_status||(z.length>0||U.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 ${te?"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:()=>b(te?null:T.id),onKeyDown:i.addNodeDaemonPicker?void 0:G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),b(te?null:T.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:T.machine_label||T.machine_nickname||T.hostname||T.workspace}):s.jsx("span",{className:"text-sm font-medium",children:T.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx(yC,{status:Z}),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: ",QC(n.find(G=>G.id===String(T.daemon_id||"")),o)," · Machine: ",T.machine_label||T.daemon_id||T.workspace]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:T.workspace}),s.jsx(zC,{node:T,saving:m===T.id,onSave:G=>h(T,G)}),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",onClick:G=>G.stopPropagation(),children:[s.jsx(yt,{label:"Preferred AI tools (capability slots)",hint:"Each slot = provider + model + thinking + the task difficulty/capability it handles + a per-slot parallel cap. Tasks are matched to the best-fit slot (order = preference). With no slots, this node uses its legacy provider order.",children:s.jsx(FC,{slots:Array.isArray((se=T.policy)==null?void 0:se.slots)?T.policy.slots:[],availableProviders:HC(T,A),saving:p===T.id,onSave:G=>u(T,G)})}),i.nodeInstruction&&s.jsxs(yt,{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:y[T.id]??"",onChange:G=>{const O=G.target.value;x(T.id,O)},onClick:G=>G.stopPropagation(),disabled:f===T.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:G=>{G.stopPropagation(),v(T)},disabled:f===T.id,children:f===T.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:G=>{G.stopPropagation(),q(T.id)},title:"Remove node",children:s.jsx(bC,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:G=>G.stopPropagation(),children:[s.jsxs("summary",{className:"cursor-pointer select-none text-[12px] text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[s.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," Details"]}),s.jsxs("div",{className:"mt-2 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 break-all",children:T.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:F.configured?"text-green-400":"text-amber-400",children:F.configured?"yes":"no preferred tool configured"})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Repo root:"})," ",s.jsx("span",{className:"font-mono break-all",children:T.repoRoot||T.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",U.length]}),i.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Added:"})," ",new Date(T.created_at||T.createdAt||Date.now()).toLocaleDateString()]})]}),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(G=>s.jsx("li",{className:"font-mono",children:VC(G)},G.id))})]}),U.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:U.map(G=>s.jsxs("li",{className:"font-mono",children:[G.provider," / ",G.status," / ",G.id]},G.id))})]})]})]})]},T.id)})})]})}function $n(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function e2({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:r,coordinatorCliType:n,onCoordinatorCliTypeChange:a,launchingCoordinator:o,launchResult:i,isHostNodeAttached:c,selectedHostNode:d,hostPinned:p,hostLabel:u,hostOnline:m,hostRebindDaemonId:h,onHostRebindDaemonIdChange:y,onLaunchCoordinator:x}){const f=s.jsx(yt,{label:"Coordinator CLI provider",hint:"Tool launched for the host coordinator session.",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:b=>a(b.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"})]})}),v=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});if(p)return s.jsxs(mt,{title:"Mesh Host daemon",description:"The daemon that owns this mesh's coordinator and live truth (status, queue, graph, node detail). Fixed when the mesh is created — it cannot be reassigned here.",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-[13px] text-text-primary ${m?"border-accent-primary/40 bg-accent-primary/10":"border-amber-500/40 bg-amber-500/10"}`,children:[s.jsx("span",{className:"text-text-muted",children:"Host:"}),s.jsx("span",{className:"font-medium",children:u||"Unknown"}),s.jsxs("span",{className:m?"text-text-muted":"text-amber-400",children:["· ",m?"online":"offline"]})]}),(d==null?void 0:d.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:["Host node: ",s.jsx("span",{className:"font-mono text-text-secondary",children:d.workspace})]})]}),!m&&s.jsxs("div",{className:"mt-4",children:[s.jsxs(Ft,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:"Host offline."})," ","The pinned host daemon is not connected. Live status/queue/graph will not load until it reconnects. You can temporarily route commands through another connected daemon below — this is a routing fallback, not a host reassignment."]}),e.length>0?s.jsx(yt,{label:"Reconnect to command",hint:"Route commands through this connected daemon until the host is back. Does not change the mesh host.",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:h,onChange:b=>y(b.target.value),children:[s.jsx("option",{value:"",children:"Wait for host to reconnect"}),e.map(b=>s.jsx("option",{value:b.id,children:$n(b)},b.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:"No connected daemons available to route commands through. Bring the host (or another daemon) online."})]}),s.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-[180px_auto] items-end",children:[f,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:x,disabled:o||!t,title:t?void 0:"No command target available — bring the host or a daemon online.",children:o?"Launching...":"Launch Host Coordinator"})]}),v]});const k=e.find(b=>b.id===t);return s.jsxs(mt,{title:"Mesh Host daemon",description:"This mesh has no host yet. Launching the coordinator on a connected daemon fixes that daemon as the mesh host (a 1:1 pin); it owns live truth thereafter.",children:[s.jsxs(Ft,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:"Set the mesh host."})," ","The host is the daemon that owns this mesh's coordinator and live truth. Launch the host coordinator below to set it — the host is fixed once established."]}),e.length>0?s.jsxs(s.Fragment,{children:[t?s.jsx("div",{className:"mb-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:c?s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:$n(k)}),d!=null&&d.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:d.workspace})]}):null,". Launching sets this daemon as the mesh host."]}):s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:$n(k)}),". Attach one of its workspaces as a node first, then launch to set the host."]})}):s.jsx(yt,{label:"Host daemon",hint:"Pick the daemon that will host this mesh. Launching the coordinator on it fixes it as the host.",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:b=>r(b.target.value),children:[s.jsx("option",{value:"",children:"Resolving host… (or pick a daemon to host)"}),e.map(b=>s.jsx("option",{value:b.id,children:$n(b)},b.id))]})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-[180px_auto] items-end mt-3",children:[f,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:x,disabled:!t||!c||o,title:t?c?void 0:"Attach a workspace from this daemon as a node first.":"Pick a host daemon (or wait for the host pin to resolve) first.",children:o?"Launching...":"Launch Host Coordinator (sets host)"})]})]}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:"No connected daemons. Bring a daemon online to host this mesh."}),v]})}function t2({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=Pp(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(mt,{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(nm,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}const Lo=[{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."}],s2=[{value:"smart",label:"Smart",description:"Match each task to the node whose capability slot best fits it (task difficulty + capability tags), then load-spread among ties. Auto-enabled when any node has capability slots."},{value:"spread",label:"Spread",description:"Distribute work evenly across eligible nodes (prefers the least-loaded, rotating ties fairly). Set a per-node priority below to bias the order."},{value:"in_order",label:"In order",description:"Assign to nodes in the order they were added — the first eligible node takes the work. No load-spreading."}];function r2(e){return e==="smart"?"fitness":e==="spread"?"least_loaded":"first_eligible"}function n2(e,t){const r=e||"first_eligible";return r==="fitness"?"smart":r==="first_eligible"?"in_order":r==="priority_only"?t!=null&&t.priorityConfigured?"spread":"in_order":r==="least_loaded"||r==="round_robin"?"spread":"in_order"}const a2={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function di(e){return{...a2,...(e==null?void 0:e.policy)||{}}}function o2(e){return{routeId:`mesh-settings:${e.meshId}`,daemonId:e.daemonId,agentName:e.meshName,agentType:"mesh",status:"idle",title:e.meshName,messages:[],workspaceName:e.meshName,displayPrimary:e.meshName,displaySecondary:"Mesh observability",streamSource:"native",tabKey:`mesh-settings:${e.meshId}`,coordinator:{meshId:e.meshId,role:"coordinator"},settings:{meshCoordinatorFor:e.meshId}}}function i2({selectedMesh:e,error:t,onDismissError:r,onBack:n,onDelete:a,displayedMeshStatus:o,graphLoading:i,graphError:c,onRefreshGraph:d,savingPolicy:p,onUpdatePolicy:u,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:h,savingCoordinatorPrompt:y,onSaveCoordinatorPrompt:x,daemons:f,coordinatorDaemonId:v,onCoordinatorDaemonIdChange:k,coordinatorCliType:b,onCoordinatorCliTypeChange:j,launchingCoordinator:C,launchResult:w,isHostNodeAttached:g,selectedHostNode:S,hostPinned:N,hostLabel:I,hostOnline:R,hostRebindDaemonId:L,onHostRebindDaemonIdChange:_,onLaunchCoordinator:P,activeDaemon:B,activeDaemonId:Y,meshQueue:M,userName:H,availableCliProviders:q,savingNodeSlotsId:A,onUpdateNodeSlots:$,savingNodeCapabilitiesId:T,onUpdateNodeCapabilities:F,nodeSystemPromptDrafts:z,onNodeSystemPromptDraftChange:U,savingNodeSystemPromptId:te,onSaveNodeSystemPrompt:Z,selectedNodeId:se,onSelectNode:G,showAddNode:O,onShowAddNode:V,onCancelAddNode:pe,nodeWorkspace:fe,onNodeWorkspaceChange:de,nodeProviderPriority:ke,onNodeProviderPriorityChange:ye,nodeDaemonId:we,onNodeDaemonIdChange:he,nodeCustomPath:K,onNodeCustomPathChange:E,nodePickerWorkspaces:J,nodePickerProviders:re,attachableDaemons:be,onAddNode:ue,onRemoveNode:D,availableCliAgents:me,features:Se,sendCommand:oe}){var qe;const Q=di(e),ve=e.nodes||[],Ne=ve.some(je=>{var Ie;const at=Number((Ie=je.policy)==null?void 0:Ie.schedulingPriority);return Number.isFinite(at)&&at!==0}),Le=!Q.schedulingStrategy,We=l.useMemo(()=>ve.some(je=>{var at;return Array.isArray((at=je.policy)==null?void 0:at.slots)&&je.policy.slots.length>0}),[ve]),le=Le?We?"smart":ve.length>=2?"spread":null:null,[Ee,Be]=l.useState(!1),Je=!!Y&&!!e.id;return s.jsxs(mn,{icon:s.jsx(Yt,{}),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:()=>d(!0),disabled:i,children:[s.jsx(fC,{size:13}),i?"Probing…":"Refresh"]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>a(e.id),children:"Delete"})]}),children:[t&&s.jsx(Ft,{variant:"error",onDismiss:r,className:"mb-4",children:t}),Se.meshHostDaemonSection&&s.jsx(e2,{daemons:f,coordinatorDaemonId:v,onCoordinatorDaemonIdChange:k,coordinatorCliType:b,onCoordinatorCliTypeChange:j,launchingCoordinator:C,launchResult:w,isHostNodeAttached:g,selectedHostNode:S,hostPinned:N,hostLabel:I,hostOnline:R,hostRebindDaemonId:L,onHostRebindDaemonIdChange:je=>{_(je),d()},onLaunchCoordinator:P}),s.jsxs(mt,{title:"Observability",description:"Open the live mesh graph, overview, and runtime status in the observability dialog.",children:[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}),s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("button",{type:"button",className:"btn btn-primary btn-sm inline-flex items-center gap-1.5",onClick:()=>Be(!0),disabled:!Je,title:Je?"Open the mesh graph / overview / status dialog":"A coordinator daemon must be selected first",children:[s.jsx(Yt,{size:14}),"Open mesh graph & status"]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:"Topology graph, overview cards (missions, ledger, queue, nodes, sessions), and per-node runtime drift."})]})]}),s.jsx(ZC,{nodes:ve,meshQueue:M,activeDaemon:B,daemons:f,selectedMeshId:e.id,userName:H,features:{addNodeDaemonPicker:Se.addNodeDaemonPicker,nodeInstruction:Se.nodeInstruction},coordinatorDaemonId:v,availableCliProviders:q,savingNodeSlotsId:A,onUpdateNodeSlots:$,savingNodeCapabilitiesId:T,onUpdateNodeCapabilities:F,nodeSystemPromptDrafts:z,onNodeSystemPromptDraftChange:U,savingNodeSystemPromptId:te,onSaveNodeSystemPrompt:Z,selectedNodeId:se,onSelectNode:G,showAddNode:O,onShowAddNode:V,onCancelAddNode:pe,nodeWorkspace:fe,onNodeWorkspaceChange:de,nodeProviderPriority:ke,onNodeProviderPriorityChange:ye,nodeDaemonId:we,onNodeDaemonIdChange:he,nodeCustomPath:K,onNodeCustomPathChange:E,nodePickerWorkspaces:J,nodePickerProviders:re,attachableDaemons:be,onAddNode:ue,onRemoveNode:D}),s.jsxs(mt,{title:"Scheduling",description:"How untargeted queue work is distributed across eligible nodes.",children:[s.jsxs("fieldset",{className:"border-none p-0 m-0",children:[s.jsx("legend",{className:"text-[13px] font-medium text-text-secondary mb-2",children:"Distribution"}),s.jsx("div",{className:"flex flex-col gap-2",children:s2.map(je=>{const Ie=n2(Q.schedulingStrategy,{priorityConfigured:Ne})===je.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${Ie?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:[s.jsx("input",{type:"radio",name:"mesh-distribution",className:"mt-0.5 accent-[var(--accent-primary)]",value:je.value,checked:Ie,disabled:p,onChange:()=>u({schedulingStrategy:r2(je.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[je.label,le===je.value&&s.jsx("span",{className:"rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-accent-primary",children:"Recommended"})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:je.description})]})]},je.value)})})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving…"})]}),s.jsx(mt,{title:"Dashboard visibility",description:"Whether the worker sessions this coordinator spawns show up in your dashboard inbox and raise notifications.",children:s.jsx(yt,{label:"Coordinator-spawned worker sessions",hint:"Hidden = keep the inbox quiet and mute their notifications; you interact through the coordinator session. Visible = show every spawned worker as its own conversation.",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:Q.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:je=>u({spawnedSessionVisibility:je.target.value==="visible"?"visible":"hidden"}),disabled:p,children:[s.jsx("option",{value:"hidden",children:"Hidden (no notifications, keep inbox quiet)"}),s.jsx("option",{value:"visible",children:"Visible (show every worker in the dashboard)"})]})})}),o&&s.jsx(mt,{title:"MAGI review panels",description:"MAGI (Multi-Agent Ground-truth Insight) runs a panel of AI agents that cross-check each other's work to surface the ground truth. Choose which agents handle each review type.",children:s.jsx(IC,{status:o,daemonId:Y,sendDaemonCommand:oe,availableProviders:q})}),s.jsx(DC,{status:o,daemonId:Y,meshId:e.id,sendCommand:oe}),Se.coordinatorPrompt&&s.jsxs(mt,{title:"Coordinator prompt",collapsible:!0,defaultOpen:!1,badge: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:"advanced"}),description:"Customize the system prompt for coordinator sessions. Per-mesh overrides apply to this mesh only; user-level overrides apply to every mesh this daemon coordinates.",children:[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-1",children:"This mesh"}),s.jsxs("p",{className:"text-[12px] text-text-muted mb-3",children:["Applies only to coordinator sessions for ",s.jsx("span",{className:"font-mono text-[11px]",children:e.name}),". Leave empty to fall through to the user-level / daemon default."]}),s.jsxs(yt,{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:m.override,onChange:je=>h({...m,override:je.target.value}),disabled:y,placeholder:"(empty — daemon default applies)"}),s.jsx(AC,{daemonId:Y,meshId:e.id,cliType:b,sendCommand:oe})]}),s.jsx(yt,{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:m.append,onChange:je=>h({...m,append:je.target.value}),disabled:y,placeholder:"(empty — nothing appended)"})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:"Available placeholders"}),s.jsx("p",{className:"mt-1 font-mono break-words",children:"{{meshName}}, {{repo}}, {{defaultBranch}}, {{cliType}}, {{nodes}}, {{policy}}, {{tools}}, {{workflow}}, {{rules}}, {{toolExposurePreflight}}"})]}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:x,disabled:y,children:y?"Saving…":"Save coordinator prompt"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>h({override:"",append:""}),disabled:y,title:"Clear both fields. Click Save to commit.",children:"Clear"})]})]}),s.jsxs("div",{className:"mt-5 border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-1",children:"User-level (this daemon)"}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:"Per-machine prompt files on the coordinator daemon. They apply to every mesh this daemon coordinates and are not synced across daemons. Per-mesh overrides above win over these."}),s.jsx(X0,{daemonId:Y||void 0})]})]}),s.jsxs(mt,{title:"Safety & Git",collapsible:!0,defaultOpen:!1,badge: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:"advanced"}),description:"Checkpointing, approval gates, and git safety behavior for coordinator-driven tasks.",children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:"Auto-commit a checkpoint before each task",key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:je=>je?"yes":"no",parse:je=>je==="yes"},{label:"Auto-commit a checkpoint after each task",key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:je=>je?"yes":"no",parse:je=>je==="yes"},{label:"Push approval",key:"requireApprovalForPush",opts:[["required","Require approval before push"],["not_required","Do not require approval"]],val:je=>je?"required":"not_required",parse:je=>je==="required"},{label:"Destructive git approval",key:"requireApprovalForDestructiveGit",opts:[["required","Require approval"],["not_required","Do not require approval"]],val:je=>je?"required":"not_required",parse:je=>je==="required"},{label:"When the workspace has uncommitted changes",key:"dirtyWorkspaceBehavior",opts:[["warn","Warn and continue"],["block","Block task"],["checkpoint_then_continue","Checkpoint then continue"]],val:je=>je||"warn",parse:je=>je},{label:"Auto-publish submodule commits (advanced)",key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled","Require explicit approval"],["enabled","Allow Refinery non-force publish"]],val:je=>je?"enabled":"disabled",parse:je=>je==="enabled"}].map(({label:je,key:at,opts:Ie,val:ot,parse:nt})=>s.jsx(yt,{label:je,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:ot(Q[at]),onChange:Qe=>u({[at]:nt(Qe.target.value)}),disabled:p,children:Ie.map(([Qe,Lt])=>s.jsx("option",{value:Qe,children:Lt},Qe))})},at))}),(()=>{const je=Q.autoFastForward&&typeof Q.autoFastForward=="object"?Q.autoFastForward:{},at=je.enabled!==!1,Ie=je.remoteNodes===!0,ot=je.mode==="continuous"?"continuous":"idle",nt=Qe=>u({autoFastForward:{...je,...Qe}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(yt,{label:"Auto fast-forward idle nodes",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:at?"enabled":"disabled",onChange:Qe=>nt({enabled:Qe.target.value==="enabled"}),disabled:p,children:[s.jsx("option",{value:"enabled",children:"Enabled (catch up online, clean, behind nodes)"}),s.jsx("option",{value:"disabled",children:"Disabled"})]})}),s.jsx(yt,{label:"Include remote nodes",hint:"Off = only the coordinator's local workspace is auto fast-forwarded.",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:Ie?"yes":"no",onChange:Qe=>nt({remoteNodes:Qe.target.value==="yes"}),disabled:p||!at,children:[s.jsx("option",{value:"no",children:"No (local workspace only)"}),s.jsx("option",{value:"yes",children:"Yes (delegate to remote owning daemons)"})]})}),s.jsx(yt,{label:"Detection mode",hint:"Idle = on a node's idle edge. Continuous = also scan periodically (base nodes only).",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:ot,onChange:Qe=>nt({mode:Qe.target.value==="continuous"?"continuous":"idle"}),disabled:p||!at||!Ie,children:[s.jsx("option",{value:"idle",children:"Idle edge only"}),s.jsx("option",{value:"continuous",children:"Continuous (periodic scan)"})]})})]})})(),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(yt,{label:"When removing a node, its sessions…",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:Q.sessionCleanupOnNodeRemove||"preserve",onChange:je=>u({sessionCleanupOnNodeRemove:je.target.value}),disabled:p,children:Lo.map(je=>s.jsx("option",{value:je.value,children:je.label},je.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((qe=Lo.find(je=>je.value===Q.sessionCleanupOnNodeRemove))==null?void 0:qe.description)||Lo[0].description})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving…"})]}),Se.hermesMcpConfig&&s.jsx(t2,{meshId:e.id,availableCliAgents:me}),Se.meshHostDaemonSection&&s.jsxs(Ft,{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."]}),Ee&&Je&&s.jsx($m,{activeConv:o2({meshId:e.id,daemonId:Y,meshName:e.name}),sendDaemonCommand:oe,onClose:()=>Be(!1)})]})}const Fr=new Map;function l2({daemons:e,primaryDaemonId:t,sendCommand:r,unwrapResult:n,normalizeMesh:a,features:o,loadDaemonMetadata:i}){const c=e.map($=>$.id).filter(Boolean).sort().join(","),[d,p]=l.useState(()=>Fr.get(c)??[]),[u,m]=l.useState(null),[h,y]=l.useState(()=>!Fr.has(c)),[x,f]=l.useState(null),[v,k]=l.useState(!1),[b,j]=l.useState(""),[C,w]=l.useState(""),[g,S]=l.useState(""),[N,I]=l.useState(""),[R,L]=l.useState(""),_=l.useMemo(()=>e.find($=>$.id===N),[e,N]),P=(_==null?void 0:_.workspaces)||[],B=l.useMemo(()=>br((_==null?void 0:_.availableProviders)||[]),[_]);l.useEffect(()=>{!o.createDaemonPicker||!i||!N||!_||!(!_.workspaces||!_.availableProviders)||Promise.resolve(i(N,{minFreshMs:3e4})).catch(()=>{})},[o.createDaemonPicker,i,N,_]);const Y=l.useMemo(()=>e.map($=>$.id).filter(Boolean).sort().join(","),[e]),M=l.useCallback(async($=!1)=>{const T=$||Fr.has(Y);y(F=>T?F:!0);try{if(o.createDaemonPicker){const F=await Promise.allSettled(e.map(async te=>{if(!te.id)return[];const Z=await r(te.id,"list_meshes",{}),se=n(Z);if((se==null?void 0:se.success)===!1)throw new Error(se.error||"Failed to load meshes");return(Array.isArray(se==null?void 0:se.meshes)?se.meshes:[]).map(G=>a(G,te.id)).filter(G=>G.id)})),z=new Map;for(const te of F)if(te.status==="fulfilled")for(const Z of te.value)z.has(Z.id)||z.set(Z.id,Z);const U=Array.from(z.values());p(U),Fr.set(Y,U),f(null)}else{if(!t)return;const F=await r(t,"list_meshes");if(F!=null&&F.success){const z=(F.meshes||[]).map(U=>a(U,t));p(z),Fr.set(Y,z),f(null)}else f((F==null?void 0:F.error)||"Failed to load meshes")}}catch(F){f((F==null?void 0:F.message)||"Failed to load meshes")}finally{y(!1)}},[Y,t,r,n,a,o.createDaemonPicker]);async function H(){var z,U;const $=o.createDaemonPicker?N:t;if(!$||!b.trim())return;const T=g.trim(),F=C.trim();if(!(!T&&!F))try{const te={name:b.trim()};T&&(te.repoRemoteUrl=T),F&&(te.repoIdentity=F);const Z=await r($,"create_mesh",te),se=n(Z);if((se==null?void 0:se.success)===!1)throw new Error(se.error||"Create failed");const G=typeof((z=se==null?void 0:se.mesh)==null?void 0:z.id)=="string"?se.mesh.id:"";if(G&&o.createDaemonPicker&&R){const O=await r($,"add_mesh_node",{meshId:G,daemonId:$,machineId:_==null?void 0:_.machineId,workspace:R,role:"host",providerPriority:nn(B)}),V=n(O);if((V==null?void 0:V.success)===!1)throw new Error(V.error||"Mesh created but failed to attach workspace")}k(!1),j(""),w(""),S(""),L(""),await M(),(U=se==null?void 0:se.mesh)!=null&&U.id&&m(se.mesh.id)}catch(te){f((te==null?void 0:te.message)||"Create failed")}}async function q($){var F;if(!confirm("Delete this mesh? This cannot be undone."))return;const T=((F=d.find(z=>z.id===$))==null?void 0:F.__sourceDaemonId)||t;try{const z=await r(T,"delete_mesh",{meshId:$}),U=n(z);if((U==null?void 0:U.success)===!1)throw new Error(U.error||"Failed to delete");u===$&&m(null),await M()}catch(z){f((z==null?void 0:z.message)||"Delete failed")}}function A(){k(!1),j(""),w(""),S("")}return{meshes:d,setMeshes:p,selectedMeshId:u,setSelectedMeshId:m,loading:h,error:x,setError:f,showCreate:v,setShowCreate:k,createName:b,setCreateName:j,createRepoIdentity:C,setCreateRepoIdentity:w,createRepoRemoteUrl:g,setCreateRepoRemoteUrl:S,newMeshDaemonId:N,setNewMeshDaemonId:I,newMeshWorkspace:R,setNewMeshWorkspace:L,createPickerWorkspaces:P,createPickerProviders:B,loadMeshes:M,handleCreate:H,handleDelete:q,cancelCreate:A}}function c2({selectedMesh:e,selectedMeshId:t,primaryDaemonId:r,activeDaemonId:n,daemons:a,sendCommand:o,unwrapResult:i,loadLiveMesh:c,resolveCommandTarget:d,launchCoordinator:p,features:u,loadMeshes:m,loadQueue:h,queueSection:y,setError:x}){const[f,v]=l.useState({}),[k,b]=l.useState(null),[j,C]=l.useState(null),[w,g]=l.useState(!1),[S,N]=l.useState(""),[I,R]=l.useState([]),[L,_]=l.useState(""),[P,B]=l.useState(!1),[Y,M]=l.useState(""),[H,q]=l.useState(!1),[A,$]=l.useState(null),[T,F]=l.useState(!1),[z,U]=l.useState({override:"",append:""}),[te,Z]=l.useState(!1),[se,G]=l.useState({}),[O,V]=l.useState(null),pe=l.useMemo(()=>a.find(oe=>oe.id===L),[a,L]),fe=(pe==null?void 0:pe.workspaces)||[],de=l.useMemo(()=>br((pe==null?void 0:pe.availableProviders)||[]),[pe]);async function ke(){const oe=(e==null?void 0:e.__sourceDaemonId)||r;if(!t||!oe)return;const Q=S.trim();if(Q)try{const ve={meshId:t,workspace:Q};u.addNodeDaemonPicker&&L&&(ve.daemonId=L,ve.machineId=pe==null?void 0:pe.machineId),ve.providerPriority=gr(I);const Ne=await o(oe,"add_mesh_node",ve),Le=i(Ne);if((Le==null?void 0:Le.success)===!1)throw new Error(Le.error||"Add node failed");g(!1),N(""),R([]),_(""),B(!1),await m(),y||await h(t)}catch(ve){x((ve==null?void 0:ve.message)||"Add node failed")}}async function ye(oe){var Le;if(!e)return;const Q=di(e),ve=((Le=[{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(We=>We.value===Q.sessionCleanupOnNodeRemove))==null?void 0:Le.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
115
-
116
- Node removal cleanup policy: ${ve}`))return;const Ne=e.__sourceDaemonId||r;try{const We=await o(Ne,"remove_mesh_node",{meshId:e.id,nodeId:oe}),le=i(We);if((le==null?void 0:le.success)===!1)throw new Error(le.error||"Remove failed");j===oe&&C(null),await m(),y||await h(t)}catch(We){x((We==null?void 0:We.message)||"Remove node failed")}}async function we(oe){if(!e)return;const Q={...di(e),...oe},ve=e.__sourceDaemonId||r;try{F(!0),x(null);const Ne=await o(ve,"update_mesh",{meshId:e.id,policy:Q}),Le=i(Ne);if((Le==null?void 0:Le.success)===!1)throw new Error(Le.error||"Policy update failed");await m()}catch(Ne){x((Ne==null?void 0:Ne.message)||"Policy update failed")}finally{F(!1)}}async function he(oe){if(!t)return;const Q=(e==null?void 0:e.__sourceDaemonId)||r,ve=f[oe.id]||d2(oe),Ne=gr(ve),Le={...oe.policy||{}};delete Le.provider_priority,Ne.length?Le.providerPriority=Ne:delete Le.providerPriority;try{b(oe.id),x(null);const We=await o(Q,"update_mesh_node",{meshId:t,nodeId:oe.id,policy:Le,providerPriority:Ne}),le=i(We);if((le==null?void 0:le.success)===!1){x(le.error||"Node policy update failed");return}await m()}catch(We){x((We==null?void 0:We.message)||"Node policy update failed")}finally{b(null)}}const[K,E]=l.useState(null);async function J(oe,Q){if(!t)return;const ve=(e==null?void 0:e.__sourceDaemonId)||r;try{E(oe.id),x(null);const Ne=await o(ve,"update_mesh_node",{meshId:t,nodeId:oe.id,policy:{slots:Q}}),Le=i(Ne);if((Le==null?void 0:Le.success)===!1){x(Le.error||"Node slots update failed");return}await m()}catch(Ne){x((Ne==null?void 0:Ne.message)||"Node slots update failed")}finally{E(null)}}const[re,be]=l.useState(null);async function ue(oe,Q){if(!t)return;const ve=(e==null?void 0:e.__sourceDaemonId)||r,Ne=Q.map(Le=>Le.trim()).filter(Boolean);try{be(oe.id),x(null);const Le=await o(ve,"update_mesh_node",{meshId:t,nodeId:oe.id,capabilities:Ne}),We=i(Le);if((We==null?void 0:We.success)===!1){x(We.error||"Node tag update failed");return}await m()}catch(Le){x((Le==null?void 0:Le.message)||"Node tag update failed")}finally{be(null)}}async function D(){if(!r||!t)return;const Q={...(e==null?void 0:e.coordinator)||{}};z.override.trim()?Q.systemPromptOverride=z.override:delete Q.systemPromptOverride,z.append.trim()?Q.systemPromptAppend=z.append:delete Q.systemPromptAppend,delete Q.systemPromptSuffix;try{Z(!0),x(null);const ve=await o(r,"update_mesh",{meshId:t,coordinator:Q}),Ne=i(ve);if((Ne==null?void 0:Ne.success)===!1){x(Ne.error||"Coordinator prompt save failed");return}await m()}catch(ve){x((ve==null?void 0:ve.message)||"Coordinator prompt save failed")}finally{Z(!1)}}async function me(oe){if(!r||!t)return;const Q=(se[oe.id]||"").trim();try{V(oe.id),x(null);const ve=await o(r,"update_mesh_node",{meshId:t,nodeId:oe.id,systemPrompt:Q}),Ne=i(ve);if((Ne==null?void 0:Ne.success)===!1){x(Ne.error||"Node instruction save failed");return}await m()}catch(ve){x((ve==null?void 0:ve.message)||"Node instruction save failed")}finally{V(null)}}async function Se(){if(e){x(null),$(null);try{q(!0);const oe=c?await c(n,e.id,e):null,Q=d(n,e.id,e,e.nodes||[],oe);if("error"in Q)throw new Error(Q.error);const ve=await p(Q.targetDaemonId,{meshId:e.id,inlineMesh:Q.inlineMesh,coordinatorNodeId:Q.coordinatorNodeId,cliType:Y.trim()||void 0});$(ve.message)}catch(oe){x((oe==null?void 0:oe.message)||"Coordinator launch failed")}finally{q(!1)}}}return{nodeProviderPriorityDrafts:f,setNodeProviderPriorityDrafts:v,savingNodePolicyId:k,selectedNodeId:j,setSelectedNodeId:C,showAddNode:w,setShowAddNode:g,nodeWorkspace:S,setNodeWorkspace:N,nodeProviderPriority:I,setNodeProviderPriority:R,nodeDaemonId:L,setNodeDaemonId:_,nodeCustomPath:P,setNodeCustomPath:B,nodePickerWorkspaces:fe,nodePickerProviders:de,coordinatorCliType:Y,setCoordinatorCliType:M,launchingCoordinator:H,launchResult:A,savingPolicy:T,coordinatorPromptDraft:z,setCoordinatorPromptDraft:U,savingCoordinatorPrompt:te,nodeSystemPromptDrafts:se,setNodeSystemPromptDrafts:G,savingNodeSystemPromptId:O,savingNodeSlotsId:K,savingNodeCapabilitiesId:re,handleAddNode:ke,handleRemoveNode:ye,handleUpdatePolicy:we,handleUpdateNodeProviderPriority:he,handleUpdateNodeSlots:J,handleUpdateNodeCapabilities:ue,handleSaveCoordinatorPrompt:D,handleSaveNodeSystemPrompt:me,handleLaunchCoordinator:Se}}function d2(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 u2(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 p2({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,y]=l.useState(null),x=l.useCallback(async v=>{if(!e||!v){c([]);return}try{const k=await r(e,"get_mesh_queue",{meshId:v});c(k!=null&&k.success?Array.isArray(k.queue)?k.queue:[]:[])}catch{c([])}},[e,r]);async function f(v){var k,b;if(v){m(!0),y(null);try{const j=a?await a(t,v.id,v):null,C=o(t,v.id,v,v.nodes||[],j);if("error"in C)throw new Error(C.error);const w=await r(C.targetDaemonId,"get_mesh_queue",{meshId:v.id}),g=n(w);if((g==null?void 0:g.success)===!1)throw new Error(g.error||"Queue load failed");const S=Array.isArray(((k=g==null?void 0:g.result)==null?void 0:k.rows)??(g==null?void 0:g.rows)??(g==null?void 0:g.queue))?((b=g==null?void 0:g.result)==null?void 0:b.rows)??(g==null?void 0:g.rows)??(g==null?void 0:g.queue):[];p(u2(S))}catch(j){y((j==null?void 0:j.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:d,queueLoading:u,queueError:h,loadQueue:x,handleLoadQueue:f}}function m2(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const Wm=new Map;function Km(e){return e?Wm.get(e)??null:null}function h2(e,t){!e||!t||Wm.set(e,t)}function f2({selectedMeshId:e,loadMeshStatus:t,extractStatus:r,normalizeNode:n,gateIncompleteGraph:a}){const[o,i]=l.useState(()=>Km(e)),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,h]=l.useState("idle"),[y,x]=l.useState(!1),f=l.useRef(!1);async function v(k,b=e,j=!1){if(!(!k||!b))try{d(!j&&o===null),h(j?"settling":"first_paint"),u(null);const C=await t(k,b,{refresh:j,retryProfile:j?"settled":"interactive"});x(m2(C));const w=r(C),g=n&&w?{...w,nodes:(w.nodes??[]).map(S=>n(S,w.meshId??b,""))}:w;if(g){if(a&&!j&&o!==null&&!Lk(ym(g))){h("settling"),f.current||(f.current=!0,Promise.resolve().then(()=>v(k,b,!0)).finally(()=>{f.current=!1}));return}i(g),h2(b,g),h("settled")}else i(null),u("mesh_status returned an unexpected payload."),h("idle")}catch(C){o||i(null),u((C==null?void 0:C.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:y,loadGraph:v}}function x2(e,t,r,n,a){if(!e.length)return"";const o=String(a||"");if(o){const d=e.find(p=>Fs(p.id,o));return d?d.id:o}const i=t.find(d=>d.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const d=e.find(p=>Fs(p.id,c));if(d)return d.id}return""}const b2=7e3,g2=45e3;function y2(){const e=hC(),{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:y,gateIncompleteGraph:x}=e,f=Sr(),v=n[0],k=(v==null?void 0:v.id)||"",b=l.useMemo(()=>((v==null?void 0:v.availableProviders)||[]).filter(Me=>Me.category==="cli").map(Me=>({id:Me.type||Me.id,name:Me.displayName||Me.name||Me.type,meshCoordinator:Me.meshCoordinator})),[v]),j=l.useMemo(()=>br((v==null?void 0:v.availableProviders)||[]),[v]),{meshes:C,selectedMeshId:w,setSelectedMeshId:g,loading:S,error:N,setError:I,showCreate:R,setShowCreate:L,createName:_,setCreateName:P,createRepoIdentity:B,setCreateRepoIdentity:Y,createRepoRemoteUrl:M,setCreateRepoRemoteUrl:H,newMeshDaemonId:q,setNewMeshDaemonId:A,newMeshWorkspace:$,setNewMeshWorkspace:T,createPickerWorkspaces:F,loadMeshes:z,handleCreate:U,handleDelete:te,cancelCreate:Z}=l2({daemons:n,primaryDaemonId:k,sendCommand:t,unwrapResult:p,normalizeMesh:u,features:y,loadDaemonMetadata:f}),se=C.find(W=>W.id===w)||null,{meshGraphStatus:G,setMeshGraphStatus:O,graphLoading:V,graphError:pe,setGraphError:fe,loadGraph:de}=f2({selectedMeshId:w,loadMeshStatus:o,extractStatus:d,normalizeNode:m,gateIncompleteGraph:x}),[ke,ye]=l.useState(""),[we,he]=l.useState(""),K=y.meshHostDaemonSection&&ke||k,{meshQueue:E,loadQueue:J}=p2({primaryDaemonId:k,activeDaemonId:K,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:h}),{setNodeProviderPriorityDrafts:re,selectedNodeId:be,setSelectedNodeId:ue,showAddNode:D,setShowAddNode:me,nodeWorkspace:Se,setNodeWorkspace:oe,nodeProviderPriority:Q,setNodeProviderPriority:ve,nodeDaemonId:Ne,setNodeDaemonId:Le,nodeCustomPath:We,setNodeCustomPath:le,nodePickerWorkspaces:Ee,nodePickerProviders:Be,coordinatorCliType:Je,setCoordinatorCliType:qe,launchingCoordinator:je,launchResult:at,savingPolicy:Ie,coordinatorPromptDraft:ot,setCoordinatorPromptDraft:nt,savingCoordinatorPrompt:Qe,nodeSystemPromptDrafts:Lt,setNodeSystemPromptDrafts:X,savingNodeSystemPromptId:ee,savingNodeSlotsId:ne,savingNodeCapabilitiesId:ie,handleAddNode:xe,handleRemoveNode:Ae,handleUpdatePolicy:De,handleUpdateNodeSlots:Ce,handleUpdateNodeCapabilities:Re,handleSaveCoordinatorPrompt:He,handleSaveNodeSystemPrompt:Xe,handleLaunchCoordinator:Oe}=c2({selectedMesh:se,selectedMeshId:w,primaryDaemonId:k,activeDaemonId:K,daemons:n,availableCliProviders:j,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:h,launchCoordinator:i,features:{addNodeDaemonPicker:y.addNodeDaemonPicker},loadMeshes:z,loadQueue:J,queueSection:y.queueSection,setError:I}),Ue=l.useMemo(()=>n.find(W=>W.id===K)||v,[n,K,v]),ae=l.useMemo(()=>new Set(((se==null?void 0:se.nodes)||[]).map(W=>String(W.daemon_id||W.daemonId||""))),[se]),ce=l.useMemo(()=>n.filter(W=>W.id&&!ae.has(W.id)),[n,ae]),ge=(se==null?void 0:se.nodes)||[],$e=l.useMemo(()=>ge.find(W=>Fs(String(W.daemon_id||W.daemonId||""),ke)),[ge,ke]),Fe=y.meshHostDaemonSection?!!$e:!0,Ye=l.useMemo(()=>{if(!y.meshHostDaemonSection||!se)return{pinned:!1,daemonId:"",label:"",online:!1};const W=se.meshHost,Me=G!=null&&G.meshId&&String(G.meshId)===String(se.id??"")?G.meshHost:void 0,Pe=Me!=null&&Me.hostDaemonId?Me:W??Me,dt=String((Pe==null?void 0:Pe.hostDaemonId)||""),Et=ge.find(fs=>fs.role==="host"),Rs=String((Pe==null?void 0:Pe.hostNodeId)||(Et==null?void 0:Et.id)||""),Mt=Rs?ge.find(fs=>String(fs.id)===Rs):void 0,vs=String((Mt==null?void 0:Mt.daemon_id)||(Mt==null?void 0:Mt.daemonId)||""),ws=dt||vs;if(!ws)return{pinned:!1,daemonId:"",label:"",online:!1};const Cr=n.find(fs=>dt&&Fs(fs.id,dt))||(vs?n.find(fs=>Fs(fs.id,vs)):void 0);if(Cr)return{pinned:!0,daemonId:Cr.id,label:v2(Cr),online:!0};const Ba=String((Mt==null?void 0:Mt.machineLabel)||"")||String((Mt==null?void 0:Mt.workspace)||"")||ws;return{pinned:!0,daemonId:ws,label:Ba,online:!1}},[se,ge,n,G,y.meshHostDaemonSection]),Ze=Ye.daemonId,rt=Ye.online,Ge=l.useMemo(()=>!y.meshHostDaemonSection||!Ye.pinned?"":!rt&&we&&n.some(W=>W.id===we)?we:Ze,[y.meshHostDaemonSection,Ye.pinned,rt,we,n,Ze]),Nt=l.useMemo(()=>G?[...new Set((G.nodes??[]).map(W=>String(W.daemonId||W.daemon_id||"")).filter(Boolean))]:[],[G]),Xt=Dm({status:G,daemonId:K||null,extraDaemonIds:Nt,meshId:w,sendData:r});l.useEffect(()=>{re(Object.fromEntries(((se==null?void 0:se.nodes)||[]).map(W=>[W.id,w2(W)])))},[se]),l.useEffect(()=>{const W=(se==null?void 0:se.coordinator)||{};nt({override:typeof W.systemPromptOverride=="string"?W.systemPromptOverride:"",append:typeof W.systemPromptAppend=="string"?W.systemPromptAppend:typeof W.systemPromptSuffix=="string"?W.systemPromptSuffix:""}),X(Object.fromEntries(((se==null?void 0:se.nodes)||[]).map(Me=>[Me.id,typeof Me.systemPrompt=="string"?Me.systemPrompt:""])))},[se]),l.useEffect(()=>{const W=y.addNodeDaemonPicker?nn(Be):nn(j);D&&Q.length===0&&W.length>0&&ve(W)},[D,j,Be,Q.length,y.addNodeDaemonPicker]),l.useEffect(()=>{const W=new Set(((se==null?void 0:se.nodes)||[]).map(Me=>Me.id));be&&!W.has(be)&&ue(null)},[se,be]);const Ht=l.useMemo(()=>{var W;if(!(!(G!=null&&G.meshId)||String(G.meshId)!==String((se==null?void 0:se.id)??"")))return(W=G.meshHost)==null?void 0:W.hostDaemonId},[G,se]),Te=l.useMemo(()=>x2(n,ge,K,k,Ht),[n,ge,K,k,Ht]);l.useEffect(()=>{if(!y.meshHostDaemonSection)return;if(!n.length&&!Ye.pinned){ye("");return}const W=Ye.pinned?Ge:Te;W&&!Fs(W,ke)&&ye(W)},[n,ke,Ye.pinned,Ge,Te,y.meshHostDaemonSection]),l.useEffect(()=>{we&&(rt||!n.some(W=>W.id===we))&&he("")},[rt,we,n]),l.useEffect(()=>{if(y.createDaemonPicker){if(!n.length){A("");return}(!q||!n.some(W=>W.id===q))&&A(n[0].id)}},[n,q,y.createDaemonPicker]),l.useEffect(()=>{var W;if(!y.createDaemonPicker||!q){T("");return}if(!F.length){T("");return}F.some(Me=>Me.path===$)||T(((W=F[0])==null?void 0:W.path)||"")},[q,$,F,y.createDaemonPicker]);const Ve=l.useRef(null);l.useEffect(()=>{if(!w)return;const W=Ve.current!==w;if(Ve.current=w,W){const Me=Km(w);O(Me),fe(null),de(K,w,Me!==null)}else fe(null),de(K,w,!0)},[w,K]);const Rt=l.useRef(de);Rt.current=de;const jt=l.useRef(!1),Kt=l.useRef(()=>{});Kt.current=()=>{jt.current||!w||!K||(jt.current=!0,Promise.resolve(Rt.current(K,w,!0)).finally(()=>{jt.current=!1}))};const Ut=y.meshStatePushRefresh?g2:b2;pC({daemonIds:l.useMemo(()=>[K,...Nt].filter(Boolean),[K,Nt]),meshId:w,sendData:r,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||Kt.current()}}),l.useEffect(()=>{if(!w||!K||typeof document>"u")return;let W=null;const Me=()=>{document.visibilityState==="visible"&&Kt.current()},Pe=()=>{W===null&&(W=setInterval(Me,Ut))},dt=()=>{W!==null&&(clearInterval(W),W=null)},Et=()=>{document.visibilityState==="visible"?Pe():dt()};return document.visibilityState==="visible"&&Pe(),document.addEventListener("visibilitychange",Et),()=>{dt(),document.removeEventListener("visibilitychange",Et)}},[w,K,Ut]),l.useEffect(()=>{y.queueSection||J(w)},[w,y.queueSection]);const zt=l.useMemo(()=>n.map(W=>W.id).filter(Boolean).sort().join(","),[n]),is=l.useRef(!1);return l.useEffect(()=>{z(is.current),is.current=!0},[zt]),k?se?s.jsx(i2,{selectedMesh:se,error:N,onDismissError:()=>I(null),onBack:()=>{g(null),O(null)},onDelete:te,displayedMeshStatus:Xt,graphLoading:V,graphError:pe,onRefreshGraph:()=>de(K,w,!0),savingPolicy:Ie,onUpdatePolicy:De,coordinatorPromptDraft:ot,onCoordinatorPromptDraftChange:nt,savingCoordinatorPrompt:Qe,onSaveCoordinatorPrompt:He,daemons:n,coordinatorDaemonId:ke,onCoordinatorDaemonIdChange:ye,coordinatorCliType:Je,onCoordinatorCliTypeChange:qe,launchingCoordinator:je,launchResult:at,isHostNodeAttached:Fe,selectedHostNode:$e,hostPinned:Ye.pinned,hostLabel:Ye.label,hostOnline:rt,hostRebindDaemonId:we,onHostRebindDaemonIdChange:W=>he(W),onLaunchCoordinator:Oe,activeDaemon:Ue,activeDaemonId:K,meshQueue:E,userName:a,availableCliProviders:j,savingNodeSlotsId:ne,onUpdateNodeSlots:Ce,savingNodeCapabilitiesId:ie,onUpdateNodeCapabilities:Re,nodeSystemPromptDrafts:Lt,onNodeSystemPromptDraftChange:(W,Me)=>X(Pe=>({...Pe,[W]:Me})),savingNodeSystemPromptId:ee,onSaveNodeSystemPrompt:Xe,selectedNodeId:be,onSelectNode:ue,showAddNode:D,onShowAddNode:()=>me(!0),onCancelAddNode:()=>me(!1),nodeWorkspace:Se,onNodeWorkspaceChange:oe,nodeProviderPriority:Q,onNodeProviderPriorityChange:ve,nodeDaemonId:Ne,onNodeDaemonIdChange:Le,nodeCustomPath:We,onNodeCustomPathChange:le,nodePickerWorkspaces:Ee,nodePickerProviders:Be,attachableDaemons:ce,onAddNode:xe,onRemoveNode:Ae,availableCliAgents:b,features:{coordinatorPrompt:y.coordinatorPrompt,meshHostDaemonSection:y.meshHostDaemonSection,hermesMcpConfig:y.hermesMcpConfig,addNodeDaemonPicker:y.addNodeDaemonPicker,nodeInstruction:y.nodeInstruction},sendCommand:t}):s.jsx(wC,{meshes:C,loading:S,error:N,onDismissError:()=>I(null),daemons:n,features:{createDaemonPicker:y.createDaemonPicker},showCreate:R,onToggleCreate:()=>L(!R),createName:_,onCreateNameChange:P,createRepoIdentity:B,onCreateRepoIdentityChange:Y,createRepoRemoteUrl:M,onCreateRepoRemoteUrlChange:H,newMeshDaemonId:q,onNewMeshDaemonIdChange:A,newMeshWorkspace:$,onNewMeshWorkspaceChange:T,createPickerWorkspaces:F,onSelectMesh:g,onCreate:U,onCancelCreate:Z}):s.jsx(mn,{icon:s.jsx(Yt,{}),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 v2(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function w2(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 j2({children:e}){const{sendCommand:t,sendData:r}=xt(),{ides:n}=hs(),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:Li,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:mC}),[t,r,a]);return s.jsx(Hm.Provider,{value:o,children:e})}function cl(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function k2(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=cl();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 ds(e,t){return await fetch(k2(e),{credentials:"same-origin",...t})}function Um(){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 N2{constructor(){et(this,"adapters",new Map);et(this,"states",new Map);et(this,"runtimeListeners",new Map);et(this,"screenshotCallbacks",new Map);et(this,"statusCallbacks",new Set);et(this,"stateChangeCallbacks",new Set);et(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 ds(`${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 cs=new N2;function S2(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=cl();return r?`${t}?token=${encodeURIComponent(r)}`:t}const En=S2(),vd=3e3,C2=3e4;let es=null,I2=0;const ba=new Map;let $s=null,Qr=null;function wd(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Or(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function A2(e){return e==="connected"?"connected":e}async function Zr(e,t,r){const n=pp(e,r||{}),a=es;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++I2}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{ba.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);ba.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 ui(e,t){const r=es;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 zm(e,t,r){const n=es;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=pp(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}}cs.registerPtyInputSender(zm);class M2{constructor(t){et(this,"daemonId");et(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(es==null?void 0:es.readyState)===WebSocket.OPEN}get connectionState(){return(es==null?void 0:es.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Zr(this.daemonId,t,r)}async sendInput(t,r){return Zr(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,$s&&(clearInterval($s),$s=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Zr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(o=>o.blob());cs.emitScreenshot(this.daemonId,a)}}catch{}};r(),$s=setInterval(r,2e3)}stopScreenshots(t){$s&&(clearInterval($s),$s=null)}}let Vt=null;function _2(e){return(!Vt||Vt.daemonId!==e)&&(Vt=new M2(e)),Vt}function T2({children:e}){const t=l.useRef(en()),r=en();t.current=r;const{setUserName:n}=hs(),a=l.useRef(n);a.current=n;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((f,v)=>{c(f),Qr==null||Qr(f,v)},[]),p=l.useRef(null),u=l.useRef(),m=l.useRef(vd),h=l.useRef(!0),y=l.useRef(!1),x=l.useRef("initial_connect");return l.useEffect(()=>{h.current=!0,y.current=!1;function f(){var b,j;if(!h.current||((b=p.current)==null?void 0:b.readyState)===WebSocket.OPEN||((j=p.current)==null?void 0:j.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${En}...`),Or("connect_attempt",{url:En,reason:x.current,delayMs:m.current});let k;try{k=new WebSocket(En)}catch(C){console.error("[Standalone WS] Failed to create WebSocket:",C),v();return}p.current=k,k.onopen=()=>{if(!h.current){k.close();return}d("connected"),m.current=vd,Or("open",{url:En,reason:x.current}),rs.resubscribeAll({sendData:ui}),console.log("[Standalone WS] Connected")},es=k,k.onmessage=C=>{var w,g;try{const S=JSON.parse(C.data);if((S.type==="command_result"||S.type==="error")&&S.requestId){const N=ba.get(S.requestId);N&&(ba.delete(S.requestId),S.type==="error"?N.reject(new Error(((w=S.data)==null?void 0:w.message)||"Command failed")):N.resolve(S.data));return}if(S.type==="session_output"){const N=S.sessionId||S.cliId||S.cliType;N&&cs.emitSessionOutput(N,typeof S.data=="string"?S.data:"",typeof S.seq=="number"?S.seq:void 0);return}if(S.type==="runtime_snapshot"){cs.emitRuntimeSnapshot(S.sessionId,typeof S.text=="string"?S.text:"",typeof S.seq=="number"?S.seq:0,!!S.truncated,typeof S.cols=="number"?S.cols:void 0,typeof S.rows=="number"?S.rows:void 0);return}if(S.type==="topic_update"){const N=S.update;N&&rs.publish(N);return}if(S.type==="status"||S.type==="initial_state"){const N=S.data;if(!N)return;const{injectEntries:I,markLoaded:R,getIdes:L}=t.current,_=N.instanceId||"standalone",P=L().find(M=>M.id===_),B=_2(_);cs.register(_,B),cs.setState(_,"connected"),d("connected",_),cs.emitStatus(_,N);const Y=sa(N,{daemonId:_,existingDaemon:P,existingEntries:L()});wd("ws_status",{type:S.type,daemonId:_,sessions:(N.sessions||[]).map(M=>({id:M.id,parentId:M.parentId,providerType:M.providerType,kind:M.kind,transport:M.transport,unread:M.unread,inboxBucket:M.inboxBucket,lastSeenAt:M.lastSeenAt,lastUpdated:M.lastUpdated,title:M.title})),recentLaunches:(N.recentLaunches||[]).map(M=>({id:M.id,providerType:M.providerType,kind:M.kind,workspace:M.workspace,lastLaunchedAt:M.lastLaunchedAt}))}),wd("entries",{daemonId:_,entries:Y.filter(M=>M.type!=="adhdev-daemon").map(M=>({id:M.id,type:M.type,unread:M.unread,inboxBucket:M.inboxBucket,lastSeenAt:M.lastSeenAt,lastUpdated:M.lastUpdated,sessionId:M.sessionId}))}),Y.length>0&&I(Y,{authoritativeDaemonIds:[_]}),R(),i.current!==_&&((g=o.current)==null||g.call(o),i.current=_,o.current=rs.subscribe({sendData:ui},_,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${_}`,params:{includeSessions:!0}},M=>{if(M.topic!=="daemon.metadata")return;const H=t.current.getIdes(),q=H.find($=>$.id===_),A=sa(M.status,{daemonId:_,existingDaemon:q,existingEntries:H,timestamp:M.timestamp});A.length>0&&t.current.injectEntries(A,{authoritativeDaemonIds:[_]}),M.userName&&a.current&&a.current(M.userName)}))}}catch(S){console.error("[Standalone WS] Parse error:",S)}},k.onclose=C=>{h.current&&(Vt==null||Vt.stopScreenshots(),Vt&&cs.setState(Vt.daemonId,"disconnected"),d("disconnected"),p.current=null,x.current=`close:${C.code}${C.wasClean?":clean":":unclean"}`,Or("close",{code:C.code,reason:C.reason||"",wasClean:C.wasClean}),v())},k.onerror=C=>{y.current||!h.current||(x.current="error",Or("error",{message:C instanceof Event?"event":String(C),readyState:k.readyState}),console.warn("[Standalone WS] Error, will reconnect:",C))}}function v(){if(!h.current)return;clearTimeout(u.current);const k=m.current;console.log(`[Standalone WS] Reconnecting in ${k}ms...`),Or("schedule_reconnect",{reason:x.current,delayMs:k}),u.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,C2),f()},k)}return f(),()=>{var k;h.current=!1,y.current=!0,(k=o.current)==null||k.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,es=null),Vt&&(Vt.stopScreenshots(),cs.unregister(Vt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function L2({children:e}){const[t,r]=l.useState("disconnected"),[n,a]=l.useState(null);l.useEffect(()=>(Qr=(i,c)=>{r(i),c&&a(c)},()=>{Qr=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=A2(t),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d}},[t,n]);return s.jsx(Vh,{connectionOverrides:o,children:s.jsx(T2,{children:e})})}const Gm="adhdev_standalone_font_preferences",Gs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Ea=[{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"}],ln=[{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"}],R2=new Set(Ea.map(e=>e.id)),P2=new Set(ln.map(e=>e.id));function ps(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Yn("chat",t.chat),code:Yn("code",t.code),terminal:Yn("terminal",t.terminal)}}function Yn(e,t){const r=Gs[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"?R2:P2).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Jn(e,t){var a;const r=Yn(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?Ea:ln;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function D2(e){const t=ps(e),r=Jn("chat",t.chat),n=Jn("code",t.code),a=Jn("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Bs(e,t=document.documentElement){const r=ps(e),n=D2(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function pi(e){const t=ps(e);try{localStorage.setItem(Gm,JSON.stringify(t))}catch{}return t}function $2(){try{const e=localStorage.getItem(Gm);if(e)return ps(JSON.parse(e))}catch{}return Gs}function E2(){return Bs($2())}function Hr(e,t){var n;const r=e==="chat"?Ea:ln;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const B2=[{id:"dashboard",path:"/dashboard",icon:s.jsx($d,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(Is,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(Yt,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(ya,{}),label:"Settings"}];function F2({children:e}){const t=cn(),r=hi(),n=l.useMemo(()=>B2.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(Bd,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(gi,{}),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 O2=[{icon:s.jsx(Is,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Xs,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Od,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(os,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(tn,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Bd,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],H2=[{icon:s.jsx(Sf,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx($d,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(jr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(gf,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Ed,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(wf,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],W2=[{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 K2(){return s.jsxs(mn,{icon:s.jsx(gi,{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(mt,{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(mt,{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:O2.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(mt,{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:mp.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:fp.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:hp.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(mt,{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:H2.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(mt,{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:W2.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(_a,{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(Pf,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Ro(e,t,r){return{...e,[t]:r}}function Po({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(F0,{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(ss,{type:"text",className:"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:Jn(e,n)})]})]})]})}function U2({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(Ft,{variant:"error",children:n}),a&&s.jsx(Ft,{variant:"success",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Po,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Ea,onChange:u=>o(Ro(e,"chat",u))}),s.jsx(Po,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:ln,onChange:u=>o(Ro(e,"code",u))}),s.jsx(Po,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:ln,onChange:u=>o(Ro(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: ",Hr("chat",e.chat.preset)," · Code: ",Hr("code",e.code.preset)," · Terminal: ",Hr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Hr("chat",Gs.chat.preset)," / ",Hr("code",Gs.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(gs,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:r||!p,children:r?"Saving…":"Save font settings"}),s.jsx(gs,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:r||!p,children:"Revert to saved"}),s.jsx(gs,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:r,children:"Reset to defaults"})]})]})}function z2(){const{ides:e}=hs(),t=e.find(O=>O.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=xt(),{userName:a}=hs(),[o,i]=l.useState(a||""),[c,d]=l.useState(null),[p,u]=l.useState(null),[m,h]=l.useState(Gs),[y,x]=l.useState(!1),[f,v]=l.useState(""),[k,b]=l.useState(""),[j,C]=l.useState("127.0.0.1"),[w,g]=l.useState(""),[S,N]=l.useState(""),[I,R]=l.useState(""),[L,_]=l.useState(""),[P,B]=l.useState(""),[Y,M]=l.useState(!1),H=async()=>{const V=await(await ds("/auth/session")).json();d(V)},q=async()=>{const V=await(await ds("/api/v1/standalone/preferences")).json();u(V),C(V.standaloneBindHost);const pe=ps(V.standaloneFontPreferences);h(pe),Bs(pe),pi(pe)};l.useEffect(()=>{a!==void 0&&i(a)},[a]),l.useEffect(()=>{Promise.all([H(),q()]).catch(O=>{_(O instanceof Error?O.message:String(O))})},[]),l.useEffect(()=>{Bs(m)},[m]);const A=O=>{const V=O.target.value.trim();t!=null&&t.id&&V!==a&&n(t.id,"set_user_name",{userName:V}).catch(console.error)},[$,T]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),F=O=>{T(O);try{localStorage.setItem("adhdev_sound",O?"1":"0")}catch{}},z=async()=>{v(""),b(""),x(!0);try{const O=ps(m),V=await ds("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:O})}),pe=await V.json();if(!V.ok)throw new Error((pe==null?void 0:pe.error)||"Failed to save standalone font preferences");const fe=ps(pe.standaloneFontPreferences);u(pe),h(fe),Bs(fe),pi(fe),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(O){v(O instanceof Error?O.message:String(O))}finally{x(!1)}},U=()=>{const O=ps(p==null?void 0:p.standaloneFontPreferences);v(""),b(""),h(O),Bs(O)},te=()=>{v(""),b(""),h(Gs),Bs(Gs)},Z=async()=>{_(""),B(""),M(!0);try{const O=await ds("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:j})}),V=await O.json();if(!O.ok)throw new Error((V==null?void 0:V.error)||"Failed to save standalone network preference");u(V),C(V.standaloneBindHost),B(V.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(O){_(O instanceof Error?O.message:String(O))}finally{M(!1)}},se=async()=>{if(_(""),B(""),S.trim().length<4){_("Password must be at least 4 characters.");return}if(S!==I){_("New password and confirmation do not match.");return}M(!0);try{const O=await ds("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,newPassword:S})}),V=await O.json();if(!O.ok)throw new Error((V==null?void 0:V.error)||"Failed to save password");d(V),await q(),g(""),N(""),R(""),B(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Um()}catch(O){_(O instanceof Error?O.message:String(O))}finally{M(!1)}},G=async()=>{_(""),B(""),M(!0);try{const O=await ds("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,clear:!0})}),V=await O.json();if(!O.ok)throw new Error((V==null?void 0:V.error)||"Failed to clear password");d(V),await q(),g(""),N(""),R(""),B("Standalone password disabled.")}catch(O){_(O instanceof Error?O.message:String(O))}finally{M(!1)}};return s.jsxs(mn,{icon:s.jsx(ya,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Ft,{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(Ft,{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(mt,{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(mt,{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:j==="127.0.0.1",onChange:()=>C("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:j==="0.0.0.0",onChange:()=>C("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(gs,{type:"button",variant:"primary",size:"sm",onClick:()=>{Z()},disabled:Y,children:Y?"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(mt,{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."}),L&&s.jsx(Ft,{variant:"error",children:L}),P&&s.jsx(Ft,{variant:"success",children:P}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(ss,{type:"password",placeholder:c!=null&&c.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:w,onChange:O=>g(O.target.value)}),s.jsx(ss,{type:"password",placeholder:c!=null&&c.hasPasswordAuth?"New password":"New standalone password",value:S,onChange:O=>N(O.target.value)}),s.jsx(ss,{type:"password",className:"md:col-span-2",placeholder:"Confirm new password",value:I,onChange:O=>R(O.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(gs,{type:"button",variant:"primary",size:"sm",onClick:()=>{se()},disabled:Y,children:Y?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&s.jsx(gs,{type:"button",variant:"danger",size:"sm",onClick:()=>{G()},disabled:Y,children:"Disable password"})]})]})}),s.jsx(mt,{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(O=>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 ${O.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:O.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:O.type})]},O.type))})}),s.jsx(mt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(V0,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(mt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsx(mv,{themeDescription:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI.",mobileDescription:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout.",fontsSlot: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(U2,{value:m,savedValue:ps(p==null?void 0:p.standaloneFontPreferences),saving:y,error:f,notice:k,onChange:h,onSave:()=>{z()},onResetToSaved:U,onResetToDefaults:te})]})})}),s.jsx(mt,{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(K0,{}),s.jsx(Es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Rf,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:$,onChange:F})]})}),s.jsx(mt,{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(bf,{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(ss,{type:"text",className:"w-48 text-right",placeholder:"Anonymous",value:o,onChange:O=>i(O.target.value),onBlur:A,onKeyDown:O=>{O.key==="Enter"&&O.currentTarget.blur()}})]})})})]})}const G2=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],zr="adhdev_onboarding_done",V2=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],q2={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function Y2({onDone:e}){const[t,r]=l.useState([]),[n,a]=l.useState(new Set(G2)),[o,i]=l.useState(!0),[c,d]=l.useState(null),[p,u]=l.useState(!1),[m,h]=l.useState(null),[y,x]=l.useState("all");l.useEffect(()=>{let w=!1;const g=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${g}/providers?sort=popular&limit=100`).then(S=>{if(!S.ok)throw new Error(`HTTP ${S.status}`);return S.json()}).then(S=>{w||r(S.providers??[])}).catch(S=>{w||d(S instanceof Error?S.message:String(S))}).finally(()=>{w||i(!1)}),()=>{w=!0}},[]);const f=t.filter(w=>y==="all"||w.category===y),v=["cli","ide","extension","acp"].map(w=>({category:w,items:f.filter(g=>g.category===w)})).filter(w=>w.items.length>0),k=l.useCallback(w=>{a(g=>{const S=new Set(g);return S.has(w)?S.delete(w):S.add(w),S})},[]),b=l.useCallback(async()=>{if(n.size===0){localStorage.setItem(zr,"1"),e();return}u(!0);const w=[];for(const g of n)try{const N=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:g})})).json().catch(()=>({}));w.push({type:g,ok:!!N.success,error:N.error})}catch(S){w.push({type:g,ok:!1,error:S instanceof Error?S.message:String(S)})}h(w),u(!1),w.every(g=>g.ok)&&localStorage.setItem(zr,"1")},[n,e]),j=l.useCallback(()=>{localStorage.setItem(zr,"1"),e()},[e]),C=l.useCallback(()=>{m&&m.every(w=>w.ok)?e():p||j()},[m,p,e,j]);return s.jsx(vu,{open:!0,onClose:C,size:"lg",contentClassName:"max-w-2xl",title:"Welcome to ADHDev",footer:s.jsxs("div",{className:"flex w-full items-center gap-2",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(gs,{variant:"secondary",size:"sm",onClick:j,disabled:p,children:"Skip"}),s.jsx(gs,{variant:"primary",size:"sm",onClick:()=>{m?(localStorage.setItem(zr,"1"),e()):b()},disabled:p||!m&&n.size===0,children:p?"Installing…":m?"Done":`Install ${n.size}`})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",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:V2.map(w=>{const g=w.key==="all"?t.length:t.filter(S=>S.category===w.key).length;return g===0&&w.key!=="all"?null:s.jsxs("button",{onClick:()=>x(w.key),className:`machine-btn text-[10px] px-2 py-0.5 ${y===w.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[w.label," ",s.jsxs("span",{className:"opacity-60",children:["(",g,")"]})]},w.key)})}),o&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"Loading registry…"}),!o&&c&&s.jsxs(Ft,{variant:"error",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:v.map(w=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:q2[w.category]??w.category}),s.jsx("div",{className:"grid gap-1.5",children:w.items.map(g=>{var L,_;const S=n.has(g.type),N=m==null?void 0:m.find(P=>P.type===g.type),I=((L=g.manifest)==null?void 0:L.icon)??"📦",R=((_=g.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 ${S?"bg-accent-primary/[0.06] border-accent-primary/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:S,onChange:()=>k(g.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:g.displayName}),R&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:R})]}),N&&s.jsx("span",{className:`text-[10px] font-semibold ${N.ok?"text-status-online":"text-status-error"}`,children:N.ok?"✓ installed":`✗ ${N.error??"failed"}`})]},g.type)})})]},w.category))})]})})}function J2(){try{return localStorage.getItem(zr)==="1"}catch{return!1}}R0();av();E2();const X2=Md({baseUrl:"",getToken:cl});function Q2({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 x=await(await ds("/auth/session")).json();r(x)}catch(y){d(y instanceof Error?y.message:String(y))}finally{a(!1)}};l.useEffect(()=>{m()},[]),l.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let y=!1;return(async()=>{try{const x=await ds("/api/v1/standalone/preferences");if(!x.ok)return;const f=await x.json();if(y)return;const v=ps(f.standaloneFontPreferences);Bs(v),pi(v)}catch{}})(),()=>{y=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const h=async y=>{y.preventDefault(),u(!0),d("");try{const x=await ds("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),f=await x.json();if(!x.ok)throw new Error((f==null?void 0:f.error)||"Login failed");r(f),i(""),Um()}catch(x){d(x instanceof Error?x.message:String(x))}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(ss,{type:"password",value:o,onChange:y=>i(y.target.value),placeholder:"Enter standalone password",autoFocus:!0}),s.jsx(gs,{type:"submit",variant:"primary",disabled:p||!o,className:"justify-center",children:p?"Signing in…":"Unlock dashboard"})]}):s.jsx(Ft,{variant:"warning",children:"Password login is not enabled on this server."}),c&&s.jsx(Ft,{variant:"error",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 jd(){const{ides:e,initialLoaded:t}=hs();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(Eo,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Eo,{to:"/dashboard",replace:!0})}function Z2(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let r=!1;if(!J2())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(Y2,{onDone:()=>t(!1)}):null}function eI(){const{ides:e}=hs(),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}=jp(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(eu,{promptSession:r,isSubmitting:o,error:a,onSubmit:i,onCancel:c})]}):null}function tI(){const e=l.useMemo(()=>({sendCommand:Zr,sendData:ui,sendPtyInput:zm}),[]);return s.jsx(_h,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Jh,{client:X2,children:s.jsx(Q2,{children:s.jsx(L2,{children:s.jsx(Qh,{value:e,children:s.jsxs(sf,{sendDaemonCommand:Zr,children:[s.jsx(eI,{}),s.jsxs(F2,{children:[s.jsx(Z2,{}),s.jsxs(Th,{children:[s.jsx(ks,{path:"/dashboard",element:s.jsx(sS,{})}),s.jsx(ks,{path:"/machine",element:s.jsx(jd,{})}),s.jsx(ks,{path:"/machines/:id",element:s.jsx(uC,{})}),s.jsx(ks,{path:"/machines",element:s.jsx(jd,{})}),s.jsx(ks,{path:"/about",element:s.jsx(K2,{})}),s.jsx(ks,{path:"/settings",element:s.jsx(z2,{})}),s.jsx(ks,{path:"/mesh",element:s.jsx(j2,{children:s.jsx(y2,{})})}),s.jsx(ks,{path:"*",element:s.jsx(Eo,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}Sy({connectionManager:cs});Lh(document.getElementById("root")).render(s.jsx(tI,{}));