@adhdev/daemon-standalone 0.9.82-rc.187 → 0.9.82-rc.188

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,105 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-CEJ2KK2o.js","assets/vendor-BwuWgaJI.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
+ var Om=Object.defineProperty;var Fm=(e,t,r)=>t in e?Om(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ue=(e,t,r)=>Fm(e,typeof t!="symbol"?t+"":t,r);import{r as l,j as s,M as Eo,a as Hm,b as Wm,c as Km,R as bt,d as Nr,t as Um,e as zm,u as _r,D as Gm,f as io,g as lo,E as Vm,i as qm,C as Ym,h as Xm,B as Jm,k as Qm,l as Zm,m as eh,n as th,H as Jr,P as Zt,o as sh,p as rh,q as nh,s as ah,v as oh,w as $o,x as ih,y as lh,z as ch,A as dh,F as es,N as co,G as uh}from"./vendor-BwuWgaJI.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 mh(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 $s=mh();function Pi(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 hh(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Di(e){return Array.isArray(e)?[...e]:[]}function kc(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?Di(e.messages):i?[]:t.messages,activeModal:n?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...r?{messages:Di(e.messages)}:{},...n?{activeModal:e.activeModal??null}:{}}}function mr(e,t){const r=hh(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:kc(e.activeChat,t==null?void 0:t.activeChat),activeInteractivePrompt:e.activeInteractivePrompt??(t==null?void 0:t.activeInteractivePrompt)??null,controlValues:e.controlValues??(t==null?void 0:t.controlValues),providerControls:e.providerControls??(t==null?void 0:t.providerControls),summaryMetadata:e.summaryMetadata??(t==null?void 0:t.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(t==null?void 0:t.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(t==null?void 0:t.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(t==null?void 0:t.lastMessagePreview),lastMessageRole:e.lastMessageRole??(t==null?void 0:t.lastMessageRole),lastMessageAt:e.lastMessageAt??(t==null?void 0:t.lastMessageAt),lastMessageHash:e.lastMessageHash??(t==null?void 0:t.lastMessageHash),unread:e.unread??(t==null?void 0:t.unread),lastSeenAt:e.lastSeenAt??(t==null?void 0:t.lastSeenAt),inboxBucket:e.inboxBucket??(t==null?void 0:t.inboxBucket),completionMarker:e.completionMarker??(t==null?void 0:t.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(t==null?void 0:t.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(t==null?void 0:t.surfaceHidden),resume:e.resume??(t==null?void 0:t.resume),runtimeKey:e.runtimeKey??(t==null?void 0:t.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(t==null?void 0:t.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(t==null?void 0:t.runtimeWorkspaceLabel),settings:e.settings??(t==null?void 0:t.settings)}}function Sc(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?mr(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 Ei(e){return!!e&&typeof e=="object"&&"text"in e}function Bo(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:Ei(o)?String(o.text||""):"").join(r):Ei(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Bs(e){return Bo(e,{normalizeWhitespace:!0})}const Nc=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}),Cc=l.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function $i(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 Ic(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,u=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),o&&(n.serverVersion=o),u&&(n.versionUpdateReason=u),a&&o&&a===o?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||i&&a&&o&&a!==o)&&(n.versionMismatch=!0),c&&(n.versionUpdateRequired=!0),n)}function ph(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function ha(e){if(!e||typeof e!="object")return"";const t=e,r=ph(Bs(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 fh(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=ha(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:ha(e[0]),last:ha(e[e.length-1])}}function uo(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function mo(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(uo(e)&&uo(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)mo(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"&&mo(n[i],a[i],r)}function xr(e,t){return Array.isArray(e)?e.map(r=>xr(r,t)):!e||typeof e!="object"?e:uo(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?fh(a,t):xr(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,xr(n,t)]))}function xh(e,t){try{const r=new WeakSet;return mo(e,t,r),JSON.stringify(xr(e,r))===JSON.stringify(xr(t,r))}catch{return!1}}function ho(e,t,r){return xh(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Mc(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function bh(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Bi(e,t,r,n){var c;const a=(c=t.chats)!=null&&c.length?t.chats:e.chats,o=Sc(e.childSessions,t.childSessions,{preserveMissing:n}),i=kc(t.activeChat,e.activeChat);return Ic(e,t,{...e,...t,chats:a,childSessions:o,activeChat:i,_lastUpdate:r})}function gh(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=Sc(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(n.chats=t.chats);for(const i of["title","workspace","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","activeInteractivePrompt","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])bh(n,t,i);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function yh(e,t,r,n){const a=gh(e,t,n),o=Object.keys(a).length>0?Ic(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return ho(e,o,r)}function vh(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=Mc(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 wh(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 jh(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function kh(e,t,r){var d,h;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(f=>({...f,_lastUpdate:n}));const o=new Map;for(const f of t)o.set(f.id,f);const{incomingIds:i,incomingDaemonIds:c,daemonIdsWithSessionEntries:u,daemonIdsWithAuthoritativeSessionList:m}=vh(e);for(const f of e){const y=o.get(f.id);if(!y){o.set(f.id,{...f,_lastUpdate:n});continue}const b=$i(f),x=$i(y),j=Mc(f),k=!a.has(j);if(b>x){const S=Bi(y,f,n,k);o.set(f.id,ho(y,S,n));continue}if(b<x){o.set(f.id,yh(y,f,n,k));continue}const p=f.timestamp||n,w=y._lastUpdate||y.timestamp||0;if(p>=w){const S=Bi(y,f,n,k);o.set(f.id,ho(y,S,n));continue}(d=f.chats)!=null&&d.length&&!((h=y.chats)!=null&&h.length)&&o.set(f.id,{...y,chats:f.chats})}for(const[f,y]of o){const b=y.daemonId||f.split(":")[0];if(!c.has(b))continue;if(a.has(b)&&m.has(b)&&!i.has(f)){o.delete(f);continue}const x=n-(y._lastUpdate||y.timestamp||0);wh(y,b,x,i,a,u)&&o.delete(f)}for(const[f,y]of o){const b=y.daemonId||f.split(":")[0];if(jh(y,b,c,u,o))continue;n-(y._lastUpdate||y.timestamp||0)>3e5&&y.status!=="online"&&o.delete(f)}return Array.from(o.values())}function Sh(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 Nh({children:e,connectionOverrides:t}){const[r,n]=l.useState([]),[a,o]=l.useState(!1),[i,c]=l.useState([]),[u,m]=l.useState(void 0),d=l.useRef(r);l.useEffect(()=>{d.current=r},[r]);const h=l.useCallback((k,p)=>{n(w=>{let S=!1;const v=w.map(g=>g.id!==k||g.chats===p?g:(S=!0,{...g,chats:p}));return S?v:w})},[]),f=l.useCallback((k,p)=>{n(w=>{const S=w.length===0?k:kh(k,w,p),v=!Sh(w,S);return v&&$s.record({kind:"dashboard.entries_applied",payload:{incoming:Pi(k),next:Pi(S)}}),v?S:w})},[]),y=l.useCallback(()=>o(!0),[]),b=l.useMemo(()=>({injectEntries:f,markLoaded:y,getIdes:()=>d.current}),[f,y]),x=t,j=l.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:a,toasts:i,setToasts:c,wsStatus:(x==null?void 0:x.wsStatus)??"connected",isConnected:(x==null?void 0:x.isConnected)??!0,connectionStates:(x==null?void 0:x.connectionStates)??{},connectionTransports:(x==null?void 0:x.connectionTransports)??{},showReconnected:(x==null?void 0:x.showReconnected)??!1,retryConnection:x==null?void 0:x.retryConnection,retryServerConnection:x==null?void 0:x.retryServerConnection,connectionLoginUrl:x==null?void 0:x.connectionLoginUrl,isP2PActive:(x==null?void 0:x.isP2PActive)??!1,p2pStates:(x==null?void 0:x.p2pStates)??{},userRole:x==null?void 0:x.userRole,connectionRetryStatuses:x==null?void 0:x.connectionRetryStatuses,userName:u,setUserName:m}),[r,h,a,i,x==null?void 0:x.wsStatus,x==null?void 0:x.isConnected,x==null?void 0:x.connectionStates,x==null?void 0:x.connectionTransports,x==null?void 0:x.showReconnected,x==null?void 0:x.retryConnection,x==null?void 0:x.retryServerConnection,x==null?void 0:x.connectionLoginUrl,x==null?void 0:x.isP2PActive,x==null?void 0:x.p2pStates,x==null?void 0:x.userRole,x==null?void 0:x.connectionRetryStatuses,u]);return s.jsx(Cc.Provider,{value:b,children:s.jsx(Nc.Provider,{value:j,children:e})})}function Xt(){return l.useContext(Nc)}function Cr(){return l.useContext(Cc)}function Ac(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 u=r==null?void 0:r(),m=a(c),d=c.startsWith("http")?new URL(m):new URL(m,typeof window<"u"?window.location.origin:"http://localhost");return u&&d.searchParams.set("token",u),!c.startsWith("http")&&!t?`${d.pathname}${d.search}${d.hash}`:d.toString()}async function i(c,u={}){const m={"Content-Type":"application/json",...u.headers||{}},d=r==null?void 0:r();d&&(m.Authorization=`Bearer ${d}`);const h=a(c),f=new AbortController,y=setTimeout(()=>f.abort(),15e3);try{const b=await fetch(h,{...u,headers:m,signal:f.signal});if(b.status===401)throw n==null||n(),new Error("Unauthorized");if(!b.ok){const x=await b.json().catch(()=>({error:b.statusText}));throw new Error(x.error||`API Error: ${b.status}`)}return b.json()}finally{clearTimeout(y)}}return{getDaemons:()=>i("/api/v1/daemons"),getDaemonStatus:c=>i(`/api/v1/daemons/${c}/status`),sendCommand:(c,u,m={})=>i(`/api/v1/daemons/${c}/command`,{method:"POST",body:JSON.stringify({type:u,payload:m})}),execTerminal:(c,u,m)=>i(`/api/v1/daemons/${c}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:m})}),sendAgentMessage:(c,u,m)=>i(`/api/v1/shortcuts/${c}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:m})}),getAgentStatus:c=>i(`/api/v1/shortcuts/${c}/status`),approveAgent:(c,u,m)=>i(`/api/v1/shortcuts/${c}/approve`,{method:"POST",body:JSON.stringify({agentType:u,action:m?"approve":"reject"})}),getMuxState:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/state`),getMuxSocketInfo:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/socket-info`),controlMux:(c,u,m={})=>i(`/api/v1/mux/${encodeURIComponent(c)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:m})}),getMuxEventsUrl:c=>o(`/api/v1/mux/${encodeURIComponent(c)}/events`),getRuntimeEventsUrl:c=>o(`/api/v1/runtime/${encodeURIComponent(c)}/events`),request:i}}const Ch=Ac({baseUrl:"http://localhost:3847"}),Ih=l.createContext(Ch);function Mh({client:e,children:t}){return s.jsx(Ih.Provider,{value:e,children:t})}const Ah={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Tc=l.createContext(Ah);function Th({value:e,children:t}){return s.jsx(Tc.Provider,{value:e,children:t})}function ot(){return l.useContext(Tc)}function _c(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function _h(e){const t=_c(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 Lh(e){const[t,r]=l.useState(null),n=l.useCallback(async(i,c)=>{const u=h=>e(i,"launch_cli",{...c,...h}),m=await u({}),d=_h(m);return d?new Promise(h=>{r({providerType:d.providerType||String(c.cliType??"?"),sourceName:d.sourceName,description:d.description,retry:()=>u({confirmExternalUntrusted:!0}),resolve:f=>{f.cancelled?h({success:!1,error:"user_cancelled_untrusted_launch"}):h(f.response)}})}):m},[e]),a=l.useCallback(async()=>{const i=t;if(i){r(null);try{const c=await i.retry(),u=_c(c);u!=null&&u.success?i.resolve({ok:!0,response:c}):i.resolve({ok:!1,error:(u==null?void 0:u.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 Rh({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 Lc=l.createContext(null);function Ph({sendDaemonCommand:e,children:t}){const r=Lh(e),n=l.useMemo(()=>({launchCli:r.launchCli}),[r.launchCli]);return s.jsxs(Lc.Provider,{value:n,children:[t,r.pending&&s.jsx(Rh,{providerType:r.pending.providerType,sourceName:r.pending.sourceName,description:r.pending.description,onConfirm:r.confirm,onCancel:r.cancel})]})}function ta(){const e=l.useContext(Lc);return e||{launchCli:async()=>{throw new Error("useLaunchCli must be used inside <LaunchCliProvider>")}}}function Dh(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 Eh(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function $h(e){return e?Dh([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Eh(e.content)]):""}const $e={size:18};function Rc({size:e=$e.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 Oo({size:e=$e.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 ns({size:e=$e.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 Pc({size:e=$e.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 Bh({size:e=$e.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 Oh({size:e=$e.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 Dc({size:e=$e.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 Fh({size:e=$e.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 sa({size:e=$e.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 Ec({size:e=$e.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 Hh({size:e=$e.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 ks({size:e=$e.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 Ot({size:e=$e.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 Fo({size:e=$e.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 Os({size:e=$e.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 ra({size:e=$e.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 Fs({size:e=$e.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 Hs({size:e=$e.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 ss({size:e=$e.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 Wh({size:e=$e.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 $c({size:e=$e.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 Ho({size:e=$e.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 Bc({size:e=$e.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 Kh({size:e=$e.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 Wo({size:e=$e.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 Uh({size:e=$e.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 Oc({size:e=$e.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 Fc({size:e=$e.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 gt({size:e=$e.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 zh({size:e=$e.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 Gh({size:e=$e.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 Vh({size:e=$e.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 qh({size:e=$e.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 Lr({size:e=$e.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 Yh({size:e=$e.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 Xh({size:e=$e.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 Jh({size:e=$e.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 Hc({size:e=$e.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 Qh({size:e=$e.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 Zh({size:e=$e.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 ep({size:e=$e.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 tp({size:e=$e.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 sp({size:e=$e.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 rp({size:e=$e.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 np({size:e=$e.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 ap({size:e=$e.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 Wc="adhdev_chat_activity_visible",Oi=new Set(["hidden","debug","internal"]),Fi=new Set(["visible","user","chat"]),op=new Set(["debug","trace","internal"]),ip=new Set(["tool_call","terminal_command","runtime_activity"]),lp=new Set(["runtime_status","provider_chrome","control"]),cp=new Set(["thought","tool","terminal"]);function Kc(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function As(e){return typeof e=="string"?e.trim().toLowerCase():""}function pa(e,t,r){return e[r]??(t==null?void 0:t[r])}function Hi(e,t,r){const n=e;return r.some(a=>n[a]===!0||(t==null?void 0:t[a])===!0)}function dp(e,t){const r=As(e.kind);return r||(t==="tool"?"tool":"standard")}function fa(e,t,r){const n=Kc(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 up(e){const t=e.content;return Array.isArray(t)&&t.some(r=>!!r&&typeof r=="object"&&r.type!=="text")}function Ko(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=Kc(e),r=As(e.role),n=dp(e,r),a=As(pa(e,t,"visibility")),o=As(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),i=As(pa(e,t,"audience")),c=As(pa(e,t,"source")),u=Oi.has(a)||Oi.has(o)||op.has(i)||Hi(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),m=Fi.has(a)||Fi.has(o)||i==="chat"||Hi(e,t,["userFacing"]),d=cp.has(n)||ip.has(c);if(u)return{surface:d?"activity":"internal",isUserFacing:!1,isActivityFacing:d,isInternal:!d,role:r,kind:n,label:fa(e,n,c)};if(m)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:fa(e,n,c)};if((r==="system"||n==="system")&&up(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:"Chat"};if(lp.has(c)||r==="system"||n==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:r,kind:n,label:"Internal"};if(d)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:r,kind:n,label:fa(e,n,c)};const h=(r==="user"||r==="human"||r==="assistant")&&(n==="standard"||n==="");return{surface:h?"chat":"internal",isUserFacing:h,isActivityFacing:!1,isInternal:!h,role:r,kind:n,label:h?"Chat":"Internal"}}function mp(e){return(Array.isArray(e)?e:[]).filter(t=>Ko(t).isUserFacing)}function Uc(e){return(Array.isArray(e)?e:[]).filter(t=>Ko(t).isActivityFacing)}function hp(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,u=Number(a.index??0)||0;return c-u})}function Wi(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(Wc))==="1"}catch{return!1}}const zc=[Hm,{singleTilde:!1}],Gc=[zc,Wm,Km],pp=[zc],Uo=200,fp=80,Ki=650,Js=new Map;function Rn(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function xp(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}:${$h(n)}`}function bp(e,t,r,n){return e||!t?!1:Rn(r,n)}function gp({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=fp,bottomThresholdPx:a=Uo}){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 yp(e){return gp({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function hr(e,t=Uo){return!!e&&e.fromBottom>=t}function vp(e,t){return Rn(e,t)?!hr(e):!0}function wp({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function jp({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function xa(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function Vc(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function kp(e,t,r){return Number(e.receivedAt||r[Pn(e,t)]||0)||0}function qc(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Sp(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function Qs(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 ba(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 Qr(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 Ui(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):qc(e)?s.jsx(Eo,{remarkPlugins:Gc,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function Zs({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:Ui(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=ba(r),o=r.alt||r.description||Qs(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:Qr("Image",o,r.mimeType)},`image-fallback-${n}`)}if(r.type==="audio"){const a=ba(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:Qr("Audio",Qs(r.uri,"audio"),r.transcript||r.mimeType)},`audio-fallback-${n}`)}if(r.type==="video"){const a=ba(r),o=r.title||r.name||r.alt||Qs(r.uri,"video"),i=[r.transcript,r.description,r.mimeType].filter(Boolean).join(`
3
+ `);return s.jsxs("div",{className:"flex flex-col gap-1",children:[a?s.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):Qr("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||Qs(r.uri,"resource"),o=[r.description,r.mimeType].filter(Boolean).join(`
4
+ `);return s.jsxs("div",{className:"flex flex-col gap-1",children:[r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",download:!0,className:"underline break-all",children:a}):Qr("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=Qs(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}),Ui(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return s.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${n}`)}return null})})}function Pn(e,t){const r=e,n=Bo(e.content,{joiner:`
5
+ `});return[e.id?`id:${e.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",e.role?`role:${e.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${t}`].filter(Boolean).join("|")}const Np=l.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(Eo,{remarkPlugins:pp,children:t.text}),s.jsx("span",{className:"action-time",children:Vc(t.timestamp)})]})},(e,t)=>e.log===t.log),Cp=l.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:i,onToggleTextExpanded:c}){var I,N,_;const u=(t.role||"").toLowerCase(),m=u==="user"||u==="human",d=t.kind||(u==="tool"?"tool":"standard"),h=Ko(t),f=Sp(t.content)?t.content:null,y=!!(f!=null&&f.some(D=>D.type!=="text")),b=Bo(t.content,{joiner:`
6
+ `});if(h.isActivityFacing&&d!=="thought"&&d!=="tool"&&d!=="terminal"){const D=h.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:D})]}),y&&f?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(Zs,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:b})]})}if(d==="thought"){const D=typeof((I=t.meta)==null?void 0:I.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":h.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(Vh,{size:13}),s.jsx("span",{children:D})]}),s.jsx("div",{className:"chat-msg-body",children:b})]})}if(d==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":h.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&&f?s.jsx("div",{className:"tool-text w-full",children:s.jsx(Zs,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:b})]});if(d==="terminal"){const D=(N=t.meta)!=null&&N.isRunning?"⏳":"✅",A=typeof((_=t.meta)==null?void 0:_.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":h.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:D}),s.jsx("span",{children:A})]}),y&&f?s.jsx("div",{className:"chat-msg-body",children:s.jsx(Zs,{parts:f,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:b})]})}if(d==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:y&&f?s.jsx(Zs,{parts:f,renderAsPreformatted:!1}):b.slice(0,100)});const x=t.meta,k=(typeof(x==null?void 0:x.renderMode)=="string"?x.renderMode.trim():"")==="preformatted",p=b,w=!1,S=p,v=k,g=!m&&!v&&qc(S),C=["chat-message-row",m?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:C,children:(p||y||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${p||y?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:m?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:Vc(r)})]}),(p||y)&&s.jsx("div",{className:"chat-markdown",children:y&&f?s.jsx(Zs,{parts:f,renderAsPreformatted:v}):v?s.jsx("pre",{className:"chat-preformatted",children:S}):g?s.jsx(Eo,{remarkPlugins:Gc,children:S}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:S})}),w]})})},(e,t)=>e.message===t.message&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),Ip=l.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:o=!1,isWorking:i=!1,contextKey:c="",receivedAtMap:u={},lastMessageHash:m,showActivityMessages:d=!1,emptyState:h,onLoadMore:f,isLoadingMore:y,hasMoreHistory:b,hiddenLiveCount:x=0,loadError:j,scrollToBottomRequestNonce:k,isVisible:p=!0},w){const S=l.useRef(null),v=l.useRef(null),g=l.useRef(null),C=l.useRef(0),I=l.useRef(""),N=l.useRef(""),_=l.useRef(!1),D=l.useRef(null),A=l.useRef(!1),M=l.useRef(null),R=l.useRef(!1),[z,T]=l.useState(new Set),[L,B]=l.useState({showTop:!1,showBottom:!1}),O=l.useRef(!1),$=l.useRef(!1),E=l.useRef(p),W=l.useRef(p),J=l.useRef(null);W.current=p;const Q=()=>{const ie=S.current;return ie?ie.scrollHeight-ie.scrollTop-ie.clientHeight<Uo:!0},ee=l.useCallback(()=>{const ie=S.current,P=ie?yp(ie):{showTop:!1,showBottom:!1};B(fe=>fe.showTop===P.showTop&&fe.showBottom===P.showBottom?fe:P)},[]),me=l.useCallback((ie="auto")=>{var fe;const P=S.current;P&&(P.scrollTo({top:P.scrollHeight,behavior:ie}),(fe=P.ownerDocument.defaultView)==null||fe.requestAnimationFrame(()=>ee()))},[ee]),je=l.useCallback((ie="auto")=>{var fe;const P=S.current;P&&(P.scrollTo({top:0,behavior:ie}),(fe=P.ownerDocument.defaultView)==null||fe.requestAnimationFrame(()=>ee()))},[ee]),Me=l.useCallback(()=>{var _e;const ie=S.current,P=(_e=window.getSelection)==null?void 0:_e.call(window);if(!ie||!P||P.rangeCount===0||P.isCollapsed){R.current=!1;return}const fe=P.anchorNode,Ce=P.focusNode;R.current=!!(fe&&Ce&&ie.contains(fe)&&ie.contains(Ce))},[]),q=l.useMemo(()=>{const ie=mp(t),P=Uc(t);return hp(ie,P,d)},[t,d]),G=q.length===t.length?m:void 0,he=xp(q,G),ue=l.useCallback(()=>{const ie=S.current;if(!ie||!c||!W.current)return;const P={top:ie.scrollTop,fromBottom:Math.max(0,ie.scrollHeight-ie.scrollTop-ie.clientHeight),messageFingerprint:he};J.current={contextKey:c,snapshot:P},Js.set(c,P)},[c,he]),ce=l.useCallback((ie="auto")=>{D.current!=null&&cancelAnimationFrame(D.current),D.current=requestAnimationFrame(()=>{D.current=null,me(ie)})},[me]),ve=l.useCallback(()=>{O.current=!1,A.current=!0,$.current=!0,M.current!=null&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{A.current=!1,M.current=null},Ki)},[]);l.useEffect(()=>{const ie=!_.current,P=N.current!==c;if(N.current=c,ie||P){_.current=!0;const Ce=c?Js.get(c):null,_e=!!Ce&&Rn(Ce,he);O.current=_e?hr(Ce):!1,A.current=vp(Ce,he),R.current||(_e?requestAnimationFrame(()=>{const se=S.current;se&&(xa(se,Ce),O.current=hr(Ce),ee(),$.current=!0)}):ce("auto")),C.current=q.length,I.current=he;return}q.length>C.current;const fe=he!==I.current;wp({hasSelection:R.current,userScrolledUp:O.current,hasChatContentChanged:fe})&&ce("auto"),C.current=q.length,I.current=he},[he,c,q.length,ce,ee]),l.useEffect(()=>{k&&(ve(),R.current||ce("auto"))},[ve,ce,k]),l.useEffect(()=>{const ie=E.current;ie&&!p&&ue(),W.current=p,E.current=p;const P=c?Js.get(c):null;if(bp(ie,p,P,he)){if(!P)return;O.current=hr(P),A.current=!1,R.current||requestAnimationFrame(()=>{const fe=S.current;fe&&(xa(fe,P),ee())});return}},[p,c,he,ve,ue,ce,ee]),l.useEffect(()=>()=>{const ie=J.current;ie&&Js.set(ie.contextKey,ie.snapshot),D.current!=null&&cancelAnimationFrame(D.current),M.current!=null&&window.clearTimeout(M.current)},[]),l.useEffect(()=>{const ie=v.current,P=S.current;if(!ie||!P)return;const fe=()=>{M.current!=null&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{A.current=!1,M.current=null},Ki)},Ce=new ResizeObserver(()=>{ee();const _e=A.current;jp({hasSelection:R.current,userScrolledUp:O.current,contextAutoScrollActive:_e})&&(ce("auto"),_e&&fe())});return Ce.observe(ie),P!==ie&&Ce.observe(P),()=>{Ce.disconnect(),M.current!=null&&(window.clearTimeout(M.current),M.current=null)}},[ce,c,ee]),l.useImperativeHandle(w,()=>({scrollToBottom:(ie="smooth")=>{me(ie)}}),[me]),l.useEffect(()=>{const ie=S.current;if(!ie)return;let P;const fe=()=>{ue(),clearTimeout(P),P=setTimeout(()=>{O.current=!Q(),ee()},50)};return ie.addEventListener("scroll",fe,{passive:!0}),()=>{ie.removeEventListener("scroll",fe),clearTimeout(P)}},[ue,ee]),l.useEffect(()=>(document.addEventListener("selectionchange",Me),()=>document.removeEventListener("selectionchange",Me)),[Me]);const X=l.useRef(0),we=l.useRef(!1);l.useEffect(()=>{const ie=S.current;if(!ie||!we.current||X.current===0)return;const P=ie.scrollHeight-X.current;P>0&&(ie.scrollTop=P),ee(),ue(),X.current=0,we.current=!1},[q.length,ue,ee]),l.useEffect(()=>{if($.current||!c)return;const ie=Js.get(c),P=S.current;if(!(!ie||!P)){if(!Rn(ie,he)){me("auto"),$.current=!0;return}xa(P,ie),O.current=hr(ie),ee(),$.current=!0}},[c,he,q.length,me,ee]);const de=()=>{const ie=S.current;ie&&(X.current=ie.scrollHeight),we.current=!0,f==null||f()},ye=()=>{O.current=!0,je("smooth"),ue()},xe=()=>{ve(),me("smooth"),ue()},ge=l.useMemo(()=>{const ie=q.map((_e,se)=>({type:"message",data:_e,index:se,ts:kp(_e,se,u)}));if(!r||r.length===0)return ie;const P=[...r].sort((_e,se)=>_e.timestamp-se.timestamp).map((_e,se)=>({type:"action",data:_e,index:se,ts:_e.timestamp})),fe=[];let Ce=0;for(const _e of ie){for(;Ce<P.length&&_e.ts>0&&P[Ce].ts<_e.ts;)fe.push(P[Ce++]);fe.push(_e)}for(;Ce<P.length;)fe.push(P[Ce++]);return fe},[q,r,u]),le=x>0||!!b,be=x>0?`↑ Show ${Math.min(x,80)} earlier messages${x>80?` (${x} hidden)`:""}`:j?`↻ ${j}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:S,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:v,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..."}),le&&!y&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:de,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${j&&x===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})}),ge.length===0&&!le&&(h||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),ge.map(ie=>{if(ie.type==="action"){const Te=ie.data;return s.jsx(Np,{log:Te},`action-${ie.index}`)}const P=ie.data,fe=ie.index,Ce=Pn(P,fe),_e=P.receivedAt||u[Ce],se=`${c}-${Ce}`,De=z.has(se);return s.jsx(Cp,{message:P,receivedAt:_e,agentName:n,userName:a,isCliMode:o,isTextExpanded:De,onToggleTextExpanded:()=>T(Te=>{const Ee=new Set(Te);return De?Ee.delete(se):Ee.add(se),Ee})},`msg-${Ce}`)}),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})]})}),(L.showTop||L.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[L.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:ye,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),L.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:xe,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Mp=l.memo(Ip,(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),Ap="modulepreload",Tp=function(e){return"/"+e},zi={},_p=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(u=>{if(u=Tp(u),u in zi)return;zi[u]=!0;const m=u.endsWith(".css"),d=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const h=document.createElement("link");if(h.rel=m?"stylesheet":Ap,m||(h.as="script"),h.crossOrigin="",h.href=u,c&&h.setAttribute("nonce",c),document.head.appendChild(h),m)return new Promise((f,y)=>{h.addEventListener("load",f),h.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${u}`)))})}))}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 Gi=!1;const Yc=l.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:o="measured"},i)=>{const c=l.useRef(null),[u,m]=l.useState(null),d=l.useRef([]),h=l.useRef(!1),f=l.useRef(!1),y=l.useRef(!1),b=l.useRef(!1),x=()=>{const j=c.current;if(j){h.current&&(j.clear(),h.current=!1);for(const k of d.current)j.write(k.data,k.onProcessed);d.current=[],f.current&&(j.fit(),f.current=!1),y.current&&(j.bumpResize(),y.current=!1),b.current&&(j.scrollToTop(),b.current=!1)}};return l.useImperativeHandle(i,()=>({write:(j,k)=>{c.current?c.current.write(j,k):d.current.push({data:j,onProcessed:k})},clear:()=>{c.current?c.current.clear():(d.current=[],h.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(d.current=[],h.current=!0)},resize:(j,k)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(j,k)},fit:()=>{c.current?c.current.fit():f.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():y.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():b.current=!0},getSelection:()=>{var j,k;return((k=(j=c.current)==null?void 0:j.getSelection)==null?void 0:k.call(j))||""},getVisibleText:()=>{var j,k;return((k=(j=c.current)==null?void 0:j.getVisibleText)==null?void 0:k.call(j))||""}}),[]),l.useEffect(()=>{u&&x()},[u]),l.useEffect(()=>{let j=!1;return _p(()=>import("./terminal-CEJ2KK2o.js"),__vite__mapDeps([0,1,2])).then(k=>{Gi||(Gi=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),j||m(()=>k.GhosttyTerminalView)}).catch(k=>{console.error("[CliTerminal] failed to load terminal renderer",k)}),()=>{j=!0}},[]),u?s.jsx(u,{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"}})});Yc.displayName="CliTerminal";function Zr({label:e,value:t,sub:r,icon:n}){return s.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsx("span",{className:"text-base flex items-center",children:n}),s.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),s.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:t}),r&&s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function Vi({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 Lp({cursorPos:e,viewportRef:t,imgRef:r}){var p;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(p=t.current)==null?void 0:p.getBoundingClientRect();if(!o)return null;const i=n.naturalWidth||a.width,c=n.naturalHeight||a.height,u=i/c,m=a.width/a.height;let d,h,f,y;u>m?(d=a.width,h=a.width/u,f=0,y=(a.height-h)/2):(h=a.height,d=a.height*u,f=(a.width-d)/2,y=0);const b=a.left-o.left+f+d*e.nx,x=a.top-o.top+y+h*e.ny,j=Math.max(8,Math.min(o.width-8,b)),k=Math.max(8,Math.min(o.height-8,x));return s.jsxs("div",{style:{position:"absolute",left:j-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 Rp({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:i,setImeText:c,handleImeSubmit:u,isConnActive:m,zoom:d,isMobile:h,mobileFillZoom:f,onZoomOut:y,onZoomReset:b,onZoomIn:x,transportType:j,screenshotUsage:k,lastActionStatus:p}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:w=>w.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(w=>!w),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:w=>w.stopPropagation(),onChange:w=>c(w.target.value),onKeyDown:w=>{u(w)},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(w=>!w),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:m?"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:m?"#22c55e":"#eab308",boxShadow:m?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:m?"#22c55e":"#eab308"},children:m?"Connected":"WS"})]}),d>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),j==="direct"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),j==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),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`}),p&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:p})]})]}),a&&s.jsxs("div",{onTouchStart:w=>w.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: ",d<=(h?f:1)+.01?h?"FILL":"FIT":`${Math.round(d*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:w=>{w.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:w=>{w.stopPropagation(),b()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:h?"FILL":"FIT"}),s.jsx("button",{onClick:w=>{w.stopPropagation(),x()},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 Pp({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 Dp(){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 qi(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 Rr(e,t){const r=l.useRef(null),n=l.useRef(0);l.useEffect(()=>{if(!Dp())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,qi(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,qi(t[i])]))}),r.current=t})}function Ep({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:i,panXRef:c,panYRef:u,setPanX:m,setPanY:d,setZoom:h,lastWheelTimeRef:f,onAction:y,setLastActionStatus:b,spawnRippleFromNormalized:x,clampPan:j,isMobile:k,mobileFillZoom:p}){const[w,S]=l.useState(null),v=l.useRef(null),g=l.useRef(null),C=l.useRef(null),I=l.useRef(!1),N=l.useRef(null),_=l.useRef(0),D=l.useRef(null),A=l.useRef(1),M=l.useRef({x:0,y:0}),R=l.useRef(!1),z=l.useRef(n),T=l.useRef(y),L=30,B=550,O=18,$=60,E=400,W=12,J=()=>{if(v.current)return;const me={nx:.5,ny:.5};v.current=me,S(me)};return l.useEffect(()=>{z.current=n,n==="mouse"&&J()},[n]),l.useEffect(()=>{T.current=y},[y]),l.useEffect(()=>{const me=e.current;if(!me)return;const je=ce=>{if(!r.current)return null;const ve=r.current.getBoundingClientRect();return!ve.width||!ve.height?null:{nx:Math.max(0,Math.min(1,(ce.clientX-ve.left)/ve.width)),ny:Math.max(0,Math.min(1,(ce.clientY-ve.top)/ve.height))}},Me=(ce,ve)=>{if(!r.current)return{dnx:0,dny:0};const X=r.current,we=X.getBoundingClientRect(),de=X.naturalWidth||we.width,ye=X.naturalHeight||we.height,xe=de/ye,ge=we.width/we.height;let le,be;return xe>ge?(le=we.width,be=we.width/xe):(be=we.height,le=we.height*xe),{dnx:ce/le,dny:ve/be}},q=(ce,ve,X)=>{if(X<=1.05)return;const we=-(ce-.5)*100,de=-(ve-.5)*100,ye=j(we,de,X);(Math.abs(ye.x-c.current)>.1||Math.abs(ye.y-u.current)>.1)&&(m(ye.x),d(ye.y),c.current=ye.x,u.current=ye.y)},G=ce=>{const ve=t.current;if(ve&&ce.target instanceof Node&&ve.contains(ce.target))ce.preventDefault();else return;if(ce.touches.length===1){const X=ce.touches[0];g.current={x:X.clientX,y:X.clientY,time:Date.now()},C.current={x:X.clientX,y:X.clientY},R.current||(I.current=!1),N.current=setTimeout(()=>{if(!I.current&&!R.current)if(I.current=!0,z.current==="mouse"){const we=v.current||{nx:.5,ny:.5};b("Right Click"),x(we.nx,we.ny,"right"),T.current("input_click",{...we,button:"right"}).catch(()=>{})}else{const we=je(X);we&&(b("Right Click"),x(we.nx,we.ny,"right"),T.current("input_click",{...we,button:"right"}).catch(()=>{}))}},500);return}if(ce.touches.length===2){N.current&&clearTimeout(N.current),I.current=!0,R.current=!0;const X=ce.touches[1].clientX-ce.touches[0].clientX,we=ce.touches[1].clientY-ce.touches[0].clientY;D.current=Math.sqrt(X*X+we*we),A.current=i.current,M.current={x:(ce.touches[0].clientX+ce.touches[1].clientX)/2,y:(ce.touches[0].clientY+ce.touches[1].clientY)/2}}},he=ce=>{const ve=t.current;if(ve&&ce.target instanceof Node&&ve.contains(ce.target)&&ce.preventDefault(),ce.touches.length===1&&C.current){const X=ce.touches[0],we=X.clientX-C.current.x,de=X.clientY-C.current.y;if(!I.current&&g.current){const ye=X.clientX-g.current.x,xe=X.clientY-g.current.y;Math.sqrt(ye*ye+xe*xe)>8&&(I.current=!0,N.current&&clearTimeout(N.current))}if(I.current)if(z.current==="mouse"){const ye=Me(we,de),xe=v.current||{nx:.5,ny:.5},ge=Math.max(0,Math.min(1,xe.nx+ye.dnx)),le=Math.max(0,Math.min(1,xe.ny+ye.dny));v.current={nx:ge,ny:le},S({nx:ge,ny:le}),b(`Cursor: ${Math.round(ge*100)}%, ${Math.round(le*100)}%`),q(ge,le,i.current);const be=Date.now();be-f.current>=30&&(f.current=be,T.current("input_mouseMoved",{nx:ge,ny:le}).catch(()=>{}))}else if(i.current>1){const ye=t.current;if(ye){const xe=ye.clientWidth,ge=ye.clientHeight,le=c.current+we/xe*100,be=u.current+de/ge*100,ie=j(le,be,i.current);m(ie.x),d(ie.y),c.current=ie.x,u.current=ie.y}}else{const ye=je(X);if(ye){const xe=Date.now();xe-f.current>=40&&(f.current=xe,b("Scroll"),T.current("input_wheel",{nx:ye.nx,ny:ye.ny,deltaX:Math.round(-we*2.5),deltaY:Math.round(-de*2.5)}).catch(()=>{}))}}C.current={x:X.clientX,y:X.clientY};return}if(ce.touches.length===2&&D.current!==null){const X=ce.touches[1].clientX-ce.touches[0].clientX,we=ce.touches[1].clientY-ce.touches[0].clientY,ye=Math.sqrt(X*X+we*we)/D.current,xe=(ce.touches[0].clientX+ce.touches[1].clientX)/2,ge=(ce.touches[0].clientY+ce.touches[1].clientY)/2,le=xe-M.current.x,be=ge-M.current.y,ie=Math.abs(ye-1)>.03;if(z.current==="mouse"){if(ie){const P=Math.max(o,Math.min(5,A.current*ye));h(P),i.current=P}else if(Math.abs(le)>2||Math.abs(be)>2){const P=v.current||{nx:.5,ny:.5},fe=Date.now();fe-f.current>=30&&(f.current=fe,b("Scroll"),T.current("input_wheel",{nx:P.nx,ny:P.ny,deltaX:Math.round(-le*3),deltaY:Math.round(-be*3)}).catch(()=>{}))}}else{const P=Math.max(o,Math.min(5,A.current*ye));h(P),i.current=P;const fe=t.current;if(fe&&P>1){const Ce=fe.clientWidth,_e=fe.clientHeight,se=c.current+le/Ce*100,De=u.current+be/_e*100,Te=j(se,De,P);m(Te.x),d(Te.y),c.current=Te.x,u.current=Te.y}}M.current={x:xe,y:ge}}},ue=ce=>{var ve;if(N.current&&clearTimeout(N.current),D.current=null,ce.touches.length===1&&R.current){const X=ce.touches[0];g.current={x:X.clientX,y:X.clientY,time:Date.now()},C.current={x:X.clientX,y:X.clientY},I.current=!0;return}if(ce.touches.length===0){if(R.current){R.current=!1,I.current=!1;return}if(ce.changedTouches.length===1){const X=ce.changedTouches[0],we=Date.now(),de=we-(((ve=g.current)==null?void 0:ve.time)||0),ye=g.current?X.clientX-g.current.x:0,xe=g.current?X.clientY-g.current.y:0,ge=Math.sqrt(ye*ye+xe*xe);if(z.current==="mouse"){if(de<L||de>B||ge>O){I.current=!1;return}const le=v.current||je(X);le&&(b(`Click: ${Math.round(le.nx*100)}%, ${Math.round(le.ny*100)}%`),x(le.nx,le.ny,"left"),T.current("input_click",{...le}).catch(()=>{}))}else{if(I.current){I.current=!1;return}if(de<$||de>E||ge>W){I.current=!1;return}const le=je(X);if(!le)return;we-_.current<300?(b("Double tap"),x(le.nx,le.ny,"double"),T.current("input_click",{...le,clickCount:2}).catch(()=>{}),_.current=0):(b(`Tap: ${Math.round(le.nx*100)}%, ${Math.round(le.ny*100)}%`),x(le.nx,le.ny,"left"),T.current("input_click",{...le}).catch(()=>{}),_.current=we)}}I.current=!1}};return me.addEventListener("touchstart",G,{passive:!1}),me.addEventListener("touchmove",he,{passive:!1}),me.addEventListener("touchend",ue,{passive:!1}),()=>{me.removeEventListener("touchstart",G),me.removeEventListener("touchmove",he),me.removeEventListener("touchend",ue),N.current&&clearTimeout(N.current)}},[e,t,r,o,i,c,u,m,d,h,f,b,x,j]),{cursorPos:w,cursorPosRef:v,handleToggleInputMode:()=>{a(me=>{const je=me==="touch"?"mouse":"touch";return je==="mouse"&&J(),je})},handleZoomReset:()=>{const me=k?p:1;h(me),i.current=me,m(0),d(0),c.current=0,u.current=0}}}function Xc({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:o}){const i=l.useRef(null),c=l.useRef(null),u=l.useRef(null),[m,d]=l.useState(null),[h,f]=l.useState(""),[,y]=l.useState(!1),[b,x]=l.useState([]),j=l.useRef(0),[k,p]=l.useState(!1),[w,S]=l.useState(!1),v=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[g,C]=l.useState(v?"mouse":"touch"),[I,N]=l.useState(1),_=l.useRef(!1),[D,A]=l.useState(1),[M,R]=l.useState(0),[z,T]=l.useState(0);Rr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:g,zoom:D,panX:M,panY:z,isMenuOpen:k,isImeOpen:w});const L=l.useRef(0),B=l.useRef(D),O=l.useRef(M),$=l.useRef(z);l.useEffect(()=>{B.current=D},[D]),l.useEffect(()=>{O.current=M},[M]),l.useEffect(()=>{$.current=z},[z]),l.useEffect(()=>{var de;(de=i.current)==null||de.focus()},[]);const E=r==="connected",W=n,J=E?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",Q=E?"The remote stream is warming up":"Waiting for the remote stream to catch up";l.useEffect(()=>{if(!v||_.current||!W)return;const de=u.current,ye=c.current;if(!de||!ye)return;const xe=()=>{const ge=ye.clientWidth,le=ye.clientHeight,be=de.naturalWidth,ie=de.naturalHeight;if(!be||!ie||!ge||!le)return;const P=Math.min(ge/be,le/ie),Ce=Math.max(ge/be,le/ie)/P;Ce>1.01&&(N(Ce),A(Ce),B.current=Ce),_.current=!0};de.complete&&de.naturalWidth?xe():de.addEventListener("load",xe,{once:!0})},[W,v]);const ee=.5;l.useEffect(()=>{D<=ee&&(R(0),T(0))},[D,ee]);const me=(de,ye,xe)=>{if(xe<=ee)return{x:0,y:0};const ge=(xe-1)/(2*xe)*100,le=(xe-1)/(2*xe)*100;return{x:Math.max(-ge,Math.min(ge,de)),y:Math.max(-le,Math.min(le,ye))}},je=(de,ye)=>{if(!u.current)return null;const xe=u.current.getBoundingClientRect();return!xe.width||!xe.height?null:{nx:Math.max(0,Math.min(1,(de-xe.left)/xe.width)),ny:Math.max(0,Math.min(1,(ye-xe.top)/xe.height))}},Me=(de,ye,xe)=>{const ge=c.current;if(!ge)return;const le=ge.getBoundingClientRect(),be=++j.current;x(ie=>[...ie,{id:be,x:de-le.left,y:ye-le.top,type:xe}]),setTimeout(()=>x(ie=>ie.filter(P=>P.id!==be)),600)},q=(de,ye,xe)=>{const ge=u.current,le=c.current;if(!ge||!le)return;const be=ge.getBoundingClientRect(),ie=le.getBoundingClientRect(),P=ge.naturalWidth||be.width,fe=ge.naturalHeight||be.height,Ce=P/fe,_e=be.width/be.height;let se,De,Te,Ee;Ce>_e?(se=be.width,De=be.width/Ce,Te=0,Ee=(be.height-De)/2):(De=be.height,se=be.height*Ce,Te=(be.width-se)/2,Ee=0);const Oe=be.left-ie.left+Te+se*de,Je=be.top-ie.top+Ee+De*ye,qe=++j.current;x(Ze=>[...Ze,{id:qe,x:Oe,y:Je,type:xe}]),setTimeout(()=>x(Ze=>Ze.filter(et=>et.id!==qe)),600)},G=async de=>{var xe;const ye=je(de.clientX,de.clientY);if(ye){d(`Click: ${Math.round(ye.nx*100)}%, ${Math.round(ye.ny*100)}%`),Me(de.clientX,de.clientY,"left"),(xe=i.current)==null||xe.focus();try{const ge=await e("input_click",{nx:ye.nx,ny:ye.ny});ge!=null&&ge.success||t(`❌ Click failed: ${ge==null?void 0:ge.error}`)}catch(ge){t(`❌ Click error: ${ge.message||ge}`)}}},he=async(de,ye,xe,ge=0)=>{try{await e("input_key",{type:xe?"char":"keyDown",key:de,code:ye,text:xe?de:void 0,unmodifiedText:xe?de:void 0,modifiers:ge})}catch(le){t(`❌ Key error: ${le.message||le}`)}},ue=async de=>{if(de.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(de.key)&&de.preventDefault();let xe=0;de.altKey&&(xe|=1),de.ctrlKey&&(xe|=2),de.metaKey&&(xe|=4),de.shiftKey&&(xe|=8),d(`Key: ${de.key}`),await he(de.key,de.code,de.key.length===1,xe)},ce=async de=>{if(de.key==="Enter"){if(de.nativeEvent.isComposing)return;if(h){const ye=h;f(""),d(`IME Sent: ${ye}`);try{const xe=await e("input_type",{text:ye});xe!=null&&xe.success||t(`❌ IME error: ${xe==null?void 0:xe.error}`)}catch(xe){t(`❌ IME error: ${xe.message}`)}}else d("Key: Enter"),await he("Enter","Enter",!1)}};l.useEffect(()=>{const de=i.current;if(!de)return;const ye=xe=>{var ge;if((ge=u.current)!=null&&ge.contains(xe.target)){xe.preventDefault();const le=Date.now();if(le-L.current<40)return;L.current=le;const be=je(xe.clientX,xe.clientY);if(!be)return;d(`Scroll: ${Math.round(xe.deltaY)}`),e("input_wheel",{nx:be.nx,ny:be.ny,deltaX:Math.round(xe.deltaX),deltaY:Math.round(xe.deltaY)}).catch(()=>{})}};return de.addEventListener("wheel",ye,{passive:!1}),()=>de.removeEventListener("wheel",ye)},[e]);const{cursorPos:ve,handleToggleInputMode:X,handleZoomReset:we}=Ep({containerRef:i,viewportRef:c,imgRef:u,inputMode:g,setInputMode:C,minZoom:ee,zoomRef:B,panXRef:O,panYRef:$,setPanX:R,setPanY:T,setZoom:A,lastWheelTimeRef:L,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:q,clampPan:me,isMobile:v,mobileFillZoom:I});return s.jsxs("div",{ref:i,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ue,onContextMenu:de=>de.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:[W?s.jsx("img",{ref:u,src:W,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${D}) translate(${M}%, ${z}%)`,transformOrigin:"center center",cursor:g==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:G,onContextMenu:de=>de.preventDefault(),onDragStart:de=>de.preventDefault()}):s.jsx(Pp,{waitingLabel:J,waitingHint:Q,transportType:o}),g==="mouse"&&W&&s.jsx(Lp,{cursorPos:ve,viewportRef:c,imgRef:u}),b.map(de=>{const xe={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[de.type];return s.jsxs("div",{style:{position:"absolute",left:de.x,top:de.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${xe}, 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(${xe}, 0.9)`,boxShadow:`0 0 12px rgba(${xe}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},de.id)})]}),s.jsx(Rp,{inputMode:g,onToggleInputMode:X,isImeOpen:w,setIsImeOpen:S,isMenuOpen:k,setIsMenuOpen:p,imeText:h,setImeText:f,handleImeSubmit:ce,isConnActive:E,zoom:D,isMobile:v,mobileFillZoom:I,onZoomOut:()=>A(de=>Math.max(.5,de-.25)),onZoomReset:we,onZoomIn:()=>A(de=>Math.min(5,de+.25)),transportType:o,screenshotUsage:a,lastActionStatus:m}),s.jsx("style",{children:`
7
+ @keyframes slideUp {
8
+ from { opacity: 0; transform: translateY(6px); }
9
+ to { opacity: 1; transform: translateY(0); }
10
+ }
11
+ @keyframes slideUpSidebar {
12
+ from { opacity: 0; transform: translateY(6px); }
13
+ to { opacity: 1; transform: translateY(0); }
14
+ }
15
+ @keyframes click-ripple-ring {
16
+ 0% { transform: scale(0.3); opacity: 1; }
17
+ 100% { transform: scale(2.2); opacity: 0; }
18
+ }
19
+ @keyframes click-ripple-dot {
20
+ 0% { transform: scale(1); opacity: 0.9; }
21
+ 50% { transform: scale(1.8); opacity: 0.6; }
22
+ 100% { transform: scale(0.5); opacity: 0; }
23
+ }
24
+ @keyframes remote-float {
25
+ 0% { transform: translateY(0px); }
26
+ 50% { transform: translateY(-7px); }
27
+ 100% { transform: translateY(0px); }
28
+ }
29
+ `})]})}function Yi(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 $p(e){var t;return Yi(e.activeInteractivePrompt)||Yi((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function Bp(e){return e.sessionId||e.instanceId||e.id}function Op(e,t){for(const r of e){const n=$p(r);if(!n)continue;const a=Bp(r);return{daemonId:r.daemonId||r.id.split(":")[0]||r.id,sessionId:a,routeId:r.id,providerType:r.type,title:r.title||r.cliName||r.type,prompt:n}}return null}function Jc(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(u=>u.trim()).filter(Boolean))),c=(n=o.freeformText)==null?void 0:n.trim();r[a.questionId]={selectedLabels:i,...c?{freeformText:c}:{}}}return{promptId:e.promptId,answers:r}}function Xi(e){const t={};for(const r of(e==null?void 0:e.prompt.questions)||[])t[r.questionId]={selectedLabels:[],freeformText:""};return t}function Fp(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 Hp({label:e,description:t,selected:r,disabled:n,onClick:a}){return s.jsx("button",{type:"button",disabled:n,onClick:a,className:`w-full text-left rounded-md border px-3 py-2 transition ${r?"border-accent-primary bg-accent-primary/15 text-text-primary":"border-border-primary bg-surface-secondary text-text-secondary hover:bg-surface-tertiary hover:text-text-primary"} ${n?"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 rounded-full border ${r?"border-accent-primary bg-accent-primary text-accent-on-primary":"border-border-secondary"}`,children:r?s.jsx(Hc,{size:12}):null}),s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block text-sm font-semibold leading-5",children:e}),t&&s.jsx("span",{className:"mt-0.5 block text-xs leading-5 text-text-muted",children:t})]})]})})}function Wp({promptSession:e,isSubmitting:t=!1,error:r,onSubmit:n,onCancel:a}){const[o,i]=l.useState(()=>Xi(e));l.useEffect(()=>{i(Xi(e))},[e==null?void 0:e.prompt.promptId]);const c=l.useMemo(()=>e?e.prompt.questions.every(f=>Fp(f,o[f.questionId])):!1,[e,o]);if(!e)return null;const u=(f,y)=>{i(b=>{const x=b[f.questionId]||{selectedLabels:[]},j=x.selectedLabels||[],k=f.multiSelect?j.includes(y)?j.filter(p=>p!==y):[...j,y]:[y];return{...b,[f.questionId]:{...x,selectedLabels:k}}})},m=(f,y)=>{i(b=>({...b,[f]:{...b[f]||{selectedLabels:[]},freeformText:y}}))},d=()=>{!c||t||n(o)},h=Jc(e.prompt,o);return s.jsx("div",{className:"fixed inset-0 z-[80] flex items-center justify-center bg-black/50 px-4 py-6",children:s.jsxs("div",{className:"w-full max-w-2xl overflow-hidden rounded-lg border border-border-primary bg-surface-primary shadow-2xl",children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 border-b border-border-primary px-5 py-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-normal text-status-warning",children:[s.jsx(Fs,{size:15})," Action Required"]}),s.jsx("h2",{className:"mt-1 text-lg font-bold text-text-primary",children:e.title||e.providerType})]}),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(gt,{size:16})})]}),s.jsxs("div",{className:"max-h-[70vh] space-y-5 overflow-auto px-5 py-4",children:[e.prompt.questions.map((f,y)=>{var x;const b=h.answers[f.questionId];return s.jsxs("section",{className:"space-y-3",children:[s.jsxs("div",{children:[f.header&&s.jsx("div",{className:"mb-1 text-xs font-semibold uppercase tracking-normal text-text-muted",children:f.header}),s.jsxs("div",{className:"text-sm font-semibold text-text-primary",children:[e.prompt.questions.length>1?`${y+1}. `:"",f.question]})]}),s.jsx("div",{className:"grid gap-2",children:f.options.map(j=>s.jsx(Hp,{label:j.label,description:j.description||j.preview,selected:b.selectedLabels.includes(j.label),disabled:t,onClick:()=>u(f,j.label)},j.label))}),f.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:((x=o[f.questionId])==null?void 0:x.freeformText)||"",disabled:t,onChange:j=>m(f.questionId,j.currentTarget.value),className:"w-full min-h-20 rounded-md border border-border-primary bg-surface-secondary px-3 py-2 text-sm text-text-primary outline-none focus:border-accent-primary"})]})]},f.questionId)}),r&&s.jsx("div",{className:"rounded-md border border-status-error/30 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:r})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-border-primary px-5 py-4",children:[s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:a,disabled:t,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:d,disabled:!c||t,children:t?"Submitting...":"Submit"})]})]})})}function na(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 u=Math.floor(c/60);if(u<24)return`${u}h${r}`;const m=Math.floor(u/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const Qc=e=>na(e);function Kp(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden,completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function Gs(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating"||e.status==="long_generating"||e.status==="streaming",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function Up(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...Kp(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 Dn(e,t){if(e.sessionId){const r=t.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,completionMarker:"",seenCompletionMarker:""}}function aa(e,t,r){const n=Dn(e,t),a=Gs(e),o=a.isReconnecting,i=a.isConnecting,c=a.isGenerating,u=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||u,d=n.inboxBucket==="working"||c,f=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:f,requiresAction:m,isWorking:d,isReconnecting:o,isConnecting:i,isGenerating:c,isWaiting:u,inboxBucket:m?"needs_attention":d?"working":f?"task_complete":"idle"}}function zp(e,t,r){return aa(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Zc({activeConv:e,onModalButton:t}){const[r,n]=l.useState(null);if(l.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Gs(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(Fs,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((c,u)=>{const m=i(c).toLowerCase(),d=/^(run|approve|accept|yes|allow|always)/.test(m),h=/^(reject|deny|delete|remove|abort)/.test(m),f=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 ${d?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${y&&!f?"opacity-40":"opacity-100"} ${y?"cursor-not-allowed":"cursor-pointer"}`,style:d?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:h?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:f?"⏳ ...":i(c)},u)})})]})]})}const zo="adhdev_controls_bar_visible",po="adhdev:controlsbarvisibilitychange";function ga(e){if(!e)return!1;try{return e.getItem(zo)==="1"}catch{return!1}}function Gp(e,t){if(t)try{t.setItem(zo,e?"1":"0")}catch{}}function Vp(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(po,{detail:{visible:e}}))}function Go(){const[e,t]=l.useState(()=>typeof window>"u"?!1:ga(window.localStorage)),r=l.useRef(e),n=l.useCallback((i,c=!0)=>{r.current=i,t(i),typeof window<"u"&&Gp(i,window.localStorage),c&&Vp(i)},[]);l.useEffect(()=>{const i=u=>{const m=u.detail,d=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:ga(window.localStorage);r.current=d,t(d)},c=u=>{if(u.key!==zo)return;const m=ga(window.localStorage);r.current=m,t(m)};return window.addEventListener(po,i),window.addEventListener("storage",c),()=>{window.removeEventListener(po,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 qp=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Yp(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function Lt(e,t){if(Yp(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":qp.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 fo(e){return Lt(e)==="generating"}function Ji(e,t){return Lt(e,t)==="waiting_approval"}function yt(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Xp(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 ya(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function ed(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 Jp(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 Qp(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Zp(e){return Jp(e.trim().replace(/\.local$/i,""))}function ef(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function td(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&&!Qp(i));if(r&&r!=="Unknown")return Zp(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Mt(e,t={}){return ef(e)||td(e,t)}function sd(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 rd(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 vs(e,t){return sd(e).join(" · ")}function Ir(e){return e.transport==="pty"}function Ds(e){return e.transport==="acp"}function tf(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:yt(e)}function Qi(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),i=yt(r||"").trim().toLowerCase();return n===a||n===o||n===i}function sf(e,t=[],r=[]){var u,m,d,h;const n=Lt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(n==="waiting_approval")return"waiting_approval";if(n==="generating")return"generating";const a=t.find(f=>Ji(f.status,{activeModal:f.activeModal})||fo(f.status));if(a)return Lt(a.status,{activeModal:a.activeModal});const o=r.find(f=>Ji(f.status,{activeModal:f.activeModal})||fo(f.status));if(o)return Lt(o.status,{activeModal:o.activeModal});if(n&&n!=="idle")return n;const i=Lt((u=t[0])==null?void 0:u.status,{activeModal:(m=t[0])==null?void 0:m.activeModal});if(i!=="idle")return i;const c=Lt((d=r[0])==null?void 0:d.status,{activeModal:(h=r[0])==null?void 0:h.activeModal});return c!=="idle"?c:"idle"}function rf(e){return Lt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function nf(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),o=t.get(a),i=Lt(n.status);if(!o){t.set(a,{...n,status:i});continue}const c=r.indexOf(o.status||"idle"),u=r.indexOf(i||"idle");u>=0&&(c<0||u<c)&&t.set(a,{...n,status:i})}return Array.from(t.values())}function af(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 of(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&&af(t.receivedAt)||0}function lf(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function xo(e){return Math.max(lf(e),of(e.activeChat))}function cf(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 Vo(e,t){return cf(xo(e),xo(t),Mt(e,{fallbackId:e.id}),Mt(t,{fallbackId:t.id}),e.id,t.id)}const nd="adhdev_notification_prefs",Zi={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function df(){try{const e=localStorage.getItem(nd);if(e){const t=JSON.parse(e);return{...Zi,...t}}}catch{}return{...Zi}}function uf(e){try{localStorage.setItem(nd,JSON.stringify(e))}catch{}}let Vt=df(),vn=[];function mf(){vn.forEach(e=>e())}function hf(e){Vt={...Vt,...e},uf(Vt),mf()}function pf(){const[,e]=l.useState(0);l.useEffect(()=>{const r=()=>e(n=>n+1);return vn.push(r),()=>{vn=vn.filter(n=>n!==r)}},[]);const t=l.useCallback(r=>{hf(r)},[]);return[{...Vt},t]}function br(e){if(!Vt.globalEnabled)return!1;switch(e){case"disconnect":return Vt.disconnectAlert;case"completion":return Vt.completionAlert;case"approval":return Vt.approvalAlert;case"browser":return Vt.browserNotifications;default:return!0}}const ff={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function ad(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function od(){return"Notification"in window&&Notification.permission==="granted"}let ls=null;function xf(e){return e!==!1}async function bf(){if(ls!==null)return ls;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return ls=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(ls=!!await e.pushManager.getSubscription(),ls):(ls=!1,!1)}catch{return ls=!1,!1}}function bo(e,t,r){if(od())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 gf(e,t={}){const r={...ff,...t},n=l.useRef(new Map),a=l.useRef(0),[o,i]=l.useState(null);l.useEffect(()=>{let u=!1;return bf().then(m=>{u||i(m)}),()=>{u=!0}},[]);const c=l.useCallback((u,m,d)=>{const h=Date.now();h-a.current<r.throttleMs||(a.current=h,bo(u,m,d))},[r.throttleMs]);l.useEffect(()=>{var u;if(!(!r.enabled||!od())&&br("browser")&&!xf(o)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,Lt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const d=n.current.get(m.id),h=Lt(m.status,{activeModal:m.activeModal}),f=m.name||m.id;if(r.onApproval&&br("approval")&&h==="waiting_approval"&&d!=="waiting_approval"){const y=((u=m.activeModal)==null?void 0:u.message)||"Action requires your approval";c(`🔔 ${f} — Approval needed`,y.slice(0,120),`approval-${m.id}`)}r.onComplete&&br("completion")&&fo(d)&&h==="idle"&&c(`✅ ${f} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&h==="error"&&d!=="error"&&c(`⚠️ ${f} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,h)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,c])}const yf=/^(run|approve|accept|yes|allow|always)/,vf=/^(run|approve|accept|yes|allow|always|proceed|save)/,wf=/^(reject|deny|delete|remove|abort|cancel|no)/;function qo(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function jf(e){const t=qo(e).toLowerCase();return yf.test(t)?"primary":wf.test(t)?"danger":"default"}function kf(e){return vf.test(qo(e).toLowerCase())?"approve":"reject"}function Sf(e){return e.map((t,r)=>({label:qo(t),variant:jf(t),action:kf(t),button:t,buttonIndex:r}))}function Nf(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Cf(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 If{constructor(){Ue(this,"dedupMap",new Map);Ue(this,"DEDUP_WINDOW_MS",5e3);Ue(this,"DEDUP_MAX_SIZE",50);Ue(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ue(this,"toastCallbacks",[]);Ue(this,"statusEventCallbacks",[]);Ue(this,"resolveActionFn",null);Ue(this,"viewRequestRespondFn",null);Ue(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,o]of this.dedupMap)r-o>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(o=>o.id===t.daemonId&&o.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const o=this.ides.find(i=>i.id===a&&i.type==="adhdev-daemon");if(o)return o}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}handleRawEvent(t,r){var b;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 x of this.statusEventCallbacks)x(t);const u=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(u==null?void 0:u.type)||"";let d=yt(m);const h=this.resolveOwningDaemon(t);if(h){const x=Mt(h,{fallbackId:h.id});x&&(d=!m||m==="adhdev-daemon"?x:`${x}/${d}`)}let f="",y="info";if(t.event==="agent:generating_completed"){const x=t.duration?` (${t.duration}s)`:"";f=`✅ ${d} agent task completed${x}`,y="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started")if(t.event==="agent:waiting_approval"){if(f=`⚡ ${d} approval needed`,y="warning",(b=t.modalButtons)!=null&&b.length&&this.resolveActionFn){const x=this.resolveActionRouteTarget(t);if(!x)return;const j=this.resolveActionFn,k=Sf(t.modalButtons).map(S=>({label:S.label,variant:S.variant,onClick:()=>{j(x,"resolve_action",{action:S.action,button:S.button,buttonIndex:S.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),p=Nf(d,t.modalMessage,f),w=Date.now();this.emitToast({id:w,message:p,type:y,timestamp:w,targetKey:n||x,actions:k,duration:15e3}),f=""}}else if(t.event==="monitor:long_generating"){const x=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";f=`⚠️ ${d} agent is taking a long time${x}`,y="warning",br("browser")&&!document.hasFocus()&&bo(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${x.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const x=t.requesterName||"A team member",j=t.requestId,k=t.orgId;if(f=`👁️ ${x} wants to view your session`,y="warning",j&&k&&this.viewRequestRespondFn){const p=Date.now(),w=Cf(k,j,this.viewRequestRespondFn,(S,v)=>console.error(`[EventManager] ${S} view request failed:`,v));this.emitToast({id:p,message:f,type:y,timestamp:p,actions:w,duration:3e4}),f=""}br("browser")&&!document.hasFocus()&&bo("👁️ View Request",`${x} wants to view your session`,`view-request-${j}`)}else t.event==="team:view_request_approved"?(f="✅ View request approved",y="success"):t.event==="team:view_request_rejected"&&(f=`❌ ${t.targetName||"Team member"} declined your view request`,y="warning");if(f){const x=Date.now();this.emitToast({id:x,message:f,type:y,timestamp:x,targetKey:n||t.daemonId,duration:5e3})}}}const Qe=new If,el=new Map;function En(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Es(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function oa(e){return En(e)?En(e.result)?e.result:e:null}function Mf(e){const t=oa(e);return!t||!En(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function en(e){const t=oa(e);return!t||!En(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function er(e){const t=oa(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function tn(e){const t=oa(e);return!!t&&t.success===!1}function Af(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";Qe.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";Qe.showToast(n.notification.body,a)}}}function Tf(e,t){return e&&Es(e.currentValue)?e.currentValue:t}function _f(e,t){return Es(t)?Es(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Lf(e,t){var o,i;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if(Es(c))return c}const n=(o=t.controlValues)==null?void 0:o[e];if(Es(n))return n;const a=(i=t.defaultValues)==null?void 0:i[e];return Es(a)?a:void 0}function wn(e,t){return e.options||t[e.id]||[]}const Rf={antigravity:new Set(["new_session"]),"claude-cli":new Set(["compact","new_session"]),"claude-code-vscode":new Set(["new_session"]),codex:new Set(["new_session"])};function Pf(e,t,r){var n;return((n=Rf[t])==null?void 0:n.has(r.id))===!0}function Yo(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Pf(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function va(e,t){return{value:t}}function Df(e,t,r){var a;return r?((a=wn(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const Ef={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function $f({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:i}){const{sendCommand:c}=ot(),u=`${e}:${t||n}`,m=Ef[n]||"#94a3b8",[d,h]=l.useState({}),f=l.useRef({}),y=l.useRef(i);f.current=d,y.current=i;const b=l.useRef(0),x={};for(const L of o||[])L.defaultValue!==void 0&&(x[L.id]=L.defaultValue);const j={...x,...i||{},...Date.now()<b.current?d:{}};l.useEffect(()=>{i&&Date.now()>b.current&&h({})},[i]);const[k,p]=l.useState(el.get(u)||{}),[w,S]=l.useState(null),[v,g]=l.useState(null),C=l.useCallback(async(L,B={})=>{const O={...B,...t&&{targetSessionId:t}};return await c(e,L,O)},[e,t,c]),I=l.useCallback(async(L,B={})=>{const O=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await C("invoke_provider_script",{...O,scriptName:L,...B})},[C,n,r,t]),N=l.useCallback((L,B,O)=>{const $=Tf(O,B);h(E=>({...E,[L.id]:$})),Af(O==null?void 0:O.effects)},[]),_=l.useCallback((L,B)=>{h(O=>{const $={...O};return B===void 0?delete $[L.id]:$[L.id]=B,$}),b.current=0},[]);if(!o||o.length===0)return null;const D=Yo(o,{hostIdeType:r,providerType:n});if(D.length===0)return null;const A=async L=>{if(w===L.id){S(null);return}if(wn(L,k).length>0){S(L.id);return}if(L.dynamic&&L.listScript){g(L.id);try{const O=await I(L.listScript,{}),$=Mf(O);if(!$){const J=er(O);J&&Qe.showToast(J,"warning");return}const E=$.options;p(J=>{const Q={...J,[L.id]:E};return el.set(u,Q),Q});const W=Lf(L.id,{localOverrideUntil:b.current,localValues:f.current,controlValues:y.current,defaultValues:x});if(_f(W,$.currentValue)){const J=$.currentValue;h(Q=>({...Q,[L.id]:J}))}S(L.id)}catch(O){const $=O instanceof Error?O.message:`Could not load ${L.label}`;Qe.showToast($,"warning")}finally{g(null)}}},M=async(L,B)=>{S(null);const O=(i==null?void 0:i[L.id])??x[L.id];h($=>({...$,[L.id]:B})),b.current=Date.now()+5e3;try{if(!L.setScript)return;const $=await I(L.setScript,va(L,B)),E=en($);if(E&&!E.ok||tn($))throw new Error((E==null?void 0:E.error)||er($)||`Could not update ${L.label}`);N(L,B,E)}catch($){_(L,O);const E=$ instanceof Error?$.message:`Could not update ${L.label}`;Qe.showToast(E,"warning")}},R=async L=>{const B=wn(L,k).map(Q=>Q.value);if(B.length===0)return;const O=String(j[L.id]||""),E=(B.indexOf(O)+1)%B.length,W=B[E];if(typeof W!="string")return;const J=(i==null?void 0:i[L.id])??x[L.id];h(Q=>({...Q,[L.id]:W})),b.current=Date.now()+5e3;try{if(!L.setScript)return;const Q=await I(L.setScript,va(L,W)),ee=en(Q);if(ee&&!ee.ok||tn(Q))throw new Error((ee==null?void 0:ee.error)||er(Q)||`Could not update ${L.label}`);N(L,W,ee)}catch(Q){_(L,J);const ee=Q instanceof Error?Q.message:`Could not update ${L.label}`;Qe.showToast(ee,"warning")}},z=async L=>{const O=!j[L.id],$=(i==null?void 0:i[L.id])??x[L.id];h(E=>({...E,[L.id]:O})),b.current=Date.now()+5e3;try{if(!L.setScript)return;const E=await I(L.setScript,va(L,O)),W=en(E);if(W&&!W.ok||tn(E))throw new Error((W==null?void 0:W.error)||er(E)||`Could not update ${L.label}`);N(L,O,W)}catch(E){_(L,$);const W=E instanceof Error?E.message:`Could not update ${L.label}`;Qe.showToast(W,"warning")}},T=async L=>{if(!L.invokeScript)return;if(L.confirmMessage){const O=[L.confirmTitle,L.confirmMessage,L.confirmLabel].filter(E=>typeof E=="string"&&E.trim().length>0);if(!window.confirm(O.join(`
30
+
31
+ `)))return}const B=(i==null?void 0:i[L.id])??x[L.id];try{const O=await I(L.invokeScript),$=en(O);if($&&!$.ok||tn(O))throw new Error(($==null?void 0:$.error)||er(O)||`Could not run ${L.label}`);$&&N(L,B??!0,$)}catch(O){_(L,B);const $=O instanceof Error?O.message:`Could not run ${L.label}`;Qe.showToast($,"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}),D.map(L=>{const B=String(j[L.id]||""),O=Df(L,k,B),$=w===L.id,E=v===L.id,W=wn(L,k),J="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(L.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${J} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:$?`${m}55`:"var(--border-default)",background:$?`${m}10`:"var(--surface-tertiary)",color:B?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void A(L),title:L.label,children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:E?"Loading…":O||L.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),$&&W.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>S(null)}),s.jsxs("div",{className:"absolute bottom-full left-0 z-[60] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[s.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:L.label}),W.map(Q=>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:Q.value===B?`${m}14`:"transparent",color:Q.value===B?"var(--text-primary)":"var(--text-secondary)",borderLeft:Q.value===B?`2px solid ${m}`:"2px solid transparent"},title:Q.description||Q.label,onMouseEnter:ee=>{ee.currentTarget.style.background=`${m}10`},onMouseLeave:ee=>{ee.currentTarget.style.background=Q.value===B?`${m}14`:"transparent"},onClick:()=>void M(L,Q.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:Q.label}),Q.value===B&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},Q.value))]})]})]},L.id);case"cycle":return s.jsxs("button",{type:"button",className:`${J} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:B?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void R(L),title:`Click to cycle: ${W.map(Q=>Q.label).join(" → ")}`,children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:O||L.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},L.id);case"toggle":return s.jsxs("button",{type:"button",className:`${J} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:B?`${m}44`:"var(--border-default)",background:B?`${m}14`:"var(--surface-tertiary)",color:B?m:"var(--text-muted)"},onClick:()=>void z(L),"aria-pressed":!!B,children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),L.label]},L.id);case"action":return s.jsxs("button",{type:"button",className:`${J} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void T(L),children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:L.resultDisplay==="inline"&&B?`${L.label}: ${B}`:L.label})]},L.id);case"display":return s.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:B?"var(--text-primary)":"var(--text-muted)"},children:[L.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:L.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:B?`${L.label}: ${B}`:L.label})]},L.id);default:return null}})]})})}function Bf({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:c,controlValues:u}){const{isVisible:m}=Go(),d=Yo(c,{hostIdeType:a,providerType:o});return!e||t||d.length===0||!m?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx($f,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:d,controlValues:u})})}const tr=5,id=10*1024*1024;function Of({hasDraft:e,isBusy:t=!1}){return!e||t}function Ff(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 Hf(e){if(e.size>id)return null;const t=await Ff(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 Wf(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const ld=l.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,onSend:i,onForceSend:c,canForceSend:u=!1,isActive:m=!0,showControlsToggle:d=!1,animateVisibility:h=!0,onControlsToggle:f,messageInput:y}){const b=l.useRef(null),x=l.useRef(null),[j,k]=l.useState(""),[p,w]=l.useState([]),[S,v]=l.useState(null),[g,C]=l.useState(!1),I=l.useRef(!1),{isVisible:N,toggleVisibility:_}=Go(),D=Wf(y),A=!!j.trim()||p.length>0;l.useEffect(()=>{k(""),w([]),v(null)},[t]),l.useEffect(()=>{var $;m&&(($=b.current)==null||$.focus({preventScroll:!0}))},[t,m]),l.useEffect(()=>{const $=b.current;$&&($.style.height="auto",$.style.height=`${Math.min($.scrollHeight,160)}px`)},[j]);const M=l.useCallback(async $=>{v(null);const E=Array.from($).filter(je=>je.type.startsWith("image/"));if(E.length===0)return;const W=tr-p.length;if(W<=0){v(`Max ${tr} images`);return}const J=E.slice(0,W);if(J.filter(je=>je.size>id).length>0){v("Image too large (max 10 MB)");return}const me=(await Promise.all(J.map(Hf))).filter(je=>je!==null);w(je=>[...je,...me])},[p.length]),R=l.useCallback($=>{w(E=>E.filter((W,J)=>J!==$))},[]),z=l.useCallback(async()=>{const $=j.trim();if(!$&&p.length===0||a||I.current)return;I.current=!0;const E=p.length>0?[...p]:void 0;try{await i($,E)!==!1&&(k(""),w([]),v(null))}finally{I.current=!1}},[j,p,a,i]),T=l.useCallback(async()=>{if(!u||!c)return;const $=j.trim();if(!$&&p.length===0||I.current)return;I.current=!0;const E=p.length>0?[...p]:void 0;try{await c($,E)!==!1&&(k(""),w([]),v(null))}finally{I.current=!1}},[p,u,j,c]),L=l.useCallback($=>{D&&($.preventDefault(),C(!0))},[D]),B=l.useCallback(()=>C(!1),[]),O=l.useCallback($=>{D&&($.preventDefault(),C(!1),$.dataTransfer.files.length>0&&M($.dataTransfer.files))},[D,M]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",h?"transition-all duration-200 ease-out":"",g?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:m?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:m?200:0,opacity:m?1:0,transform:m?"translateY(0)":"translateY(10px)",padding:m?"10px 12px":"0 12px",pointerEvents:m?"auto":"none"},"aria-hidden":!m,onDragOver:L,onDragLeave:B,onDrop:O,children:[p.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:p.map(($,E)=>s.jsxs("div",{className:"relative group w-14 h-14 rounded-lg overflow-hidden border border-border-subtle shrink-0",style:{background:"var(--surface-secondary)"},children:[s.jsx("img",{src:$.previewUrl,alt:$.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>R(E),className:"absolute top-0.5 right-0.5 w-4 h-4 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-[10px] leading-none","aria-label":`Remove ${$.name}`,children:"✕"})]},E))}),s.jsxs("div",{className:"flex gap-2 items-center",title:m?`Send message to ${r}`:void 0,children:[d&&s.jsx("button",{type:"button",onClick:()=>{_(),f==null||f()},"aria-label":N?"Hide controls":"Show controls","aria-pressed":N,title:N?"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"})]})}),D&&s.jsxs(s.Fragment,{children:[s.jsx("input",{ref:x,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:$=>{$.target.files&&M($.target.files),$.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var $;return($=x.current)==null?void 0:$.click()},disabled:p.length>=tr,title:p.length>=tr?`Max ${tr} 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:b,rows:1,placeholder:o||(D&&p.length>0?"Add a message (optional)...":`Send message to ${r}... (Shift+Enter for newline)`),value:j,onChange:$=>k($.target.value),onPaste:$=>{D&&$.clipboardData.files.length>0&&Array.from($.clipboardData.files).some(W=>W.type.startsWith("image/"))&&($.preventDefault(),M($.clipboardData.files))},onKeyDown:$=>{$.key==="Enter"&&($.nativeEvent.isComposing||$.shiftKey||($.preventDefault(),z()))},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:()=>{z()},disabled:Of({hasDraft:A,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${A&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:A&&!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:A?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})}),u&&s.jsx("button",{type:"button",onClick:()=>{T()},disabled:!A,className:`h-10 px-3 rounded-full text-[11px] font-medium border border-border-subtle shrink-0 transition-colors ${A?"bg-bg-secondary text-text-primary hover:bg-[var(--surface-tertiary)]":"bg-bg-secondary text-text-muted cursor-default opacity-60"}`,"aria-label":"Force send message now",title:"Force send message now",children:"Force"})]}),(S||D&&g)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${S?"text-red-400":"text-[var(--accent-primary)]"}`,children:S||"Drop image here"}),o&&!S&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:o})]})});function tl(e){if(!e||!Number.isFinite(e))return"—";try{return`${new Date(e).toLocaleString()} (${e})`}catch{return String(e)}}function sl(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 Kf({sessionId:e,daemonId:t,onClose:r}){const{sendCommand:n}=ot(),[a,o]=l.useState(!0),[i,c]=l.useState(null),[u,m]=l.useState(null),d=l.useCallback(async()=>{o(!0),m(null);try{const h=await n(t,"get_session_info",{targetSessionId:e}),f=h&&typeof h=="object"?h:{},y=f.result&&typeof f.result=="object"?f.result:f;y!=null&&y.success?c(y):(m((y==null?void 0:y.error)||"Failed to load session info"),c(null))}catch(h){m((h==null?void 0:h.message)||String(h)),c(null)}finally{o(!1)}},[n,t,e]);return l.useEffect(()=>{d()},[d]),l.useEffect(()=>{const h=f=>{f.key==="Escape"&&r()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[r]),s.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Session info",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onClick:r,style:{pointerEvents:"auto"},children:s.jsxs("div",{className:"bg-[var(--surface-primary)] text-text-primary border border-border-default rounded-lg shadow-xl max-w-2xl w-full max-h-[85vh] flex flex-col",onClick:h=>h.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-border-subtle px-4 py-3",children:[s.jsx("h2",{className:"text-base font-semibold",children:"Session info"}),s.jsx("button",{type:"button",onClick:r,className:"text-text-secondary hover:text-text-primary px-2 py-1 rounded","aria-label":"Close",children:"×"})]}),s.jsxs("div",{className:"overflow-y-auto px-4 py-3 text-sm space-y-4",children:[a&&s.jsx("div",{className:"text-text-secondary",children:"Loading…"}),u&&s.jsx("div",{className:"text-red-500",children:u}),(i==null?void 0:i.session)&&s.jsxs(rl,{title:"Session",children:[s.jsx(Pt,{k:"Session ID",v:s.jsx(sr,{children:i.session.sessionId})}),s.jsx(Pt,{k:"Provider",v:`${i.session.providerName||i.session.providerType} (${i.session.providerType})`}),i.session.transport&&s.jsx(Pt,{k:"Transport",v:i.session.transport}),i.session.workspace&&s.jsx(Pt,{k:"Workspace",v:s.jsx(sr,{children:i.session.workspace})}),s.jsx(Pt,{k:"Spawned at",v:s.jsxs(s.Fragment,{children:[tl(i.session.spawnedAtMs),i.session.spawnedAtMs?s.jsx("span",{className:"text-text-secondary ml-2",children:sl(i.session.spawnedAtMs)}):null]})}),i.session.providerSessionId&&s.jsx(Pt,{k:"Provider session ID",v:s.jsx(sr,{children:i.session.providerSessionId})})]}),(i==null?void 0:i.coordinator)&&s.jsxs(rl,{title:"Mesh coordinator",children:[s.jsx(Pt,{k:"Mesh ID",v:s.jsx(sr,{children:i.coordinator.meshId})}),i.coordinator.cliType&&s.jsx(Pt,{k:"Coordinator CLI",v:i.coordinator.cliType}),s.jsx(Pt,{k:"Started at",v:s.jsxs(s.Fragment,{children:[tl(i.coordinator.startedAt),i.coordinator.startedAt?s.jsx("span",{className:"text-text-secondary ml-2",children:sl(i.coordinator.startedAt)}):null]})}),i.coordinator.injection&&s.jsx(Pt,{k:"Prompt injection",v:`${i.coordinator.injection.mode}${i.coordinator.injection.target?` → ${i.coordinator.injection.target}`:""}`}),i.coordinator.mcpConfigPath&&s.jsx(Pt,{k:"MCP config",v:s.jsx(sr,{children:i.coordinator.mcpConfigPath})}),i.coordinator.extraSystemPrompt&&s.jsx(nl,{title:"Per-launch extra prompt",body:i.coordinator.extraSystemPrompt,defaultOpen:!0}),i.coordinator.systemPrompt&&s.jsx(nl,{title:"Final system prompt (click to expand)",body:i.coordinator.systemPrompt})]}),i&&!i.coordinator&&s.jsx("div",{className:"text-text-secondary italic",children:"This isn't a mesh coordinator session, so no coordinator-specific prompt was injected. The agent runs with whatever defaults its CLI ships with."})]}),s.jsxs("div",{className:"border-t border-border-subtle px-4 py-2 flex justify-end gap-2",children:[s.jsx("button",{type:"button",onClick:()=>void d(),className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:"px-3 py-1 text-sm rounded bg-accent text-white hover:opacity-90",children:"Close"})]})]})})}function rl({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 Pt({k:e,v:t}){return s.jsxs("div",{className:"flex gap-3",children:[s.jsx("div",{className:"w-44 shrink-0 text-text-secondary",children:e}),s.jsx("div",{className:"min-w-0 break-all",children:t})]})}function sr({children:e}){return s.jsx("code",{className:"font-mono text-xs",children:e})}function nl({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 Uf({sessionId:e,daemonId:t}){const[r,n]=l.useState(!1);return!e||!t?null:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:()=>n(!0),title:"Session info — system prompt, MCP config, spawned at, …","aria-label":"Session info",className:"inline-flex items-center justify-center w-6 h-6 rounded-full text-text-secondary hover:text-text-primary hover:bg-surface-secondary text-sm leading-none",style:{pointerEvents:"auto"},children:"ⓘ"}),r&&s.jsx(Kf,{sessionId:e,daemonId:t,onClose:()=>n(!1)})]})}const Xe=e=>e.transport==="pty",Vs=(e,t)=>Xe(e)?e.mode||"terminal":"chat",cd=(e,t)=>Xe(e)&&Vs(e)==="terminal",Ge=e=>e.transport==="acp",zf=180;function as(e){return e.streamSource!=="agent-stream"}function Ss(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function dd(e){return e.machineName||""}function Pr(e){return Ss(e)}function Ut(e){return e.agentType||""}function $n(e){return e.hostIdeType||""}function Xo(e){return e.displayPrimary||e.agentName||"Agent"}function ud(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Gf(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function md(e){const t=Gf(e),r=Bs(t==null?void 0:t.content),n=Bs(e.lastMessagePreview);return r||n||""}function Vf(e,t=zf){const r=Bs(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 qf(e){return Vf(md(e)||e.displaySecondary||"")}function hd(e){return[e.displaySecondary,dd(e)].filter(Boolean)}function Ws(e){return e.agentName||yt(Ut(e))}function Yf(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 yt($n(e)||Ut(e))}function pd(e){return as(e)?e.sessionId:e.nativeSessionId}function al(e){return as(e)?"native":e.tabKey}function Xf(e){return e.sessionId}function Jf(e,t){if(t)return as(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function Qf(e,t){const r=Ut(e),n=as(e),a=Xe(e)||Ge(e),o=n?a?Ws(e)||(t==null?void 0:t.cliName)||yt($n(e)||r):t!=null&&t.type?yt(t.type):yt($n(e)||r):Ws(e);return{isNativeConversation:n,isCli:Xe(e),isAcp:Ge(e),isCliTerminal:cd(e),providerType:r,displayLabel:o,targetEntry:Jf(e,t)}}function hs(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:Xe(e)||Ge(e)?{agentType:Ut(e)}:e.streamSource==="agent-stream"?{agentType:Ut(e)}:t}function ps(e){return e?Pr(e):""}function rr(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Jo(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function ol(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 fd(){return"select_session"}function Zf(){return"open_panel"}function ex({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function il(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function sn(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function gr(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Qo(e){return e instanceof Error?e.message:String(e||"")}function ll(e){const t=Qo(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function cl(e,t){const r=Qo(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function dl(e,t,r,n={}){const a=hs(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 ia({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,o]=l.useState(!1),[i,c]=l.useState(!1),[u,m]=l.useState(null),d=l.useRef(!1),h=l.useRef(null);l.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const f=l.useCallback(async(k,p)=>{if(!t||d.current)return!1;const w=k.trim(),S=Jo(t);if(ex({hasMessage:!!w,blockedMessage:S,sendInFlight:d.current}))return S&&m(S),!1;const v=Date.now(),g={tabKey:t.tabKey,message:w,timestamp:v};if(il(h.current,g))return m(null),!0;d.current=!0,c(!0),m(null),h.current=g;try{const C=ps(t);if(!C)return h.current=sn(h.current,g),m("Unable to send message right now."),!1;const I=await e(C,"send_chat",dl(w,p,t)),N=gr(I);if(N!=null&&N.deduplicated)return m(null),!0;if((N==null?void 0:N.sent)===!1)throw new Error((N==null?void 0:N.error)||"Send failed");if((N==null?void 0:N.success)===!1)throw new Error((N==null?void 0:N.error)||"Send failed");return m(null),!0}catch(C){const I=Qo(C);return I.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",I):console.warn("Send blocked/failed",C),h.current=sn(h.current,g),m(ol(C)),!1}finally{d.current=!1,c(!1)}},[t,e]),y=l.useCallback(async(k,p)=>{if(!t||d.current)return!1;const w=k.trim();if(!w&&(!p||p.length===0))return!1;const S=Date.now(),v={tabKey:t.tabKey,message:`force:${w}`,timestamp:S};if(il(h.current,v))return m(null),!0;d.current=!0,c(!0),m(null),h.current=v;try{const g=ps(t);if(!g)return h.current=sn(h.current,v),m("Unable to send message right now."),!1;const C=await e(g,"send_chat",dl(w,p,t,{force:!0})),I=gr(C);if((I==null?void 0:I.success)===!1||(I==null?void 0:I.sent)===!1)throw new Error((I==null?void 0:I.error)||"Send failed");return m(null),!0}catch(g){return console.warn("Force send blocked/failed",g),h.current=sn(h.current,v),m(ol(g)),!1}finally{d.current=!1,c(!1)}},[t,e]),b=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]),x=l.useCallback(async k=>{if(t)try{const w=(t.modalButtons||[]).indexOf(k),S=k.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),v=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(S),g=ps(t);if(!g)return;const C=await e(g,"resolve_action",{button:k,action:v?"approve":"reject",...w>=0&&{buttonIndex:w},...hs(t)}),I=gr(C);I.success||r(N=>[...N,{routeId:t.tabKey,text:cl(k,I==null?void 0:I.error),timestamp:Date.now()}])}catch(p){ll(p)||console.error("[ModalButton] Error:",p),r(w=>[...w,{routeId:t.tabKey,text:ll(p)?cl(k,p):`❌ **${k}** error`,timestamp:Date.now()}])}},[t,e,r]),j=l.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,Zf(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(k){console.error("Focus agent failed",k)}finally{o(!1)}}},[t,a,e]);return{isSendingChat:i,sendFeedbackMessage:u,isFocusingAgent:a,handleSendChat:f,handleForceSendChat:y,handleRelaunch:b,handleModalButton:x,handleFocusAgent:j}}const tx=10,sx=8e3,rx=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function nx(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 go(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(rx.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=nx(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=>go(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,go(a,n,r+1)]))}function nr(e,t){return Array.isArray(e)?e.slice(-t):[]}function ax(e,t=Date.now()){const r=e&&t-e.firstAt<=sx,n=r?e.count+1:1;return n>=tx?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function xd(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:nr(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:nr(t.messages,10),visibleMessagesTail:nr(e.visibleMessages,5),historyMessagesTail:nr(e.chatTailState.historyMessages,5),actionLogsTail:nr(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 go(r)}function bd(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 gd(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 yd(e){const t=e&&typeof e=="object"?e:{};if(t.delivery==="daemon_file"){const r=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(t.bundleId||"")}`,`savedPath: ${String(t.savedPath||"")}`,`sizeBytes: ${String(t.sizeBytes||"")}`,`createdAt: ${String(t.createdAt||"")}`];return t.summary&&typeof t.summary=="object"&&r.push("","summary:",JSON.stringify(t.summary,null,2)),Array.isArray(t.warnings)&&t.warnings.length>0&&r.push("","warnings:",...t.warnings.map(n=>`- ${String(n)}`)),r.join(`
32
+ `)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
33
+
34
+ \`\`\`json
35
+ ${JSON.stringify(t.bundle,null,2)}
36
+ \`\`\``:`# ADHDev Chat Debug Bundle
37
+
38
+ \`\`\`json
39
+ ${JSON.stringify(t,null,2)}
40
+ \`\`\``}function wa(e,t){return`${e}:${t}`}function ox(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function ix(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Cs(e,t){ix()&&console.debug(`[subscription-manager] ${e}`,t)}class lx{constructor(){Ue(this,"active",new Map);Ue(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var d,h;const i=wa(n.topic,n.key),c=this.active.get(i);let u=!0;if(c)c.handlers.add(a),(!ox(c.request,n)||c.daemonId!==r)&&(c.daemonId=r,c.request=n,u=((d=t.sendData)==null?void 0:d.call(t,r,n))??!1,!u&&(o!=null&&o.retryIntervalMs)?this.scheduleRetry(i,t,o.retryIntervalMs):u&&this.clearRetry(i),Cs("subscribe_update",{daemonId:r,topic:n.topic,key:n.key,accepted:u})),c.lastUpdate&&a(c.lastUpdate);else{const f={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,f),Cs("subscribe",{daemonId:r,topic:n.topic,key:n.key}),u=((h=t.sendData)==null?void 0:h.call(t,r,n))??!1,!u&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(i,t,o.retryIntervalMs)}const m=()=>{var b;this.clearRetry(i);const f=this.active.get(i);if(!f||(f.handlers.delete(a),f.handlers.size>0))return;this.active.delete(i);const y={type:"unsubscribe",topic:n.topic,key:n.key};Cs("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(b=t.sendData)==null||b.call(t,r,y)};return m.initialSendAccepted=u,m}publish(t){const r=wa(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,$s.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),$s.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=wa(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;Cs("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);Cs("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;Cs("subscribe_retry",{id:t,accepted:i,topic:o.request.topic,key:o.request.key}),i||this.scheduleRetry(t,r,n)},n);this.retryTimers.set(t,a)}clearRetry(t){const r=this.retryTimers.get(t);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(t))}}const zt=new lx;function cx(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 dx(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 ja(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function ux(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function mx(e){ux()&&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 Bn(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:i}=t,c=i||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:m,childrenByParent:d}=dx(u),h=cx(o,n),f=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,y=m.filter(j=>j.kind==="workspace"&&j.transport==="cdp-page"),b=m.filter(j=>j.kind==="agent"&&j.transport==="pty"),x=m.filter(j=>j.kind==="agent"&&j.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:c,...e.version&&{version:e.version},...f&&{machine:f,platform:f.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:y.some(j=>!!j.cdpConnected)});for(const j of y){const k=h.get(j.id),p=mr(j,k),w=(d.get(j.id)||[]).map(S=>mr(S,h.get(S.id)));r.push({id:`${n}:ide:${j.id}`,sessionId:j.id,providerSessionId:j.providerSessionId??(k==null?void 0:k.providerSessionId),parentSessionId:p.parentId,sessionKind:p.kind,transport:p.transport,sessionCapabilities:p.capabilities,type:p.providerType,status:p.cdpConnected?"online":"detected",daemonId:n,instanceId:ja(n,j.id),workspace:p.workspace,terminals:0,childSessions:w,agents:w.map(S=>({id:S.id,name:S.providerName||S.providerType,type:S.providerType,status:S.status})),activeChat:p.activeChat,...p.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:p.activeInteractivePrompt},chats:[],cdpConnected:p.cdpConnected,...p.lastMessagePreview!==void 0&&{lastMessagePreview:p.lastMessagePreview},...p.lastMessageRole!==void 0&&{lastMessageRole:p.lastMessageRole},...p.lastMessageAt!==void 0&&{lastMessageAt:p.lastMessageAt},...p.lastMessageHash!==void 0&&{lastMessageHash:p.lastMessageHash},lastUpdated:p.lastUpdated,unread:p.unread,lastSeenAt:p.lastSeenAt,inboxBucket:p.inboxBucket,completionMarker:p.completionMarker,seenCompletionMarker:p.seenCompletionMarker,surfaceHidden:p.surfaceHidden,...p.controlValues!==void 0&&{controlValues:p.controlValues},...p.providerControls!==void 0&&{providerControls:p.providerControls},...p.summaryMetadata!==void 0&&{summaryMetadata:p.summaryMetadata},...p.settings!==void 0&&{settings:p.settings},...p.messageInput!==void 0&&{messageInput:p.messageInput},timestamp:c})}for(const j of b){const k=h.get(j.id),p=mr(j,k);r.push({id:`${n}:cli:${j.id}`,sessionId:j.id,providerSessionId:j.providerSessionId??(k==null?void 0:k.providerSessionId),parentSessionId:p.parentId,sessionKind:p.kind,transport:p.transport,sessionCapabilities:p.capabilities,type:p.providerType,agentType:p.providerType,status:p.status||"running",daemonId:n,instanceId:ja(n,j.id),cliName:p.providerName||p.providerType,mode:p.mode||(k==null?void 0:k.mode)||"terminal",workspace:p.workspace||"",activeChat:p.activeChat,...p.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:p.activeInteractivePrompt},...p.resume!==void 0&&{resume:p.resume},...p.runtimeKey!==void 0&&{runtimeKey:p.runtimeKey},...p.runtimeDisplayName!==void 0&&{runtimeDisplayName:p.runtimeDisplayName},...p.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:p.runtimeWorkspaceLabel},...p.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:p.runtimeWriteOwner},...p.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:p.runtimeAttachedClients},...p.lastMessagePreview!==void 0&&{lastMessagePreview:p.lastMessagePreview},...p.lastMessageRole!==void 0&&{lastMessageRole:p.lastMessageRole},...p.lastMessageAt!==void 0&&{lastMessageAt:p.lastMessageAt},...p.lastMessageHash!==void 0&&{lastMessageHash:p.lastMessageHash},lastUpdated:p.lastUpdated,unread:p.unread,lastSeenAt:p.lastSeenAt,inboxBucket:p.inboxBucket,completionMarker:p.completionMarker,seenCompletionMarker:p.seenCompletionMarker,surfaceHidden:p.surfaceHidden,...p.controlValues!==void 0&&{controlValues:p.controlValues},...p.providerControls!==void 0&&{providerControls:p.providerControls},...p.summaryMetadata!==void 0&&{summaryMetadata:p.summaryMetadata},...p.settings!==void 0&&{settings:p.settings},...p.messageInput!==void 0&&{messageInput:p.messageInput},timestamp:c,_isCli:!0})}for(const j of x){const k=h.get(j.id),p=mr(j,k);r.push({id:`${n}:acp:${j.id}`,sessionId:j.id,providerSessionId:j.providerSessionId??(k==null?void 0:k.providerSessionId),parentSessionId:p.parentId,sessionKind:p.kind,transport:p.transport,sessionCapabilities:p.capabilities,type:p.providerType,agentType:p.providerType,status:p.status||"running",daemonId:n,instanceId:ja(n,j.id),cliName:p.providerName||p.providerType,mode:"chat",workspace:p.workspace||"",activeChat:p.activeChat,...p.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:p.activeInteractivePrompt},...p.runtimeKey!==void 0&&{runtimeKey:p.runtimeKey},...p.runtimeDisplayName!==void 0&&{runtimeDisplayName:p.runtimeDisplayName},...p.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:p.runtimeWorkspaceLabel},...p.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:p.runtimeWriteOwner},...p.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:p.runtimeAttachedClients},...p.lastMessagePreview!==void 0&&{lastMessagePreview:p.lastMessagePreview},...p.lastMessageRole!==void 0&&{lastMessageRole:p.lastMessageRole},...p.lastMessageAt!==void 0&&{lastMessageAt:p.lastMessageAt},...p.lastMessageHash!==void 0&&{lastMessageHash:p.lastMessageHash},lastUpdated:p.lastUpdated,unread:p.unread,lastSeenAt:p.lastSeenAt,inboxBucket:p.inboxBucket,completionMarker:p.completionMarker,seenCompletionMarker:p.seenCompletionMarker,surfaceHidden:p.surfaceHidden,...p.controlValues!==void 0&&{controlValues:p.controlValues},...p.providerControls!==void 0&&{providerControls:p.providerControls},...p.summaryMetadata!==void 0&&{summaryMetadata:p.summaryMetadata},...p.settings!==void 0&&{settings:p.settings},...p.messageInput!==void 0&&{messageInput:p.messageInput},timestamp:c,_isAcp:!0})}return mx(r),r}const hx=15e3,px=15e3,fx=6e4,xx=1200,ul=12,bx=8e3,gx=4e3,ka=new Map,Sa=new Map,rn=new Set,yr=new Map;function yx(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 ml(e,t){const r=yr.get(e);!r||r.size===0||(yr.delete(e),r.forEach(n=>n(t)))}function vx(e,t){return new Promise(r=>{const n=yr.get(e)||new Set;yr.set(e,n);const a=i=>{clearTimeout(o),n.delete(a),n.size===0&&yr.delete(e),r(i)},o=setTimeout(()=>a(!1),t);n.add(a)})}function Dr(){const{sendCommand:e,sendData:t}=ot(),{injectEntries:r,getIdes:n}=Cr();return l.useCallback(async(a,o)=>{if(!a)return;const i=(o==null?void 0:o.minFreshMs)??fx,c=Sa.get(a)||0;if(!(o!=null&&o.force)&&rn.has(a)&&c>0||!(o!=null&&o.force)&&c>0&&Date.now()-c<i)return;const u=ka.get(a);if(u)return u;const m=(async()=>{if(t&&!rn.has(a)){const x=zt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},j=>{const k=n(),p=k.find(S=>S.id===a),w=Bn(j.status,{daemonId:a,existingDaemon:p,existingEntries:k,timestamp:j.timestamp});w.length>0&&r(w),Sa.set(a,Date.now()),ml(a,!0)});if(x.initialSendAccepted?rn.add(a):rn.delete(a),!(o!=null&&o.force)&&x.initialSendAccepted&&await vx(a,xx))return}const d=await e(a,"get_status_metadata"),h=yx(d);if(!h)return;const f=n(),y=f.find(x=>x.id===a),b=Bn(h,{daemonId:a,existingDaemon:y,existingEntries:f,timestamp:h.timestamp||Date.now()});b.length>0&&r(b,{authoritativeDaemonIds:[a]}),Sa.set(a,Date.now()),ml(a,!0)})().finally(()=>{ka.delete(a)});return ka.set(a,m),m},[n,r,e,t])}function wx(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const jx=60,kx=50;function vd(e={}){return e.isCliLike?kx:jx}function Sx(e={}){return vd(e)}function vt(e){return(typeof e=="string"?e.trim():"")||void 0}function qt(e,t){const r=vt(t);return r?`${e}:${r}`:void 0}function rs(e,t,r){const n=qt(t,r),a=vt(r);n&&e.push(n),a&&e.push(a)}function Rs(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function wd(e){return vt(e.providerSessionId)||vt(e.sessionId)||vt(e.tabKey)||vt(e.routeId)}function la(e){return Rs([vt(e.historySessionId),vt(e.providerSessionId),vt(e.sessionId)])}function Yt(e){const t=[];return rs(t,"provider",e.providerSessionId),rs(t,"session",e.sessionId),rs(t,"tab",e.tabKey),rs(t,"route",e.routeId),Rs(t)}function Nx(e){const t=[];return vt(e.providerSessionId)?(rs(t,"provider",e.providerSessionId),Rs(t)):vt(e.sessionId)?(rs(t,"session",e.sessionId),Rs(t)):vt(e.tabKey)?(rs(t,"tab",e.tabKey),Rs(t)):vt(e.routeId)?(rs(t,"route",e.routeId),Rs(t)):[]}function Mr(e){return qt("provider",e.providerSessionId)||qt("session",e.sessionId)||qt("tab",e.tabKey)||qt("route",e.routeId)||"unknown:"}function Er(e){return la(e)[0]}function Cx(e){const t=vt(e.providerSessionId),r=vt(e.sessionId),n=vt(e.tabKey),a=vt(e.routeId),o=[qt("provider",t),qt("session",r),qt("tab",n),qt("route",a)].filter(u=>typeof u=="string"),i=Yt({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),c=Mr({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:c,targetKey:c,targetValue:wd({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:Er({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:i}}function yo(e,t){const r=Cx(e);return Nx(t).some(n=>r.lookupKeys.includes(n))}const $r=60,Ix=1e3,Zo=12e4,Mx=new Set(["generating","waiting_approval","starting","streaming","working"]),vo=new Map;function ei(e,t,r){return`${e}::${t}::${r||t}`}function On(e=$r){return{liveMessages:[],hasLiveSnapshot:!1,cursor:Ax([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Ax(e,t=$r){return{tailLimit:t}}function hl(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 wo(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(wo).join(`
41
+ `);if(typeof e=="object"){const t=e;return wo(t.text??t.content??t.value??"")}return String(e)}function Tx(e){return wo(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function _x(e){return e.length===0||e.every(Tx)}function Lx(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="generating"||t==="long_generating"||t==="streaming"||t==="working"||t==="starting"}function jd(e,t){return Math.max(Math.max(0,t),Array.isArray(e.liveMessages)?e.liveMessages.length:0)}function Rx(e,t,r,n,a){if(!Lx(n))return!1;const o=jd(e,t);if(o<=0)return!1;if(_x(r))return!0;if(a&&typeof a=="object"){const i=a.selected,c=a.fallbackReason;if(i==="native-history"||typeof c=="string"&&c!==""&&!c.startsWith("native_history_"))return!1}return r.length<o}function Px(e,t,r,n){if(r.length!==0||jd(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 Dx(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}function pl(e,t){const r=e[t];return typeof r=="string"?r:""}class Ex{constructor(t){Ue(this,"manager");Ue(this,"sendData");Ue(this,"daemonId");Ue(this,"sessionId");Ue(this,"historySessionId");Ue(this,"subscriptionKey");Ue(this,"fallbackRecentCount");Ue(this,"snapshot");Ue(this,"transportSubscription",null);Ue(this,"listeners",new Set);Ue(this,"retainCount",0);Ue(this,"loadHistoryPromise",null);Ue(this,"pendingDisconnectTimer",null);this.manager=t.manager||zt,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount??0),this.snapshot=On(Math.max(0,t.tailLimit??$r))}updateOptions(t){const r=this.sendData,n=this.daemonId,a=this.sessionId;if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount)),t.tailLimit!==void 0){const o=Math.max(0,t.tailLimit);o!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:o}},this.transportSubscription&&(this.disconnect(),this.connect()))}this.retainCount>0&&(r!==this.sendData||n!==this.daemonId||a!==this.sessionId)&&(this.disconnect(),this.connect())}getSnapshot(){return this.snapshot}clearLiveSnapshot(){this.snapshot={...On(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;this.snapshot={...this.snapshot,historyMessages:[...i,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+i.length,hasMoreHistory:c?!0:o.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),t=>{this.handleUpdate(t)},{retryIntervalMs:Ix}))}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=pl(t,"sessionId");if(r&&r!==this.sessionId)return;const n=pl(t,"historySessionId");if(n&&this.historySessionId&&n!==this.historySessionId)return;const a=Dx(t),o=t.messageSource;if(Rx(this.snapshot,this.fallbackRecentCount,a,t.status,o)||Px(this.snapshot,this.fallbackRecentCount,a,o))return;const i={tailLimit:this.snapshot.cursor.tailLimit};hl(this.snapshot.liveMessages)===hl(a)&&this.snapshot.cursor.tailLimit===i.tailLimit||(this.snapshot={...this.snapshot,liveMessages:a,hasLiveSnapshot:!0,cursor:i,messageSource:o},this.emit())}}function kd(e){const t=ei(e.daemonId,e.sessionId,e.historySessionId),r=vo.get(t);if(r)return r.updateOptions(e),r;const n=new Ex(e);return vo.set(t,n),n}function $x(e,t,r){if(!e||!t)return;const n=`${e}::${t}::`,a=ei(e,t,r);for(const[o,i]of vo.entries())(o===a||o.startsWith(n))&&i.clearLiveSnapshot()}function Bx(e,t){return{...e,loadHistoryPage:t}}function Ox(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Fx(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Mx.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??Zo)),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 Hx(e=Zo){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Wx(e,t={}){const r=new Set,n=[];for(const a of e){if(!Fx(a,t))continue;const o=Pr(a),i=a.sessionId||"";if(!o||!i)continue;const c=Er(a),u=ei(o,i,c||i);r.has(u)||(r.add(u),n.push({daemonId:o,sessionId:i,historySessionId:c||i,subscriptionKey:`daemon:${o}:session:${i}`}))}return n.sort(Ox),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Kx(e,t){const{sendData:r,sendCommand:n}=ot(),a=(t==null?void 0:t.enabled)!==!1,o=Pr(e),i=e.sessionId||"",c=Er(e)||i,u=`daemon:${o}:session:${i}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??$r),d=l.useMemo(()=>!a||!o||!i?null:kd({daemonId:o,sessionId:i,historySessionId:c,subscriptionKey:u,sendData:r,tailLimit:m,fallbackRecentCount:e.messages.length}),[e.messages.length,o,a,c,r,i,u,m]),[h,f]=l.useState(()=>(d==null?void 0:d.getSnapshot())||On(m));l.useEffect(()=>{if(!d){f(On(m));return}d.retain(),f(d.getSnapshot());const b=d.subscribe(x=>{f(x)});return()=>{b(),d.release()}},[d,m]);const y=l.useCallback(async()=>{!d||!o||!i||await d.loadHistoryPage(async({offset:b,excludeRecentCount:x})=>{const j=e.agentType,k=await n(o,"chat_history",{agentType:j,offset:b,limit:30,targetSessionId:i,historySessionId:c,excludeRecentCount:x}),p=k&&typeof k=="object"&&"result"in k?k.result||{}:k||{};return{messages:Array.isArray(p.messages)?p.messages:[],hasMore:p.hasMore===!0}})},[e.agentType,d,o,c,n,i]);return l.useMemo(()=>Bx(h,y),[y,h])}function Ux(e,t){const{sendData:r}=ot(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??$r),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Zo)),i=Hx(o),[c,u]=l.useState(0);l.useEffect(()=>{if(!n||e.length===0)return;const d=setInterval(()=>{u(h=>h+1)},i);return()=>{clearInterval(d)}},[e.length,n,i]);const m=l.useMemo(()=>Wx(e,{recentActivityMs:o}),[e,o,c]);l.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const d=m.descriptors.map(h=>kd({...h,sendData:r,tailLimit:a}));return d.forEach(h=>{h.retain()}),()=>{d.forEach(h=>h.release())}},[m.signature,n,r,a])}function zx(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function fl(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 Gx(e,t){if(e.length===0)return[];if(t.some(fl))return[];const r=[],n=new Set;for(let a=e.length-1;a>=0&&r.length<2;a-=1){const o=e[a];if(!o||!fl(o))continue;const i=String(o.role||"").toLowerCase();n.has(i)||(n.add(i),r.unshift(o))}return r}function Vx(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=Gx(o,i),u=c.length>0?[...c,...i]:i;return t.length===0?u:[...t,...u]}function qx(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Yx(e){return qx(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const jn=new Map,jo=new Set;function xl(e,t){!e||jn.get(e)===t||(t?jn.set(e,!0):jn.delete(e),jo.forEach(n=>n(e,t)))}function Xx(e){return e?jn.get(e)===!0:!1}function Jx(e){return jo.add(e),()=>{jo.delete(e)}}function Qx(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function Zx(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function eb(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Sd(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function Nd(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 tb(e){return Sd(e)?!1:e.inboxBucket==="task_complete"&&Nd(e).length>0}function bl(e){return e.branch||"detached HEAD"}function sb(e){if(e.error)return`${bl(e)} · Git error: ${e.error}`;const t=[bl(e)];return e.changedFiles>0?t.push(Qx(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 rb(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${sb(t)}`}function nb(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function ab(e,t={}){if(t.enabled===!1)return[];if(!eb(e))return[];const r=Sd(e)?"working":tb(e)?"complete":null;if(!r)return[];const n=r==="complete"?Nd(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${Zx(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:rb(r,e.git),timestamp:nb(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 ob=60;function ib(e){return e.status==="long_generating"?"Agent has been generating for a long time. Send queues your message; Force sends it immediately.":e.status==="generating"||e.status==="streaming"?"Agent is generating. Send queues your message; Force sends it immediately.":e.status==="waiting_approval"&&(!e.modalButtons||e.modalButtons.length===0)?"Agent is waiting for approval. Approval controls will appear when available.":null}function ko({activeConv:e,ideEntry:t,handleSendChat:r,handleForceSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:u,userName:m,scrollToBottomRequestNonce:d,isInputActive:h=!0,isVisible:f=!0}){var X,we,de,ye,xe,ge,le;const y=l.useRef(new Map),b=l.useRef(void 0),x=Dr(),{sendCommand:j}=ot(),{isVisible:k}=Go();Rr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:u.length,isSendingChat:a});const p=bt.useMemo(()=>Gs(e),[e.status,e.connectionState]);bt.useEffect(()=>{const be=e.sessionId;if(be)return xl(be,p.isGenerating),()=>{xl(be,!1)}},[e.sessionId,p.isGenerating]);const w=l.useMemo(()=>Qf(e,t),[e,t]),S=l.useMemo(()=>{var be;return Yo((be=w.targetEntry)==null?void 0:be.providerControls,{hostIdeType:e.hostIdeType,providerType:w.providerType})},[e.hostIdeType,w.providerType,(X=w.targetEntry)==null?void 0:X.providerControls]),v=vd({isCliLike:w.isCli||w.isAcp}),g=Sx({isCliLike:w.isCli||w.isAcp}),C=Kx(e,{enabled:f&&!!e.sessionId,tailLimit:g}),[I,N]=l.useState(v),[_,D]=l.useState(()=>Wi()),A=e.tabKey,M=C.historyMessages,R=C.hasMoreHistory,z=C.historyError,T=zx(e,C),L=Uc(T).length;l.useEffect(()=>{N(v)},[v,A]);const B=Math.max(0,T.length-I),O=Xo(e),$=Pr(e),E=Yx(e),W=Jo(e),J=ib(e),Q=o||W||J,ee=!!W,[me,je]=l.useState(!1);l.useEffect(()=>{const be=w.targetEntry;$&&(!be||be.providerControls===void 0||be.controlValues===void 0)&&x($,{minFreshMs:3e4}).catch(()=>{})},[$,w.isAcp,(we=w.targetEntry)==null?void 0:we.providerControls,(de=w.targetEntry)==null?void 0:de.controlValues,x]);const Me=l.useCallback(async()=>{if(!me){if(T.length>I){N(be=>Math.min(T.length,be+ob));return}je(!0);try{await C.loadHistoryPage()}finally{je(!1)}}},[C,me,T.length,I]),{allMessages:q,receivedAtMap:G}=l.useMemo(()=>{const be=Vx({historyMessages:M,liveMessages:T,visibleLiveCount:I}),ie=ab(e),P=ie.length>0?[...be,...ie]:be,fe={};return P.forEach((Ce,_e)=>{const se=`${e.tabKey}:${Pn(Ce,_e)}`;let De=wx(Ce)||y.current.get(se)||0;De||(De=Date.now(),y.current.set(se,De)),fe[Pn(Ce,_e)]=De}),{allMessages:P,receivedAtMap:fe}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,B,M,T,I]),he=l.useMemo(()=>u.filter(be=>be.routeId===e.tabKey).sort((be,ie)=>be.timestamp-ie.timestamp),[u,e.tabKey]),ue=l.useCallback(async()=>{var _e,se;if(!$)return;const be=xd({activeConv:e,visibleMessages:q,actionLogs:u,controls:(_e=w.targetEntry)==null?void 0:_e.providerControls,controlValues:(se=w.targetEntry)==null?void 0:se.controlValues,visibleBarControlCount:S.length,chatTailState:{liveMessages:C.liveMessages,hasLiveSnapshot:C.hasLiveSnapshot,hasMoreHistory:R,historyError:z,historyMessages:M},ui:{controlsVisible:k,visibleLiveCount:I,activityVisible:_,activityCount:L,hiddenLiveCount:B,isInputActive:h,isVisible:f}}),ie=await j($,"get_chat_debug_bundle",{agentType:w.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:be}),P=gr(ie),fe=yd(P),Ce=await gd(fe);Ce==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),Qe.showToast(bd(P,{locatorCopyStatus:Ce}),Ce==="failed"?"warning":"success")},[e,u,L,q,k,C.hasLiveSnapshot,C.liveMessages,w.providerType,(ye=w.targetEntry)==null?void 0:ye.controlValues,(xe=w.targetEntry)==null?void 0:xe.providerControls,$,R,B,M,h,f,z,j,_,S.length,I]);l.useEffect(()=>{const be=ie=>{ie.key===Wc&&D(Wi())};return window.addEventListener("storage",be),()=>window.removeEventListener("storage",be)},[]);const ce=l.useCallback(()=>{const be=ax(b.current);b.current=be.state,be.shouldCollect&&ue().catch(ie=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",ie),Qe.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[ue]),ve=l.useMemo(()=>{if(T.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((p.isGenerating||e.status==="streaming")&&je(!1),e.status==="not_monitored"&&E)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Hs,{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(Os,{size:14})," Open ",O," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&E)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx($c,{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(Os,{size:14})," Open ",O," 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"&&!me)return!R&&M.length===0?s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"No messages yet"})]}):s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,E,i,R,M.length,c,me,T.length,O,p.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[s.jsx("div",{className:"chat-activity-toggle-bar",children:s.jsx("div",{className:"ml-auto flex items-center gap-1",children:s.jsx(Uf,{sessionId:e.sessionId,daemonId:e.daemonId})})}),s.jsx(Mp,{messages:q,actionLogs:he,agentName:Ws(e)||O||"Agent",userName:m,isCliMode:w.isCli||w.isAcp,isWorking:p.isGenerating,contextKey:e.tabKey,receivedAtMap:G,lastMessageHash:e.lastMessageHash,showActivityMessages:_,onLoadMore:Me,isLoadingMore:me,hasMoreHistory:R,hiddenLiveCount:B,loadError:z??void 0,emptyState:ve,scrollToBottomRequestNonce:d,isVisible:f}),s.jsx(Bf,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:w.providerType,displayLabel:w.displayLabel,controls:(ge=w.targetEntry)==null?void 0:ge.providerControls,controlValues:(le=w.targetEntry)==null?void 0:le.controlValues,isActive:h,isCliTerminal:w.isCliTerminal}),!w.isCliTerminal&&s.jsx(ld,{contextKey:e.tabKey,panelLabel:O,isSending:a,isBusy:ee,statusMessage:Q,onSend:r,onForceSend:n,canForceSend:!!n&&p.isGenerating&&!ee,isActive:h,showControlsToggle:S.length>0,onControlsToggle:ce,messageInput:e.messageInput})]})}let Cd=Xt;function Id(){return Cd()}class lb{constructor(){Ue(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 Md=new lb;class cb{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 it=new cb;function db(e){e.dashboardWS&&(Md=e.dashboardWS),e.connectionManager&&(it=e.connectionManager),e.useDaemonsHook&&(Cd=e.useDaemonsHook)}const ub=.5,mb=1.25;function at(e){return Xo(e)}function ws(e){return hd(e).join(" · ")}function hb(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("메시 노드"),n&&t.push("코디네이터"),t}function pb(e){var i,c,u;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((u=e.settings)==null?void 0:u.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor.trim():"",o=n||a;if(r&&t.push(`메시 노드: ${r}`),o&&t.push(`코디네이터: ${o}`),e.meshQueueStats){const{pending:m,assigned:d,completed:h,failed:f}=e.meshQueueStats;t.push(`Queue: ${m} pending, ${d} assigned, ${h} completed, ${f} failed`)}return t.join(" · ")}function Ad(e){const t=md(e);return t||(e.title?e.title:ws(e)||"No messages yet")}function Td(e,t){const{isReconnecting:r,isConnecting:n}=Gs(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function fb(e,t){const r=["Chat",...hd(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function fs(e){return Td(e)||ws(e)}function xb(e){return`${at(e)} · ${Ad(e)}`}function bb(e){const t=$n(e),r=t?yt(t):Ws(e);return`${at(e)} — ${r||"Agent"}`}function gb(e){return Ws(e)||"CLI"}function _d(e){return ud(e)}function Ld(e){return e?`Remote · ${at(e)||e.workspaceName||"Session"}`:"Remote"}function yb({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var re;Xt();const{sendPtyInput:u}=ot(),[m,d]=l.useState(!1),h=l.useRef(!1);h.current=m;const[f,y]=l.useState("Runtime terminal unavailable"),[b,x]=l.useState(!1),[j,k]=l.useState(null),[p,w]=l.useState(!1),[S,v]=l.useState(!1),[g,C]=l.useState(1),[I,N]=l.useState(!1),[_,D]=l.useState({width:0,height:0}),[A,M]=l.useState({width:0,height:0}),[R,z]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[T,L]=l.useState(null),B=l.useRef(null),O=l.useRef(null),$=l.useRef(!1),E=l.useRef(!1),W=l.useRef(i),J=l.useRef(0),Q=l.useRef(!1),ee=l.useRef(""),me=l.useRef(null),je=l.useRef(!1),Me=l.useRef(!1),q=l.useRef(null),G=l.useRef(null),he=l.useRef(null),ue=32*1024,ce=()=>{var H,V,te,oe;return((V=(H=B.current)==null?void 0:H.ownerDocument)==null?void 0:V.defaultView)||((oe=(te=O.current)==null?void 0:te.ownerDocument)==null?void 0:oe.defaultView)||window},ve=H=>{const V=ce();return{ownerWindow:V,frameId:V.requestAnimationFrame(H)}},X=()=>{const H=q.current;if(H){try{H.ownerWindow.cancelAnimationFrame(H.frameId)}catch{}q.current=null}},we=()=>{const H=G.current;if(H){try{H.ownerWindow.clearTimeout(H.timeoutId)}catch{}G.current=null}},de=()=>{const H=he.current;if(H){try{H.ownerWindow.clearTimeout(H.timeoutId)}catch{}he.current=null}},ye=()=>{i&&q.current===null&&(q.current=ve(()=>{et()}))},xe=e.tabKey,ge=e.sessionId||"",le=e.daemonId||((re=e.routeId)==null?void 0:re.split(":")[0])||e.routeId||"",be=Jo(e),ie=m?o||be:f,P=ub,fe=mb,Ce=.05,_e=()=>{const H=A.width,V=A.height;if(!Number.isFinite(_.width)||_.width<=0||!Number.isFinite(_.height)||_.height<=0||!Number.isFinite(H)||H<=0||!Number.isFinite(V)||V<=0)return 1;const te=_.width/H,oe=_.height/V;return Number(Math.min(fe,Math.max(P,Math.min(te,oe))).toFixed(2))},se=_e(),De=$.current&&g>se,Te=Number.isFinite(A.width)&&A.width>0?Math.max(_.width,Math.round(A.width*g)):_.width,Ee=Number.isFinite(A.height)&&A.height>0?Math.max(_.height,Math.round(A.height*g)):_.height,Oe=()=>{ve(()=>{const H=O.current;H&&(H.scrollLeft=0,H.scrollTop=H.scrollHeight-H.clientHeight)})},Je=()=>{var H,V;J.current=0,Q.current=!1,ee.current="",me.current=null,je.current=!1,Me.current=!1,$.current||(E.current=!1,C(1)),q.current!==null&&X(),d(!1),y("Runtime terminal unavailable"),de(),we(),k(null),L(null),N(!1),x(!1),w(!1),v(!1),(V=(H=r.current)==null?void 0:H.reset)==null||V.call(H)},qe=()=>{var H,V;J.current=0,Q.current=!1,ee.current="",me.current=null,je.current=!1,Me.current=!1,q.current!==null&&X(),d(!0),y(""),de(),we(),k(null),L(null),N(!1),x(!1),w(!1),v(!1),(V=(H=r.current)==null?void 0:H.reset)==null||V.call(H)},Ze=()=>{Me.current&&(Me.current=!1,ve(()=>{var H,V;(V=(H=r.current)==null?void 0:H.scrollToTop)==null||V.call(H)}))},et=()=>{if(q.current=null,!i)return;const H=ee.current;if(!H)return;const V=H.slice(0,ue);ee.current=H.slice(V.length);const te=r.current;if(!te){ee.current=V+ee.current,ye();return}te.write(V,()=>{if(ee.current.length>0){ye();return}Ze()})},dt=H=>{H&&(ee.current+=H,ye())},ut=(H,V=0,te,oe,Ne={})=>{var F,ne,pe,Se;const Le=!!Ne.force;!Le&&V>0&&J.current>=V||!Le&&V===0&&Q.current||(J.current=V,V>0&&w(!0),d(!0),y(""),typeof te=="number"&&typeof oe=="number"&&te>0&&oe>0&&((ne=(F=r.current)==null?void 0:F.resize)==null||ne.call(F,te,oe)),ee.current="",(Se=(pe=r.current)==null?void 0:pe.reset)==null||Se.call(pe),H?dt(H):Ze())};l.useEffect(()=>{Je()},[ge]),l.useEffect(()=>{var V;if(!ge)return;const H=((V=it.onRuntimeEvent)==null?void 0:V.call(it,ge,te=>{if(!(!te||te.sessionId!==ge)){if(te.type==="runtime_snapshot"){if(!i){me.current={text:te.text||"",seq:te.seq||0,cols:te.cols,rows:te.rows,force:!!te.force};return}ut(te.text||"",te.seq||0,te.cols,te.rows,{force:!!te.force});return}if(te.type==="session_output"){Q.current=!0,typeof te.seq=="number"&&(J.current=Math.max(J.current,te.seq),te.seq>0&&w(!0)),h.current||d(!0),h.current||y(""),typeof te.data=="string"&&dt(te.data);return}if(te.type==="session_cleared"){if(!i){je.current=!0,ee.current="",me.current=null;return}qe();return}if(te.type==="session_io_error"){const oe=typeof te.error=="string"&&te.error?te.error:typeof te.reason=="string"&&te.reason?te.reason:"unknown error";d(!1),y(`Runtime input failed: ${oe}`);return}}},le))||(()=>{});return()=>{H()}},[le,ge,r,i]);const xt=async(H={})=>{var V;if(!le||!ge)return{success:!1,error:"daemonId and sessionId are required"};H.preserveStatus||y(H.loadingMessage||"Loading runtime terminal...");try{const te=await((V=it.requestRuntimeSnapshot)==null?void 0:V.call(it,le,ge,{sinceSeq:H.sinceSeq,force:H.force}));return te&&te.success===!1?(H.preserveStatus||(d(!1),y(`Runtime terminal unavailable: ${te.error}`)),te):te||{success:!0}}catch(te){const oe=(te==null?void 0:te.message)||String(te);return H.preserveStatus||(d(!1),y(`Runtime terminal unavailable: ${oe}`)),{success:!1,error:oe}}},Ae=async H=>{var Le,F;const V=((Le=B.current)==null?void 0:Le.ownerDocument)||document,te=V.defaultView||window,oe=(F=te.navigator)==null?void 0:F.clipboard;if(oe!=null&&oe.writeText&&te.isSecureContext)try{return await oe.writeText(H),!0}catch{}let Ne=null;try{return Ne=V.createElement("textarea"),Ne.value=H,Ne.setAttribute("readonly","true"),Ne.style.position="fixed",Ne.style.left="-9999px",Ne.style.top="0",V.body.appendChild(Ne),Ne.focus(),Ne.select(),V.execCommand("copy")}catch{return!1}finally{Ne==null||Ne.remove()}},He=H=>{we(),L(H);const V=ce();G.current={ownerWindow:V,timeoutId:V.setTimeout(()=>{G.current=null,L(te=>te===H?null:te)},2200)}},rt=H=>{de(),k(H);const V=ce();he.current={ownerWindow:V,timeoutId:V.setTimeout(()=>{he.current=null,k(te=>te===H?null:te)},2200)}},Ye=async()=>{var Ne,Le,F,ne;const H=((Le=(Ne=r.current)==null?void 0:Ne.getSelection)==null?void 0:Le.call(Ne))||"",V=((ne=(F=r.current)==null?void 0:F.getVisibleText)==null?void 0:ne.call(F))||"",te=H.trimEnd()||V.trimEnd();if(!te){He("Nothing to copy");return}if(!await Ae(te)){He("Copy failed");return}He(H.trimEnd()?"Copied selection":"Copied visible terminal")},tt=H=>{if(!m||!i)return;((u==null?void 0:u(le,ge,H))??!1)||He("Terminal input failed")},K=async()=>{if(b)return;x(!0),k("Loading older terminal output..."),Me.current=!0;const H=await xt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(x(!1),(H==null?void 0:H.success)===!1){Me.current=!1,k(`Older terminal output unavailable: ${H.error}`);return}v(!0),rt("Older terminal output loaded"),ve(()=>{var V;(V=r.current)==null||V.bumpResize()})};l.useEffect(()=>{var V,te;if(!ge)return;le&&((V=it.getState)==null?void 0:V.call(it,le))==="connected"&&xt();const H=(te=it.onStateChange)==null?void 0:te.call(it,(oe,Ne)=>{oe!==le||Ne!=="connected"||xt()});return()=>{H==null||H()}},[le,ge,r]),l.useEffect(()=>{t&&Je()},[t,xe,r]),l.useEffect(()=>{var oe,Ne;const H=B.current,V=(Ne=(oe=H==null?void 0:H.ownerDocument)==null?void 0:oe.defaultView)==null?void 0:Ne.ResizeObserver;if(!H||!V)return;const te=new V(Le=>{const F=Le[0];if(!F)return;const{width:ne,height:pe}=F.contentRect;D(Se=>{const Ie=Math.round(ne),We=Math.round(pe);return Se.width===Ie&&Se.height===We?Se:{width:Ie,height:We}})});return te.observe(H),()=>te.disconnect()},[]),l.useEffect(()=>{if($.current)return;const H=_e();!Number.isFinite(H)||H<=0||C(V=>E.current?H<V-Ce?H:V:(E.current=!0,H))},[A.height,A.width,_.height,_.width]),l.useEffect(()=>{De&&Oe()},[De,Ee,Te]),l.useEffect(()=>{var te;const H=W.current;if(W.current=i,!i)return;H||v(!1),je.current&&(je.current=!1,qe());const V=me.current;V&&(me.current=null,ut(V.text,V.seq,V.cols,V.rows,{force:!!V.force})),le&&ge&&((te=it.getState)==null?void 0:te.call(it,le))==="connected"&&xt(),ee.current&&q.current===null&&ye(),ve(()=>{var oe;(oe=r.current)==null||oe.bumpResize()})},[le,i,ge]),l.useEffect(()=>()=>{q.current!==null&&X(),we(),de()},[]),l.useEffect(()=>{const H=oe=>{var Le;const Ne=oe.detail;Ne!=null&&Ne.sessionId&&Ne.sessionId!==ge||m&&((Le=r.current)==null||Le.bumpResize())},V=ce(),te=V===window?[window]:[window,V];for(const oe of te)oe.addEventListener("adhdev:fit-cli-terminal",H);return()=>{for(const oe of te)oe.removeEventListener("adhdev:fit-cli-terminal",H)}},[m,ge,r]);const Y=m&&p&&!S&&(R.atTop||!R.canScroll)||b||!!j;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:B,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[Y&&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:()=>{K()},disabled:!ge||b,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:b?"Loading older...":"Load older terminal output"}),j&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:j})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[T&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:T}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Ye()},disabled:!m,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:()=>N(H=>!H),disabled:!m,"aria-label":"Open terminal control keys","aria-expanded":I,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),I&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":"Terminal control keys",className:"absolute right-0 top-10 w-56 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>N(!1),"aria-label":"Close terminal control keys",children:"×"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt("\x1B"),children:"Esc"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt(" "),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:()=>tt("\r"),children:"Enter"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt("\x1B[A"),"aria-label":"Arrow up",children:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt("\x1B[D"),"aria-label":"Arrow left",children:"←"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt("\x1B[B"),"aria-label":"Arrow down",children:"↓"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt("\x1B[C"),"aria-label":"Arrow right",children:"→"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt(""),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:()=>tt(""),children:"Ctrl-D"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt(""),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:()=>{$.current=!0,C(H=>{const V=Math.max(se,Number((H-.1).toFixed(2)));return V>se&&Oe(),V})},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:()=>{$.current=!0,C(H=>{const V=Math.min(fe,Number((H+.1).toFixed(2)));return V>se&&Oe(),V})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:O,className:De?"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:Te>0?`${Te}px`:"100%",height:Ee>0?`${Ee}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:A.width>0?`${A.width}px`:"100%",height:A.height>0?`${A.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:g},children:s.jsx(Yc,{ref:r,readOnly:!m||!i,sizingMode:"measured",onViewportMetrics:M,onScrollMetrics:z,onInput:H=>{!m||(u==null||u(le,ge,H))}})})})}),!m&&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:f})]}),s.jsx(ld,{contextKey:e.tabKey,panelLabel:at(e),isSending:a,isBusy:!!be,statusMessage:ie,onSend:async H=>be?!1:n(H),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1})]})}const vb=5e3,wb=12e3;function jb(e){return e==="disconnected"||e==="reconnecting"}function kb({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=vb,reconnectActionDelayMs:o=wb}){const i=jb(e),[c,u]=l.useState(()=>!i||a<=0),[m,d]=l.useState(()=>!i||o<=0),h=l.useRef(!1);l.useEffect(()=>{if(!i){u(!1);return}if(h.current=!1,a<=0){h.current=!0,u(!0);return}u(!1);const v=setTimeout(()=>{h.current=!0,u(!0)},a);return()=>clearTimeout(v)},[a,i]),l.useEffect(()=>{if(!i){d(!1);return}if(o<=0){d(!0);return}d(!1);const v=setTimeout(()=>{d(!0)},o);return()=>clearTimeout(v)},[o,i]);const f=i?c:e==="offline"||e==="auth_failed",y=!!(n&&e!=="auth_failed"&&(!i||m)),b=l.useMemo(()=>!t||e!=="connected"?!1:a<=0||h.current,[a,t,e]),x=e==="auth_failed"?"red":e==="offline"?"orange":"accent",j={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},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)"},p={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},w="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",S={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[f&&s.jsx("div",{className:w,style:S,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:j[x],border:k[x],color:p[x]},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"})]})}),b&&s.jsx("div",{className:w,style:S,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 Sb({terminalBackend:e,isStandalone:t=!1,machineLabel:r,machineKey:n}){const a=l.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[o,i]=l.useState(!1);if(l.useEffect(()=>{if(!a){i(!1);return}try{i(localStorage.getItem(a)==="1")}catch{i(!1)}},[a]),!t||!e||e.backend!=="xterm"||o)return null;const c=(r==null?void 0:r.trim())||"This machine",u=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}i(!0)};return s.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[s.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[s.jsxs("span",{children:[c," is using `xterm` fallback."]}),s.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),s.jsx("button",{type:"button",onClick:u,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function Rd({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(Wo,{size:n}):s.jsx(ks,{size:n})})}const Wt="New session",Pd="A connected machine is ready. Start a new session with any installed provider — CLI, ACP, or IDE.";function Nb(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 Cb(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 Ib(e){switch(e){case"conflict":return"border-red-500/25 bg-red-500/[0.08] text-red-400";case"error":return"border-yellow-500/25 bg-yellow-500/[0.08] text-yellow-500";case"dirty":return"border-orange-500/25 bg-orange-500/[0.08] text-orange-400";case"quiet":default:return"border-emerald-500/15 bg-emerald-500/[0.06] text-emerald-500"}}function Fn({git:e,className:t="",compact:r=!1}){const n=Nb(e),a=Cb(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 ${Ib(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 Mb({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 gl({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function yl({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const i=na(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:u=>{u.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),o()},children:"Delete"})]})]})}function Ab({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:u,onHideConversation:m,hiddenConversations:d=[],onShowConversation:h,onShowAllHidden:f,onResetPanelsToMain:y,inboxOpen:b,onInboxOpenChange:x,hiddenOpen:j,onHiddenOpenChange:k,onOpenNewSession:p,onOpenDashboardGuide:w,guideNudgeVisible:S=!1,actionShortcuts:v,notifications:g,notificationUnreadCount:C,onOpenNotification:I,onMarkNotificationRead:N,onMarkNotificationUnread:_,onDeleteNotification:D,onOpenGitDialog:A,onOpenMeshGraph:M}){var ve;const{ides:R,p2pStates:z={}}=Xt(),T=!!e&&Xe(e)&&!Ge(e),L=!!e&&Ge(e),B=!!(e!=null&&e.daemonId)&&!!((ve=e==null?void 0:e.coordinator)!=null&&ve.meshId),O=c||(e?cd(e)?"terminal":"chat":null),[$,E]=l.useState(!1),W=l.useRef(null),J=l.useRef(null),Q=R.filter(X=>X.type==="adhdev-daemon"),ee=Mb({wsStatus:t,isConnected:r,daemonCount:Q.length,p2pStates:z}),me=ee.subtitle,je=ee.tone==="connected"?"#22c55e":ee.tone==="limited"?"#eab308":"#ef4444",Me=ee.tone==="connected"?"0 0 4px #22c55e80":ee.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",q=l.useMemo(()=>g.filter(X=>!X.readAt),[g]),G=l.useMemo(()=>g.filter(X=>!!X.readAt),[g]),he=l.useMemo(()=>q.slice(0,9),[q]),ue=C;l.useEffect(()=>{if(!b)return;const X=we=>{var de;(de=W.current)!=null&&de.contains(we.target)||x(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[b,x]),l.useEffect(()=>{if(!j)return;const X=we=>{var de;(de=J.current)!=null&&de.contains(we.target)||k(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[j,k]),l.useEffect(()=>{if(!j&&!b)return;const X=we=>{if(!we.altKey)return;const de=we.code.match(/^Digit([1-9])$/);if(!de)return;const ye=Number(de[1])-1,xe=j?d[ye]:void 0,ge=b?he[ye]:void 0;if(!(!xe&&!ge)){if(we.preventDefault(),we.stopPropagation(),xe){h==null||h(xe),k(!1);return}ge&&(I(ge),x(!1))}};return window.addEventListener("keydown",X,!0),()=>window.removeEventListener("keydown",X,!0)},[d,j,b,he,k,x,I,h]);const ce=X=>{if(!X)return;const we=n.find(de=>de.tabKey===X);we&&(m==null||m(we))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(ks,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?at(e):"Dashboard"}),s.jsx("span",{title:ee.title,"aria-label":ee.title,className:"header-title-status-dot",style:{background:je,boxShadow:Me}}),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:je,boxShadow:Me}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[me&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",me]}),p&&s.jsx("button",{type:"button",onClick:p,className:"btn btn-secondary btn-sm ml-2",title:`${Wt}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":Wt,children:s.jsx(Fc,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[w&&s.jsxs("button",{type:"button",onClick:w,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:"?"}),S&&s.jsx("span",{children:"Guide"})]}),e&&(T||L||!Ge(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:ws(e)||at(e),children:at(e)}),A&&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:()=>A(e.daemonId,e.workspacePath),children:s.jsx(Fn,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Fn,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),B&&M&&s.jsxs("button",{type:"button",onClick:()=>M(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:"Open live repo mesh graph",children:[s.jsx(ss,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:"Mesh graph"})]}),(T||L)&&i&&s.jsxs(s.Fragment,{children:[T&&u&&O&&s.jsx(Rd,{mode:O,onChange:u,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:L?"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(gt,{size:14})})]}),!Ge(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(Fo,{size:14})}),!T&&!Ge(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Ot,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:W,children:[s.jsxs("div",{className:`dashboard-header-hidden${$?" is-drop-target":""}`,ref:J,onDragEnter:X=>{X.dataTransfer.types.includes("text/tab-key")&&(X.preventDefault(),E(!0))},onDragOver:X=>{X.dataTransfer.types.includes("text/tab-key")&&(X.preventDefault(),X.dataTransfer.dropEffect="move",E(!0))},onDragLeave:X=>{X.currentTarget.contains(X.relatedTarget)||E(!1)},onDrop:X=>{const we=X.dataTransfer.getData("text/tab-key");X.preventDefault(),E(!1),ce(we)},children:[s.jsxs("button",{type:"button",onClick:()=>k(!j),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(Ho,{size:16}),d.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:d.length})]}),j&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),s.jsx(gl,{value:v==null?void 0:v.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"}),d.length>0&&f&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),k(!1)},children:"Restore all"})]})]}),e&&m&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(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(gl,{value:v==null?void 0:v.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:at(e)})]}),d.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(X=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(X),k(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:at(X)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(X)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(X)+1]}):null,ws(X)]})]},X.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>x(!b),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Lr,{size:16}),ue>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ue})]}),b&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[q.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),q.map(X=>s.jsx(yl,{notification:X,shortcutIndex:he.indexOf(X)>=0?he.indexOf(X)+1:void 0,onOpen:()=>I(X),onMarkRead:()=>N(X.id),onMarkUnread:()=>_(X.id),onDelete:()=>D(X.id)},X.id))]}),G.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),G.map(X=>s.jsx(yl,{notification:X,onOpen:()=>I(X),onMarkRead:()=>N(X.id),onMarkUnread:()=>_(X.id),onDelete:()=>D(X.id)},X.id))]}),g.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function kt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Tb(e,t){return String(e||"")!==String(t||"")}function _b(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(u=>String(u||"").toLowerCase()).join(`
42
+ `).includes(r)||n&&!String(i.workspace||"").toLowerCase().includes(n)||a&&!sd(i.summaryMetadata).map(u=>u.toLowerCase()).join(`
43
+ `).includes(a)))}function Lb(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 Dd(e,t={}){return Lb(_b(e,t),t.sortMode||"recent")}function Hn(e){return e?"Resume saved history":"Start fresh"}function ti(e){return e?"Resuming saved history…":"Starting fresh…"}function Rb(){return"Start fresh"}function Pb(e,t=!1){return e==="cli"?Hn(t):e==="ide"?"Start IDE":"Start ACP session"}function Db(e,t=!1){return e==="cli"?ti(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Eb(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function $b(){return"Open saved history"}function Bb(){return"Saved History"}function si(){return"Use saved history when you want continuity in the same provider conversation."}function Ob(){return"No saved history found yet."}function Fb(){return"Refresh saved history"}function Hb(){return"Refreshing saved history…"}function Wn(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function Kn(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 Un(e){return e==="start-fresh"?"Start fresh":"Restart"}function zn(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Ed(e){return`Resume saved history with ${e}?`}function $d(){return"Review or change the target workspace before resuming saved history."}function Wb(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 Bd({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:u,onSavedHistoryFiltersChange:m,onClose:d,onNewChat:h,onSwitchSession:f,onRefreshHistory:y,onResumeSavedSession:b}){var D;const x=t.find(A=>A.id===e.routeId),j=(x==null?void 0:x.chats)||[],k=(D=x==null?void 0:x.activeChat)==null?void 0:D.id,p=Xe(e)&&!Ge(e),[w,S]=l.useState(()=>kt()),v=c||w,g=String(u||"").trim(),C=A=>{if(m){m(A);return}S(A)},I=l.useMemo(()=>a.map(A=>{const M=String(A.workspace||"").trim();return A.canResume||M||!g?A:{...A,workspace:g,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[g,a]),N=l.useMemo(()=>Dd(I,{textQuery:v.textQuery,workspaceQuery:v.workspaceQuery,modelQuery:v.modelQuery,resumableOnly:v.resumableOnly,sortMode:v.sortMode}),[I,v.modelQuery,v.resumableOnly,v.sortMode,v.textQuery,v.workspaceQuery]),_=s.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:d,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:p?Bb():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:bb(e)}),p&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:si()})]}),s.jsx("button",{onClick:d,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(gt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!p&&s.jsx("button",{onClick:h,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"}),p?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:v.textQuery,onChange:A=>C({...v,textQuery:A.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:v.workspaceQuery,onChange:A=>C({...v,workspaceQuery:A.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:v.modelQuery,onChange:A=>C({...v,modelQuery:A.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:v.sortMode,onChange:A=>C({...v,sortMode:A.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[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:v.resumableOnly,onChange:A=>C({...v,resumableOnly:A.target.checked})}),"Resume-ready only"]})]}),N.map(A=>{const M=e.providerSessionId===A.providerSessionId,R=M||!A.canResume||!!i,z=A.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{R||!b||b(A)},disabled:R,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${M?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${R?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[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 ${M?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:A.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:A.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Wb(A.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:A.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:[A.workspace||"Workspace unknown",z?" · selected workspace":"",vs(A.summaryMetadata)?` · ${vs(A.summaryMetadata)}`:"",A.messageCount>0?` · ${A.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:M?"ACTIVE":A.canResume?z?"RESUME IN SELECTED WORKSPACE":i===A.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},A.id)})]}):j.map(A=>s.jsxs("div",{onClick:()=>{f(e.routeId,A.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${k===A.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===A.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:A.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:[A.id.substring(0,12),"..."]}),k===A.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},A.id)),(p&&!o&&N.length===0||!p&&j.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(qh,{size:32})}),s.jsx("div",{className:"text-[13px]",children:p?a.length>0?"No saved history matches these filters.":Ob():"No recent chat sessions found."})]}),p&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Hb()})})]}),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(ra,{size:13})," ",p?Fb():"Refresh History"]})})})]})]});return typeof document>"u"?_:Nr.createPortal(_,document.body)}const vl={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 Od({toasts:e,onDismiss:t,onClickToast:r}){return s.jsx("div",{className:"fixed right-4 z-[9999] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const a=vl[n.type]||vl.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(gt,{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 Kb=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Ub(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function zb(e){return e.sessionId||e.instanceId||e.agentType}function Na(e,t){return t||e||"unknown"}function Fd(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Mt(r,{fallbackId:r.id}));return t}function Hd(e,t={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=t.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:t.connectionStates?t.connectionStates[r]||t.defaultConnectionState||"new":t.defaultConnectionState}}function ri(e,t={}){return Gb(e,Hd(e,t))}function Gb(e,t={}){var h,f,y,b,x,j,k;const r=[],n=t.machineName,a=t.connectionState,o=Ub(e),i=e.workspace||"",c=tf(e.type,{agentName:e.cliName}),u=Xe(e)||Ge(e)?c:yt(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(p=>{var w,S,v;return{sessionId:p.id,instanceId:p.id,providerSessionId:p.providerSessionId,activeChatId:(w=p.activeChat)==null?void 0:w.id,transport:p.transport,sessionCapabilities:p.capabilities,agentType:p.providerType,agentName:p.providerName||yt(p.providerType),status:p.status,title:p.title,lastMessagePreview:p.lastMessagePreview,lastMessageRole:p.lastMessageRole,lastMessageAt:p.lastMessageAt,lastMessageHash:p.lastMessageHash,messages:((S=p.activeChat)==null?void 0:S.messages)||[],activeModal:((v=p.activeChat)==null?void 0:v.activeModal)||void 0,unread:p.unread,lastSeenAt:p.lastSeenAt,lastUpdated:p.lastUpdated,inboxBucket:p.inboxBucket,completionMarker:p.completionMarker,surfaceHidden:p.surfaceHidden,git:p.git,settings:p.settings,coordinator:p.coordinator,messageInput:p.messageInput}}):[],d=Kb(e);if(d){const p=e.sessionId||e.instanceId,w=(h=e.settings)==null?void 0:h.meshCoordinatorFor,S=(f=e.settings)==null?void 0:f.meshNodeFor,v=w?" (Coordinator)":S?" (Mesh Node)":"",g=c+v,C=(y=e.activeChat)==null?void 0:y.activeModal,I=C&&Array.isArray(C.buttons)&&C.buttons.length>0,N=sf(e.activeChat,[{status:e.status,activeModal:(b=e.activeChat)==null?void 0:b.activeModal}],e.agents||[]),_=e.activeChat||{title:"",messages:[]};let D=_.title&&String(_.title).trim()?String(_.title).trim():"";const A=(x=e.activeChat)==null?void 0:x.id,M=e.chats;if(A&&Array.isArray(M)&&M.length>0){const E=M.find(W=>W.id===A||W.id&&String(W.id)===String(A));E!=null&&E.title&&String(E.title).trim()&&(D=String(E.title).trim())}const R=(Xe(e)||Ge(e),e.type),z=(Xe(e)||Ge(e))&&Qi(D,g,R)?"":D,T=_.messages||[],L=typeof A=="string"?A.trim():"",B=(Xe(e)||Ge(e))&&L===String(e.type||"").trim(),O=L&&!B?L:e.providerSessionId,$=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:p,providerSessionId:e.providerSessionId,historySessionId:O,nativeSessionId:p,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:Xe(e)?e.mode||"terminal":"chat",agentName:g,agentType:R,status:N,title:z,messages:T,resume:e.resume,hostIdeType:!Xe(e)&&!Ge(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:z||o||(Xe(e)?e.mode==="chat"?g:`Terminal${v}`:g),displaySecondary:Xe(e)&&o?g:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:I?C.buttons:void 0,modalMessage:I?C.message:void 0,streamSource:"native",tabKey:Na(p,e.id),machineName:n,connectionState:a,settings:e.settings,coordinator:$,messageInput:e.messageInput})}if(d&&(Xe(e)||Ge(e)))return r;for(const p of m){const w=p.activeModal&&Array.isArray(p.activeModal.buttons)&&p.activeModal.buttons.length>0,S=rf(p),v=zb(p),g=`${e.id}:${v}`,C=p.title&&String(p.title).trim()||"",I=Qi(C,p.agentName,p.agentType)?"":C,N=p.messages||[];if(!(p.transport==="cdp-webview"||!!p.sessionId||!!p.providerSessionId||N.length>0||w||!!I||!["idle","panel_hidden","disconnected","not_monitored"].includes(S)))continue;const D=p.coordinator||(typeof((k=p.settings)==null?void 0:k.meshCoordinatorFor)=="string"&&p.settings.meshCoordinatorFor?{meshId:p.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:p.sessionId||p.instanceId,providerSessionId:p.providerSessionId,historySessionId:p.activeChatId||p.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:p.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:p.sessionCapabilities,mode:"chat",agentName:p.agentName,agentType:p.agentType,status:S,title:I,messages:N,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:p.git||e.git,displayPrimary:I||o||p.agentName||u,displaySecondary:`${u} · ${p.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:p.lastMessagePreview,lastMessageRole:p.lastMessageRole,lastMessageAt:p.lastMessageAt,lastMessageHash:p.lastMessageHash,lastUpdated:p.lastUpdated||e.lastUpdated,inboxBucket:p.inboxBucket,completionMarker:p.completionMarker,modalButtons:w?p.activeModal.buttons:void 0,modalMessage:w?p.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Na(p.sessionId||p.instanceId,g),machineName:n,connectionState:a,settings:p.settings,coordinator:D,messageInput:p.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||u,displaySecondary:u,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Na(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function Wd(e){return String(e.type||e.id||"").trim()}function Vb(e){var t;return e.category!=="cli"||!Wd(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 qb(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!Vb(a))continue;const o=Wd(a);if(!o||t.has(o))continue;t.add(o);const i=String(a.displayName||a.name||o),c=a.detectedPath||((n=a.lastDetection)==null?void 0:n.path)||null;r.push({type:o,label:i,icon:a.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c})}return r}function Br(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 So(e,t){const r=new Set(t.map(n=>n.type));return Br(e).filter(n=>r.has(n))}function Yb(e){return e.map(t=>t.type)}function Xb(e,t){const r=Br(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function Jb(e,t){return Br(e).filter(r=>r!==t)}function wl(e,t,r){const n=Br(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 jl({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 kl({value:e,availableProviders:t,onChange:r,disabled:n=!1,saveButton:a}){const[o,i]=l.useState(""),c=l.useMemo(()=>new Map(t.map(f=>[f.type,f])),[t]),u=l.useMemo(()=>So(e,t),[e,t]),m=e.length-u.length,d=t.filter(f=>!u.includes(f.type)),h=()=>{o&&(r(Xb(u,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:u.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."}):u.map((f,y)=>{const b=c.get(f);return s.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border-subtle bg-bg-primary px-3 py-2 sm:flex-row sm:items-center sm:justify-between",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",y+1]}),(b==null?void 0:b.icon)&&s.jsx("span",{"aria-hidden":"true",children:b.icon}),s.jsx("span",{className:"font-mono text-[12px] text-text-primary",children: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("div",{className:"mt-1 text-[10px] text-text-muted",children:b?`${b.label} · ${b.statusLabel}`:f})]}),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(wl(u,f,"up")),children:s.jsx(jl,{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===u.length-1,title:"Move down",onClick:()=>r(wl(u,f,"down")),children:s.jsx(jl,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(Jb(u,f)),children:"Remove"})]})]},f)})}),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:f=>i(f.target.value),disabled:n||d.length===0,children:[s.jsx("option",{value:"",children:d.length?"Select provider…":"No additional detected CLI providers"}),d.map(f=>s.jsxs("option",{value:f.type,children:[f.label," (",f.type,")"]},f.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!o,onClick:h,children:"Add provider"}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Inventory is filtered to CLI providers detected on this machine. New launches use this order; existing running sessions may need restart.",m>0?` ${m} provider${m===1?"":"s"} from the saved policy are not detected now and will be omitted when saved.`:""]})]})}function Qb(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 Kd(e,t){const r=Qb(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Ud=[{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:"🏄"}],zd=[{id:"aider-cli",name:"Aider",icon:"🛠️"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"gemini-cli",name:"Gemini CLI",icon:"✨"},{id:"github-copilot-cli",name:"GitHub Copilot CLI",icon:"🤖"},{id:"goose-cli",name:"Goose",icon:"🪿"},{id:"opencode-cli",name:"OpenCode CLI",icon:"🧩"}],Gd=[{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:"🟠"}],Zb=Ud,eg=zd,tg=Gd;function Jt(...e){return Um(zm(e))}function sg({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:Jt("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 vr({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(sg,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Jt("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const No="adhdev:themechange";function rg(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Ts(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function _s(e){return e==="system"?rg():e}function Vd(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function kn(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(No,{detail:{preference:e,theme:t}}))}function ng(){const e=Ts(),t=_s(e);Vd(t),kn(e,t)}function qs(){const[e,t]=l.useState(Ts),[r,n]=l.useState(()=>_s(Ts()));l.useEffect(()=>{Vd(r)},[r]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=u=>{if(e==="system"){const m=u.matches?"light":"dark";n(m),kn("system",m)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=u=>{const m=u.detail||{},d=m.preference,h=m.theme;t(d==="dark"||d==="light"||d==="system"?d:Ts()),n(h==="dark"||h==="light"?h:_s(Ts()))},c=u=>{if(u.key!=="theme")return;const m=Ts(),d=_s(m);t(m),n(d)};return window.addEventListener(No,i),window.addEventListener("storage",c),()=>{window.removeEventListener(No,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=_s(i);t(i),n(c);try{localStorage.setItem("theme",i)}catch{}kn(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",u=_s(c);n(u);try{localStorage.setItem("theme",c)}catch{}return kn(c,u),c})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const Sl={dark:"Dark",light:"Light",system:"System"};function ag({collapsed:e}){const{preference:t,cycleTheme:r}=qs(),n=t==="dark"?s.jsx(Xh,{size:16}):t==="light"?s.jsx(Yh,{size:16}):s.jsx(Jh,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Sl[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:Sl[t]})]})}function Ca(e,t){return e?typeof e=="function"?e(t):e:null}function og({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:u="sidebar-collapsed"}){const[m,d]=l.useState(!1),[h,f]=l.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),y=()=>d(!0),b=()=>d(!1),x=()=>{f(w=>{const S=!w;try{localStorage.setItem(u,S?"1":"0")}catch{}return S})},j=l.useMemo(()=>({collapsed:h,mobileMenuOpen:m,openMobileMenu:y,closeMobileMenu:b,toggleCollapsed:x}),[h,m]),k=w=>`nav-item${w.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${w.className?` ${w.className}`:""}`,p=w=>s.jsxs("div",{className:k(w),id:`nav-${w.id}`,onClick:()=>{w.onSelect(),b()},title:h?w.title??(typeof w.label=="string"?w.label:void 0):w.title,children:[s.jsx("span",{className:"nav-icon",children:w.icon}),!h&&w.label]},w.id);return s.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${h?" 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"})]}),m&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:b,onKeyDown:w=>w.key==="Escape"&&b()}),s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:Ca(t,j)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:b,children:s.jsx(gt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(p)}),n.map(w=>s.jsxs("div",{className:w.className??"border-t border-border-subtle pt-2 mt-2",children:[!h&&w.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:w.title}):null,w.items.map(p)]},w.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(p),Ca(o,j),s.jsx(ag,{collapsed:h}),Ca(i,j)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function ct({title:e,icon:t,description:r,accentColor:n,className:a,children:o}){return s.jsxs("div",{className:Jt("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&s.jsxs("div",{className:"mb-4",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[t&&s.jsx("span",{className:"mr-1.5",children:t}),e]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),o]})}function Gn({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:Jt("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 ig={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"},lg={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ps({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:Jt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",ig[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:lg[e]}),s.jsx("span",{children:t})]}),r&&s.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function ft({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:Jt("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 Is(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:Jt("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 cg={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"},dg={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function ug({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:Jt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",cg[e],r),children:[s.jsx("span",{className:Jt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",dg[e])}),n]})}function us({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 mg({onPrefChange:e}){const[t,r]=pf(),[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(us,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Lr,{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(us,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ot,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:i=>o("browserNotifications",i)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{ad().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&s.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(us,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Hc,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:i=>o("completionAlert",i)}),s.jsx(us,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Qh,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:i=>o("approvalAlert",i)}),s.jsx(us,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Hs,{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 Vn(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function hg(e,t){const r=Vn(e),n=Vn(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 ni(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function wr(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||hg(r,t)>=0)return!1;const n=Vn(r),a=Vn(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function pg(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Ia(e,t){return e instanceof Error?e.message:t}function fg({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(Gn,{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(bg,{ide:i,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},i.id))})}function Nl({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:o}){const i=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return Nr.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:c=>c.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${i}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function xg(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Zb,...eg,...tg].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 bg({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var R,z;const[o,i]=l.useState("idle"),[c,u]=l.useState(""),[m,d]=l.useState(null),[h,f]=l.useState("idle"),[y,b]=l.useState(""),x=e.version||null,j=((R=e.machine)==null?void 0:R.platform)||((z=e.system)==null?void 0:z.platform)||"",k=Mt(e,{fallbackId:e.id}),p=j==="win32"?"🪟":j==="darwin"?"🍎":"🐧",w=t.filter(T=>T.daemonId===e.id&&T.transport==="cdp-page"),S=t.filter(T=>T.daemonId===e.id&&T.transport==="pty"),v=t.filter(T=>T.daemonId===e.id&&T.transport==="acp"),g=e.p2p,C=async()=>{if(r){i("upgrading"),u("Starting upgrade...");try{const T=pg(await r(e.id,"daemon_upgrade",{}));T.alreadyLatest?(i("done"),u(`Already on v${T.version||"latest"}.`)):T.upgraded||T.success?(i("done"),u(`Upgrade to v${T.version||"latest"} started. Daemon is restarting...`)):(i("error"),u(T.error||"Upgrade failed"))}catch(T){i("error"),u(Ia(T,"Connection lost during upgrade"))}}},I=async()=>{if(d(null),!!n){f("loading");try{await n(e.id),f("done"),b("Machine disconnected.")}catch(T){f("error"),b(Ia(T,"Failed to disconnect"))}}},N=async()=>{if(d(null),!!a){f("loading");try{await a(e.id),f("done"),b("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(T){f("error"),b(Ia(T,"Failed to revoke token"))}}},_="0.9.82",D=ni(e,_),A=wr(e,_),M=w.length+S.length+v.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:p}),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),"…"]}),x&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${D?"":"bg-bg-secondary"}`,style:D?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",x,!D&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&D&&s.jsx("button",{onClick:C,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${_}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${A?"↑ Update now":`↑ Update${` to v${_}`}`}`}),n&&s.jsx("button",{onClick:()=>d("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>d("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(ug,{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-green-400":"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&&M>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),M>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[w.map(T=>{const L=xg(T.type),B=T.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:L.icon}),s.jsx("span",{children:L.name}),B!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${B?"bg-green-400":"animate-pulse"}`,style:B?void 0:{background:"var(--status-warning)"},title:B?"CDP connected":"CDP connecting..."})]},T.id)}),S.map(T=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:T.cliName||"CLI"})]},T.id)),v.map(T=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:T.cliName||"ACP"})]},T.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(c||y)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||h==="error"?"text-red-400":o==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:y||c})]}),m==="disconnect"&&s.jsx(Nl,{title:"🔌 Disconnect Machine",message:`Disconnect "${k}" from ADHDev?
44
+
45
+ This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
46
+
47
+ Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:I,onCancel:()=>d(null)}),m==="revoke"&&s.jsx(Nl,{title:"⚠️ Remove Machine",message:`Remove "${k}" from your dashboard?
48
+
49
+ This will:
50
+ • Immediately disconnect the machine
51
+ • Delete the machine registration
52
+ • Require restarting ADHDev on that machine
53
+
54
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:N,onCancel:()=>d(null)})]})}const gg=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function yg({daemonId:e,knownCliTypes:t=gg}){const{sendCommand:r}=ot(),[n,a]=l.useState({}),[o,i]=l.useState({}),[c,u]=l.useState(!0),[m,d]=l.useState(null),[h,f]=l.useState(null),[y,b]=l.useState(""),x=l.useCallback(async()=>{if(e){u(!0),f(null);try{const p=await r(e,"list_coordinator_prompts",{}),w=p!=null&&p.result&&typeof p.result=="object"?p.result:p;if(!(w!=null&&w.success)){f((w==null?void 0:w.error)||"Failed to load");return}const S=w.entries||{};b(w.dir||"");const v={};for(const g of t)v[g]=S[g]||{override:"",append:""};for(const g of Object.keys(S))v[g]||(v[g]=S[g]);a(v),i(JSON.parse(JSON.stringify(v)))}catch(p){f((p==null?void 0:p.message)||String(p))}finally{u(!1)}}},[r,e,t]);l.useEffect(()=>{x()},[x]);const j=l.useCallback(async(p,w)=>{var S;if(e){d(`${p}:${w}`),f(null);try{const v=((S=n[p])==null?void 0:S[w])||"",g=await r(e,"write_coordinator_prompt",{key:p,kind:w,content:v}),C=g!=null&&g.result&&typeof g.result=="object"?g.result:g;if(!(C!=null&&C.success)){f((C==null?void 0:C.error)||"Save failed");return}i(I=>({...I,[p]:{...I[p]||{override:"",append:""},[w]:v}}))}catch(v){f((v==null?void 0:v.message)||String(v))}finally{d(null)}}},[r,e,n]),k=l.useMemo(()=>(p,w)=>{var S,v;return(((S=n[p])==null?void 0:S[w])||"")!==(((v=o[p])==null?void 0:v[w])||"")},[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."]})]}),h&&s.jsx("div",{className:"text-[12px] text-red-400 bg-red-500/10 border border-red-500/20 rounded px-3 py-2",children:h}),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(([p,w])=>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:p}),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:w.override,onChange:S=>a(v=>({...v,[p]:{...v[p],override:S.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:m===`${p}:override`}),s.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void j(p,"override"),disabled:m===`${p}:override`||!k(p,"override"),children:m===`${p}:override`?"Saving…":k(p,"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:w.append,onChange:S=>a(v=>({...v,[p]:{...v[p],append:S.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:m===`${p}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void j(p,"append"),disabled:m===`${p}:append`||!k(p,"append"),children:m===`${p}:append`?"Saving…":k(p,"append")?"Save append":"Saved"})})]},p))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const vg=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function wg(){const{preference:e,setPreference:t}=qs();return s.jsx("div",{className:"flex gap-2",children:vg.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 jg(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 kg(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Ma(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Cl(e){const{r:t,g:r,b:n}=kg(e);return .2126*Ma(t)+.7152*Ma(r)+.0722*Ma(n)}function Il(e,t){const r=Cl(e),n=Cl(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function qd(e){const t=jg(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return Il(t,r)>=Il(t,n)?r:n}const Co={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},Io={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},Sg=[{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"}}}],Yd="adhdev-chat-theme",Xd="adhdev-chat-theme-custom";function Sn(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Yd)||"ember"}catch{return"ember"}}function $t(e){try{const t=localStorage.getItem(Xd);if(t){const r=JSON.parse(t);return{...e==="dark"?Co:Io,...r[e]}}}catch{}return e==="dark"?Co:Io}function nn(e,t){try{localStorage.setItem(Xd,JSON.stringify({dark:e,light:t}))}catch{}}function Tt(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 qn(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 Ng={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function jr(e,t){var a;const r=(a=Ng[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",qn(r,24)),n.style.setProperty("--accent-on-primary",qd(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${qn(r,18)})`),n.style.setProperty("--border-accent",Tt(r,.35)),n.style.setProperty("--nav-active-bg",Tt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Tt(r,.06)}`)}function xs(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Tt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Tt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Tt(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",Tt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Tt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",qn(e.accentColor,30)),t.style.setProperty("--accent-on-primary",qd(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${qn(e.accentColor,40)})`),t.style.setProperty("--border-accent",Tt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Tt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Tt(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 ${Tt(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 ai(){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 Cg(e){try{localStorage.setItem(Yd,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=bs()?"dark":"light";xs($t(t))}else ai(),jr(e,bs()?"dark":"light")}function Ig(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Sn();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=bs()?"dark":"light";xs($t(t))}else ai(),jr(e,bs()?"dark":"light")}function bs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function wt({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 ar({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 Mg({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=l.useState(()=>$t(r));l.useEffect(()=>{a($t(r))},[r]);const o=l.useCallback((i,c)=>{a(u=>{const m={...u,[i]:c},h=$t(r==="dark"?"light":"dark");return r==="dark"?nn(m,h):nn(h,m),xs(m),t(m),m})},[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(ar,{title:"App Background",children:[s.jsx(wt,{label:"Background",value:n.bgPrimary,onChange:i=>o("bgPrimary",i)}),s.jsx(wt,{label:"Surface",value:n.bgSecondary,onChange:i=>o("bgSecondary",i)}),s.jsx(wt,{label:"Card",value:n.surfacePrimary,onChange:i=>o("surfacePrimary",i)})]}),s.jsxs(ar,{title:"App Text",children:[s.jsx(wt,{label:"Primary",value:n.textPrimary,onChange:i=>o("textPrimary",i)}),s.jsx(wt,{label:"Secondary",value:n.textSecondary,onChange:i=>o("textSecondary",i)}),s.jsx(wt,{label:"Muted",value:n.textMuted,onChange:i=>o("textMuted",i)})]}),s.jsxs(ar,{title:"Borders & Accent",children:[s.jsx(wt,{label:"Border subtle",value:n.borderSubtle,onChange:i=>o("borderSubtle",i)}),s.jsx(wt,{label:"Border default",value:n.borderDefault,onChange:i=>o("borderDefault",i)}),s.jsx(wt,{label:"Accent",value:n.accentColor,onChange:i=>o("accentColor",i)})]})]}),s.jsxs("div",{children:[s.jsxs(ar,{title:"Chat Bubbles",children:[s.jsx(wt,{label:"User bubble",value:n.userBubble,onChange:i=>o("userBubble",i)}),s.jsx(wt,{label:"User text",value:n.userText,onChange:i=>o("userText",i)}),s.jsx(wt,{label:"Agent bubble",value:n.assistantBubble,onChange:i=>o("assistantBubble",i)}),s.jsx(wt,{label:"Agent text",value:n.assistantText,onChange:i=>o("assistantText",i)})]}),s.jsxs(ar,{title:"Chat Layout",children:[s.jsx(wt,{label:"Chat BG",value:n.containerBg,onChange:i=>o("containerBg",i)}),s.jsx(wt,{label:"Send button",value:n.sendButton,onChange:i=>o("sendButton",i)}),s.jsx(wt,{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?Co:Io,u=$t(e?"light":"dark");e?nn(i,u):nn(u,i),a(i),xs(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 Ag(){const[e,t]=l.useState(Sn),[r,n]=l.useState(!0),[a,o]=l.useState(()=>$t("dark"));l.useEffect(()=>{n(bs());const u=new MutationObserver(()=>{const h=bs();n(h);const f=Sn();f==="custom"?xs($t(h?"dark":"light")):jr(f,h?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const h=bs();n(h);const f=Sn();f==="custom"?xs($t(h?"dark":"light")):jr(f,h?"dark":"light")};return m.addEventListener("change",d),()=>{u.disconnect(),m.removeEventListener("change",d)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?xs($t(r?"dark":"light")):(ai(),jr(e,r?"dark":"light"))},[e,r]),l.useEffect(()=>{o($t(r?"dark":"light"))},[r]);const i=u=>{t(u),Cg(u)},c=[...Sg,{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(u=>{const m=e===u.id,d=r?u.preview.dark:u.preview.light,h=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>i(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:m?"var(--bg-glass-hover)":"var(--bg-glass)",border:m?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:m?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:d.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.userBubble,color:h},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[m&&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:u.id==="custom"?"🎨 Custom":u.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&s.jsx(Mg,{dark:r,onColorsChange:u=>o(u)})]})}const oi="adhdev_mobileDashboardMode_v1",Mo="adhdev:mobile-dashboard-mode-change";function ii(){try{return localStorage.getItem(oi)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Tg(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??ii())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==oi||t()};return window.addEventListener(Mo,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Mo,r),window.removeEventListener("storage",n)}}function _g(e){try{localStorage.setItem(oi,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Mo,{detail:e}))}function Lg(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(ii()==="chat")},[]),s.jsx(us,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ks,{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),_g(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Aa=new Map,Ml=new Map;function Rg(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 Pg(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 Jd(){const{sendCommand:e}=ot(),{injectEntries:t,getIdes:r}=Cr();return l.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??px,i=Ml.get(n)||0;if(!(a!=null&&a.force)&&i>0&&Date.now()-i<o)return;const c=Aa.get(n);if(c)return c;const u=(async()=>{const m=await e(n,"get_machine_runtime_stats"),d=Rg(m);if(!d)return;const h=r().find(y=>y.id===n),f=Pg(h,n,d.machine,d.timestamp||Date.now());t([f]),Ml.set(n,Date.now())})().finally(()=>{Aa.delete(n)});return Aa.set(n,u),u},[r,t,e])}function Dg(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 Eg(e,t){const{sendData:r}=ot(),{injectEntries:n,getIdes:a}=Cr(),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(u=>zt.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:t==null?void 0:t.intervalMs}},d=>{const h=a().find(y=>y.id===u),f=Dg(h,u,d);n([f])}));return()=>{c.forEach(u=>u())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function $g(e,t){const{sendData:r}=ot(),[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 u=zt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},m=>{c&&(clearTimeout(c),c=null),a(m.diagnostics),i(!1)});return u.initialSendAccepted?c=setTimeout(()=>{i(!1)},gx):i(!1),()=>{c&&clearTimeout(c),u()}},[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 Bg(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Qd(e){const{sendData:t}=ot(),[r,n]=l.useState({});return l.useEffect(()=>{const a=Bg(e);if(!a||!e.sessionId||!t){n({});return}const o=zt.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{n({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),$s.record({interactionId:i.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:i.status,modalButtonCount:Array.isArray(i.modalButtons)?i.modalButtons.length:0}})});return o.initialSendAccepted||n({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const Zd="adhdev_hiddenTabs",eu="adhdev_autoHiddenMeshTabs";function Og(){try{const e=localStorage.getItem(Zd);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function cs(e){try{localStorage.setItem(Zd,JSON.stringify([...e]))}catch{}}function Fg(){try{const e=localStorage.getItem(eu);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function Al(e){try{localStorage.setItem(eu,JSON.stringify([...e]))}catch{}}function pr(e){return Mr(e)}function ca(e,t){return Yt(t).some(r=>e.has(r))}function tu(e){var t,r,n;return((t=e.settings)==null?void 0:t.launchedByCoordinator)===!0&&typeof((r=e.settings)==null?void 0:r.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0&&((n=e.settings)==null?void 0:n.spawnedSessionVisibility)==="hidden"}function Hg(e,t,r=new Set){return e.filter(n=>{if(!tu(n))return!1;const a=pr(n);return r.has(a)?!1:!ca(t,n)})}function Wg(){const[e,t]=l.useState(Og),[r,n]=l.useState(Fg),a=l.useCallback(f=>{const y=pr(f);t(b=>{const x=new Set(b);return x.has(y)?x.delete(y):x.add(y),cs(x),x})},[]),o=l.useCallback(f=>{const y=pr(f);t(b=>{if(b.has(y))return b;const x=new Set(b);return x.add(y),cs(x),x})},[]),i=l.useCallback(f=>{const y=pr(f);t(b=>{if(b.has(y))return b;const x=new Set(b);return x.add(y),cs(x),x}),n(b=>{if(b.has(y))return b;const x=new Set(b);return x.add(y),Al(x),x})},[]),c=l.useCallback(f=>{const y=pr(f);t(b=>{if(!b.has(y))return b;const x=new Set(b);return x.delete(y),cs(x),x}),n(b=>{if(b.has(y))return b;const x=new Set(b);return x.add(y),Al(x),x})},[]),u=l.useCallback(()=>{t(f=>{if(f.size===0)return f;const y=new Set;return cs(y),y})},[]),m=l.useCallback((f,y)=>{t(b=>{const x=new Set(b);for(const j of y)x.add(j);return cs(x),x})},[]),d=l.useCallback((f,y)=>{t(b=>{const x=new Set(b);for(const j of y)x.delete(j);return cs(x),x})},[]),h=l.useCallback(f=>ca(e,f),[e]);return{hiddenTabs:e,autoHiddenTabs:r,toggleTarget:a,hideTarget:o,autoHideTarget:i,showTarget:c,showAllTabs:u,hideAllForDaemon:m,showAllForDaemon:d,isHidden:h}}const an="adhdev_mutedConversations",Ta="adhdev_autoMutedMeshConversations";function Tl(e){try{const t=localStorage.getItem(e);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function or(e,t){try{localStorage.setItem(e,JSON.stringify([...t]))}catch{}}function Kg(e,t){return Yt(t).some(r=>e.has(r))}function Ug(){const[e,t]=l.useState(()=>Tl(an)),[r,n]=l.useState(()=>Tl(Ta)),a=l.useCallback(m=>{const d=Mr(m);t(h=>{if(h.has(d))return h;const f=new Set(h);return f.add(d),or(an,f),f})},[]),o=l.useCallback(m=>{const d=Yt(m);t(h=>{let f=!1;const y=new Set(h);for(const b of d)y.delete(b)&&(f=!0);return f?(or(an,y),y):h}),n(h=>{let f=!1;const y=new Set(h);for(const b of d)y.delete(b)&&(f=!0);return f?(or(Ta,y),y):h})},[]),i=l.useCallback(m=>{Yt(m).some(f=>e.has(f))?o(m):a(m)},[e,a,o]),c=l.useCallback(m=>{if(!tu(m))return;const d=Mr(m);r.has(d)||(n(h=>{if(h.has(d))return h;const f=new Set(h);return f.add(d),or(Ta,f),f}),t(h=>{if(h.has(d))return h;const f=new Set(h);return f.add(d),or(an,f),f}))},[r]),u=l.useCallback(m=>Kg(e,m),[e]);return{mutedTargets:e,autoMutedTargets:r,muteTarget:a,unmuteTarget:o,toggleTarget:i,autoMuteIfCoordinator:c,isMuted:u}}function zg(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function Gg(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 Vg(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 qg({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(!zg(o))throw new Error(Gg(o));return}await Vg(e.sessionId,t,a)}function Yg(e){const{ides:t,isP2PActive:r,p2pStates:n}=Xt(),{sendCommand:a}=ot(),[o,i]=l.useState(null),[c,u]=l.useState(!1),[m,d]=l.useState(null),h=l.useMemo(()=>{const b=Op(t);return b?b.prompt.promptId===o?null:b:null},[o,t,e]),f=l.useCallback(async b=>{if(!h)return;const x=Jc(h.prompt,b);u(!0),d(null);try{const j=(n==null?void 0:n[h.daemonId])==="connected"||r===!0;await qg({promptSession:h,response:x,useP2PCommand:j,sendCommand:a}),i(h.prompt.promptId)}catch(j){throw d(j instanceof Error?j.message:String(j)),j}finally{u(!1)}},[r,n,h,a]),y=l.useCallback(()=>{h&&i(h.prompt.promptId)},[h]);return{promptSession:h,responseError:m,isSubmitting:c,submit:f,cancel:y}}function su(e){return e instanceof Error?e.message:String(e||"")}function Xg(e){const t=su(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 Jg(e){const t=su(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function ru({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!Xe(e)||Ge(e))return;const o=Vs(e);if(o===t)return;const i=e.sessionId;i&&a(c=>({...c,[i]:t}));try{await n(Ss(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Ut(e),mode:t})}catch(c){const u=Jg(c);i&&!u&&a(m=>{const d={...m};return o===nu(r,i)?delete d[i]:d[i]=o,d}),Xg(c)?console.warn(u?"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 _l(e,t){const r=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!r||e.transport!=="pty")return e;const n=t[r];return!n||e.mode===n?e:{...e,mode:n}}function Qg(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=_l(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(u=>_l(u,t)):a.childSessions,c=i!==a.childSessions;return o!==a||c?(r=!0,{...o,...c?{childSessions:i}:{}}):a});return r?n:e}function nu(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 Zg(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,o]of Object.entries(e))nu(t,a)===o&&(delete n[a],r=!0);return r?n:e}function ey({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){l.useEffect(()=>{ad()},[]);const a=l.useMemo(()=>e.map(o=>({id:o.tabKey,name:_d(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return gf(a),l.useEffect(()=>{if(Object.keys(t).length===0)return;const i=setTimeout(()=>{r(c=>{const u=Date.now(),m={};for(const[d,h]of Object.entries(c))u-h<5e3&&(m[d]=h);return Object.keys(m).length===Object.keys(c).length?c:m})},5500);return()=>clearTimeout(i)},[t,r]),l.useEffect(()=>{const o=setInterval(()=>{const i=Date.now()-3e5;n(c=>{const u=c.filter(m=>m.timestamp>i).slice(-100);return u.length===c.length?c:u})},6e4);return()=>clearInterval(o)},[n]),null}function Ll(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 gs(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=Ll(t==null?void 0:t.receivedAt)||Ll(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function Ao(e,t=0){return gs(e)||e.lastUpdated||t||0}function au(e){return gs(e)||e.lastUpdated||0}function ou(e,t,r=au){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 To(e){var r;const t=Lt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function ty(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!To(e)&&!e.title.trim()}function sy(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(To(r))-Number(To(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:ou(t,r)})[0]||null}function Bt(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=sy(a);return n?o&&ty(n)?o:n:o||r[0]||null}function ry(e){const t=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return!t||r.startsWith(`${t}:`)?r:`${t}:${r}`}function ny(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=ry(n),o=r.get(a);if(!o){r.set(a,n);continue}const i=(o.workspace?1:0)+(o.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(o.timestamp||0))&&r.set(a,n)}return Array.from(r.values())}function _a(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 ay(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 Rl(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?ay(Bs(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 oy(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||""),Rl(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||""),Rl(r.activeChat)].join(":"))].join("|")}function iy(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 ly(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of Yt({routeId:n.routeId}))r.set(o,a);for(const o of Yt({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Yt({tabKey:n.tabKey}))r.set(o,n)}return r}function cy(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function dy(e){const t=cy(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=Bs(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function uy({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=l.useMemo(()=>ny(e),[e]),o=l.useMemo(()=>Fd(e),[e]),i=l.useRef([]),c=l.useRef([]),u=l.useRef([]),m=l.useRef(new Map),d=l.useRef(new Map),h=l.useMemo(()=>{const S=new Map,v=[];for(const N of a){const{connectionState:_="new",machineName:D}=Hd(N,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),A=oy(N),M=m.current.get(N.id);if(M&&M.ide===N&&M.sourceSignature===A&&M.connectionState===_&&M.machineName===D){S.set(N.id,M),v.push(...M.conversations);continue}const R=ri(N,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),z={ide:N,sourceSignature:A,connectionState:_,machineName:D,conversations:R};S.set(N.id,z),v.push(...R)}m.current=S;const g=new Map,C=N=>{const _=dy(N),D=d.current.get(N.tabKey);if(D&&D.signature===_)return g.set(N.tabKey,D),D.timestamp;const A={signature:_,timestamp:au(N)||(D==null?void 0:D.timestamp)||0};return g.set(N.tabKey,A),A.timestamp},I=[...v].sort((N,_)=>ou(N,_,C));return d.current=g,I},[a,t,o]),f=l.useMemo(()=>{const S=iy(h,r);return _a(i.current,S)?i.current:(i.current=S,S)},[h,r]),y=l.useMemo(()=>{const S=new Map,v=Array.from(new Set(f.map(g=>g.routeId)));for(const g of v){const C=Bt(f,g);C&&S.set(g,C)}return S},[f]),b=l.useMemo(()=>{const S=new Map;for(const v of f){const g=y.get(v.routeId),C=v.streamSource==="native"&&g?g:v;for(const I of Yt({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))S.set(I,C)}return S},[f,y]),x=l.useMemo(()=>ly(f,y),[f,y]),j=l.useCallback(S=>{if(S)return b.get(S)},[b]),k=l.useCallback(S=>{if(S)return x.get(S)},[x]),p=l.useMemo(()=>{const S=f.filter(v=>!ca(n,v));return _a(c.current,S)?c.current:(c.current=S,S)},[f,n]),w=l.useMemo(()=>{const S=p.map(v=>v.tabKey);return _a(u.current,S)?u.current:(u.current=S,S)},[p]);return{chatIdes:a,conversations:f,visibleConversations:p,visibleTabKeys:w,resolveConversationBySessionId:j,resolveConversationByTarget:k}}function my({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 u=new URLSearchParams(c);return u.delete("activeTab"),u},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function hy({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){l.useEffect(()=>{Qe.setIdes(e)},[e]),l.useEffect(()=>{Qe.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=Qe.onToast(o=>{r(c=>c.some(m=>m.message===o.message&&o.timestamp-m.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(u=>u.id!==o.id)),i)});return()=>{a()}},[r]),l.useEffect(()=>{const a=Md.on("status_event",o=>{Qe.handleRawEvent(o,"ws")});return()=>{a()}},[]),l.useEffect(()=>{var o;const a=i=>{var x;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 u=c.targetSessionId||c.targetKey||c.daemonId,m=n(u),d=(m==null?void 0:m.routeId)||c.daemonId;if(!d)return;const h=Number(c.buttonIndex),f=c.button||((x=m==null?void 0:m.modalButtons)==null?void 0:x[h])||"Approve",y=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),b=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(y);t(d,"resolve_action",{action:b?"approve":"reject",button:f,...Number.isFinite(h)&&{buttonIndex:h},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(j=>console.error("[SW Action] approval failed:",j))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",a)}},[n,t])}const py="adhdev_dashboardLayout_v1",fy="adhdev_dashboardDockview_v1",xy="adhdev_dashboardDockviewHiddenRestore_v1",ir={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function li(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function by(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function iu(e){return`${py}:${e}`}function gy(e){const t=iu(e);return li(t,null)}function yy(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=iu(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function lu(e){return`${fy}:${e}`}function vy(e){const t=lu(e);return li(t,null)}function wy(e,t){try{const r=lu(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function cu(e){return`${xy}:${e}`}function jy(e){const t=cu(e);return li(t,{})}function ky(e,t){try{const r=cu(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Sy(){return{groupAssignments:[...ir.groupAssignments],focusedGroup:ir.focusedGroup,groupActiveTabIds:{...ir.groupActiveTabIds},groupTabOrders:{...ir.groupTabOrders},groupSizes:[...ir.groupSizes]}}function Ny(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Cy(){const[e]=l.useState(()=>by(typeof window<"u"?window.innerWidth:1280)),[t,r]=l.useState(()=>new Map),[n,a]=l.useState(0),[o,i]=l.useState({}),[c,u]=l.useState({}),[m,d]=l.useState([]),[h,f]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[y,b]=l.useState(!1),x=l.useCallback(()=>{if(y)return;const N=gy(e)??Sy();r(new Map(N.groupAssignments)),a(N.focusedGroup),i(N.groupActiveTabIds),u(N.groupTabOrders),d(N.groupSizes),b(!0)},[y,e]);l.useEffect(()=>{y&&yy(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:c,groupSizes:m})},[y,e,t,n,o,c,m]),l.useEffect(()=>{const N=window.matchMedia("(max-width: 767px)"),_=D=>f(D.matches);return N.addEventListener("change",_),()=>N.removeEventListener("change",_)},[]);const j=l.useCallback(N=>{r(N)},[]),k=l.useCallback(N=>{a(N)},[]),p=l.useCallback(N=>{i(N)},[]),w=l.useCallback(N=>{u(N)},[]),S=l.useCallback(N=>{d(N)},[]),v=l.useCallback(N=>{k(N)},[k]),g=l.useCallback((N,_)=>{i(D=>(D[N]??null)===(_??null)?D:{...D,[N]:_})},[]),C=l.useCallback((N,_)=>{u(D=>{const A=D[N];return Ny(A,_)?D:{...D,[N]:_}})},[]),I=l.useCallback((N,_)=>{const D=_.get(N)??0;return g(D,N),v(D),D},[v,g]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:j,focusedGroup:n,updateFocusedGroup:k,focusGroup:v,groupActiveTabIds:o,updateGroupActiveTabIds:p,setGroupActiveTab:g,groupTabOrders:c,updateGroupTabOrders:w,setGroupTabOrder:C,groupSizes:m,updateGroupSizes:S,isMobile:h,hasHydratedStoredLayout:y,hydrateStoredLayout:x,focusConversationTab:I}}function Iy(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=la(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function My({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:u,activeConv:m,isRefreshingHistory:d,ides:h,handleRefreshHistory:f}){const y=l.useRef(!1),b=l.useRef(!1),x=l.useRef(null),j=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,b.current=!0,x.current!=null&&(window.clearTimeout(x.current),x.current=null),c(p=>{const w=new URLSearchParams(p);return w.delete("activeTab"),w},{replace:!0}))},[e,t,r,n,a,o,i,c]),l.useEffect(()=>{if(!(b.current||a)&&t.length!==0){if(!e){o(),b.current=!0;return}if(y.current){b.current=!0;return}if(x.current==null)return x.current=window.setTimeout(()=>{x.current=null,!(b.current||a)&&(o(),b.current=!0)},1500),()=>{x.current!=null&&(window.clearTimeout(x.current),x.current=null)}}},[e,t.length,a,o]),l.useEffect(()=>{if(!u){j.current=!1;return}if(!m||j.current||d)return;const k=h.find(p=>p.id===m.routeId);k&&(!k.chats||k.chats.length===0||Iy(k.chats,m))&&(j.current=!0,f())},[u,m,d,h,f])}function La(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=la(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function du({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[i,c]=l.useState(!1),[u,m]=l.useState(!1),d=l.useCallback(async b=>{try{await e("standalone","launch_ide",{ideType:b,enableCdp:!0})}catch(x){console.error("Launch failed",x)}},[e]),h=l.useCallback(async(b,x)=>{try{const j=b||(t==null?void 0:t.daemonId)||"",k=await e(j,"switch_chat",{id:x,sessionId:x,...hs(t)}),p=k==null?void 0:k.result;if((k==null?void 0:k.success)===!0||p==="switched"||p==="switched-by-title")return;p===!1||p==="not_found"?rr(a,"⚠️ Session tab not found — try refreshing history"):typeof p=="string"&&p.startsWith("error:")?rr(a,`⚠️ Switch error: ${p}`):rr(a,"⚠️ Session switch failed")}catch(j){console.error("Switch failed",j),rr(a,`❌ Switch failed: ${j.message||"connection error"}`)}},[t,e,a]),f=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const b=ps(t);await e(b,"new_chat",{...hs(t)}),$x(b,t.sessionId,la(t)[0]),o(x=>({...x,[t.tabKey]:Date.now()}))}catch(b){console.error("New chat failed",b)}finally{c(!1)}}},[t,i,e,o]),y=l.useCallback(async()=>{var b,x;if(!(!t||u)){m(!0);try{const j=ps(t),k=async()=>e(j,"list_chats",{forceExpand:!0,...hs(t)});let p=await k(),w=(p==null?void 0:p.chats)||((b=p==null?void 0:p.result)==null?void 0:b.chats);La(w,t)&&(await new Promise(S=>setTimeout(S,450)),p=await k(),w=(p==null?void 0:p.chats)||((x=p==null?void 0:p.result)==null?void 0:x.chats)),p!=null&&p.success&&Array.isArray(w)&&(n(t.routeId,w),La(w,t)&&!La(r,t)&&rr(a,"⚠️ History dialog did not fully open — try once more"))}catch(j){console.error("Refresh history failed",j)}finally{m(!1)}}},[t,r,u,e,n,a]);return{isCreatingChat:i,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:h,handleNewChat:f,handleRefreshHistory:y}}function Ay(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 Ty(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Pl(e,t){const r=Object.keys(e),n=Object.keys(t);return r.length!==n.length?!1:r.every(a=>t[Number(a)]===e[Number(a)])}function on(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[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 u=a[c];typeof u=="number"&&u>0&&o.set(i,u)}return{assignments:o,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function Dl(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 _y(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 Ly(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 El(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 $l(e){return Array(e).fill(100/e)}function Ry({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:u,visibleTabKeys:m}){const d=l.useRef(null),h=l.useMemo(()=>on(e,m),[e,m]),f=h.assignments,y=l.useMemo(()=>c?1:h.groupCount,[h.groupCount,c]),b=y>1,x=l.useCallback((v,g)=>{t(C=>{const I=new Map(on(C,m).assignments);return g===0?I.delete(v):I.set(v,g),I}),n(C=>({...C,[g]:v})),r(g)},[t,m,n,r]),j=l.useCallback(v=>{t(g=>{const C=on(g,m).assignments,I=new Map;for(const[N,_]of C)_!==v&&(_>v?I.set(N,_-1):I.set(N,_));return I}),i(g=>{if(g.length<=1)return[];const C=[...g];C.splice(v,1);const I=C.reduce((N,_)=>N+_,0);return I>0?C.map(N=>N/I*100):[]}),r(0)},[t,m,i,r]),k=l.useCallback((v,g)=>{g.preventDefault();const C=d.current;if(!C)return;const I=g.clientX,N=C.offsetWidth,_=o.length===y?[...o]:$l(y),D=M=>{const z=(M.clientX-I)/N*100,T=[..._];T[v]=Math.max(15,_[v]+z),T[v+1]=Math.max(15,_[v+1]-z),i(T)},A=()=>{document.removeEventListener("mousemove",D),document.removeEventListener("mouseup",A),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",D),document.addEventListener("mouseup",A)},[o,y,i]),p=l.useCallback((v,g,C)=>{if(y>=4)return;const I=C==="left"?g:g+1;t(N=>{const _=on(N,m).assignments,D=new Map;for(const A of u){const M=_.get(A.tabKey)??0,R=M>=I?M+1:M;R>0&&D.set(A.tabKey,R)}return I>0&&D.set(v,I),D}),i(N=>{const _=N.length===y?[...N]:$l(y),D=_[g]??100/y,A=Math.max(15,D/2),M=Math.max(15,D/2),R=[..._];R[g]=A,R.splice(I,0,M);const z=R.reduce((T,L)=>T+L,0);return R.map(T=>T/z*100)}),n(N=>{const _=El(N,I);return _[I]=v,_}),a(N=>{const _=El(N,I);return _[I]=[v],_}),r(I)},[y,t,m,u,i,n,a,r]);l.useEffect(()=>{Ay(e,f)||t(f)},[e,f,t]),l.useEffect(()=>{const{mapping:v,usedGroups:g}=h;n(C=>{const I=Dl(C,v);return Pl(C,I)?C:I}),a(C=>{const I=Dl(C,v);return Pl(C,I)?C:I}),r(C=>{const I=c?0:_y(C,g,v);return C===I?C:I}),i(C=>{const I=c?[]:Ly(C,g,h.groupCount);return Ty(C,I)?C:I})},[h,c,n,a,r,i]);const w=l.useMemo(()=>{const v=Array.from({length:y},()=>[]);for(const g of u){const C=f.get(g.tabKey)??0,I=Math.min(C,y-1);v[I].push(g)}return v},[u,f,y]),S=l.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:d,normalizedGroupAssignments:f,numGroups:y,isSplitMode:b,groupedConvs:w,moveTabToGroup:x,closeGroup:j,handleResizeStart:k,splitTabRelative:p,clearAllSplits:S}}function Ra(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 Py(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 ln(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function ci(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=Ra(t.channel)||Ra(e.updateChannel)||Ra(e.releaseChannel)||void 0,n=Py(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=ln(t.targetVersion)||ln(e.serverVersion)||void 0,o=ln(t.minVersion)||void 0,i=ln(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 Ls(e,t=null){return ci(e).targetVersion||t}function uu(e){return ci(e).channel||null}function mu(e){const t=ci(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 Dy({ides:e,sendDaemonCommand:t}){const r="0.9.82",n=l.useMemo(()=>e.filter(h=>h.type!=="adhdev-daemon"?!1:ni(h,Ls(h,r))).sort((h,f)=>Number(wr(f,Ls(f,r)))-Number(wr(h,Ls(h,r)))),[r,e]),a=l.useMemo(()=>n.some(h=>wr(h,Ls(h,r))),[r,n]),o=l.useMemo(()=>n.map(h=>Ls(h,r)).find(h=>typeof h=="string"&&h.trim().length>0)||r,[r,n]),[i,c]=l.useState(!1),[u,m]=l.useState({}),d=l.useCallback(async h=>{var y,b;const f=e.find(x=>x.id===h);if(f){m(x=>({...x,[h]:"upgrading"}));try{const x=await t(h,"daemon_upgrade",mu(f));(y=x==null?void 0:x.result)!=null&&y.upgraded||(b=x==null?void 0:x.result)!=null&&b.success?m(j=>({...j,[h]:"done"})):m(j=>({...j,[h]:"error"}))}catch{m(x=>({...x,[h]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:u,handleBannerUpgrade:d}}const hu=80;function Nn(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function Ey(e){return{...e,createdAt:Nn(e.createdAt),updatedAt:Nn(e.updatedAt,e.createdAt),lastEventAt:Nn(e.lastEventAt,e.updatedAt||e.createdAt)}}function $y(e){const t=Mr(e);return t==="unknown:"?e.id:t}function By(e){return[e.type,wd(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Oy(e,t=hu){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=$y(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 Fy(e,t){const r=Date.now(),n=[];for(const a of e){const o=a.sessionId?t.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden)continue;const i=aa(a,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const u=Nn(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),m=By({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(Ey({id:m,dedupKey:m,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:ud(a),preview:qf(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return Oy(n)}function Hy(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function Wy(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=hu}=e,a=l.useMemo(()=>Fy(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=l.useMemo(()=>Hy(a),[a]);return{notifications:a,unreadCount:o}}function Ky({notifications:e,sendDaemonCommand:t}){const r=l.useCallback(o=>{const i=e.find(u=>u.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),n=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}const Uy=l.createContext(null);function pu(){return l.useContext(Uy)}function di(...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 zy(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 ui(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=zy(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 Gy(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 Vy(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function mi(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=Vy(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=(m,d)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${d}`:m==="/"||m==="\\"?`${i}${d}`:`${m.replace(/[\\/]+$/,"")}${i}${d}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(m=>(m==null?void 0:m.type)==="directory"&&typeof(m==null?void 0:m.name)=="string").map(m=>({name:m.name,path:typeof(m==null?void 0:m.path)=="string"&&m.path.trim()?m.path:c(o,m.name)})).sort((m,d)=>m.name.localeCompare(d.name)):[];return{path:o,directories:u}}function qy(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 fu(e,t={}){const r=e==null?void 0:e.mcpConfig;return(r==null?void 0:r.mode)!=="manual"?null:{serverName:r.serverName||"adhdev-mesh",configFormat:r.format,configPathCommand:r.configPathCommand,requiresRestart:r.requiresRestart===!0,instructions:r.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:qy(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function Yy(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 Ar(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function xu(e){return Er(e)||e.tabKey||e.routeId||null}function bu(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=Bt(e.conversations,n)||e.conversations.find(i=>i.routeId===n);if(o!=null&&o.tabKey)return o.tabKey}return t||r||n||null}function ts(e){return String(e||"").trim()}function gu(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Yn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Xy(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Jy(e,t){const r=ts(e.providerSessionId),n=ts(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(ts).filter(Boolean);return!!(r&&i.includes(r)||n&&i.includes(n))});return a?a.tabKey:n||r||null}function Qy(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=gu(t.daemonId);if(n&&n!==e.machineId)return null;const a=ts(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=ts(e.resumeSessionId),i=ts(e.launchedSessionId),c=ts(t.providerSessionId),u=ts(t.targetSessionId);if(o&&o!==c&&o!==u||i&&i!==c&&i!==u)return null;const m=Yn(e.workspacePath);if(m){const d=Yn(t.workspaceName);if(d&&!Xy(d,m))return null}return Jy(t,r)}function Bl(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Zy({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(u=>{o.current=u,a(u)},[]);return l.useEffect(()=>{if(!n)return;const u=Yn(n.workspacePath),m=e.find(h=>{var j,k,p,w;if(!h||h.type==="adhdev-daemon"||gu(h.daemonId||h.id)!==n.machineId||(Ir(h)?"cli":Ds(h)?"acp":"ide")!==n.kind)return!1;const b=String(h.agentType||h.type||"");if(n.providerType&&b!==n.providerType)return!1;if(n.resumeSessionId)return String(h.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const S=String(n.launchedSessionId||"");return[h.providerSessionId,h.sessionId,h.instanceId,h.id].map(g=>String(g||"")).filter(Boolean).includes(S)}if(u){const S=Yn(h.workspace||h.runtimeWorkspaceLabel);return S?S===u:!1}return Number(h.lastUpdated||h._lastUpdate||h.timestamp||((w=(p=(k=(j=h.activeChat)==null?void 0:j.messages)==null?void 0:k.at)==null?void 0:p.call(k,-1))==null?void 0:w.timestamp)||0)>=n.startedAt-5e3});if(!m)return;const d=bu({entrySessionId:m.sessionId,entryInstanceId:m.instanceId,entryRouteId:m.id,conversations:t});d&&(i(),r(d))},[i,t,e,r,n]),l.useEffect(()=>Qe.onStatusEvent(u=>{const m=o.current;if(!m)return;const d=Qy(m,u,t);d&&(i(),r(d))}),[i,t,r]),l.useEffect(()=>{if(!n)return;const u=window.setTimeout(()=>{a(m=>!m||m.startedAt!==n.startedAt?m:(o.current=null,null))},45e3);return()=>window.clearTimeout(u)},[n]),{trackPendingLaunch:c}}function e0({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const i=pu(),{launchCli:c}=ta(),u=l.useCallback(async(j,k)=>mi(e,j,k),[e]),m=l.useCallback(async(j,k)=>{if(!k.trim())return{ok:!1,error:"Choose a workspace path first."};try{const p=await e(j,"workspace_add",{path:k.trim()});return p!=null&&p.success?{ok:!0}:{ok:!1,error:(p==null?void 0:p.error)||"Could not save workspace"}}catch(p){return{ok:!1,error:p instanceof Error?p.message:"Could not save workspace"}}},[e]),d=l.useCallback(async(j,k,p)=>{var w;try{const S={ideType:k,enableCdp:!0};(w=p==null?void 0:p.workspacePath)!=null&&w.trim()&&(S.workspace=p.workspacePath.trim());const v=await e(j,"launch_ide",S);return!(v!=null&&v.success)&&(v==null?void 0:v.success)!==void 0?{ok:!1,error:(v==null?void 0:v.error)||"Could not launch IDE"}:(t({machineId:j,kind:"ide",providerType:k,workspacePath:(p==null?void 0:p.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(S){return{ok:!1,error:S instanceof Error?S.message:"Could not launch IDE"}}},[e,t]),h=l.useCallback(async(j,k,p,w)=>{var v,g,C;const S=Date.now();try{const I={cliType:p};(v=w==null?void 0:w.workspacePath)!=null&&v.trim()?I.dir=w.workspacePath.trim():w!=null&&w.workspaceId&&(I.workspaceId=w.workspaceId),(g=w==null?void 0:w.resumeSessionId)!=null&&g.trim()&&(I.resumeSessionId=w.resumeSessionId.trim()),Array.isArray(w==null?void 0:w.cliArgs)&&w.cliArgs.length>0&&(I.cliArgs=w.cliArgs),(C=w==null?void 0:w.initialModel)!=null&&C.trim()&&(I.initialModel=w.initialModel.trim());const N=await c(j,I),_=(N==null?void 0:N.result)||N,D=(_==null?void 0:_.sessionId)||(_==null?void 0:_.id);return N!=null&&N.success&&D?(t({machineId:j,kind:k,providerType:p,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,launchedSessionId:D,startedAt:S}),{ok:!0}):N!=null&&N.success?(t({machineId:j,kind:k,providerType:p,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:S}),{ok:!0}):{ok:!1,error:(N==null?void 0:N.error)||(_==null?void 0:_.error)||`Could not launch ${k.toUpperCase()} session`}}catch(I){return Bl(I)?(t({machineId:j,kind:k,providerType:p,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:S}),{ok:!0}):{ok:!1,error:I instanceof Error?I.message:`Could not launch ${k.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async j=>{var k;if(i!=null&&i.listMeshes)return i.listMeshes(j);if(!j)return[];try{const p=await e(j,"list_meshes",{}),w=(p==null?void 0:p.result)??p;if((w==null?void 0:w.success)===!1)throw new Error((w==null?void 0:w.error)||"Could not load meshes");return(Array.isArray(w==null?void 0:w.meshes)?w.meshes:Array.isArray((k=w==null?void 0:w.result)==null?void 0:k.meshes)?w.result.meshes:[]).map(v=>{var g;return{id:String((v==null?void 0:v.id)||""),name:String((v==null?void 0:v.name)||(v==null?void 0:v.id)||"Untitled mesh"),repoIdentity:(v==null?void 0:v.repoIdentity)||(v==null?void 0:v.repo_identity)||null,workspace:Array.isArray(v==null?void 0:v.nodes)&&v.nodes.length>0?String(((g=v.nodes[0])==null?void 0:g.workspace)||""):null,nodesCount:Array.isArray(v==null?void 0:v.nodes)?v.nodes.length:void 0,status:(v==null?void 0:v.status)||null}}).filter(v=>v.id)}catch(p){throw console.error("List meshes failed",p),p}},[i,e]),y=l.useCallback(async(j,k,p)=>{if(!k.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(j,k,p);const w=Date.now();try{const S={meshId:k.trim()};p.trim()&&(S.cliType=p.trim());const v=await e(j,"launch_mesh_coordinator",S),g=(v==null?void 0:v.result)??v;if((g==null?void 0:g.success)===!1||(v==null?void 0:v.success)===!1){const I=String((g==null?void 0:g.code)||(v==null?void 0:v.code)||""),N=Yy((g==null?void 0:g.meshCoordinatorSetup)||(g==null?void 0:g.manualSetup)||(v==null?void 0:v.meshCoordinatorSetup)||(v==null?void 0:v.manualSetup));return{ok:!1,error:(g==null?void 0:g.error)||(v==null?void 0:v.error)||"Could not launch mesh coordinator",code:I||void 0,manualSetup:N}}const C=(g==null?void 0:g.sessionId)||(g==null?void 0:g.id);return C?r(C):t({machineId:j,kind:"cli",providerType:(g==null?void 0:g.cliType)||p.trim()||void 0,workspacePath:(g==null?void 0:g.workspace)||null,startedAt:w}),{ok:!0}}catch(S){return Bl(S)?(t({machineId:j,kind:"cli",providerType:p.trim()||void 0,startedAt:w}),{ok:!0}):{ok:!1,error:S instanceof Error?S.message:"Could not launch mesh coordinator"}}},[i,r,e,t]),b=l.useCallback(async(j,k)=>{if(!j||!k)return[];try{const p=await e(j,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),w=(p==null?void 0:p.result)??p;return Array.isArray(w==null?void 0:w.sessions)?w.sessions:[]}catch(p){return console.error("List saved sessions failed",p),[]}},[e]),x=l.useCallback(async j=>{await ru({conversation:n,mode:j,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:u,handleSaveMachineWorkspace:m,handleLaunchMachineIde:d,handleLaunchMachineProvider:h,handleListMachineMeshes:f,handleLaunchMeshCoordinator:y,handleListMachineSavedSessions:b,setActiveCliViewMode:x}}function t0(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 s0(e,t,r=Date.now()){return!e||!t0(t)?null:{tabKey:e,nonce:r}}function r0({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:i}){const[c,u]=l.useState(null),[m,d]=l.useState(null),h=l.useMemo(()=>{var j,k;if(!e){if(c){const p=t.find(w=>w.tabKey===c);if(p)return p}return r[0]}const x=n[a];if(x){const p=t.find(w=>w.tabKey===x);if(p)return p}return((j=o[a])==null?void 0:j[0])||((k=o[0])==null?void 0:k[0])},[t,c,a,n,o,e,r]),f=l.useCallback(x=>{u(x)},[]),y=l.useCallback(x=>{u(x.tabKey),i(j=>{const k=new URLSearchParams(j),p=Xf(x);return p?k.set("activeTab",p):k.delete("activeTab"),k},{replace:!0})},[i]),b=l.useCallback((x,j)=>{const k=s0(x,j);k&&d(k)},[]);return{activeConv:h,openDesktopConversation:y,requestScrollToBottom:b,scrollToBottomRequest:m,setDesktopActiveTab:f}}function n0(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 a0(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 o0({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),u=l.useRef(null);l.useEffect(()=>{const m=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null),o.current=null};if(t){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const d=Dn(e,r),h=a0({tabKey:e.tabKey,historySessionId:Er(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:gs(e),liveState:d}),f=h.autoReadKey,y=n0({autoReadKey:f,shouldMarkSeen:h.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!h.shouldMarkSeen){y.shouldCancelPending&&m(),a.current=f;return}if(!y.shouldSchedule)return;y.shouldCancelPending&&m();const b=()=>{if(document.visibilityState!=="visible"||a.current===f)return;a.current=f,o.current=null,i.current=null,c.current=null,u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null);const j=h.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:j,completionMarker:h.completionMarker}).catch(()=>{})};if(o.current=y.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(b,1500);const j=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};u.current=j,document.addEventListener("visibilitychange",j);return}const x=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(b,800),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null))};u.current=x,document.addEventListener("visibilitychange",x)},[e,t,r,n]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),u.current&&document.removeEventListener("visibilitychange",u.current)},[])}function Pa(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 i0({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:u}){var B;const{launchCli:m}=ta(),[d,h]=l.useState(!1),[f,y]=l.useState([]),[b,x]=l.useState(()=>kt()),[j,k]=l.useState(!1),[p,w]=l.useState(null),S=l.useRef(null),v=l.useMemo(()=>r||t||e,[e,r,t]),g=!!v&&Xe(v)&&!Ge(v),C=l.useMemo(()=>{if(!v||!g)return null;const O=v.daemonId||v.routeId||"",$=Ut(v),E=Pa(v);return`${O}:${$}:${v.providerSessionId||""}:${E}`},[v,g]),I=l.useMemo(()=>!v||!g?"":Pa(v),[v,g]),{isCreatingChat:N,isRefreshingHistory:_,handleSwitchSession:D,handleNewChat:A,handleRefreshHistory:M}=du({sendDaemonCommand:a,activeConv:v,chats:(B=n.find(O=>O.id===(v==null?void 0:v.routeId)))==null?void 0:B.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),R=l.useCallback(()=>{h(!0)},[]),z=l.useCallback(()=>{h(!1)},[]),T=l.useCallback(async()=>{if(!(!v||!g||j)){k(!0);try{const O=v.daemonId||v.routeId,$=Ut(v),E=Pa(v),W=await a(O,"list_saved_sessions",{agentType:$,providerType:$,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},...E?{workspace:E}:{}}),J=(W==null?void 0:W.result)??W;y(Array.isArray(J==null?void 0:J.sessions)?J.sessions:[])}catch(O){console.error("Refresh saved sessions failed",O),y([])}finally{k(!1)}}},[v,j,g,a]);l.useEffect(()=>{if(!d){S.current=null;return}if(!g){S.current=null,y([]),k(!1);return}!C||j||S.current!==C&&(S.current=C,T())},[T,d,j,g,C]);const L=l.useCallback(async O=>{if(!v||!g||!O.providerSessionId||!O.workspace)return;const $=v.daemonId||v.routeId,E=Ut(v);try{w(O.providerSessionId);const W=await m($,{cliType:E,dir:O.workspace,resumeSessionId:O.providerSessionId,initialModel:rd(O.summaryMetadata,"model",{preferShortValue:!0})||void 0}),J=(W==null?void 0:W.result)??W,Q=typeof(J==null?void 0:J.sessionId)=="string"?J.sessionId:typeof(J==null?void 0:J.id)=="string"?J.id:"";Q&&u(ee=>{const me=new URLSearchParams(ee);return me.set("activeTab",Q),me},{replace:!0}),z()}catch(W){console.error("Resume saved session failed",W)}finally{w(null)}},[z,v,g,a,u]);return{historyModalOpen:d,openHistoryModal:R,closeHistoryModal:z,historyTargetConv:v,isSavedSessionHistoryTarget:g,isHistoryCreatingChat:N,isHistoryRefreshingHistory:_,handleHistorySwitchSession:D,handleHistoryNewChat:A,handleHistoryRefresh:M,savedHistorySessions:f,savedHistoryFilters:b,setSavedHistoryFilters:x,missingWorkspaceResumePath:I,isSavedHistoryLoading:j,resumingSavedHistorySessionId:p,handleRefreshSavedHistory:T,handleResumeSavedHistorySession:L}}function l0({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}){const[u,m]=l.useState(null),[d,h]=l.useState(null),f=l.useMemo(()=>{if(e||!n)return null;const k=c(n);return k&&!Xe(k)&&!Ge(k)?k:null},[e,n,c]),y=l.useMemo(()=>{const k=u==null?void 0:u.routeId;if(!k)return null;const p=u!=null&&u.tabKey?o.find(w=>w.tabKey===u.tabKey):a?o.find(w=>w.tabKey===a):null;return(p==null?void 0:p.routeId)===k?p:Bt(o,k)},[o,u,a]),b=l.useMemo(()=>{if(y)return i.find(k=>k.id===y.routeId)},[i,y]);l.useEffect(()=>{f&&(m({routeId:f.routeId,tabKey:al(f)}),h(f),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,f]);const x=l.useCallback(k=>{k&&(m({routeId:k.routeId,tabKey:al(k)}),h(k))},[]),j=l.useCallback(()=>{m(null),h(null)},[]);return{remoteDialogConv:y,remoteDialogIdeEntry:b,remoteDialogActiveConv:d,setRemoteDialogActiveConv:h,openRemoteDialog:x,closeRemoteDialog:j}}function c0({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:u,sendDaemonCommand:m}){const{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:f,setRemoteDialogActiveConv:y,openRemoteDialog:b,closeRemoteDialog:x}=l0({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}),[j,k]=l.useState(!1),[p,w]=l.useState(null),S=l.useCallback(async C=>{const I=C||u;!I||!Xe(I)&&!Ge(I)||(w(I),k(!0))},[u]),v=l.useCallback(()=>{k(!1),w(null)},[]),g=l.useCallback(async C=>{const I=p||u;if(!I||!Xe(I)&&!Ge(I)){v();return}k(!1);try{const N=Ut(I),_=I.routeId||I.daemonId||"";await m(_,"stop_cli",{cliType:N,targetSessionId:I.sessionId,mode:C})}catch(N){console.error("Stop CLI failed:",N)}finally{w(null)}},[u,v,p,m]);return{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:f,setRemoteDialogActiveConv:y,openRemoteDialog:b,closeRemoteDialog:x,cliStopDialogOpen:j,cliStopTargetConv:p,requestCliStop:S,cancelCliStop:v,confirmCliStop:g}}function Da(e,t=!0){return(e??!0)&&t}const hi=l.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:u,handleForceSendChat:m,isSendingChat:d,sendFeedbackMessage:h=null,handleFocusAgent:f,isFocusingAgent:y,actionLogs:b,userName:x,scrollToBottomRequestNonce:j,isInputActive:k=!0,isVisible:p=!0}){const w=n,S=!n,v=Da(p,w),g=Da(p,S),C=Da(p),I=Qd(t),N=I.status||I.modalMessage||I.modalButtons?{...t,...I.status?{status:I.status}:{},...I.modalMessage!==void 0?{modalMessage:I.modalMessage}:{},...I.modalButtons!==void 0?{modalButtons:I.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Zc,{activeConv:N,onModalButton:i}),N.transport!=="pty"&&N.transport!=="acp"&&N.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(Fs,{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,N.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:w?"visible":"hidden",pointerEvents:w?"auto":"none"},children:s.jsx(yb,{activeConv:N,clearToken:r,terminalRef:o,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:h,isVisible:v,isInputActive:k&&v})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:S?"visible":"hidden",pointerEvents:S?"auto":"none"},children:s.jsx(ko,{activeConv:N,ideEntry:a,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:h,handleFocusAgent:f,isFocusingAgent:y,actionLogs:b,userName:x,scrollToBottomRequestNonce:j,isInputActive:k&&g,isVisible:g})})]}):s.jsx(ko,{activeConv:N,ideEntry:a,handleSendChat:u,handleForceSendChat:m,isSendingChat:d,sendFeedbackMessage:h,handleFocusAgent:f,isFocusingAgent:y,actionLogs:b,userName:x,scrollToBottomRequestNonce:j,isInputActive:k&&C,isVisible:C})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.handleForceSendChat===t.handleForceSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function d0({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var w,S,v;const i=_r(),c=Ss(e),u=o?null:dd(e),m=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),d=!o&&e.streamSource==="agent-stream"&&!!e.agentName,h=!o&&!d&&(e.transport==="pty"||e.transport==="acp"),f=Ws(e),y=Yf(e),b=(w=e.settings)==null?void 0:w.meshNodeFor,x=e.meshQueueStats,j=((S=e.coordinator)==null?void 0:S.meshId)||((v=e.settings)==null?void 0:v.meshCoordinatorFor),k=l.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),p=l.useCallback(()=>{if(r){r();return}const g=xu(e);g&&i(Ar(g))},[e,i,r]);return!m&&!d&&!h&&!u&&!b&&!x?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[m&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:p,title:y,children:[s.jsx(Ot,{size:12}),s.jsx("span",{children:y})]}):s.jsxs("span",{className:"conversation-meta-chip",title:y,children:[s.jsx(Ot,{size:12}),s.jsx("span",{children:y})]})),d&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[s.jsx(Hs,{size:12}),s.jsx("span",{children:f})]}),h&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[s.jsx(Hs,{size:12}),s.jsx("span",{children:f})]}),u&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:k,title:u,children:[s.jsx(ns,{size:12}),s.jsx("span",{children:u})]}):s.jsxs("span",{className:"conversation-meta-chip",title:u,children:[s.jsx(ns,{size:12}),s.jsx("span",{children:u})]})),b&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(ns,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),j&&x&&s.jsxs("span",{className:`conversation-meta-chip ${x.pending>0?"is-active":""}`,style:x.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${x.pending} pending, ${x.assigned} assigned, ${x.completed} completed, ${x.failed} failed`,children:[s.jsx(Wh,{size:12}),s.jsxs("span",{children:[x.pending," Pending"]})]})]})}function u0({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:u,onBack:m,onOpenNativeConversation:d,onOpenMachine:h,onOpenHistory:f,onOpenRemote:y,onOpenMeshGraph:b,onStopCli:x,cliViewMode:j,onSetCliViewMode:k,handleSendChat:p,handleForceSendChat:w,handleFocusAgent:S,handleModalButton:v,handleRelaunch:g}){var A,M;const C=l.useRef(null),I=Xe(e)&&!t,N=I&&j==="terminal",_=!!e.daemonId&&!!((A=e.coordinator)!=null&&A.meshId||(M=e.settings)!=null&&M.meshCoordinatorFor),D=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 ${D} 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(Oo,{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:at(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(d0,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>h(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[I&&j&&s.jsx(Rd,{mode:j,onChange:k,compact:!0}),I&&x&&s.jsx("button",{onClick:()=>{x(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(gt,{size:14})}),_&&b&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>b(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(ss,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(Fo,{size:14})}),!t&&!I&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(e),type:"button",children:s.jsx(Ot,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(hi,{activeConv:e,clearToken:0,isCliTerminal:N,ideEntry:n,terminalRef:C,handleModalButton:v,handleRelaunch:g,handleSendChat:p,handleForceSendChat:w,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:S,isFocusingAgent:u,actionLogs:a,userName:o})})]})}const Ea={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 m0(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function yu(){const[e,t]=l.useState("unix"),[r,n]=l.useState("powershell"),[a,o]=l.useState(!1),i=e==="unix"?"unix":r;l.useEffect(()=>{t(m0())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(Ea[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:Ea[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Ea[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 vu({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Ot},{key:"chats",label:"Chats",icon:ks}];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 cn({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 Ms({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 lr({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 h0({conversation:e,onCancel:t,onConfirm:r}){const n=at(e),a=ws(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"fade-in relative w-full sm:w-[min(92vw,420px)] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] border border-border-subtle bg-bg-primary shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border-subtle bg-[var(--surface-primary)] px-4 py-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base font-extrabold text-text-primary",children:"Hide this chat from the inbox?"}),s.jsx("div",{className:"mt-1 text-[13px] leading-relaxed text-text-muted",children:"This only collapses the chat locally. You can restore it from Hidden tabs."})]}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary text-text-secondary transition-colors hover:bg-surface-primary hover:text-text-primary",onClick:t,"aria-label":"Cancel hide chat",children:s.jsx(gt,{size:16})})]}),s.jsx("div",{className:"px-4 py-4",children:s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary/60 px-3.5 py-3",children:[s.jsx("div",{className:"truncate text-sm font-bold text-text-primary",children:n}),s.jsx("div",{className:"mt-1 truncate text-xs text-text-muted",children:a})]})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-border-subtle bg-bg-secondary px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))]",children:[s.jsx("button",{type:"button",className:"btn btn-secondary min-h-[40px] px-4 text-sm",onClick:t,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary min-h-[40px] px-4 text-sm",onClick:r,children:"Hide tab"})]})]})]})}function dn({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onOpenMeshGraph:o,onCollectChatDebugBundle:i,isMuted:c,onToggleMute:u}){var A,M;const m=t==="needs_attention"||t==="task_complete",d=t==="working",h=t==="earlier",f=t==="task_complete",{isReconnecting:y,isConnecting:b}=Gs(e.conversation),x=at(e.conversation),j=ws(e.conversation),k=Td(e.conversation,{requiresAction:t==="needs_attention"}),p=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":d?"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",w=m?"bg-accent-primary shadow-glow":d?"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",S=h?"text-text-secondary":"text-text-primary",v=h?"text-text-muted":"text-text-secondary",g=h?"text-text-secondary opacity-80":"text-text-muted",C=h?"text-text-muted opacity-80":"text-text-muted",I=!d&&!f,N=!!e.conversation.daemonId&&!!((A=e.conversation.coordinator)!=null&&A.meshId||(M=e.conversation.settings)!=null&&M.meshCoordinatorFor),_="text-[color:var(--status-warning)]",D=R=>{if(!i)return;R.preventDefault(),R.stopPropagation();const z=i==null?void 0:i(e.conversation);Promise.resolve(z).catch(T=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",T)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${p}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||d?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 ${w}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:r(x)}),a&&s.jsxs("button",{type:"button",className:"mobile-inbox-hide-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-border-subtle bg-bg-primary/70 px-2 text-[10px] font-semibold text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:R=>{R.preventDefault(),R.stopPropagation(),a()},"aria-label":`Hide ${x}`,title:"Hide conversation",children:[s.jsx(Ho,{size:11}),s.jsx("span",{children:"Hide"})]}),u&&s.jsxs("button",{type:"button",className:`mobile-inbox-mute-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border px-2 text-[10px] font-semibold transition-colors ${c?"border-amber-500/40 bg-amber-500/10 text-amber-300 hover:bg-amber-500/20":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:R=>{R.preventDefault(),R.stopPropagation(),u()},"aria-label":c?`Unmute ${x}`:`Mute ${x}`,title:c?"Unmute (resume notifications)":"Mute notifications",children:[s.jsx(Lr,{size:11}),s.jsx("span",{children:c?"Muted":"Mute"})]}),N&&o&&s.jsxs("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-border-subtle bg-bg-primary/70 px-2 text-[10px] font-semibold text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:R=>{R.preventDefault(),R.stopPropagation(),o(e.conversation)},"aria-label":`Open mesh graph for ${x}`,title:"Open live repo mesh graph",children:[s.jsx(ss,{size:11}),s.jsx("span",{children:"Graph"})]})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:D,type:"button",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${S}`,children:x}),I&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${C}`,children:Qc(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${v}`,children:[s.jsx("span",{className:"truncate",children:j}),s.jsx(Fn,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),y?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${_} animate-pulse`,children:"Reconnecting…"})]}):b?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):k==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:_,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${g}`,children:e.preview})]}),m&&!f&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),f&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),d&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]})},e.conversation.tabKey)}function Ol({size:e=32}){return s.jsx("div",{className:"flex flex-col items-center gap-2.5",children:s.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}})})}function p0({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:u,sendDaemonCommand:m,onOpenConversation:d,onShowAllHidden:h,onHideConversation:f,onOpenMeshGraph:y,onOpenNewSession:b,onOpenMachine:x,onOpenSettings:j,onSectionChange:k,wsStatus:p="connected",isStandalone:w=!1,onCollectChatDebugBundle:S,isConversationMuted:v,onToggleMuteConversation:g}){const[C,I]=l.useState(null),N=p==="disconnected"||p==="reconnecting"||p==="offline"||p==="auth_failed",_=i.length>0,D=t.length>0||r.length>0||n.length>0||a.length>0,A=e==="machines"?"Machines":"Chats",M=w?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",R=w?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",z=l.useCallback(async B=>{const O=ps(B);if(!O)return;const $=Array.isArray(B.messages)?B.messages:[],E=xd({activeConv:B,visibleMessages:$,actionLogs:u,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:$.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),W=await m(O,"get_chat_debug_bundle",{...hs(B),delivery:"daemon_file",frontendSnapshot:E}),J=gr(W),Q=yd(J),ee=await gd(Q);ee==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),Qe.showToast(bd(J,{locatorCopyStatus:ee}),ee==="failed"?"warning":"success")},[u,m]),T=S||z,L=l.useCallback(()=>{C&&(f==null||f(C),I(null))},[C,f]);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 ${M}`,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:A}),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(Lr,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:j,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(sa,{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] ${R}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:N?s.jsx(lr,{icon:s.jsx(Ol,{}),title:p==="offline"?"Network offline":p==="auth_failed"?"Session expired":"Reconnecting",subtitle:p==="offline"?"Waiting for network…":p==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):i.length===0?s.jsx(lr,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:w?"Waiting for your daemon":"Connect your machines",subtitle:w?"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:!w&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(yu,{})})}):s.jsx(Ms,{children:i.map((B,O)=>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] ${O>0?"border-t border-border-subtle/70":""}`,onClick:()=>x(B.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:c(B.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:B.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:B.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[B.unread," new"]}):B.total>0?`${B.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:B.subtitle}),B.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[B.total," chat",B.total!==1?"s":"",B.unread>0?` · ${B.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},B.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(cn,{title:"Needs attention",className:"mb-0"}),s.jsx(Ms,{children:t.map((B,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(dn,{item:B,type:"needs_attention",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>I(B.conversation):void 0,onOpenMeshGraph:y,onCollectChatDebugBundle:T,isMuted:v==null?void 0:v(B.conversation),onToggleMute:g?()=>g(B.conversation):void 0})},B.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(cn,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(Ms,{children:r.map((B,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(dn,{item:B,type:"task_complete",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>I(B.conversation):void 0,onOpenMeshGraph:y,onCollectChatDebugBundle:T,isMuted:v==null?void 0:v(B.conversation),onToggleMute:g?()=>g(B.conversation):void 0})},B.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(cn,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(Ms,{children:n.map((B,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(dn,{item:B,type:"working",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>I(B.conversation):void 0,onOpenMeshGraph:y,onCollectChatDebugBundle:T,isMuted:v==null?void 0:v(B.conversation),onToggleMute:g?()=>g(B.conversation):void 0})},B.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(cn,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(Ms,{children:a.map((B,O)=>s.jsx("div",{className:O>0?"border-t border-border-subtle/70":"",children:s.jsx(dn,{item:B,type:"earlier",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>I(B.conversation):void 0,onOpenMeshGraph:y,onCollectChatDebugBundle:T,isMuted:v==null?void 0:v(B.conversation),onToggleMute:g?()=>g(B.conversation):void 0})},B.conversation.tabKey))}):D?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):N?s.jsx(lr,{icon:s.jsx(Ol,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):_?s.jsx(lr,{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(ks,{size:20})}),title:"No conversations yet",subtitle:Pd,children:b&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:b,"aria-label":Wt,title:Wt,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:Wt})]})}):s.jsx(lr,{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(Ms,{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:h,children:"Restore all"})]})})})]}),e==="chats"&&b&&D&&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:b,"aria-label":Wt,title:Wt,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),C&&s.jsx(h0,{conversation:C,onCancel:()=>I(null),onConfirm:L}),s.jsx(vu,{section:e,onSectionChange:k})]})}function f0(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 wu(e){const t=[e.workspace||"Workspace unknown"],r=vs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=f0(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function pi({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:u,onConfirm:m}){const[d,h]=l.useState(r);l.useEffect(()=>{h(r)},[r]);const f=Gy(r),y=d.trim();return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:c,"aria-label":"Close folder browser",children:s.jsx(gt,{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:()=>{!f||a||u(f)},disabled:!f||a,children:[s.jsx(Oo,{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:d,onChange:b=>h(b.target.value),onKeyDown:b=>{b.key!=="Enter"||!y||a||(b.preventDefault(),u(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||u(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(b=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(b.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Os,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:b.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:b.path})]})]},b.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(y||r),disabled:!y&&!r||a,children:i})]})]})})}function ju({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:i="Launch",busyLabel:c="Launching…",busy:u=!1,showArgsInput:m,argsValue:d,onArgsChange:h,showModelInput:f,modelValue:y,onModelChange:b,historyProviderNode:x,onConfirm:j,onCancel:k}){const p=n==null?void 0:n.find(w=>w.key===a);return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:k,"aria-label":"Close launch confirmation",children:s.jsx(gt,{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:w=>o(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:u,children:n.map(w=>s.jsx("option",{value:w.key,children:w.label},w.key))}),(p==null?void 0:p.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:p.description})]}),x,r.map(w=>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:w.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:w.value})]},`${w.label}:${w.value}`)),f&&b&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:y||"",onChange:w=>b(w.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),m&&h&&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:d||"",onChange:w=>h(w.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),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:u,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:j,disabled:u,children:[s.jsx(Oc,{size:14}),u?c:i]})]})]})})}function Fl(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ku(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 u of t.workspaces||[])o.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${Fl(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const i=(r==null?void 0:r.trim())||"",c=i?(t.workspaces||[]).find(u=>u.path===i):null;if(i&&!c&&o.push({key:`custom:${i}`,label:Fl(i),description:i,workspaceId:null,workspacePath:i}),n){const u=`saved:${n}`;if(o.some(m=>m.key===u))return{options:o,selectedKey:u}}return c?{options:o,selectedKey:`saved:${c.id}`}:i?{options:o,selectedKey:`custom:${i}`}:{options:o,selectedKey:"__home__"}}function x0(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function b0(e){return[x0(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function g0(e){return e.lastLaunchedAt?na(e.lastLaunchedAt):""}function Su(e){return{metaText:b0(e),updatedLabel:g0(e)}}function $a(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function y0({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var et,dt,ut,xt;const i=Dr(),[c,u]=l.useState(!1),m=(((et=e.detectedIdes)==null?void 0:et.length)||0)>0,d=l.useMemo(()=>(e.workspaces||[]).map(Ae=>({id:Ae.id,path:Ae.path,label:Ae.label})),[e]),h=e.defaultWorkspaceId||null,[f,y]=l.useState(h||((dt=d[0])==null?void 0:dt.id)||""),[b,x]=l.useState(""),[j,k]=l.useState(""),[p,w]=l.useState([]),[S,v]=l.useState(!1),[g,C]=l.useState(""),[I,N]=l.useState(!1),[_,D]=l.useState($a(m,t.length,r.length)),A=l.useRef(null),[M,R]=l.useState(null),z=l.useRef("__home__"),[T,L]=l.useState("__home__"),[B,O]=l.useState(""),[$,E]=l.useState(""),[W,J]=l.useState(""),[Q,ee]=l.useState([]),[me,je]=l.useState(()=>kt().textQuery),[Me,q]=l.useState(()=>kt().workspaceQuery),[G,he]=l.useState(()=>kt().modelQuery),[ue,ce]=l.useState(()=>kt().resumableOnly),[ve,X]=l.useState(()=>kt().sortMode),[we,de]=l.useState(!1),[ye,xe]=l.useState(!1),ge=l.useRef(null),le=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const be=f==="__custom__"?b.trim():((ut=d.find(Ae=>Ae.id===f))==null?void 0:ut.path)||"",ie=f==="__custom__"&&!!be&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),P=f!=="__custom__"&&((xt=d.find(Ae=>Ae.id===f))==null?void 0:xt.path)||"",fe=l.useMemo(()=>(e.recentLaunches||[]).map(Ae=>Ae.workspace),[e]),Ce=l.useCallback(async Ae=>{v(!0),C("");try{const He=await a(Ae);k(He.path),x(He.path),w(He.directories)}catch(He){C(He instanceof Error?He.message:"Could not load folder")}finally{v(!1)}},[a]),_e=l.useCallback(()=>{var He;y("__custom__"),N(!0);const Ae=ui(e.platform,di(b.trim(),P,fe,e.defaultWorkspacePath,(He=d.find(rt=>rt.id===h))==null?void 0:He.path,d.map(rt=>rt.path)));Ce(Ae)},[b,h,Ce,fe,P,e.platform,d]),se=l.useCallback(Ae=>{if(Ae!=null&&Ae.workspaceId){y(Ae.workspaceId),x("");return}if(Ae!=null&&Ae.workspacePath){y("__custom__"),x(Ae.workspacePath);return}y(""),x("")},[]),De=l.useCallback(Ae=>{if(y(Ae),Ae==="__custom__"){_e();return}x("")},[_e]),Te=l.useCallback(Ae=>{y("__custom__"),x(Ae)},[]),Ee=l.useCallback((Ae,He)=>{A.current=He,z.current=Ae.selectedWorkspaceKey||"__home__",L(Ae.selectedWorkspaceKey||"__home__"),O(Ae.initialArgs||""),E(Ae.initialModel||""),J(""),ee([]);const rt=Ae.providerType?`${e.id}:${Ae.providerType}`:null;if(Tb(le.current,rt)){const Ye=kt();je(Ye.textQuery),q(Ye.workspaceQuery),he(Ye.modelQuery),ce(Ye.resumableOnly),X(Ye.sortMode)}le.current=rt,R(Ae),Ae.providerType&&o&&(de(!0),o(Ae.providerType).then(Ye=>ee(Ye||[])).catch(Ye=>console.warn("Failed to load saved sessions",Ye)).finally(()=>de(!1)))},[o,e.id]),Oe=l.useMemo(()=>Dd(Q,{textQuery:me,workspaceQuery:Me,modelQuery:G,resumableOnly:ue,sortMode:ve}),[G,ue,Q,ve,me,Me]);l.useEffect(()=>{W&&(Oe.some(Ae=>Ae.providerSessionId===W)||J(""))},[Oe,W]);const Je=l.useCallback(()=>{A.current&&(xe(!0),A.current().finally(()=>{A.current=null,xe(!1),R(null)}))},[]),qe=l.useCallback(()=>{A.current=null,R(null)},[]),Ze=l.useCallback(Ae=>{z.current=Ae,L(Ae)},[]);return l.useEffect(()=>{var Ae;ge.current!==e.id&&(ge.current=e.id,y(h||((Ae=d[0])==null?void 0:Ae.id)||"__custom__"),x(""),k(""),w([]),C(""),N(!1),je(kt().textQuery),q(kt().workspaceQuery),he(kt().modelQuery),ce(kt().resumableOnly),X(kt().sortMode),le.current=null,D($a(m,t.length,r.length)))},[r.length,t.length,h,m,e.id,d]),l.useEffect(()=>{var Ae;f!=="__custom__"&&(f&&d.some(He=>He.id===f)||y(h||((Ae=d[0])==null?void 0:Ae.id)||"__custom__"))},[h,f,d]),l.useEffect(()=>{_==="ide"&&m||_==="cli"&&t.length>0||_==="acp"&&r.length>0||D($a(m,t.length,r.length))},[_,r.length,t.length,m]),{showAllRecent:c,setShowAllRecent:u,hasIdeOptions:m,workspaceRows:d,defaultWorkspaceId:h,workspaceChoice:f,customWorkspacePath:b,browseCurrentPath:j,browseDirectories:p,browseBusy:S,browseError:g,browseDialogOpen:I,activeLauncherKind:_,launchConfirm:M,launchConfirmWorkspaceKeyRef:z,launchConfirmWorkspaceKey:T,launchConfirmArgs:B,launchConfirmModel:$,launchConfirmResumeId:W,launchConfirmSavedSessions:Q,launchConfirmTextFilter:me,launchConfirmWorkspaceFilter:Me,launchConfirmModelFilter:G,launchConfirmResumableOnly:ue,launchConfirmSortMode:ve,filteredLaunchConfirmSavedSessions:Oe,launchConfirmSessionsLoading:we,launchConfirmBusy:ye,resolvedWorkspacePath:be,canCreateMissingWorkspace:ie,openBrowseDialog:_e,loadBrowsePath:Ce,handleWorkspaceChoiceChange:De,chooseCustomWorkspacePath:Te,setCustomWorkspacePath:x,setBrowseDialogOpen:N,setActiveLauncherKind:D,openLaunchConfirm:Ee,handleConfirmLaunch:Je,closeLaunchConfirm:qe,setWorkspaceSelectionFromOption:se,setLaunchConfirmWorkspaceKeyAndSync:Ze,setLaunchConfirmArgs:O,setLaunchConfirmModel:E,setLaunchConfirmResumeId:J,setLaunchConfirmTextFilter:je,setLaunchConfirmWorkspaceFilter:q,setLaunchConfirmModelFilter:he,setLaunchConfirmResumableOnly:ce,setLaunchConfirmSortMode:X}}function v0({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:u,section:m,showBottomNav:d,onBack:h,onSectionChange:f,onOpenConversation:y,onOpenRecent:b,onOpenMachineDetails:x,onMachineUpgrade:j,onLaunchDetectedIde:k,onAddWorkspace:p,onBrowseDirectory:w,onLaunchWorkspaceProvider:S,onListSavedSessions:v}){const g=T=>T==="ide"?"Workspace":T==="cli"?"CLI":"ACP",C=r.slice(0,4),I=t.slice(0,3),N=y0({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:c,onBrowseDirectory:w,onListSavedSessions:v}),_=l.useMemo(()=>C.map(T=>{const{metaText:L,updatedLabel:B}=Su(T);return{key:`recent-launch:${T.id}`,primary:T.label,secondary:L,updatedLabel:B,onClick:()=>{const{options:O,selectedKey:$}=ku({machine:{workspaces:N.workspaceRows,defaultWorkspaceId:N.defaultWorkspaceId},currentWorkspacePath:T.workspace});N.openLaunchConfirm({title:T.kind==="ide"?Wn("restart-ide",T.label):T.providerSessionId?Ed(T.label):Wn("start-fresh",T.label),description:T.kind==="ide"?Kn("restart-ide"):T.providerSessionId?$d():Kn("start-fresh"),confirmLabel:T.kind==="ide"?Un("restart-ide"):T.providerSessionId?Hn(!0):Un("start-fresh"),busyLabel:T.kind==="ide"?zn("restart-ide"):T.providerSessionId?ti(!0):zn("start-fresh"),workspaceOptions:O,selectedWorkspaceKey:$,details:[{label:"Mode",value:g(T.kind)},...T.providerType?[{label:"Provider",value:T.providerType}]:[]]},async()=>{const E=O.find(W=>W.key===N.launchConfirmWorkspaceKeyRef.current);N.setWorkspaceSelectionFromOption(E),await b({...T,workspace:(E==null?void 0:E.workspacePath)??null})})}}}),[N,b,C]),D=l.useMemo(()=>I.map(T=>({key:`recent-chat:${T.conversation.tabKey}`,primary:at(T.conversation),secondary:fb(T.conversation,{timestampLabel:T.timestamp?Qc(T.timestamp):null}),unread:T.unread,onClick:()=>y(T.conversation)})),[y,I]),A=N.showAllRecent?_:_.slice(0,4),M=_.length>0,R=D.length>0,z=u?"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 ${z} 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:h,type:"button","aria-label":"Back",children:s.jsx(Oo,{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:Mt(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:[R&&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:D.map(T=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${T.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:T.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:T.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:T.secondary})]},T.key))})]}),M&&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:A.map(T=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:T.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:T.primary}),T.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:T.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:T.secondary})]},T.key))}),_.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:()=>N.setShowAllRecent(T=>!T),children:N.showAllRecent?"Show fewer":`Show ${_.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:j,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:x,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"})]})]})]})]}),N.browseDialogOpen&&s.jsx(pi,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:N.browseCurrentPath,directories:N.browseDirectories,busy:N.browseBusy,error:N.browseError,confirmLabel:"Use this folder",onClose:()=>N.setBrowseDialogOpen(!1),onNavigate:T=>{N.loadBrowsePath(T)},onConfirm:T=>{N.chooseCustomWorkspacePath(T),N.setBrowseDialogOpen(!1)}}),N.launchConfirm&&s.jsx(ju,{title:N.launchConfirm.title,description:N.launchConfirm.description,details:N.launchConfirm.details,workspaceOptions:N.launchConfirm.workspaceOptions,selectedWorkspaceKey:N.launchConfirmWorkspaceKey,onWorkspaceChange:N.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:N.launchConfirm.providerType?Hn(!!N.launchConfirmResumeId):N.launchConfirm.confirmLabel,busyLabel:N.launchConfirm.providerType?void 0:N.launchConfirm.busyLabel,busy:N.launchConfirmBusy,showArgsInput:N.launchConfirm.showArgsInput,argsValue:N.launchConfirmArgs,onArgsChange:N.setLaunchConfirmArgs,showModelInput:N.launchConfirm.showModelInput,modelValue:N.launchConfirmModel,onModelChange:N.setLaunchConfirmModel,historyProviderNode:N.launchConfirm.providerType&&(N.launchConfirmSessionsLoading||N.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"}),N.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:si()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:N.launchConfirmTextFilter,onChange:T=>N.setLaunchConfirmTextFilter(T.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:N.launchConfirmBusy||N.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:N.launchConfirmWorkspaceFilter,onChange:T=>N.setLaunchConfirmWorkspaceFilter(T.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:N.launchConfirmBusy||N.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:N.launchConfirmModelFilter,onChange:T=>N.setLaunchConfirmModelFilter(T.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:N.launchConfirmBusy||N.launchConfirmSessionsLoading}),s.jsxs("select",{value:N.launchConfirmSortMode,onChange:T=>N.setLaunchConfirmSortMode(T.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:N.launchConfirmBusy||N.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:N.launchConfirmResumableOnly,onChange:T=>N.setLaunchConfirmResumableOnly(T.target.checked),disabled:N.launchConfirmBusy||N.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:N.launchConfirmResumeId,onChange:T=>N.setLaunchConfirmResumeId(T.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:N.launchConfirmBusy||N.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Rb()}),N.filteredLaunchConfirmSavedSessions.map(T=>s.jsxs("option",{value:T.providerSessionId,disabled:!T.canResume,children:[T.title||T.providerSessionId," ",T.canResume?"":"(workspace missing)"]},T.providerSessionId))]}),!N.launchConfirmSessionsLoading&&N.launchConfirmSavedSessions.length>0&&N.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),N.launchConfirmResumeId&&(()=>{const T=N.filteredLaunchConfirmSavedSessions.find(B=>B.providerSessionId===N.launchConfirmResumeId);if(!T)return null;const L=wu(T);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:L.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:L.providerSessionId}),s.jsx("div",{className:"mt-1",children:L.metaLine}),L.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:L.updatedLabel}),L.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:L.preview})]})})()]}),onConfirm:N.handleConfirmLaunch,onCancel:N.closeLaunchConfirm}),d&&s.jsx(vu,{section:m,onSectionChange:f})]})}function Cn(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function w0(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:Cn(e)}function j0(e){var r;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":"Offline"}function k0(e,t){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:vs(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var i;const a=Ir(n)?"cli":Ds(n)?"acp":"ide",o=vs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||(Ir(n)?n.cliName||n.type:Ds(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ds(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 S0(e,t){const r=new Map;for(const n of t){const a=Ss(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((h,f)=>f.timestamp-h.timestamp)[0]||null,i=(o==null?void 0:o.conversation)||null,c=xo(n),u=a.filter(h=>h.unread||h.requiresAction).length,m=j0(n),d=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:Mt(n,{fallbackId:n.id}),subtitle:d.join(" · "),unread:u,total:a.length,latestConversation:i,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:c,preview:i?xb(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 N0(e){return e==="chat"}function un(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 C0({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:y,setSelectedTabKey:b,setScreen:x,setSelectedMachineId:j,setSection:k,setMachineBackTarget:p,resetMachineAction:w}){const S=l.useRef(null),v=l.useCallback(g=>{if(!(g!=null&&g.sessionId))return;const C=Dn(g,i),I=Math.max(Date.now(),gs(g),C.lastUpdated||0);un("mark_read:start",{tabKey:g.tabKey,sessionId:g.sessionId,displayPrimary:at(g),inboxBucket:C.inboxBucket,unread:C.unread,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,activityAt:gs(g),readAt:I}),c(Ss(g)||g.routeId,"mark_session_seen",{sessionId:g.sessionId,providerSessionId:g.providerSessionId,seenAt:I,completionMarker:C.completionMarker}).then(N=>{un("mark_read:result",{tabKey:g.tabKey,sessionId:g.sessionId,result:N})}).catch(N=>{un("mark_read:error",{tabKey:g.tabKey,sessionId:g.sessionId,error:N instanceof Error?N.message:String(N)})})},[i,c]);return l.useEffect(()=>{var C;if(!n){N0(o)&&x("inbox"),b(((C=e[0])==null?void 0:C.tabKey)||null),S.current=null;return}if(o!=="chat"){S.current=null;return}const g=`${n.tabKey}:${n.sessionId||""}`;S.current!==g&&(S.current=g,v(n))},[e,v,o,n,x,b]),l.useEffect(()=>{if(!u)return;const g=e.find(C=>C.tabKey===u);g&&(b(g.tabKey),x("chat"),m==null||m())},[e,m,u,x,b]),l.useEffect(()=>{if(!d)return;const g=t.find(C=>C.id===d);g&&(j(g.id),w(),k("machines"),p("inbox"),x("machine"),h==null||h())},[t,h,d,w,p,x,k,j]),l.useEffect(()=>{f&&(k(f),x("inbox"),y==null||y())},[y,f,x,k]),l.useEffect(()=>{const g=r.filter(C=>C.inboxBucket==="task_complete"||C.unread);g.length!==0&&un("inbox_state",{screen:o,selectedTabKey:a,items:g.map(C=>{const I=Dn(C.conversation,i);return{liveState:I,tabKey:C.conversation.tabKey,sessionId:C.conversation.sessionId,displayPrimary:at(C.conversation),serverBucket:I.inboxBucket,computedBucket:C.inboxBucket,serverUnread:I.unread,computedUnread:C.unread,lastSeenAt:I.lastSeenAt,lastUpdated:I.lastUpdated,activityAt:gs(C.conversation)}})})},[r,i,o,a]),{markConversationRead:v}}function I0(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Hl(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function M0(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function A0({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const{launchCli:a}=ta(),[o,i]=l.useState("idle"),[c,u]=l.useState(""),[m,d]=l.useState(null),h=l.useCallback(()=>{i("idle"),u(""),d(null)},[]),f=l.useCallback(async(w,S,v)=>{var g;try{i("loading"),u(`Launching ${S}…`);const C={ideType:S,enableCdp:!0};(g=v==null?void 0:v.workspacePath)!=null&&g.trim()&&(C.workspace=v.workspacePath.trim()),await e(w,"launch_ide",C),i("done"),u(`${S} launch requested`)}catch(C){i("error"),u(C instanceof Error?C.message:"Launch IDE failed"),console.error("Launch IDE failed",C)}},[e]),y=l.useCallback(async(w,S,v)=>{if(S.trim())try{i("loading"),u(v!=null&&v.createIfMissing?"Creating folder…":"Saving workspace…");const g=await e(w,"workspace_add",{path:S.trim(),createIfMissing:(v==null?void 0:v.createIfMissing)===!0});if(g!=null&&g.success){i("done"),u(v!=null&&v.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),u((g==null?void 0:g.error)||"Could not save workspace")}catch(g){i("error"),u(g instanceof Error?g.message:"Could not save workspace")}},[e]),b=l.useCallback(async w=>{var S,v,g,C,I,N;try{i("loading"),u("Starting daemon upgrade…");const _=await e(w,"daemon_upgrade",{});if((S=_==null?void 0:_.result)!=null&&S.alreadyLatest){i("done"),u(`Already on v${((v=_==null?void 0:_.result)==null?void 0:v.version)||"latest"}.`);return}if((g=_==null?void 0:_.result)!=null&&g.upgraded||(C=_==null?void 0:_.result)!=null&&C.success){i("done"),u(`Upgrade to v${((I=_==null?void 0:_.result)==null?void 0:I.version)||"latest"} started. Daemon is restarting…`);return}i("error"),u(((N=_==null?void 0:_.result)==null?void 0:N.error)||"Upgrade failed")}catch(_){i("error"),u(_ instanceof Error?_.message:"Upgrade failed")}},[e]),x=l.useCallback(async(w,S,v,g)=>{var N,_,D;const C=Date.now(),I={machineId:w,kind:S,providerType:v,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:C};try{i("loading"),u(`Launching ${v}…`),d(I);const A={cliType:v};(N=g==null?void 0:g.workspacePath)!=null&&N.trim()?A.dir=g.workspacePath.trim():g!=null&&g.workspaceId&&(A.workspaceId=g.workspaceId),g!=null&&g.resumeSessionId&&(A.resumeSessionId=g.resumeSessionId),(_=g==null?void 0:g.args)!=null&&_.trim()&&(A.cliArgs=g.args.trim().split(/\s+/).filter(Boolean)),(D=g==null?void 0:g.model)!=null&&D.trim()&&(A.initialModel=g.model.trim());const M=await a(w,A),R=(M==null?void 0:M.result)||M,z=(R==null?void 0:R.sessionId)||(R==null?void 0:R.id);if(M!=null&&M.success&&z){d(null),i("done"),u(`${v} launched`),t(Ar(z));return}if(M!=null&&M.success){i("loading"),u(`${v} launch requested — waiting for session…`);return}d(null),i("error"),u((M==null?void 0:M.error)||(R==null?void 0:R.error)||`Could not launch ${S.toUpperCase()} workspace`)}catch(A){if(M0(A)){i("loading"),u(`${v} launch requested — waiting for session…`);return}d(null),i("error"),u(A instanceof Error?A.message:`Could not launch ${S.toUpperCase()} workspace`)}},[t,e]),j=l.useCallback(async(w,S)=>{try{const v=await e(w,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),g=(v==null?void 0:v.result)??v;return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]}catch(v){return console.error("Failed to list saved sessions on mobile:",v),[]}},[e]),k=l.useCallback(async(w,S)=>mi(e,w,S),[e]);l.useEffect(()=>{if(!m)return;const w=Hl(m.workspacePath),S=r.find(g=>{var A,M,R,z;if(!g||g.type==="adhdev-daemon"||I0(g.daemonId||g.id)!==m.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==m.kind||String(g.agentType||g.type||"")!==m.providerType)return!1;const _=String(g.providerSessionId||"");if(m.resumeSessionId&&_)return _===m.resumeSessionId;if(w){const T=Hl(g.workspace||g.runtimeWorkspaceLabel);return T?T===w:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((z=(R=(M=(A=g.activeChat)==null?void 0:A.messages)==null?void 0:M.at)==null?void 0:R.call(M,-1))==null?void 0:z.timestamp)||0)>=m.startedAt-5e3});if(!S)return;const v=bu({entrySessionId:S.sessionId,entryInstanceId:S.instanceId,entryRouteId:S.id,conversations:n});v&&(d(null),i("done"),u(`${m.providerType} launched`),t(Ar(v)))},[n,r,t,m]),l.useEffect(()=>{if(!m)return;const w=window.setTimeout(()=>{d(S=>!S||S.startedAt!==m.startedAt?S:(i("error"),u("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(w)},[m]);const p=l.useCallback(async(w,S)=>{if(S.kind==="ide"&&S.providerType){await f(w,S.providerType,{workspacePath:S.workspace||null});return}(S.kind==="cli"||S.kind==="acp")&&S.providerType&&await x(w,S.kind,S.providerType,{workspacePath:S.workspace||null,resumeSessionId:S.providerSessionId||null})},[f,x]);return{machineAction:{state:o,message:c},resetMachineAction:h,handleLaunchDetectedIde:f,handleAddWorkspace:y,handleMachineUpgrade:b,handleLaunchWorkspaceProvider:x,handleListSavedSessions:j,handleBrowseDirectory:k,handleOpenRecent:p}}function T0({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:u,setMachineBackTarget:m}){const d=l.useCallback(k=>{o(k.tabKey),i("chat"),n(k)},[n,i,o]),h=l.useCallback(k=>{const p=e.find(w=>w.routeId===k.routeId&&w.streamSource==="native");p&&(o(p.tabKey),i("chat"),n(p))},[e,n,i,o]),f=l.useCallback(()=>{n(t),i("inbox")},[n,t,i]),y=l.useCallback((k,p="inbox")=>{c(k),a(),u("machines"),m(p),i("machine")},[a,m,i,u,c]),b=l.useCallback(k=>{const p=Ss(k);p&&y(p,"chat")},[y]),x=l.useCallback(()=>{a(),i(r)},[r,a,i]),j=l.useCallback(k=>{u(k),i("inbox")},[i,u]);return{openConversation:d,openNativeConversation:h,backFromConversation:f,openMachine:y,openConversationMachine:b,backFromMachine:x,changeMachineSection:j}}function Ks(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function _0(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function L0({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:y,onOpenHistory:b,onOpenRemote:x,onStopCli:j,wsStatus:k,isConnected:p,onShowAllHiddenConversations:w,onHideConversation:S,onOpenMeshGraph:v,onOpenNewSession:g,liveSessionInboxState:C,setCliViewModeOverrides:I}){const[N,_]=l.useState(()=>{var se;return((se=e[0])==null?void 0:se.tabKey)||null}),[D,A]=l.useState(()=>e[0]?"chat":"inbox"),[M,R]=l.useState("chats"),[z,T]=l.useState(null),[L,B]=l.useState("inbox"),O=l.useRef([]),$=_r(),E="0.9.82",W=l.useMemo(()=>e.find(se=>se.tabKey===N)||e[0]||null,[e,N]),J=l.useMemo(()=>W?r.find(se=>se.id===W.routeId):void 0,[r,W]),Q=l.useMemo(()=>!W||Ge(W)||!Xe(W)?null:Vs(W),[W]),ee=l.useMemo(()=>r.filter(se=>se.type==="adhdev-daemon").sort(Vo),[r]),me=l.useMemo(()=>ee.find(se=>se.id===z)||null,[ee,z]),je=ia({sendDaemonCommand:a,activeConv:W||void 0,setActionLogs:o,isStandalone:i}),Me=A0({sendDaemonCommand:a,navigate:$,ides:r,conversations:e}),q=l.useMemo(()=>e.map(se=>{const De=D==="chat"&&(W==null?void 0:W.tabKey)===se.tabKey,Te=aa(se,C,{hideOpenTaskCompleteUnread:!0,isOpenConversation:De}),Ee=gs(se),Oe=Ad(se);return{conversation:se,timestamp:Ee,preview:Oe,unread:Te.unread,requiresAction:Te.requiresAction,isWorking:Te.isWorking,inboxBucket:Te.inboxBucket}}),[e,C,D,W]),{markConversationRead:G}=C0({conversations:e,machineEntries:ee,items:q,selectedConversation:W,selectedTabKey:N,screen:D,liveSessionInboxState:C,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:y,setSelectedTabKey:_,setScreen:A,setSelectedMachineId:T,setSection:R,setMachineBackTarget:B,resetMachineAction:Me.resetMachineAction}),he=T0({conversations:e,selectedConversation:W,machineBackTarget:L,markConversationRead:G,resetMachineAction:Me.resetMachineAction,setSelectedTabKey:_,setScreen:A,setSelectedMachineId:T,setSection:R,setMachineBackTarget:B}),{isMuted:ue,autoMuteIfCoordinator:ce,toggleTarget:ve}=Ug();l.useEffect(()=>{if(i)for(const se of q)ce(se.conversation)},[q,i,ce]);const X=l.useMemo(()=>Cn(q.filter(se=>se.requiresAction&&!ue(se.conversation))),[q,ue]),we=l.useMemo(()=>Cn(q.filter(se=>se.unread&&!se.requiresAction&&!ue(se.conversation))),[q,ue]),de=l.useMemo(()=>w0(q.filter(se=>!se.unread&&!se.requiresAction&&se.isWorking),O.current),[q]);l.useEffect(()=>{O.current=de.map(se=>se.conversation.tabKey)},[de]);const ye=l.useMemo(()=>Cn(q.filter(se=>!se.unread&&!se.requiresAction&&!se.isWorking)),[q]),xe=l.useMemo(()=>me?q.filter(se=>Ss(se.conversation)===me.id):[],[q,me]),ge=l.useMemo(()=>k0(me,r),[r,me]),le=(me==null?void 0:me.version)||null,be=!!me&&!!le&&!0&&le!==E,ie=l.useMemo(()=>(me==null?void 0:me.availableProviders)||[],[me]),P=l.useMemo(()=>ie.filter(se=>Ks(se,"cli")).map(se=>({type:se.type,displayName:se.displayName||se.type,icon:se.icon})),[ie]),fe=l.useMemo(()=>ie.filter(se=>Ks(se,"acp")).map(se=>({type:se.type,displayName:se.displayName||se.type,icon:se.icon})),[ie]),Ce=l.useMemo(()=>S0(ee,q),[q,ee]),_e=l.useCallback(async se=>{me&&await Me.handleOpenRecent(me.id,se)},[Me,me]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:D==="chat"&&W?s.jsx(u0,{selectedConversation:W,isAcp:Ge(W),isStandalone:i,selectedIdeEntry:J,actionLogs:n,userName:c,isSendingChat:je.isSendingChat,sendFeedbackMessage:je.sendFeedbackMessage,isFocusingAgent:je.isFocusingAgent,handleModalButton:je.handleModalButton,handleRelaunch:je.handleRelaunch,onBack:he.backFromConversation,onOpenNativeConversation:he.openNativeConversation,onOpenMachine:he.openConversationMachine,onOpenHistory:b,onOpenRemote:x,onOpenMeshGraph:v,onStopCli:j,cliViewMode:Q,onSetCliViewMode:async se=>{await ru({conversation:W,mode:se,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:I})},handleSendChat:je.handleSendChat,handleForceSendChat:je.handleForceSendChat,handleFocusAgent:je.handleFocusAgent}):D==="machine"&&me?s.jsx(v0,{selectedMachineEntry:me,selectedMachineConversations:xe,selectedMachineRecentLaunches:ge,cliProviders:P,acpProviders:fe,selectedMachineNeedsUpgrade:be,appVersion:E,machineAction:Me.machineAction,isStandalone:i,section:M,showBottomNav:L==="inbox",onBack:he.backFromMachine,onSectionChange:he.changeMachineSection,onOpenConversation:he.openConversation,onOpenRecent:_e,onOpenMachineDetails:()=>$(`/machines/${me.id}`),onMachineUpgrade:()=>Me.handleMachineUpgrade(me.id),onLaunchDetectedIde:(se,De)=>Me.handleLaunchDetectedIde(me.id,se,De),onAddWorkspace:(se,De)=>Me.handleAddWorkspace(me.id,se,De),onBrowseDirectory:se=>Me.handleBrowseDirectory(me.id,se),onLaunchWorkspaceProvider:(se,De,Te)=>Me.handleLaunchWorkspaceProvider(me.id,se,De,Te),onListSavedSessions:se=>Me.handleListSavedSessions(me.id,se)}):s.jsx(p0,{section:M,attentionItems:X,unreadItems:we,workingItems:de,completedItems:ye,hiddenConversations:t,machineCards:Ce,getAvatarText:_0,actionLogs:n,sendDaemonCommand:a,onOpenConversation:he.openConversation,onShowAllHidden:w,onHideConversation:S,onOpenMeshGraph:v,onOpenNewSession:g,onOpenMachine:he.openMachine,onOpenSettings:()=>$("/settings"),onSectionChange:R,wsStatus:k,isConnected:p,isStandalone:i,isConversationMuted:i?ue:void 0,onToggleMuteConversation:i?ve:void 0})})}function Ba(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function R0({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const i=l.useRef(0),[c,u]=l.useState(!1),[m,d]=l.useState(null),h=l.useCallback(()=>{i.current=0,u(!1),d(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const f=l.useCallback(j=>{j.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,u(!0))},[]),y=l.useCallback(j=>{if(!j.dataTransfer.types.includes("text/tab-key"))return;if(j.preventDefault(),!Ba(t,r)){d("merge");return}const k=j.currentTarget.getBoundingClientRect(),p=j.clientX-k.left,w=k.width/3;p<w?d("split-left"):p>w*2?d("split-right"):d("merge")},[t,r]),b=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,u(!1),d(null))},[]),x=l.useCallback(j=>{i.current=0,u(!1);const k=j.dataTransfer.getData("text/tab-key"),p=k?e.some(S=>S.tabKey===k):!1,w=m;if(d(null),o(),!!k){if(j.preventDefault(),w==="split-left"&&Ba(t,r)){r==null||r(k,"split-left");return}if(w==="split-right"&&Ba(t,r)){r==null||r(k,"split-right");return}if(p){a(k);return}n==null||n(k)}},[e,m,t,r,n,a,o]);return{dragOver:c,dropAction:m,resetDragState:h,handleDragEnter:f,handleDragOver:y,handleDragLeave:b,handleDrop:x}}function P0(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 D0({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,i]=l.useState(t??null),[c,u]=l.useState(r??[]),[m,d]=l.useState(null),h=l.useRef(null),f=l.useRef(null),y=l.useRef(n),b=l.useRef(a);l.useEffect(()=>{y.current=n},[n]),l.useEffect(()=>{b.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{u(C=>{const I=P0(C,e);return I.length===C.length&&I.every((N,_)=>N===C[_])?C:I})},[e]);const x=l.useMemo(()=>{const C=m??c;if(C.length===0)return e;const I=new Map(C.map((N,_)=>[N,_]));return[...e].sort((N,_)=>{const D=I.get(N.tabKey)??999,A=I.get(_.tabKey)??999;return D-A})},[e,m,c]);l.useEffect(()=>{var I,N;if(x.length===0){o!==null&&(i(null),(I=y.current)==null||I.call(y,null));return}if(o&&x.some(_=>_.tabKey===o))return;const C=x[0].tabKey;C!==o&&(i(C),(N=y.current)==null||N.call(y,C))},[x,o]);const j=l.useMemo(()=>x.find(C=>C.tabKey===o),[x,o]),k=l.useCallback(C=>{var I;i(C),(I=y.current)==null||I.call(y,C)},[]),p=l.useCallback((C,I,N)=>{u(_=>{var R;const D=_.filter(z=>z!==C),A=D.indexOf(I);if(A<0)return _;const M=N==="left"?A:A+1;return D.splice(M,0,C),(R=b.current)==null||R.call(b,D),D}),d(null)},[]),w=l.useCallback((C,I,N)=>{const D=(c.length>0?c:e.map(R=>R.tabKey)).filter(R=>R!==C),A=D.indexOf(I);if(A<0)return;const M=N==="left"?A:A+1;D.splice(M,0,C),h.current=D,d(D)},[c,e]),S=l.useCallback(()=>{var I;const C=h.current;C&&(u(C),(I=b.current)==null||I.call(b,C))},[]),v=l.useCallback(()=>{h.current=null,d(null)},[]),g=l.useCallback(C=>{u(I=>{var _;const N=I.filter(D=>D!==C);return N.push(C),(_=b.current)==null||_.call(b,N),N})},[]);return{activeTabId:o,activeConv:j,sortedConversations:x,previewOrderRef:h,draggingTabRef:f,selectTab:k,handleTabReorder:p,updatePreviewOrder:w,commitPreviewOrder:S,clearPreviewOrder:v,moveTabToEnd:g,setDraggingTabKey:C=>{f.current=C}}}function E0({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 fi({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,u=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?Pd: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:u}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),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:Wt,"aria-label":Wt,children:[s.jsx(Fc,{size:14}),s.jsx("span",{children:Wt})]})}),i&&s.jsx(yu,{}),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 Nu="adhdev-tab-shortcuts";function Cu(){try{return JSON.parse(localStorage.getItem(Nu)||"{}")}catch{return{}}}function Iu({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>Cu()),[c,u]=l.useState(null),m=l.useCallback(h=>{const f=[];return h.metaKey&&f.push(a?"⌘":"Meta"),h.ctrlKey&&f.push("Ctrl"),h.altKey&&f.push(a?"⌥":"Alt"),h.shiftKey&&f.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(f.push(h.key.length===1?h.key.toUpperCase():h.key),f.join("+"))},[a]),d=l.useCallback(h=>{i(h);try{localStorage.setItem(Nu,JSON.stringify(h))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const h=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){u(null);return}const y=m(f);if(!y)return;const b={...o};for(const[x,j]of Object.entries(b))j===y&&delete b[x];b[c]=y,d(b),u(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,c,o,d,m]),l.useEffect(()=>{if(!e)return;const h=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[y,b]of Object.entries(o))if(t.includes(y)&&m(f)===b){f.preventDefault(),r(),n(y);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,o,t,r,n,m]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:u,saveShortcuts:d}}const Oa=e=>{e.preventDefault()},$0=l.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:u,onSelectTab:m,onConversationActivated:d,onPreviewReorder:h,onReorderTab:f,onCommitPreviewOrder:y,onClearPreviewOrder:b,onDragStateReset:x,onDragTabKeyChange:j,onReceiveTab:k,onOpenContextMenu:p,longPressTimer:w,isGroupActive:S}){const v=Gs(t),g=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",C=v.isReconnecting,I=hb(t),N=pb(t),_=l.useCallback(O=>{c.current=t.tabKey,j(t.tabKey),O.dataTransfer.setData("text/tab-key",t.tabKey),O.dataTransfer.effectAllowed="move"},[t.tabKey,c,j]),D=l.useCallback(()=>{c.current=null,j(null),y(),b(),x()},[c,j,y,b,x]),A=l.useCallback(O=>{const $=c.current;if(!(!$||$===t.tabKey)&&O.dataTransfer.types.includes("text/tab-key")){O.preventDefault(),O.stopPropagation();const E=O.currentTarget.getBoundingClientRect(),W=O.clientX<E.left+E.width/2?"left":"right";h($,t.tabKey,W)}},[t.tabKey,c,h]),M=l.useCallback(O=>{O.preventDefault(),O.stopPropagation();const $=O.dataTransfer.getData("text/tab-key");if($&&$!==t.tabKey){const E=O.currentTarget.getBoundingClientRect(),W=O.clientX<E.left+E.width/2?"left":"right";i.includes($)?f($,t.tabKey,W):k&&k($)}b()},[t.tabKey,i,f,k,b]),R=l.useCallback(O=>{O.stopPropagation(),u(),m(t.tabKey),d(t)},[t,d,u,m]),z=l.useCallback(O=>{O.preventDefault(),p(O.clientX,O.clientY,t.tabKey)},[t.tabKey,p]),T=l.useCallback(O=>{const $=O.touches[0];w.current=setTimeout(()=>{p($.clientX,$.clientY,t.tabKey)},600)},[t.tabKey,w,p]),L=l.useCallback(()=>{w.current&&clearTimeout(w.current)},[w]),B=["adhdev-dockview-tab",g,r&&"is-active",S&&"is-group-active",C&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:B,draggable:!0,onDragStart:_,onDragEnd:D,onDragOver:A,onDrop:M,onClick:R,onContextMenu:z,onTouchStart:T,onTouchEnd:L,onTouchMove:L,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:v.isGenerating?s.jsx("div",{className:"tab-spinner"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):C?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.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:"○"})}),I.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:N,"aria-label":N||I.join(" · "),children:I.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:at(t),children:at(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[C?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:fs(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[fs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:fs(t)}),s.jsx(Fn,{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 B0({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:m,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:f,onDragTabKeyChange:y,onReceiveTab:b,onHideTab:x,isGroupActive:j,allowTabShortcuts:k=!0}){const[p,w]=l.useState(null),S=l.useRef(null),v=l.useRef(null),g=l.useMemo(()=>e.map(M=>M.tabKey),[e]);Rr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(p==null?void 0:p.tabKey)||null});const{isMac:C,tabShortcuts:I,shortcutListening:N,setShortcutListening:_,saveShortcuts:D}=Iu({enabled:k,sortedTabKeys:e.map(M=>M.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!p)return;const M=R=>{const z=document.querySelector("[data-pane-context-menu]");z&&z.contains(R.target)||w(null)};return window.addEventListener("mousedown",M,!0),()=>window.removeEventListener("mousedown",M,!0)},[p]),l.useEffect(()=>{const M=v.current;if(!M)return;const R=z=>{Math.abs(z.deltaY)<=Math.abs(z.deltaX)||(z.preventDefault(),M.scrollLeft+=z.deltaY)};return M.addEventListener("wheel",R,{passive:!1}),()=>M.removeEventListener("wheel",R)},[]);const A=l.useCallback((M,R,z)=>{w({x:M,y:R,tabKey:z})},[]);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:v,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(M=>s.jsx($0,{conv:M,isActive:t===M.tabKey,isDraggedTab:a.current===M.tabKey,isTaskCompleteUnread:n.has(M.tabKey),shortcut:k?I[M.tabKey]:void 0,conversationKeys:g,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:m,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:f,onDragTabKeyChange:y,onReceiveTab:b,onOpenContextMenu:A,longPressTimer:S,isGroupActive:j},M.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),p&&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:p.x,top:p.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:Oa,onClick:M=>{M.stopPropagation(),_(p.tabKey),w(null)},children:["⌨ ",I[p.tabKey]?`Change shortcut (${I[p.tabKey]})`:"Set shortcut"]}),I[p.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:Oa,onClick:()=>{const M={...I};delete M[p.tabKey],D(M),w(null)},children:"✕ Remove shortcut"})]}),x&&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:Oa,onClick:()=>{x(p.tabKey),w(null)},children:"🚫 Hide from Dashboard"})]})]}),k&&N&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>_(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:M=>M.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",C?"⌘+1":"Ctrl+1",", ",C?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function O0({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,userName:u,groupIndex:m,onFocus:d,isSplitMode:h,numGroups:f,onMoveTab:y,onReceiveTab:b,style:x,onActiveTabChange:j,initialActiveTabId:k,initialTabOrder:p,onTabOrderChange:w,onHideTab:S,isFocused:v,allowTabShortcuts:g=!0,onOpenNewSession:C,liveSessionInboxState:I}){const{sendCommand:N}=ot(),_=l.useRef(null),{activeTabId:D,activeConv:A,sortedConversations:M,draggingTabRef:R,selectTab:z,handleTabReorder:T,updatePreviewOrder:L,commitPreviewOrder:B,clearPreviewOrder:O,moveTabToEnd:$,setDraggingTabKey:E}=D0({conversations:e,initialActiveTabId:k,initialTabOrder:p,onActiveTabChange:j,onTabOrderChange:w}),W=ia({sendDaemonCommand:a,activeConv:A,setActionLogs:o,isStandalone:i}),{dragOver:J,dropAction:Q,resetDragState:ee,handleDragEnter:me,handleDragOver:je,handleDragLeave:Me,handleDrop:q}=R0({conversations:e,numGroups:f,onMoveTab:y,onReceiveTab:b,onOwnTabDrop:$,onClearPreviewOrder:O}),G=A&&!Ge(A)&&Vs(A)==="terminal",he=l.useMemo(()=>A?t.find(X=>X.id===A.routeId):void 0,[t,A]),ue=l.useMemo(()=>A?n.filter(X=>X.routeId===A.tabKey):[],[n,A]),ce=l.useMemo(()=>new Set(M.filter(X=>zp(X,I,{isOpenConversation:X.tabKey===D})).map(X=>X.tabKey)),[D,I,M]);Rr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:D,dragOver:J});const ve=l.useCallback(X=>{X.streamSource==="agent-stream"&&X.agentType&&N(X.routeId,fd(),{agentType:X.agentType,...X.sessionId&&{targetSessionId:X.sessionId}}).catch(()=>{})},[N]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:d,style:{...x,outline:J?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(B0,{conversations:M,activeTabId:D,groupIndex:m,numGroups:f,unreadTabKeys:ce,draggingTabRef:R,onFocus:d,onSelectTab:z,onConversationActivated:ve,onPreviewReorder:L,onReorderTab:T,onCommitPreviewOrder:B,onClearPreviewOrder:O,onDragStateReset:ee,onDragTabKeyChange:E,onMoveTab:y,onReceiveTab:b,onHideTab:S,isGroupActive:v??!1,allowTabShortcuts:g}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:me,onDragOver:je,onDragLeave:Me,onDrop:q,children:[J&&s.jsx(E0,{dropAction:Q,canSplit:!!(f<4&&y)}),A?s.jsx(hi,{activeConv:A,clearToken:r[A.tabKey]||0,isCliTerminal:!!G,ideEntry:he,terminalRef:_,handleModalButton:W.handleModalButton,handleRelaunch:W.handleRelaunch,handleSendChat:W.handleSendChat,handleForceSendChat:W.handleForceSendChat,isSendingChat:W.isSendingChat,sendFeedbackMessage:W.sendFeedbackMessage,handleFocusAgent:W.handleFocusAgent,isFocusingAgent:W.isFocusingAgent,actionLogs:ue,userName:u,isInputActive:!h||!!v}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(fi,{conversationsCount:e.length,isSplitMode:h,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:C})})]})]})}function F0({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:m,isStandalone:d,hasRegisteredMachines:h,userName:f,focusedGroup:y,focusGroup:b,moveTabToGroup:x,splitTabRelative:j,closeGroup:k,handleResizeStart:p,groupActiveTabIds:w,setGroupActiveTab:S,groupTabOrders:v,setGroupTabOrder:g,toggleHiddenTab:C,onOpenNewSession:I,allowTabShortcuts:N=!0,liveSessionInboxState:_}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((D,A)=>{const M=t&&n.length===r?`${n[A]}%`:void 0;return s.jsxs(bt.Fragment,{children:[t&&A>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:R=>p(A-1,R),onDoubleClick:()=>k(A),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(O0,{style:t?{flexBasis:M??`${100/r}%`,flexGrow:M?0:1,flexShrink:M?0:1}:void 0,conversations:D,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:m,isStandalone:d,hasRegisteredMachines:h,userName:f,groupIndex:A,isFocused:t&&y===A,onFocus:()=>b(A),isSplitMode:t,numGroups:r,onMoveTab:(R,z)=>{z==="left"&&A>0?x(R,A-1):z==="right"&&A<r-1?x(R,A+1):z==="split-left"&&r<4?j(R,A,"left"):z==="split-right"&&r<4&&j(R,A,"right")},onReceiveTab:R=>x(R,A),onActiveTabChange:R=>S(A,R),initialActiveTabId:w[A],initialTabOrder:v[A],onTabOrderChange:R=>g(A,R),onHideTab:C,onOpenNewSession:I,allowTabShortcuts:N,liveSessionInboxState:_})]},A)})})}function Mu({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?it.onScreenshot("ide-page",(d,h)=>{if(d!==e)return;const f=new FileReader;f.onload=()=>o(f.result),f.readAsDataURL(h)}):void 0,[e]),l.useEffect(()=>{r!=="connected"&&o(null)},[r]),l.useEffect(()=>{var d;return e?((d=it.onStatus)==null?void 0:d.call(it,(h,f)=>{h===e&&f!=null&&f.screenshotUsage&&c(f.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const m=e?it.get(e):null;if(!(!m||r!=="connected"))return n!=="chat"&&t?m.startScreenshots(t):m.stopScreenshots(t),()=>{m.stopScreenshots(t)}},[n,r,t,e]);const u=l.useCallback(async(m,d)=>{const h=e?it.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(m,d,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:i,handleRemoteAction:u}}const Au="adhdev-dashboard-action-shortcuts",H0=1200,W0=[["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 K0(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function st(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 Tu(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:st("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:st("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:st("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:st("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:st("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:st("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:st("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:st("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:st("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:st("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:st("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:st("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:st("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:st("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:st("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:st("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:st("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:st("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:st("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:st("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:st("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:st("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:st("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:st("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:st("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:st("toggleCliView",e)}]}function _o(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Xn(e){const t=Object.fromEntries(Tu(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Au)||"{}"),n={...t,...r};for(const[a,o]of W0)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function _u(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function U0({enabled:e=!0,onTrigger:t}){const r=K0(),[n,a]=l.useState(()=>Xn(r)),[o,i]=l.useState(null),[c,u]=l.useState([]),m=l.useRef({parts:[],timer:null}),d=l.useCallback(x=>{const j=[];return x.metaKey&&j.push(r?"⌘":"Meta"),x.ctrlKey&&j.push("Ctrl"),x.altKey&&j.push(r?"⌥":"Alt"),x.shiftKey&&x.key.length!==1&&j.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(x.key)?null:(j.push(_u(x.key)),j.join("+"))},[r]),h=l.useCallback(x=>{a(x);try{localStorage.setItem(Au,JSON.stringify(x))}catch{}},[]);l.useEffect(()=>{const x=Xn(r),j=Object.entries(n),k=Object.entries(x);j.length===k.length&&j.every(([p,w])=>x[p]===w)||h(x)},[n,r,h]);const f=l.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),y=l.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},H0))},[]);l.useEffect(()=>{if(!o)return;const x=j=>{if(j.preventDefault(),j.stopPropagation(),j.key==="Escape"){i(null),u([]);return}const k=d(j);if(!k)return;const w=!(j.metaKey||j.ctrlKey||j.altKey)&&/^[A-Z0-9]$/.test(k);if(c.length===0&&w){u([k]);return}const v=[...c,k].slice(0,2).join(" "),g={...n};for(const[C,I]of Object.entries(g))I===v&&delete g[C];g[o]=v,h(g),i(null),u([])};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[n,d,h,o,c]),l.useEffect(()=>{if(!e||o)return;const x=j=>{if(j.defaultPrevented)return;const k=d(j);if(!k)return;const p=j.metaKey||j.ctrlKey||j.altKey;if(_o(j.target))return;const w=m.current.parts,S=p?[k]:[...w.slice(-1),k].slice(-2),v=S.join(" "),g=S[S.length-1],C=Object.entries(n).filter(([,A])=>!!A),I=C.find(([,A])=>A===v);if(I){j.preventDefault(),f(),t(I[0]);return}if(C.some(([,A])=>A.startsWith(`${v} `))){j.preventDefault(),m.current.parts=S,y();return}const _=C.find(([,A])=>A===g);if(_){j.preventDefault(),f(),t(_[0]);return}if(C.some(([,A])=>A.startsWith(`${g} `))){j.preventDefault(),m.current.parts=[g],y();return}f()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[n,y,e,d,t,f,o]),l.useEffect(()=>()=>f(),[f]);const b=l.useMemo(()=>Tu(r),[r]);return{isMac:r,actionDefinitions:b,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:u,saveShortcuts:h}}function z0({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 Lu(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Wl({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!Lu(n):!0}function G0({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:Lu(r)}const Ru=1e3,V0=4;function Kl(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Ul(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function q0({detachDelayMs:e=Ru,stillnessThresholdPx:t=V0,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,u=null,m=null,d=!1;const h=()=>{m!=null&&(a(m),m=null)},f=()=>{h(),c=null},y=()=>{h(),o=null,i=null,c=null,u=null,d=!1},b=()=>{!o||!c||!u||d||m!=null||(m=n(()=>{m=null,!(!o||!c||!u||d)&&Kl(u,i)&&(Ul(c,u,t)||(d=!0,r({panelId:o,clientX:u.clientX,clientY:u.clientY})))},e))},x=k=>{if(!(!o||d)){if(!Kl(k,i)){u={clientX:k.clientX,clientY:k.clientY},f();return}(!c||Ul(c,k,t))&&(h(),c={clientX:k.clientX,clientY:k.clientY}),u={clientX:k.clientX,clientY:k.clientY},b()}},j=k=>{!o||d||(k&&(u={clientX:k.clientX,clientY:k.clientY}),f())};return{startDrag:k=>{h(),o=k.panelId,i=k.selfPanelBounds??null,c=null,u={clientX:k.clientX,clientY:k.clientY},d=!1},markSelfPanel:x,markNonSelfPanel:j,markNoDropTarget:j,markDockTarget:j,endDrag:y,isDragging:()=>o!=null,hasDetached:()=>d,dispose:y}}function Y0(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function mn(e){return e.isActive}function zl(e){return e.isVisible}const Pu=l.createContext(null);function da(){const e=l.useContext(Pu);if(!e)throw new Error("DashboardDockviewContext missing");return e}function In(e){return at(e)||e.tabKey}function X0(e){return`remote:${e}`}function Dt(e){return e.startsWith("remote:")}function Gl(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function J0(e){e.preventDefault()}function Fa(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 Ha(e,t){e.classList.remove(io.className,lo.className),e.classList.add(t==="light"?io.className:lo.className)}function Vl(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 Q0(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 Z0(e,t,r){var i;const n=[t];let a;for(const c of n){let u;for(const m of c){const d=e.addPanel({id:m.tabKey,component:"conversation",title:In(m),params:{kind:"conversation",tabKey:m.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=d.id)}a=u??a}return r??((i=t[0])==null?void 0:i.tabKey)??null}function ql(e,t){const r=new Set(t.map(a=>a.tabKey)),n=new Map;for(const a of t)n.set(a.tabKey,(n.get(a.tabKey)||0)+1);for(const a of[...e.panels])Dt(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!==In(a)&&o.api.setTitle(In(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:In(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 Yl(e,t,r){var u,m;const n=r?X0(r):null;for(const d of[...e.panels])Dt(d.id)&&(!n||d.id!==n)&&e.removePanel(d);if(!r||!n)return;const a=Bt(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),i=Ld(a);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((m=e.panels.find(d=>!Dt(d.id)))==null?void 0:m.id);e.addPanel({id:n,component:"remote",title:i,params:{kind:"remote",routeId:r},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function ev({params:e,api:t}){var y;const r=da(),n=l.useRef(null),[a,o]=l.useState(()=>mn(t)),[i,c]=l.useState(()=>zl(t)),u=r.conversationsByTabKey.get(e.tabKey),m=ia({sendDaemonCommand:r.sendDaemonCommand,activeConv:u,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});l.useEffect(()=>{o(mn(t)),c(zl(t));const b=[t.onDidActiveChange(x=>o(x.isActive)),t.onDidActiveGroupChange(x=>{if(!mn(t)&&!x.isActive){o(!1);return}o(mn(t))}),t.onDidVisibilityChange(x=>c(x.isVisible))];return()=>{for(const x of b)x.dispose()}},[t]);const d=l.useMemo(()=>u?r.ides.find(b=>b.id===u.routeId):void 0,[r.ides,u]),h=l.useMemo(()=>u?r.actionLogs.filter(b=>b.routeId===u.tabKey):[],[r.actionLogs,u]);if(!u)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(fi,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const f=!Ge(u)&&Vs(u)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(hi,{activeConv:u,clearToken:r.clearedTabs[u.tabKey]||0,isCliTerminal:f,ideEntry:d,terminalRef:n,handleModalButton:m.handleModalButton,handleRelaunch:m.handleRelaunch,handleSendChat:m.handleSendChat,handleForceSendChat:m.handleForceSendChat,isSendingChat:m.isSendingChat,handleFocusAgent:m.handleFocusAgent,isFocusingAgent:m.isFocusingAgent,actionLogs:h,userName:r.userName,scrollToBottomRequestNonce:((y=r.scrollToBottomRequest)==null?void 0:y.tabKey)===u.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:i})})}function tv({params:e}){var u;const t=da(),r=l.useMemo(()=>Bt([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=l.useMemo(()=>t.ides.find(m=>m.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=Mu({doId:a,targetSessionId:r?pd(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(Xc,{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 sv(){const e=da();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(fi,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function rv(e){var p,w;Q0(e);const t=da(),r=l.useCallback(S=>{"button"in S&&S.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(S=>Jx(S),[]),i=l.useCallback(()=>Xx(a),[a]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const S=Bt([...t.conversationsByTabKey.values()],e.params.routeId),v=((p=e.api.group.activePanel)==null?void 0:p.id)===e.api.id,g=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${v?" is-active":""}${g?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(S==null?void 0:S.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:S!=null&&S.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:S.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const u=t.conversationsByTabKey.get(e.params.tabKey);if(!u)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 m=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,d=e.api.isGroupActive,h=aa(u,t.liveSessionInboxState,{isOpenConversation:m}),f=h.isReconnecting,y=h.isConnecting,b=h.isGenerating||c,x=h.isWaiting,j=h.unread,k=t.tabShortcuts[u.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${m?" is-active":""}${d?" is-group-active":""}${f?" is-reconnecting":""}`,title:at(u),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:S=>{var v;S.preventDefault(),r(S),t.openTabContextMenu({x:S.clientX,y:S.clientY,tabKey:u.tabKey,sourceDocument:((v=S.target)==null?void 0:v.ownerDocument)??document})},children:[j&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:b?s.jsx("div",{className:"tab-spinner"}):x?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):y?s.jsx("div",{className:"tab-connecting-spinner"}):u.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:at(u)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:fs(u)}):y?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:fs(u)}):s.jsx("span",{children:fs(u)})})]}),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 nv({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:u,userName:m,toggleHiddenTab:d,actionShortcuts:h,registerActionHandlers:f,onActiveTabChange:y,onOpenNewSession:b,onRequestScrollToBottom:x,requestedActiveTabKey:j,requestedRemoteIdeId:k,onRequestedActiveTabConsumed:p,scrollToBottomRequest:w,liveSessionInboxState:S,layoutProfile:v}){var rt,Ye,tt;const{theme:g}=qs(),{sendCommand:C}=ot(),I=l.useRef(null),N=l.useRef(null),_=l.useRef(null),D=l.useRef(!1),A=l.useRef(!1),M=l.useRef(!1),R=l.useRef(null),z=l.useRef([]),[T,L]=l.useState(null),[B,O]=l.useState(0),$=l.useRef(typeof window>"u"?{}:jy(v)),E=l.useMemo(()=>new Map(e.map(K=>[K.tabKey,K])),[e]),W=l.useMemo(()=>{const K=I.current;return K?K.groups.some(U=>{try{const Y=U.model.location.type;return Y!=="floating"&&Y!=="popout"?!1:U.panels.some(re=>E.has(re.id))}catch{return!1}}):!1},[E,B,e]),J=l.useCallback(()=>{var K;(K=I.current)==null||K.focus()},[]),Q=l.useCallback((K,U)=>{x==null||x(K,U)},[x]),ee=l.useCallback(K=>{const U=document,Y=K.document;for(const oe of U.querySelectorAll('link[rel="stylesheet"]')){const Ne=Y.createElement("link");Ne.rel="stylesheet",Ne.href=oe.href,oe.crossOrigin&&(Ne.crossOrigin=oe.crossOrigin),Y.head.appendChild(Ne)}for(const oe of U.querySelectorAll("style")){const Ne=Y.createElement("style");Ne.textContent=oe.textContent,Y.head.appendChild(Ne)}const re=[];for(const oe of U.styleSheets)try{for(const Ne of oe.cssRules)Ne instanceof CSSStyleRule&&(Ne.selectorText===":root"||Ne.selectorText==="html")&&re.push(Ne.cssText)}catch{}if(re.length>0){const oe=Y.createElement("style");oe.textContent=re.join(`
55
+ `),Y.head.appendChild(oe)}const H=U.documentElement.getAttribute("data-theme");H&&Y.documentElement.setAttribute("data-theme",H),Y.documentElement.style.colorScheme=H==="light"?"light":"dark",Y.body.className=U.body.className;const V=U.documentElement.getAttribute("style");V&&Y.documentElement.setAttribute("style",V);const te=Y.getElementById("dv-popout-window");te instanceof HTMLElement&&(te.classList.add("adhdev-dockview"),Ha(te,g))},[g]),me=l.useCallback(()=>{var U;const K=I.current;if(K)for(const Y of K.groups)try{const re=(U=Y.element)==null?void 0:U.ownerDocument;if(!re||re===document)continue;const H=re.getElementById("dv-popout-window");H instanceof HTMLElement&&(H.classList.add("adhdev-dockview"),Ha(H,g));const V=document.documentElement.getAttribute("data-theme");V&&re.documentElement.setAttribute("data-theme",V),re.documentElement.style.colorScheme=V==="light"?"light":"dark",re.body.className=document.body.className;const te=document.documentElement.getAttribute("style");te?re.documentElement.setAttribute("style",te):re.documentElement.removeAttribute("style")}catch{}},[g]),je=l.useCallback(K=>{const U=I.current;if(!U)return;const Y=U.getPanel(K);Y&&U.addPopoutGroup(Y,{popoutUrl:"/popout.html",onDidOpen:({window:re})=>{ee(re),we();const H=E.get(K);re.document.title=H?`${at(H)} — ADHDev`:"ADHDev — Popout"}})},[E,ee]),Me=l.useCallback(K=>{const U=I.current,Y=U==null?void 0:U.getPanel(K);if(!U||!Y)return;const re=U.groups.filter(H=>{var V;try{return((V=H.element)==null?void 0:V.ownerDocument)===document}catch{return!0}});re.length>0?Y.api.moveTo({group:re[0],position:"center"}):Y.api.moveTo({position:"center"}),Y.api.setActive()},[]),q=l.useCallback(K=>{var re;const U=I.current;if(!U)return!1;const Y=U.getPanel(K);if(!Y)return!1;try{return((re=Y.group.element)==null?void 0:re.ownerDocument)!==document}catch{return!1}},[]),G=l.useCallback(K=>{q(K)&&Me(K),d(K)},[q,Me,d]),he=l.useCallback(K=>{const U=I.current,Y=U==null?void 0:U.getPanel(K);!U||!Y||U.addFloatingGroup(Y,{width:600,height:500})},[]),ue=l.useCallback(K=>{var Y;const U=(Y=I.current)==null?void 0:Y.getPanel(K);if(!U)return!1;try{return U.group.model.location.type==="floating"}catch{return!1}},[]),ce=l.useCallback(()=>{var U,Y;const K=(Y=(U=I.current)==null?void 0:U.activePanel)==null?void 0:Y.id;return!K||Dt(K)?null:E.has(K)?K:null},[E]),ve=l.useCallback(K=>{const U=I.current,Y=U==null?void 0:U.getPanel(K);if(!U||!Y)return;const re=U.groups.filter(H=>{try{return H.model.location.type==="grid"}catch{return!0}});re.length>0?Y.api.moveTo({group:re[0],position:"center"}):Y.api.moveTo({position:"center"}),Y.api.setActive()},[]),X=l.useCallback(()=>{var V;const K=I.current;if(!K)return;const Y=K.groups.filter(te=>{var oe;try{return((oe=te.element)==null?void 0:oe.ownerDocument)===document&&te.model.location.type==="grid"}catch{return!1}})[0]||null,re=[...K.panels];for(const te of re){const oe=(V=te.group.element)==null?void 0:V.ownerDocument,Ne=te.group.model.location.type;oe===document&&Ne==="grid"||(Y&&Y.id!==te.group.id?te.api.moveTo({group:Y,position:"center"}):te.api.moveTo({position:"center"}))}const H=K.activePanel;H&&(H.group.model.openPanel(H),H.api.setActive()),Fa(document)},[]),we=l.useCallback(()=>{var U,Y;const K=I.current;if(K)for(const re of K.groups){const H=(U=re.element)==null?void 0:U.ownerDocument;if(!H||H===document)continue;const V=H.getElementById("dv-popout-window");if(!(V instanceof HTMLElement))continue;let te=null,oe=H.title||"ADHDev",Ne="Popout workspace";const Le=re.activePanel;if(Le)if(te=Le.id,Dt(Le.id)){const Ie=((Y=Le.params)==null?void 0:Y.routeId)||Le.id.slice(7),We=Bt([...E.values()],Ie);oe=Ld(We),Ne=We!=null&&We.machineName?`Remote view · ${We.machineName}`:"Remote view"}else{const Ie=E.get(Le.id);oe=Ie?at(Ie):Le.title||Le.id,Ne=Ie?fs(Ie):"Dockview panel"}H.title=`${oe} — ADHDev`;const F=Array.from(H.querySelectorAll("#adhdev-popout-header"));for(const Ie of F)Ie.remove();const ne=H.createElement("div");ne.id="adhdev-popout-header",H.body.appendChild(ne),ne.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(";")),ne.innerHTML=`
56
+ <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
57
+ <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
58
+ <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Gl(oe)}</div>
59
+ <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Gl(Ne)}</div>
60
+ </div>
61
+ <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
62
+ <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>
63
+ <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>
64
+ </div>
65
+ `,V.style.top="52px",V.style.height="calc(100% - 52px)";const pe=ne.querySelector("[data-adhdev-popout-focus]");pe&&(pe.onclick=()=>{window.focus()});const Se=ne.querySelector("[data-adhdev-popout-dock]");Se&&(Se.disabled=!te,Se.style.opacity=te?"1":"0.5",Se.style.cursor=te?"pointer":"default",Se.onclick=()=>{var Ie;te&&Me(te),(Ie=H.defaultView)==null||Ie.focus()})}},[E,Me]),de=l.useCallback(K=>{var re;const U=I.current,Y=U==null?void 0:U.getPanel(K);if(!(!U||!Y)){Y.group.model.openPanel(Y),Y.api.setActive(),Q(K,"dockview-shortcut");try{const H=Y.group.model.location;H.type==="popout"?H.getWindow().focus():Fa((re=Y.group.element)==null?void 0:re.ownerDocument)}catch{}}},[Q]),ye=l.useCallback(K=>{const U=I.current,Y=U==null?void 0:U.activePanel,re=(U==null?void 0:U.activeGroup)||(Y==null?void 0:Y.group);if(!U||!Y||!re)return;const H=re.panels||[];if(H.length<=1)return;const V=H.findIndex(Ne=>Ne.id===Y.id);if(V<0)return;const te=(V+K+H.length)%H.length,oe=H[te];oe&&(oe.group.model.openPanel(oe),oe.api.setActive(),Dt(oe.id)||Q(oe.id,"dockview-shortcut"))},[Q]),xe=l.useCallback(K=>{var pe;const U=I.current,Y=(U==null?void 0:U.activeGroup)||((pe=U==null?void 0:U.activePanel)==null?void 0:pe.group);if(!U||!Y)return;const re=U.groups||[],H=re.find(Se=>Se.id===Y.id);if(!H)return;const V=H.element.getBoundingClientRect(),te=V.left+V.width/2,oe=V.top+V.height/2,Ne=(Se,Ie,We,ze)=>Math.max(0,Math.min(Ie,ze)-Math.max(Se,We)),Le=Se=>{const Ie=Se.element.getBoundingClientRect(),We=Ie.left+Ie.width/2,ze=Ie.top+Ie.height/2;let Be=0,mt=0,lt=0,pt=!1;if(K==="left"?(pt=We<te,Be=Math.max(0,V.left-Ie.right),mt=Math.abs(ze-oe),lt=Ne(V.top,V.bottom,Ie.top,Ie.bottom)):K==="right"?(pt=We>te,Be=Math.max(0,Ie.left-V.right),mt=Math.abs(ze-oe),lt=Ne(V.top,V.bottom,Ie.top,Ie.bottom)):K==="above"?(pt=ze<oe,Be=Math.max(0,V.top-Ie.bottom),mt=Math.abs(We-te),lt=Ne(V.left,V.right,Ie.left,Ie.right)):(pt=ze>oe,Be=Math.max(0,Ie.top-V.bottom),mt=Math.abs(We-te),lt=Ne(V.left,V.right,Ie.left,Ie.right)),!pt)return Number.POSITIVE_INFINITY;const Fe=lt>0?0:120;return Be*3+mt+Fe};let F=null,ne=Number.POSITIVE_INFINITY;for(const Se of re){if(Se.id===H.id)continue;const Ie=Le(Se);Number.isFinite(Ie)&&(Ie>=ne||(ne=Ie,F=Se))}return F||void 0},[]),ge=l.useCallback(K=>{var re;const U=xe(K);if(!U)return;const Y=U.activePanel||U.panels[0];Y&&(U.model.openPanel(Y),Y.api.setActive(),Dt(Y.id)||Q(Y.id,"dockview-focus"),Fa((re=U.element)==null?void 0:re.ownerDocument))},[xe,Q]),le=l.useCallback((K,U)=>{const Y=I.current,re=Y==null?void 0:Y.activePanel,H=(Y==null?void 0:Y.activeGroup)||(re==null?void 0:re.group);if(!Y||!re||!H)return;let V=xe(K);!V&&(U!=null&&U.createGroupIfMissing)&&(V=Y.addGroup({referenceGroup:H,direction:K})),V&&(re.api.moveTo({group:V,position:"center"}),re.group.model.openPanel(re),re.api.setActive(),Dt(re.id)||Q(re.id,U!=null&&U.createGroupIfMissing?"dockview-split":"dockview-move"))},[xe,Q]),{isMac:be,tabShortcuts:ie,shortcutListening:P,setShortcutListening:fe,saveShortcuts:Ce}=Iu({sortedTabKeys:e.map(K=>K.tabKey),onFocus:J,onSelectTab:de}),_e=l.useCallback(()=>{var Y;const K=I.current;if(!K)return;const U=K.activePanel;if(U){if(Dt(U.id)){const re=((Y=U.params)==null?void 0:Y.routeId)||U.id.slice(7),H=Bt(e,re);H!=null&&H.tabKey&&fe(H.tabKey);return}E.has(U.id)&&fe(U.id)}},[E,de,fe,e]),se=l.useCallback(K=>{const U=[];return K.metaKey&&U.push(be?"⌘":"Meta"),K.ctrlKey&&U.push("Ctrl"),K.altKey&&U.push(be?"⌥":"Alt"),K.shiftKey&&K.key.length!==1&&U.push(be?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(K.key)?null:(U.push(_u(K.key)),U.join("+"))},[be]),De=l.useCallback(K=>{var U,Y;switch(K){case"splitActiveTabRight":le("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":le("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const re=ce();re&&he(re);return}case"popoutActiveTab":{const re=ce();re&&je(re);return}case"dockActiveTab":{const re=ce();if(!re)return;q(re)?Me(re):ue(re)&&ve(re);return}case"focusLeftPane":ge("left");return;case"focusRightPane":ge("right");return;case"focusUpPane":ge("above");return;case"focusDownPane":ge("below");return;case"moveActiveTabToLeftPane":le("left");return;case"moveActiveTabToRightPane":le("right");return;case"moveActiveTabToUpPane":le("above");return;case"moveActiveTabToDownPane":le("below");return;case"selectPreviousGroupTab":ye(-1);return;case"selectNextGroupTab":ye(1);return;case"setActiveTabShortcut":_e();return;case"hideCurrentTab":{const re=(Y=(U=I.current)==null?void 0:U.activePanel)==null?void 0:Y.id;re&&!Dt(re)&&G(re);return}default:return}},[ye,ve,ge,he,ce,G,ue,q,Me,le,je,_e]);l.useEffect(()=>{if(!T)return;const K=T.sourceDocument,U=K.defaultView??window,Y=re=>{const H=K.querySelector("[data-dockview-tab-context-menu]");H&&H.contains(re.target)||L(null)};return U.addEventListener("mousedown",Y,!0),U!==window&&window.addEventListener("mousedown",()=>L(null),!0),()=>{U.removeEventListener("mousedown",Y,!0),U!==window&&window.removeEventListener("mousedown",()=>L(null),!0)}},[T]);const Te=l.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:E,hasDetachedConversationPanels:W,ides:r,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:b,liveSessionInboxState:S,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:G,userName:m,scrollToBottomRequest:w,tabShortcuts:ie,openTabContextMenu:({x:K,y:U,tabKey:Y,sourceDocument:re})=>L({x:K,y:U,tabKey:Y,sourceDocument:re??document}),popoutTab:je,moveTabBackToMain:Me,isTabInPopout:q,floatTab:he,isTabFloating:ue}),[n,t,E,W,r,i,c,b,S,a,o,G,m,w,ie,je,Me,q,he,ue]),Ee=T?z0({isTabInPopout:q(T.tabKey),isTabFloating:ue(T.tabKey),tabShortcut:ie[T.tabKey],actionShortcuts:h}):[],Oe=l.useCallback(K=>{var re;const U=I.current;if((((re=U==null?void 0:U.activePanel)==null?void 0:re.id)??null)===K.id){K.group.model.openPanel(K);return}K.group.model.openPanel(K),K.api.setActive()},[]),Je=l.useCallback((K,U="requested-tab")=>{if(!K)return!1;const Y=I.current;if(!Y)return!1;const re=Y.getPanel(K);return re?(Oe(re),Q(K,U),p==null||p(),!0):!1},[Oe,p,Q]),qe=l.useCallback(()=>{if(M.current)return!1;const K=Je(R.current,"stored-layout-restore");return K&&(M.current=!0),K},[Je]),Ze=l.useCallback(()=>{var U;const K=I.current;K&&wy(v,{activeTabId:((U=K.activePanel)==null?void 0:U.id)??null,layout:K.toJSON()})},[v]),et=l.useCallback(()=>{ky(v,$.current)},[v]),dt=l.useCallback(K=>{var re,H,V,te;const U=I.current;if(!U)return{kind:"grid"};const Y=U.toJSON();for(const oe of Y.floatingGroups||[])if((H=(re=oe.data)==null?void 0:re.views)!=null&&H.includes(K)&&oe.position)return{kind:"floating",position:oe.position};for(const oe of Y.popoutGroups||[])if((te=(V=oe.data)==null?void 0:V.views)!=null&&te.includes(K))return{kind:"popout",position:oe.position,popoutUrl:oe.url};return{kind:"grid"}},[]),ut=l.useCallback(K=>{const U=I.current;if(!U)return;const Y=U.getPanel(K),re=$.current[K];if(!Y||!re||re.kind==="grid")return;if(Y.group.model.location.type===re.kind){delete $.current[K],et();return}if(re.kind==="floating"){U.addFloatingGroup(Y,{x:re.position.left??24,y:re.position.top??24,width:re.position.width,height:re.position.height}),delete $.current[K],et();return}delete $.current[K],et()},[et]);l.useEffect(()=>(f==null||f({setShortcutForActiveTab:_e,restoreHiddenTabToSavedLocation:ut,activateConversationTab:de,resetAllPanelsToMain:X,activatePreviousTabInGroup:()=>ye(-1),activateNextTabInGroup:()=>ye(1),floatActiveTab:()=>{const K=ce();K&&he(K)},popoutActiveTab:()=>{const K=ce();K&&je(K)},dockActiveTab:()=>{const K=ce();K&&(q(K)?Me(K):ue(K)&&ve(K))},splitActiveTabRight:()=>le("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>le("below",{createGroupIfMissing:!0}),focusLeftPane:()=>ge("left"),focusRightPane:()=>ge("right"),focusUpPane:()=>ge("above"),focusDownPane:()=>ge("below"),moveActiveTabToLeftPane:()=>le("left"),moveActiveTabToRightPane:()=>le("right"),moveActiveTabToUpPane:()=>le("above"),moveActiveTabToDownPane:()=>le("below")}),()=>f==null?void 0:f(null)),[ye,ve,he,ge,ce,ue,q,le,Me,je,f,X,ut,de,_e]),l.useEffect(()=>()=>{var K;(K=_.current)==null||K.call(_),_.current=null},[]);const xt=l.useCallback(K=>{var Y,re;I.current=K.api,(Y=_.current)==null||Y.call(_),_.current=null;const U=vy(v);if(R.current=(U==null?void 0:U.activeTabId)??null,U!=null&&U.layout&&K.api.fromJSON(U.layout,{reuseExistingPanels:!1}),A.current=Wl({hasStoredLayout:!!(U!=null&&U.layout),initialDataLoaded:u,visibleConversationCount:e.length,ides:r}),A.current||(ql(K.api,e),Yl(K.api,e,k)),K.api.totalPanels===0&&e.length>0){const H=Z0(K.api,e,j);if(H){const V=K.api.getPanel(H);V&&Oe(V)}}else!A.current&&!Je(j)&&qe();if(D.current=!0,K.api.onDidActivePanelChange(H=>{var te;if(R.current=(H==null?void 0:H.id)??null,M.current=!0,we(),H&&Dt(H.id)){const oe=((te=H.params)==null?void 0:te.routeId)||H.id.slice(7),Ne=Bt(e,oe);y((Ne==null?void 0:Ne.tabKey)??null),Ze();return}if(y((H==null?void 0:H.id)??null),Ze(),!H)return;const V=E.get(H.id);(V==null?void 0:V.streamSource)==="agent-stream"&&V.agentType&&C(V.routeId,fd(),{agentType:V.agentType,...V.sessionId&&{targetSessionId:V.sessionId}}).catch(()=>{})}),K.api.onDidLayoutChange(()=>{Ze(),we(),O(H=>H+1)}),Y0()){const H=ne=>({clientX:ne.clientX,clientY:ne.clientY}),V=ne=>{const pe=ne==null?void 0:ne.getBoundingClientRect();return pe?{left:pe.left,right:pe.right,top:pe.top,bottom:pe.bottom}:null},te=ne=>{var Se;const pe=(Se=N.current)==null?void 0:Se.getBoundingClientRect();return pe?ne.clientX<pe.left||ne.clientX>pe.right||ne.clientY<pe.top||ne.clientY>pe.bottom:!1},oe=q0({detachDelayMs:Ru,onDetach:({panelId:ne,clientX:pe,clientY:Se})=>{var lt,pt;const Ie=K.api.getPanel(ne);if(!Ie)return;try{if(Ie.group.model.location.type!=="grid")return}catch{return}const We=(lt=N.current)==null?void 0:lt.getBoundingClientRect(),ze=(pt=Ie.group.element)==null?void 0:pt.getBoundingClientRect(),Be=Math.round(Math.min(Math.max((ze==null?void 0:ze.width)??600,360),720)),mt=Math.round(Math.min(Math.max((ze==null?void 0:ze.height)??500,260),640));K.api.addFloatingGroup(Ie,{x:We?Math.max(0,pe-We.left-32):void 0,y:We?Math.max(0,Se-We.top-18):void 0,width:Be,height:mt}),Ie.api.setActive(),Ze(),we(),O(Fe=>Fe+1)}}),Ne=[K.api.onWillDragPanel(ne=>{if(!(ne.nativeEvent.defaultPrevented||ne.nativeEvent.shiftKey)){try{if(ne.panel.group.model.location.type!=="grid")return}catch{return}oe.startDrag({panelId:ne.panel.id,selfPanelBounds:V(ne.panel.group.element),...H(ne.nativeEvent)})}}),K.api.onWillShowOverlay(ne=>{if(oe.hasDetached()){ne.preventDefault();return}oe.markDockTarget(H(ne.nativeEvent))}),K.api.onWillDrop(ne=>{if(oe.hasDetached()){ne.preventDefault(),oe.endDrag();return}oe.markDockTarget(H(ne.nativeEvent))}),K.api.onDidDrop(()=>oe.endDrag()),K.api.onUnhandledDragOverEvent(ne=>{oe.isDragging()&&oe.markSelfPanel(H(ne.nativeEvent))})],Le=ne=>{if(!oe.isDragging())return;const pe=H(ne);te(pe)&&oe.markNonSelfPanel(pe)},F=()=>oe.endDrag();window.addEventListener("dragover",Le,!0),window.addEventListener("drop",F,!0),window.addEventListener("dragend",F,!0),_.current=()=>{oe.dispose();for(const ne of Ne)ne.dispose();window.removeEventListener("dragover",Le,!0),window.removeEventListener("drop",F,!0),window.removeEventListener("dragend",F,!0)}}K.api.onDidAddGroup(H=>{requestAnimationFrame(()=>{var V,te;try{const oe=(V=H.element)==null?void 0:V.ownerDocument;if(!oe||oe===document)return;(te=oe.getElementById("dv-popout-window"))==null||te.classList.add("adhdev-dockview");const Ne=document.documentElement.getAttribute("data-theme");Ne&&oe.documentElement.setAttribute("data-theme",Ne),oe.body.className=document.body.className;const Le=document.documentElement.getAttribute("style");Le&&oe.documentElement.setAttribute("style",Le)}catch{}we(),O(oe=>oe+1)})}),y(((re=K.api.activePanel)==null?void 0:re.id)??null)},[Oe,Je,E,r,u,v,y,Ze,j,k,C,we,e]);l.useLayoutEffect(()=>{const K=I.current;if(!K||!D.current||A.current&&Wl({hasStoredLayout:!0,initialDataLoaded:u,visibleConversationCount:e.length,ides:r}))return;A.current&&(A.current=!1);const U=z.current,Y=new Set(U),re=e.map(F=>F.tabKey),H=new Set(re),V=G0({previousVisibleConversationCount:U.length,visibleConversationCount:e.length,ides:r});let te=!1;for(const F of U)H.has(F)||V||($.current[F]=dt(F),te=!0);te&&et(),V||(ql(K,e),Yl(K,e,k));const oe=re.filter(F=>!Y.has(F));let Ne=!1;for(const F of oe){const ne=K.getPanel(F),pe=$.current[F];if(!ne||!pe||pe.kind==="grid")continue;if(ne.group.model.location.type===pe.kind){delete $.current[F],Ne=!0;continue}if(pe.kind==="floating"){K.addFloatingGroup(ne,{x:pe.position.left??24,y:pe.position.top??24,width:pe.position.width,height:pe.position.height}),delete $.current[F],Ne=!0;continue}}if(Ne&&et(),z.current=re,j&&Je(j))return;!K.activePanel&&K.panels[0]&&Oe(K.panels[0]),!!(K.activePanel&&K.getPanel(K.activePanel.id))||qe()},[Oe,Je,qe,r,u,et,dt,j,k,e]),l.useEffect(()=>{D.current&&Je(j)},[Je,j]),l.useEffect(()=>{const K=Y=>{const re=Y.target;if(!re)return;const H=re.querySelector("[data-tab-key]")||re.closest("[data-tab-key]");if(H){const V=H.getAttribute("data-tab-key");if(V&&Y.dataTransfer){const te=re.closest(".dv-tab")||H.closest(".dv-tab")||H;Y.dataTransfer.effectAllowed="move",Y.dataTransfer.setData("text/tab-key",V),te instanceof HTMLElement&&Y.dataTransfer.setDragImage(te,Math.max(12,Math.round(te.clientWidth/2)),Math.max(10,Math.round(te.clientHeight/2)))}}};window.addEventListener("dragstart",K);const U=Vl(I.current);for(const Y of U)Y.addEventListener("dragstart",K);return()=>{window.removeEventListener("dragstart",K);for(const Y of U)Y.removeEventListener("dragstart",K)}},[B]),l.useEffect(()=>{var U;const K=(U=N.current)==null?void 0:U.querySelector(".adhdev-dockview");K instanceof HTMLElement&&Ha(K,g),me(),we()},[we,me,g]),l.useEffect(()=>{we()},[we]),l.useEffect(()=>{const K=U=>{if(U.defaultPrevented||P)return;const Y=se(U);if(!Y)return;const re=U.metaKey||U.ctrlKey||U.altKey;_o(U.target)&&!re||Xn(be).setActiveTabShortcut!==Y||(U.preventDefault(),U.stopPropagation(),_e())};return window.addEventListener("keydown",K,!0),()=>window.removeEventListener("keydown",K,!0)},[se,be,P,_e]),l.useEffect(()=>{const K=N.current;if(!K)return;const U=Y=>{var oe,Ne;if(!Y.isTrusted)return;const re=(Ne=(oe=Y.target)==null?void 0:oe.closest)==null?void 0:Ne.call(oe,".dv-scrollable");if(!re)return;Y.preventDefault(),Y.stopPropagation();const H=Math.abs(Y.deltaX),V=Math.abs(Y.deltaY),te=H>V?Y.deltaX:Y.deltaY;re.dispatchEvent(new WheelEvent("wheel",{deltaY:te,deltaMode:Y.deltaMode,bubbles:!1,cancelable:!0}))};return K.addEventListener("wheel",U,{passive:!1,capture:!0}),()=>K.removeEventListener("wheel",U,{capture:!0})},[]),l.useEffect(()=>{const K=Vl(I.current);if(K.length===0)return;const U=K.map(Y=>{let re=[],H=null;const V=()=>{H!=null&&Y.clearTimeout(H),H=null,re=[]},te=()=>{H!=null&&Y.clearTimeout(H),H=Y.setTimeout(()=>{H=null,re=[]},1200)},oe=Le=>{if(!Le.ctrlKey&&!Le.metaKey&&!Le.altKey)return;const F=se(Le);if(!F)return;const ne=Cu();for(const[pe,Se]of Object.entries(ne))if(e.some(Ie=>Ie.tabKey===pe)&&Se===F){Le.preventDefault(),de(pe);return}},Ne=Le=>{if(Le.defaultPrevented||P)return;const F=se(Le);if(!F)return;const ne=Le.metaKey||Le.ctrlKey||Le.altKey;if(_o(Le.target))return;const pe=Xn(be),Se=Object.entries(pe).filter(([Fe,Qt])=>!!Qt&&(Fe==="splitActiveTabRight"||Fe==="splitActiveTabDown"||Fe==="floatActiveTab"||Fe==="popoutActiveTab"||Fe==="dockActiveTab"||Fe==="focusLeftPane"||Fe==="focusRightPane"||Fe==="focusUpPane"||Fe==="focusDownPane"||Fe==="moveActiveTabToLeftPane"||Fe==="moveActiveTabToRightPane"||Fe==="moveActiveTabToUpPane"||Fe==="moveActiveTabToDownPane"||Fe==="selectPreviousGroupTab"||Fe==="selectNextGroupTab"||Fe==="setActiveTabShortcut"||Fe==="hideCurrentTab")),Ie=ne?[F]:[...re.slice(-1),F].slice(-2),We=Ie.join(" "),ze=Ie[Ie.length-1],Be=Se.find(([,Fe])=>Fe===We);if(Be){Le.preventDefault(),V(),De(Be[0]);return}if(Se.some(([,Fe])=>Fe.startsWith(`${We} `))){Le.preventDefault(),re=Ie,te();return}const lt=Se.find(([,Fe])=>Fe===ze);if(lt){Le.preventDefault(),V(),De(lt[0]);return}if(Se.some(([,Fe])=>Fe.startsWith(`${ze} `))){Le.preventDefault(),re=[ze],te();return}V()};return Y.addEventListener("keydown",oe),Y.addEventListener("keydown",Ne),()=>{V(),Y.removeEventListener("keydown",oe),Y.removeEventListener("keydown",Ne)}});return()=>{for(const Y of U)Y()}},[se,be,B,de,P,De,e]);const Ae=g==="light"?io:lo,He=((tt=(Ye=(rt=I.current)==null?void 0:rt.activePanel)==null?void 0:Ye.group.element)==null?void 0:tt.ownerDocument)??document;return s.jsxs(Pu.Provider,{value:Te,children:[s.jsx("div",{ref:N,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(Gm,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:ev,remote:tv},defaultTabComponent:rv,watermarkComponent:sv,onReady:xt,singleTabMode:"default",tabAnimation:"smooth",theme:Ae,popoutUrl:"/popout.html"})}),T&&Nr.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:T.x,top:T.y},children:Ee.map(K=>{if(K.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},K.id);let U=s.jsx(rp,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{};switch(K.id){case"dockInWindow":case"dockBackToGrid":U=s.jsx(ap,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{ve(T.tabKey),L(null)};break;case"moveBackToMain":U=s.jsx(sp,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{Me(T.tabKey),L(null)};break;case"floatAsPanel":U=s.jsx(np,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{he(T.tabKey),L(null)};break;case"openInNewWindow":U=s.jsx(tp,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{je(T.tabKey),L(null)};break;case"setShortcut":Y=re=>{re.stopPropagation(),fe(T.tabKey),L(null)};break;case"removeShortcut":U=s.jsx(gt,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{const re={...ie};delete re[T.tabKey],Ce(re),L(null)};break;case"hideTab":U=s.jsx(Ho,{size:13,className:"shrink-0 opacity-70"}),Y=()=>{G(T.tabKey),L(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 ${K.tone==="muted"?"text-text-muted":""}`,onMouseDown:J0,onClick:Y,children:[U,s.jsx("span",{className:"flex-1 min-w-0",children:K.label}),K.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:K.shortcut}):null]},K.id)})}),T.sourceDocument.body),P&&Nr.createPortal(s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>fe(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:K=>K.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"})]})}),He.body)]})}const Du="adhdev-recent-launch-args-v1",av=8;function ov(e){return String(e||"").trim().replace(/\s+/g," ")}function Eu(e,t){return`${e.trim()}::${t.trim()}`}function $u(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Du)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function iv(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Du,JSON.stringify(e))}catch{}}function lv(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=$u().byKey[Eu(r,n)])==null?void 0:o.items)||[]}function cv(e,t,r){var d;const n=String(e||"").trim(),a=String(t||"").trim(),o=ov(r);if(!n||!a||!o)return;const i=$u(),c=Eu(n,a),u=((d=i.byKey[c])==null?void 0:d.items)||[],m=[o,...u.filter(h=>h!==o)].slice(0,av);i.byKey[c]={items:m},iv(i)}function dv(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Mn({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 uv({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 mv({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:i,onOpenHistory:c,onClearSelection:u}){const m=o?wu(o):null,d=uv({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Mn,{title:"Saved history",description:si(),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:$b()})]}),children:[m?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:m.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:m.providerSessionId}),s.jsx("div",{className:"mt-1",children:m.metaLine}),m.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:m.updatedLabel}),m.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:m.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:u,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:d}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function Bu({setup:e,providerName:t,className:r=""}){return e?s.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${r}`,children:[s.jsxs("div",{className:"font-semibold",children:["Manual MCP setup required",t?` for ${t}`:""]}),e.instructions&&s.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-text-muted",children:[e.serverName&&s.jsxs("span",{children:["Server: ",s.jsx("code",{children:e.serverName})]}),e.configFormat&&s.jsxs("span",{children:["Format: ",s.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&s.jsxs("span",{children:["Config path: ",s.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&s.jsx("span",{children:"Start a fresh CLI session after editing config."})]}),e.template&&s.jsx("pre",{className:"mt-3 max-h-72 overflow-auto rounded-lg border border-border-subtle bg-bg-primary p-3 text-xs font-mono leading-relaxed text-text-primary select-all whitespace-pre-wrap",children:e.template})]}):null}function hv({workspaceMode:e,activeKind:t,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:o,onSelect:i}){return e==="mesh"?null:s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:r},{id:"ide",label:"Workspace",enabled:n},{id:"acp",label:"ACP",enabled:a}].map(c=>s.jsx("button",{type:"button",className:`btn btn-sm ${t===c.id?"btn-primary":"btn-secondary"}`,onClick:()=>i(c.id),disabled:!c.enabled||o,children:c.label},c.id))})]})}function Wa(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>Ks(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>Ks(a,"acp"))?"acp":null}function hn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function pv({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:u,onListSavedSessions:m}){var Fe,Qt;const d=Dr(),h=l.useMemo(()=>[...e].sort(Vo),[e]),[f,y]=l.useState(((Fe=h[0])==null?void 0:Fe.id)||""),b=l.useMemo(()=>h.find(Z=>Z.id===f)||h[0],[f,h]),x=l.useMemo(()=>((b==null?void 0:b.workspaces)||[]).map(Z=>({id:Z.id,path:Z.path,label:Z.label})),[b]),j=(b==null?void 0:b.defaultWorkspaceId)||null,[k,p]=l.useState("workspace"),[w,S]=l.useState(""),[v,g]=l.useState(""),[C,I]=l.useState([]),[N,_]=l.useState(""),[D,A]=l.useState(!1),[M,R]=l.useState(null),[z,T]=l.useState(""),[L,B]=l.useState(Wa(h[0])),[O,$]=l.useState(""),[E,W]=l.useState(""),[J,Q]=l.useState([]),[ee,me]=l.useState(""),[je,Me]=l.useState([]),[q,G]=l.useState(!1),[he,ue]=l.useState(!1),[ce,ve]=l.useState(""),[X,we]=l.useState(!1),[de,ye]=l.useState(()=>kt()),[xe,ge]=l.useState(null),[le,be]=l.useState(!1),[ie,P]=l.useState(""),[fe,Ce]=l.useState(null),[_e,se]=l.useState(!1),[De,Te]=l.useState(""),[Ee,Oe]=l.useState([]),[Je,qe]=l.useState(!1),[Ze,et]=l.useState(""),[dt,ut]=l.useState(!1),xt=l.useRef(null),Ae=l.useRef(0);l.useEffect(()=>{var Z;!f&&((Z=h[0])!=null&&Z.id)&&y(h[0].id)},[f,h]),l.useEffect(()=>{!b||!(!b.workspaces||!b.availableProviders||!b.detectedIdes||!b.recentLaunches)||d(b.id,{minFreshMs:3e4}).catch(()=>{})},[d,b]);const He=l.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(Z=>Ks(Z,"cli")),[b]),rt=l.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(Z=>Ks(Z,"acp")),[b]),Ye=l.useMemo(()=>((b==null?void 0:b.detectedIdes)||[]).map(Z=>({id:Z.type,label:Z.name||Z.type,meta:Z.running?"Detected locally":"Available to open"})),[b]),tt=l.useMemo(()=>L==="cli"?He.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"CLI provider"})):L==="acp"?rt.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"ACP provider"})):Ye,[rt,L,He,Ye]),K=l.useMemo(()=>C.find(Z=>Z.id===N)||null,[C,N]),U=l.useMemo(()=>He.find(Z=>Z.type===O)||null,[He,O]),Y=l.useMemo(()=>fu(U==null?void 0:U.meshCoordinator,{meshId:(K==null?void 0:K.id)||"",workspace:(K==null?void 0:K.workspace)||""}),[U,K]),re=fe||Y,H=l.useCallback(async Z=>{A(!0),T("");try{const Re=await c(Z);I(Re),_(ae=>{var Pe;return Re.some(Nt=>Nt.id===ae)?ae:((Pe=Re[0])==null?void 0:Pe.id)||""}),R(Z)}catch(Re){I([]),_(""),R(Z),T(Re instanceof Error?Re.message:"Could not load meshes")}finally{A(!1)}},[c]);l.useEffect(()=>{var Re;if(!b)return;if(xt.current!==b.id){xt.current=b.id,p("workspace"),S(j||((Re=x[0])==null?void 0:Re.id)||"__home__"),g(""),I([]),_(""),R(null),T(""),B(Wa(b)),$(""),W(""),me(""),Me([]),ue(!1),ve(""),ye(kt()),P(""),Ce(null);return}S(ae=>{var Pe;return ae==="__custom__"||ae==="__home__"||x.some(Nt=>Nt.id===ae)?ae:j||((Pe=x[0])==null?void 0:Pe.id)||"__home__"}),B(ae=>ae==="ide"&&Ye.length>0||ae==="cli"&&He.length>0||ae==="acp"&&rt.length>0?ae:Wa(b))},[rt.length,He.length,j,Ye.length,b,x]),l.useEffect(()=>{!b||k!=="mesh"||M===b.id||D||H(b.id)},[H,M,D,b,k]),l.useEffect(()=>{k==="mesh"&&L!=="cli"&&He.length>0&&B("cli")},[L,He.length,k]),l.useEffect(()=>{var Z;L&&(tt.some(Re=>Re.id===O)||$(((Z=tt[0])==null?void 0:Z.id)||""))},[L,tt,O]),l.useEffect(()=>{Ce(null)},[b==null?void 0:b.id,N,O,k]);const V=l.useCallback(async(Z,Re)=>{const ae=Ae.current+1;return Ae.current=ae,G(!0),ve(""),m(Z,Re).then(Pe=>{Ae.current===ae&&Me(Pe)}).catch(Pe=>{Ae.current===ae&&(Me([]),ve(Pe instanceof Error?Pe.message:"Could not load saved sessions"))}).finally(()=>{Ae.current===ae&&(G(!1),ue(!0))})},[m]),te=l.useCallback((Z,Re)=>{Q(lv(Z,Re))},[]);l.useEffect(()=>{Ae.current+=1,me(""),ye(kt()),!b||!O||L==="ide"?Q([]):te(b.id,O),ue(!1),Me([]),ve(""),G(!1)},[L,te,V,b,O]),l.useEffect(()=>{if(!ee)return;const Z=je.find(Re=>Re.providerSessionId===ee);Z!=null&&Z.canResume||me("")},[je,ee]);const oe=w==="__custom__"?v.trim():w==="__home__"?"":((Qt=x.find(Z=>Z.id===w))==null?void 0:Qt.path)||"",Ne=l.useMemo(()=>b?t.filter(Z=>Z.id!==b.id&&Z.daemonId===b.id).map(Z=>Z.workspace):[],[t,b]),Le=l.useMemo(()=>((b==null?void 0:b.recentLaunches)||[]).map(Z=>Z.workspace),[b]),F=l.useCallback(Z=>{const Re=String(Z.workspace||"").trim();if(!Re)return;const ae=x.find(Pe=>hn(Pe.path)===hn(Re));if(ae){S(ae.id),g("");return}S("__custom__"),g(Re)},[x]),ne=l.useCallback(Z=>{const Re=String(Z.workspace||"").trim();if(!Re)return{workspaceId:null,workspacePath:null};const ae=x.find(Pe=>hn(Pe.path)===hn(Re));return ae?{workspaceId:ae.id,workspacePath:null}:{workspaceId:null,workspacePath:Re}},[x]),pe=l.useMemo(()=>je.find(Z=>Z.providerSessionId===ee)||null,[je,ee]),Se=l.useMemo(()=>{var Re;if(L!=="cli"||!b||!O)return null;const Z=((Re=He.find(ae=>ae.type===O))==null?void 0:Re.displayName)||O;return{routeId:b.id,daemonId:b.id,providerSessionId:ee||void 0,transport:"pty",mode:"chat",agentName:Z,agentType:O,status:"idle",title:Z,messages:[],ideType:O,workspaceName:oe,workspacePath:oe,displayPrimary:Z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${b.id}:${O}`,machineName:Mt(b,{fallbackId:b.id})}},[L,He,oe,b,ee,O]),Ie=l.useCallback(()=>{var Re;if(!b)return;S("__custom__"),se(!0),et("");const Z=ui(b.platform,di(v.trim(),oe,Ne,Le,b.defaultWorkspacePath,(Re=x.find(ae=>ae.id===j))==null?void 0:Re.path,x.map(ae=>ae.path)));qe(!0),n(b.id,Z).then(ae=>{Te(ae.path),g(ae.path),Oe(ae.directories)}).catch(ae=>{et(ae instanceof Error?ae.message:"Could not load folder")}).finally(()=>qe(!1))},[v,j,Le,Ne,n,oe,b,x]),We=l.useCallback(Z=>{b&&(qe(!0),et(""),n(b.id,Z).then(Re=>{Te(Re.path),g(Re.path),Oe(Re.directories)}).catch(Re=>{et(Re instanceof Error?Re.message:"Could not load folder")}).finally(()=>qe(!1)))},[n,b]),ze=l.useCallback(async()=>{if(!b||!oe)return;ut(!0),P("");const Z=await a(b.id,oe);if(ut(!1),!Z.ok){P(Z.error||"Could not save workspace");return}P("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,oe,b]),Be=l.useCallback(async()=>{if(!b)return;if(k==="mesh"){if(!N||!O)return;be(!0),P(""),Ce(null);const ae=await u(b.id,N,O);if(be(!1),!ae.ok){if(ae.code==="mesh_coordinator_manual_mcp_setup_required"&&ae.manualSetup){Ce(ae.manualSetup),P("Manual MCP setup required before this provider can act as mesh coordinator.");return}P(ae.error||"Could not start mesh coordinator");return}r();return}if(!L||!O)return;be(!0),P("");const Z=E.trim()?E.trim().split(/\s+/).filter(Boolean):[],Re=L==="ide"?await o(b.id,O,{workspacePath:oe||null}):await i(b.id,L,O,{workspaceId:w!=="__home__"&&w!=="__custom__"?w:null,workspacePath:w==="__custom__"&&oe||null,resumeSessionId:L==="cli"&&ee?ee:null,cliArgs:Z});if(be(!1),!Re.ok){P(Re.error||"Could not start session");return}L!=="ide"&&E.trim()&&(cv(b.id,O,E),te(b.id,O)),r()},[L,E,te,r,o,u,i,oe,b,N,ee,O,w,k]),mt=k==="mesh"?"Start mesh coordinator":L?Pb(L,L==="cli"&&!!ee):"Start",lt=k==="mesh"?"Starting coordinator…":L?Db(L,L==="cli"&&!!ee):"Starting…",pt=h.length>5;return b?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(gt,{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:[h.length>1&&s.jsx(Mn,{title:"Machine",children:pt?s.jsx("select",{"aria-label":"Machine",value:b.id,onChange:Z=>y(Z.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:le,children:h.map(Z=>s.jsx("option",{value:Z.id,children:Mt(Z,{fallbackId:Z.id})},Z.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:h.map(Z=>{const Re=Mt(Z,{fallbackId:Z.id}),ae=b.id===Z.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${Re}`,"aria-pressed":ae,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${ae?"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(Z.id),disabled:le,title:Re,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${Z.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:Re})]},Z.id)})})}),s.jsxs(Mn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:k==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ie,disabled:le,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(Z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":k===Z.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${k===Z.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:()=>{p(Z.id),P(""),Z.id==="mesh"&&b&&M!==b.id&&!D&&H(b.id)},disabled:le,children:[s.jsx("div",{className:"text-sm font-semibold",children:Z.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:Z.desc})]},Z.id))}),k==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:w,onChange:Z=>{const Re=Z.target.value;S(Re),Re==="__custom__"?Ie():P("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:le,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),x.map(Z=>s.jsxs("option",{value:Z.id,children:[Z.id===j?"⭐ ":"",ed(Z.path,Z.label)||Z.path]},Z.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:w==="__home__"?"Launch without a workspace.":oe||"Select a workspace folder."}),w==="__custom__"&&oe&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ie,disabled:le,children:[s.jsx(Os,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ze,disabled:le||dt,children:dt?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[D&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!D&&z&&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:z}),!D&&!z&&C.length===0&&s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker."}),C.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:C.map(Z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":N===Z.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${N===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>_(Z.id),disabled:le,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[Z.repoIdentity||"Repo mesh",typeof Z.nodesCount=="number"?` · ${Z.nodesCount} node${Z.nodesCount===1?"":"s"}`:""]}),Z.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",Z.workspace]})]},Z.id))}),K&&s.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),s.jsx(hv,{workspaceMode:k,activeKind:L,cliEnabled:He.length>0,ideEnabled:Ye.length>0,acpEnabled:rt.length>0,busy:le,onSelect:B}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:L==="ide"?"Choose IDE":L==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[tt.map(Z=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${O===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(Z.id),disabled:le,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Z.meta})]},Z.id)),tt.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"&&re&&s.jsx(Bu,{setup:re,providerName:(U==null?void 0:U.displayName)||(U==null?void 0:U.name)||O}),k!=="mesh"&&L!=="ide"&&s.jsxs(Mn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:E,onChange:Z=>W(Z.target.value),placeholder:"Optional flags...",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:le}),J.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:J.map(Z=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>W(Z),disabled:le,title:Z,children:Z},Z))})]}),k!=="mesh"&&L==="cli"&&s.jsx(mv,{busy:le,savedSessionsLoading:q,savedSessionsError:ce,selectedSession:pe,onRefresh:()=>{!b||!O||V(b.id,O)},onOpenHistory:()=>{!b||!O||(we(!0),dv({hasLoadedInitialResults:he,isLoading:q})&&V(b.id,O))},onClearSelection:()=>me("")}),ie&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ie.includes("saved")||ie.includes("requested")||ie.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:ie})]}),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:le,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:Be,disabled:le||(k==="mesh"?!N||!O||L!=="cli"||D:!L||!O||w==="__custom__"&&!oe),children:[s.jsx(Oc,{size:14}),le?lt:mt]})]})]})}),_e&&s.jsx(pi,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:De,directories:Ee,busy:Je,error:Ze,onClose:()=>se(!1),onNavigate:We,onConfirm:Z=>{g(Z),Te(Z),S("__custom__"),se(!1)}}),X&&Se&&s.jsx(Bd,{activeConv:Se,ides:[],isCreatingChat:!1,isRefreshingHistory:q,savedSessions:je,isSavedSessionsLoading:q,isResumingSavedSessionId:xe,savedHistoryFilters:de,missingWorkspaceResumePath:oe||null,onSavedHistoryFiltersChange:ye,onClose:()=>we(!1),onNewChat:()=>{me(""),we(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!b||!O||V(b.id,O)},onResumeSavedSession:Z=>{if(!b||!O||xe||!Z.canResume)return;const Re=ne(Z);me(Z.providerSessionId),F(Z),ge(Z.providerSessionId),we(!1),be(!0),P(""),i(b.id,"cli",O,{workspaceId:Re.workspaceId,workspacePath:Re.workspacePath,resumeSessionId:Z.providerSessionId}).then(ae=>{if(!ae.ok){P(ae.error||"Could not resume session");return}r()}).finally(()=>{be(!1),ge(ae=>ae===Z.providerSessionId?null:ae)})}})]}):null}function Ou(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 Fu(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=Ou(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(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 Hu(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function fv(e){var t;return!Hu(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 pn(e){return[...new Set(e.filter(t=>!!t))]}function xv(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?pn([t==null?void 0:t.id,...n.map(i=>i.id)]):a.length>0?pn(a.map(i=>i.id)):o.length>0?pn(o.map(i=>i.id)):pn(e.nodes.map(i=>i.id))}function Wu(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 bv(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${Wu(e)}::${n}x${a}`}const gv={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"},yv={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"},vv={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"},wv={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 Ys(e){return e==="light"?{theme:e,isDark:!1,flowColorMode:"light",textPrimary:"text-slate-900",textSecondary:"text-slate-700",textMuted:"text-slate-500",graphShellClass:"relative w-full min-w-0 overflow-hidden rounded-2xl border border-slate-200 bg-[radial-gradient(circle_at_top,_rgba(14,165,233,0.16),_rgba(248,250,252,0.98)_42%,_rgba(255,255,255,1))]",graphStatChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-slate-700 shadow-sm",graphHintChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-[10px] text-slate-500 shadow-sm",graphControlsClass:"!bottom-4 !left-4 !shadow-md",graphBackgroundDotColor:"rgba(148, 163, 184, 0.34)",edgeLabelTextColor:"#334155",edgeLabelBackgroundColor:"rgba(255, 255, 255, 0.96)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.45)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[rgba(148,163,184,0.22)] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"flex h-[100dvh] w-full flex-col overflow-hidden bg-white md:h-[min(90vh,960px)] 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:"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 overflow-y-auto bg-[linear-gradient(180deg,rgba(248,250,252,0.98),rgba(241,245,249,0.96))] px-4 py-4 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 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:"text-slate-500",rowValueClass:"max-w-[65%] 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 justify-between gap-3 border-b border-slate-200/80 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-500",panelFieldValueClass:"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=>yv[t],actionButton:t=>wv[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative w-full min-w-0 overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",graphStatChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-slate-200",graphHintChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-[10px] text-slate-300",graphControlsClass:"!bottom-4 !left-4 !shadow-lg",graphBackgroundDotColor:"rgba(148, 163, 184, 0.22)",edgeLabelTextColor:"#cbd5e1",edgeLabelBackgroundColor:"rgba(2, 6, 23, 0.86)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.2)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[#030617]/[0.58] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"flex h-[100dvh] w-full flex-col overflow-hidden bg-slate-950 md:h-[min(90vh,960px)] 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:"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 overflow-y-auto bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] px-4 py-4 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 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:"text-slate-400",rowValueClass:"max-w-[65%] 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 justify-between gap-3 border-b border-white/6 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-400",panelFieldValueClass:"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=>gv[t],actionButton:t=>vv[t]}}const Us={worktreeCardWidth:256,submoduleCardWidth:256,minSubmoduleCardHeight:110,maxEstimatedCardHeight:178,layerGap:200,nodeGap:72,edgeLabelBuffer:160,placeholderTopOffset:0},Or={worktreeCardWidth:188,submoduleCardWidth:188,minSubmoduleCardHeight:88,maxEstimatedCardHeight:124,layerGap:160,nodeGap:52,edgeLabelBuffer:120},jv={maxWidth:180};function kv(e){return e==="TB"?"DOWN":"RIGHT"}function xi(e,t){return{"elk.algorithm":"layered","elk.direction":kv(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 Sv=xi(Us,"LR");xi(Or,"LR");function Nv(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 Cv=new Vm;function Jn(e,t=!1){const r=t?Or:Us;return e.type==="submoduleNode"?r.submoduleCardWidth:r.worktreeCardWidth}function Ka(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=Ou(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 Ku(e,t=!1){const r=t?Or:Us;return e.type==="submoduleNode"?r.minSubmoduleCardHeight:r.maxEstimatedCardHeight}function Iv(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 Mv(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function Av(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 Tv(e,t,r){return{id:e.id,x:t,y:r,width:Jn(e),height:Ku(e)}}function _v(e,t){return{id:`${e.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:t.repoIdentity,branch:e.branch,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:null,locality:"unknown",health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],nextStepHint:"Waiting for worktree nodes to report live mesh status.",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{nodeId:`${e.id}__placeholder`,machineLabel:"",workspace:t.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}}function Uu(e){const t=[...e.nodes].sort(Iv),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,_v(r,e)]}function Lv(e,t=Sv,r=!1,n="LR"){const a=Uu(e),o=new Set(a.map(u=>u.id)),i=a.map(u=>({id:u.id,width:Jn(u,r),height:Ku(u,r)})),c=e.edges.filter(u=>o.has(u.source)&&o.has(u.target)).sort(Mv).map(u=>({id:u.id,sources:[u.source],targets:[u.target]}));return{id:`${e.meshId||"mesh"}__elk_root`,layoutOptions:{...t},children:i,edges:c}}function Rv(e,t=!1){const r=[...new Set(e.map(a=>Math.round(a.x)))].sort((a,o)=>a-o),n=t?Or.layerGap:Us.layerGap;return r.length<2?n:Math.min(...r.slice(1).map((a,o)=>a-r[o]))}async function Pv(e,t=!1,r="LR"){var f,y;const a=xi(t?Or:Us,r),o=Uu(e),i=new Map(o.map(b=>[b.id,b])),c=await Cv.layout(Lv(e,a,t,r)),u=(c.children??[]).map(b=>{const x=i.get(b.id);return x?Av(x,Math.round(b.x??0),Math.round(b.y??Us.placeholderTopOffset),!b.id.endsWith("__placeholder")):null}).filter(Boolean),m=new Map(o.map((b,x)=>[b.id,x]));u.sort((b,x)=>(m.get(b.id)??0)-(m.get(x.id)??0));const d=u.map(b=>Tv(b.graphNode,b.position.x,b.position.y)),h=new Map;for(const b of c.edges??[]){const x=b.sections;if(!x||x.length===0)continue;const j=x[0],k=(f=b.sources)==null?void 0:f[0],p=(y=b.targets)==null?void 0:y[0];if(!k||!p)continue;const w=[];w.push({x:Math.round(j.startPoint.x),y:Math.round(j.startPoint.y)});for(const S of j.bendPoints??[])w.push({x:Math.round(S.x),y:Math.round(S.y)});w.push({x:Math.round(j.endPoint.x),y:Math.round(j.endPoint.y)}),h.set(b.id,{id:b.id,source:k,target:p,points:w})}return{nodes:u,bounds:d,edgeRoutes:h,columnGap:Rv(d,t),layoutOptions:{...a}}}function Dv(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 zu(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function Ev(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(Dv),...e.edges.map(zu)].join("::")}function $v(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(zu)].join("::")}const Bv=7,bi=l.createContext(Ys("dark")),Gu=l.createContext(!1),Vu=l.createContext("LR"),qu={overflowWrap:"anywhere",wordBreak:"break-word"},Ov={...qu,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},Fv={...qu,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function Yu(e){return e.activeSessionCount>0}function Hv(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function Xl(e,t,r){const n=Yu(e),a=Hv(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=Fu(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 At(e,t){switch(e){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 Jl(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 Ql(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 Wv(e){return e.replace(/_/g," ")}function Gt(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 Ua(e,t){const r=Gt(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":At("health",t)}function Kv(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function Zl(e){const t=Kv(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 za(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function cr(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function Uv(e){if(e.sessionDetails.length===0)return null;const t=e.sessionDetails.filter(o=>Gt(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 ec(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function zv(e){return e.locality==="remote"?"meta":"health"}function Gv({data:e,selected:t}){const r=l.useContext(bi),n=l.useContext(Gu),a=l.useContext(Vu),o=e.graphNode,i=o.type==="defaultBranchNode",c=o.type==="submoduleNode",u=fv(o),m=i?"default branch anchor":c?o.submodulePath||"submodule checkout":[o.machineLabel,ec(o.locality)].filter(Boolean).join(" · ")||o.workspace,d=o.submoduleCommit?o.submoduleCommit.slice(0,7):null,h=Fu(o),f=Hu(o),y=Yu(o),b=o.sessionDetails,x=o.sessionDetails,j=Uv(o),k=o.sessionDetails.map(S=>{const v=Gt(S),g=S.providerType||"provider unknown",C=cr(S),I=S.startedAt||S.createdAt||null,N=S.statusNote?` · ${S.statusNote}`:"";return`Session: ${S.sessionId} · ${g} · ${v} · ${C} · ${Zl(I)}${N}`});if(n)return s.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${Xl(o,t,r.isDark)}`,style:{width:Jn(o,!0)},title:[o.label,o.branch?`Branch: ${o.branch}`:null,o.machineLabel?`Machine: ${o.machineLabel}`:null,o.workspace?`Workspace: ${o.workspace}`:null,h?`Status: ${h.label}`:null,Ka(o),...k].filter(Boolean).join(`
66
+ `),children:[s.jsx(Jr,{type:"target",position:a==="TB"?Zt.Top:Zt.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:m})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[y&&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:Ql(o.health)},"aria-hidden":!0})]})]}),h&&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] ${Jl(h.tone,r.isDark)}`,title:h.label,children:s.jsx("span",{className:"truncate",children:h.label})}),!h&&o.branch&&!c&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[10px] ${At("meta",r.isDark)} rounded-full border px-2 py-0.5 inline-block`,title:o.branch,children:o.branch}),j&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[9px] ${r.isDark?"text-cyan-100/85":"text-sky-700"}`,title:k.join(`
67
+ `),children:j}),x.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:x.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: ${Gt(S)}`,`Role: ${cr(S)}`].filter(Boolean).join(`
68
+ `),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] ${Ua(S,r.isDark)}`,children:Gt(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:za(S.sessionId)}),s.jsx("span",{className:"shrink-0",children:cr(S)})]})]},S.sessionId))}),s.jsx(Jr,{type:"source",position:a==="TB"?Zt.Bottom:Zt.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]});const p=t,w=[o.label,m,h?`Status: ${h.label}`:null,Ka(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,u&&f?`Note: ${f}`:null,...k].filter(Boolean).join(`
69
+ `);return s.jsxs("div",{className:`group rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all ${Xl(o,t,r.isDark)}`,style:{width:Jn(o)},title:w,children:[s.jsx(Jr,{type:"target",position:a==="TB"?Zt.Top:Zt.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:m})]}),s.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 shrink-0",children:[y&&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:Ql(o.health)},"aria-hidden":!0})]})]}),h?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] ${Jl(h.tone,r.isDark)}`,title:h.label,children:s.jsx("span",{className:"truncate",children:h.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] ${At("meta",r.isDark)}`,title:o.branch,children:s.jsx("span",{className:"truncate",children:o.branch})}):null,j&&s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[10px] font-medium ${r.isDark?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}`,title:k.join(`
70
+ `),children:s.jsx("span",{className:"truncate",children:j})}),x.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:x.map(S=>{const v=cr(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: ${Gt(S)}`,`Role: ${v}`].filter(Boolean).join(`
71
+ `),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] ${Ua(S,r.isDark)}`,children:Gt(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:za(S.sessionId)}),s.jsx("span",{children:v})]})]},S.sessionId)})}),s.jsxs("div",{className:`overflow-hidden transition-all ${p?"mt-3 max-h-[400px] opacity-100":"mt-0 max-h-0 opacity-0 group-hover:mt-3 group-hover:max-h-[400px] group-hover:opacity-100"}`,children:[s.jsxs("div",{className:"flex min-w-0 flex-wrap gap-1.5 text-[10px]",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${At("health",r.isDark)}`,children:Wv(o.health)}),c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${At("submodule",r.isDark)}`,children:"submodule"}),!i&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${At(zv(o),r.isDark)}`,children:ec(o.locality)}),d&&c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${At("meta",r.isDark)}`,children:d}),o.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${At("dirty",r.isDark)}`,children:c?"local changes":`${o.dirtyFiles} dirty`}),o.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${At("conflict",r.isDark)}`,children:"out of sync"}),o.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${At("conflict",r.isDark)}`,children:"conflicts"}),!c&&o.upstream&&o.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${At("orphan",r.isDark)}`,children:"upstream unverified"}),o.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${At("orphan",r.isDark)}`,children:"needs follow-up"})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,style:Ov,children:Ka(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 v=S.startedAt||S.createdAt||null,g=cr(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: ${Gt(S)}`,`Role: ${g}`,v?`Started: ${v}`:"Started: not reported",S.statusNote?`Note: ${S.statusNote}`:null].filter(Boolean).join(`
72
+ `),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:za(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] ${Ua(S,r.isDark)}`,children:Gt(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:g}),s.jsx("span",{children:Zl(v)})]}),S.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${r.textMuted}`,children:S.statusNote})]},S.sessionId)})})]}),u&&f&&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:Fv,children:f})]}),s.jsx(Jr,{type:"source",position:a==="TB"?Zt.Bottom:Zt.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const Vv={meshNode:Gv},qv=8;function Yv(e){if(e.length<2)return null;if(e.length===2){const[m,d]=e;return{d:`M ${m.x},${m.y} L ${d.x},${d.y}`,labelX:(m.x+d.x)/2,labelY:(m.y+d.y)/2}}const t=qv,r=[`M ${e[0].x},${e[0].y}`];for(let m=1;m<e.length-1;m+=1){const d=e[m-1],h=e[m],f=e[m+1],y=Math.sign(h.x-d.x),b=Math.sign(h.y-d.y),x=Math.sign(f.x-h.x),j=Math.sign(f.y-h.y),k=Math.hypot(h.x-d.x,h.y-d.y),p=Math.hypot(f.x-h.x,f.y-h.y),w=Math.min(t,k/2,p/2);if(w<1||y===x&&b===j){r.push(`L ${h.x},${h.y}`);continue}const S=h.x-y*w,v=h.y-b*w,g=h.x+x*w,C=h.y+j*w;r.push(`L ${S},${v}`),r.push(`Q ${h.x},${h.y} ${g},${C}`)}const n=e[e.length-1];r.push(`L ${n.x},${n.y}`);let a=0;const o=[0];for(let m=1;m<e.length;m+=1)a+=Math.hypot(e[m].x-e[m-1].x,e[m].y-e[m-1].y),o.push(a);const i=a/2;let c=e[0].x,u=e[0].y;for(let m=1;m<e.length;m+=1)if(o[m]>=i){const d=o[m]-o[m-1],h=d===0?0:(i-o[m-1])/d;c=e[m-1].x+(e[m].x-e[m-1].x)*h,u=e[m-1].y+(e[m].y-e[m-1].y)*h;break}return{d:r.join(" "),labelX:c,labelY:u}}function Xv(e){const t=e.data.routePoints;if(t&&t.length>=2){const o=Yv(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=oh(r):n.type==="worktreeLink"||n.type==="submoduleLink"||n.type==="cloneLink"?a=nh(r):a=ah(r),[a[0],a[1],a[2]]}function Jv(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 Qv(e){const t=l.useContext(bi),r=e.data.graphEdge,[n,a,o]=Xv(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(eh,{id:e.id,path:n,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(th,{children:s.jsx("div",{className:Jv(r,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${a}px, ${o}px)`,pointerEvents:"none",maxWidth:jv.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const Zv={meshEdge:Qv};async function ew(e,t=Ys("dark"),r=!1,n="LR"){const a=await Pv(e,r,n),o=new Set(a.nodes.map(d=>d.id)),i=a.nodes.map(d=>({id:d.id,type:d.type,position:d.position,data:{graphNode:d.graphNode,compact:r},selected:d.selected,draggable:d.draggable,selectable:d.selectable})),c=e.edges.filter(d=>o.has(d.source)&&o.has(d.target)),u=rw(c),m=c.map(d=>{var h;return{id:d.id,source:d.source,target:d.target,label:u.has(d.id)?d.label:void 0,type:"meshEdge",data:{graphEdge:d,routePoints:(h=a.edgeRoutes.get(d.id))==null?void 0:h.points},animated:d.type==="orphanLink",markerEnd:d.direction==="directed"?{type:Zm.ArrowClosed,width:d.type==="submoduleLink"?16:18,height:d.type==="submoduleLink"?16:18,color:sc(d)}:void 0,style:{stroke:sc(d),strokeWidth:d.type==="orphanLink"?2.25:d.type==="submoduleLink"?1.7:d.type==="worktreeLink"?1.8:d.type==="cloneLink"?1.6:2,strokeDasharray:d.type==="orphanLink"?"5 4":d.type==="submoduleLink"?"4 3":d.type==="cloneLink"?"6 3":void 0},labelStyle:{fill:t.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:t.edgeLabelBackgroundColor,fillOpacity:1,stroke:t.edgeLabelBorderColor},labelBgPadding:[6,4],labelBgBorderRadius:7}});return{nodes:i,edges:m}}const tw=3,sw=2;function tc(e){switch(e.type){case"orphanLink":return 5;case"parentBranch":return 4;case"submoduleLink":return 3;case"cloneLink":return 2;case"worktreeLink":return 1;case"sessionLink":return 0;default:return 0}}function rw(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<tw){for(const o of n)t.add(o.id);continue}const a=[...n].sort((o,i)=>{const c=tc(i)-tc(o);return c!==0?c:o.id.localeCompare(i.id)});for(const o of a.slice(0,sw))t.add(o.id)}return t}function sc(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 nw(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 aw(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 ow({data:e,viewportKey:t}){const r=sh(),n=rh(),a=l.useRef(null),o=l.useMemo(()=>Wu(e),[e]),i=l.useMemo(()=>xv(e),[e]);return l.useEffect(()=>{if(!r||e.nodes.length===0||a.current===t)return;let c=!1;const u=requestAnimationFrame(()=>{if(c)return;const m=i.length>0&&i.length<e.nodes.length;n.fitView({nodes:m?i.map(d=>({id:d})):void 0,padding:m?.24:.2,maxZoom:m?.98:.9,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(u)}},[e.nodes.length,i,o,r,n,t]),null}function iw(e){return e>=16?"h-[720px] min-h-[720px] sm:h-[860px] xl:h-[980px]":e>=10?"h-[580px] min-h-[580px] sm:h-[700px] xl:h-[820px]":"h-[460px] min-h-[460px] sm:h-[560px] xl:h-[680px]"}const lw=12;function cw({data:e,selectedNodeId:t=null,onNodeClick:r}){const{theme:n}=qs(),a=l.useMemo(()=>Ys(n),[n]),o=l.useMemo(()=>Ev(e),[e]),i=l.useMemo(()=>$v(e),[e]),c=e.nodes.length>=Bv,[u,m]=l.useState("auto"),d=l.useMemo(()=>u==="auto"?Nv(e):u,[u,o,e]),h=e.nodes.length>=lw,[f,y]=l.useState({nodes:[],edges:[]}),b=l.useRef(null),[x,j]=l.useState({width:0,height:0}),k=l.useMemo(()=>`${bv(e,x.width,x.height)}::${d}`,[o,e,x.height,x.width,d]);l.useEffect(()=>{let v=!1;return ew(e,a,c,d).then(g=>{v||y(g)}),()=>{v=!0}},[e,i,a,c,d]);const p=l.useMemo(()=>f.nodes.map(v=>({...v,selected:v.id===t})),[f.nodes,t]);l.useEffect(()=>{const v=b.current;if(!v)return;const g=()=>{const I=Math.max(0,Math.round(v.clientWidth)),N=Math.max(0,Math.round(v.clientHeight));j(_=>_.width===I&&_.height===N?_:{width:I,height:N})};g();const C=typeof ResizeObserver=="function"?new ResizeObserver(()=>g()):null;return C==null||C.observe(v),window.addEventListener("resize",g),()=>{C==null||C.disconnect(),window.removeEventListener("resize",g)}},[]);const w=iw(e.nodes.length),S=v=>v?a.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":a.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(bi.Provider,{value:a,children:s.jsx(Gu.Provider,{value:c,children:s.jsx(Vu.Provider,{value:d,children:s.jsxs("div",{ref:b,className:a.graphShellClass,children:[s.jsxs("div",{className:`flex flex-wrap items-center justify-between gap-2 px-3 pt-3 pb-2 text-[11px] ${a.textSecondary}`,children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs("span",{className:a.graphStatChipClass,children:[e.stats.totalNodes," node",e.stats.totalNodes===1?"":"s"]}),e.stats.totalActiveSessions>0&&s.jsxs("span",{className:a.isDark?"rounded-full border border-emerald-400/25 bg-emerald-500/12 px-3 py-1 text-emerald-100":"rounded-full border border-emerald-300 bg-emerald-50 px-3 py-1 text-emerald-700",children:[e.stats.totalActiveSessions," active session",e.stats.totalActiveSessions===1?"":"s"]}),e.stats.orphanNodes>0&&s.jsxs("span",{className:a.isDark?"rounded-full border border-orange-400/25 bg-orange-500/12 px-3 py-1 text-orange-100":"rounded-full border border-orange-300 bg-orange-50 px-3 py-1 text-orange-700",children:[e.stats.orphanNodes," need attention"]}),c&&s.jsx("span",{className:a.isDark?"rounded-full border border-white/8 bg-white/[0.03] px-3 py-1 text-slate-400":"rounded-full border border-slate-200 bg-slate-50/80 px-3 py-1 text-slate-500",children:"dense view · hover for details"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:a.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:()=>m("auto"),className:S(u==="auto"),title:`Auto (currently ${d==="TB"?"top-bottom":"left-right"})`,children:"Auto"}),s.jsx("button",{type:"button",onClick:()=>m("LR"),className:S(u==="LR"),title:"Left to right",children:"LR"}),s.jsx("button",{type:"button",onClick:()=>m("TB"),className:S(u==="TB"),title:"Top to bottom",children:"TB"})]}),s.jsx("div",{className:a.graphHintChipClass,children:"drag or scroll to pan"})]})]}),s.jsx("div",{className:`w-full min-w-0 ${w}`,children:s.jsxs(qm,{nodes:p,edges:f.edges,nodeTypes:Vv,edgeTypes:Zv,minZoom:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(v,g)=>r==null?void 0:r(g.data.graphNode),className:"h-full w-full",colorMode:a.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(ow,{data:e,viewportKey:k}),s.jsx(Ym,{className:a.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),h&&s.jsx(Xm,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:nw,nodeClassName:aw,nodeStrokeWidth:3,className:a.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(Jm,{variant:Qm.Dots,gap:18,size:1.2,color:a.graphBackgroundDotColor})]})})]})})})})}function nt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function ke(...e){for(const t of e){if(typeof t!="string")continue;const r=t.trim();if(r)return r}}function It(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function St(...e){for(const t of e)if(typeof t=="boolean")return t}function Ga(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function gi(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 dw(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 uw(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=nt(n),o=ke(a.path),i=ke(a.commit),c=ke(a.repoPath,a.repo_root)??dw(t,o);return!o||!i||!c?null:{path:o,commit:i,repoPath:c,dirty:St(a.dirty)??!1,outOfSync:St(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:It(a.lastCheckedAt,a.last_checked_at)??Date.now(),...ke(a.error)?{error:ke(a.error)}:{}}}).filter(n=>n!==null);return r.length>0?r:void 0}function mw(e){return St(e.isGitRepo)!==void 0||!!ke(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||It(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 An(e,t,r){const n=St(e.isGitRepo);if(!Object.keys(e).length||!mw(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(w=>typeof w=="string"):[],i=It(e.conflicts)??o.length,c=St(e.hasConflicts)??i>0,u=ke(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,m=uw(e.submodules,u),d=ke(e.upstreamStatus,e.upstream_status),h=It(e.upstreamFetchedAt,e.upstream_fetched_at),f=ke(e.upstreamFetchError,e.upstream_fetch_error),y=ke(e.error),b=It(e.staged)??0,x=It(e.modified)??0,j=It(e.untracked)??0,k=It(e.deleted)??0,p=It(e.renamed)??0;return{workspace:ke(e.workspace,t.workspace)||"",repoRoot:u??null,isGitRepo:a,branch:ke(e.branch)??null,headCommit:ke(e.headCommit)??null,headMessage:ke(e.headMessage)??null,upstream:ke(e.upstream)??null,upstreamStatus:d??"unchecked",...h!==void 0?{upstreamFetchedAt:h}:{},...f?{upstreamFetchError:f}:{},ahead:It(e.ahead)??0,behind:It(e.behind)??0,staged:b,modified:x,untracked:j,deleted:k,renamed:p,dirty:St(e.dirty,e.isDirty,e.is_dirty)??(b+x+j+k+p>0||c),hasConflicts:c,conflictFiles:o,stashCount:It(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??It(e.lastCheckedAt,e.last_checked_at)??Date.now(),...m?{submodules:m}:{},...y?{error:y}:{}}}function hw(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+=gi(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 pw(e){const t=nt(e.lastGit??e.last_git),r=nt(t.result),n=nt(t.status),a=nt(r.status),o=nt(e.lastProbe??e.last_probe),i=nt(o.git),c=nt(i.result),u=nt(i.status),m=nt(c.status);let d=null;for(const h of[n,a,u,m]){const f=An(h,e,{lastCheckedAt:Date.now()});if(!f)continue;const y=hw(f);(!d||y>d.score)&&(d={git:f,score:y})}return d==null?void 0:d.git}function fw(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 xw(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 Qn(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=fw(e);return t.outOfSync?"degraded":t.dirty||xw(e)?"dirty":"online"}function bw(e,t){const r=t?Qn(t):void 0;return!e||e==="unknown"?r:e}function Xu(e){const t=nt(e),r=ke(t.sessionId,t.session_id,t.id);return r?{sessionId:r,...ke(t.providerType,t.provider)?{providerType:ke(t.providerType,t.provider)}:{},...ke(t.state,t.status)?{state:ke(t.state,t.status)}:{},...ke(t.chatStatus,t.chat_status)?{chatStatus:ke(t.chatStatus,t.chat_status)}:{},...ke(t.lifecycle)?{lifecycle:ke(t.lifecycle)}:{},...ke(t.surfaceKind,t.surface_kind)?{surfaceKind:ke(t.surfaceKind,t.surface_kind)}:{},...ke(t.recoveryState,t.recovery_state)?{recoveryState:ke(t.recoveryState,t.recovery_state)}:{},...ke(t.workspace)?{workspace:ke(t.workspace)}:{},...ke(t.title)?{title:ke(t.title)}:{},...ke(t.role)?{role:ke(t.role)}:{},...St(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:St(t.isSelfCoordinator,t.is_self_coordinator)}:{},...ke(t.statusNote,t.status_note)?{statusNote:ke(t.statusNote,t.status_note)}:{},...ke(t.createdAt,t.created_at)?{createdAt:ke(t.createdAt,t.created_at)}:{},...ke(t.startedAt,t.started_at)?{startedAt:ke(t.startedAt,t.started_at)}:{},...ke(t.lastActivityAt,t.last_activity_at)?{lastActivityAt:ke(t.lastActivityAt,t.last_activity_at)}:{},...St(t.isCached,t.is_cached)!==void 0?{isCached:St(t.isCached,t.is_cached)}:{}}:null}function gw(e){const t=Array.isArray(e.activeSessionDetails)?e.activeSessionDetails:Array.isArray(e.active_session_details)?e.active_session_details:Array.isArray(e.sessions)?e.sessions:null;if(t){const a=t.map(Xu).filter(o=>o!==null);if(a.length>0)return a}const r=nt(e.activeSession??e.active_session),n=ke(r.id,r.sessionId,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id);if(n)return[{sessionId:n,...ke(r.providerType,r.provider)?{providerType:ke(r.providerType,r.provider)}:{},...ke(r.state,r.status)?{state:ke(r.state,r.status)}:{},...ke(r.chatStatus,r.chat_status)?{chatStatus:ke(r.chatStatus,r.chat_status)}:{},...ke(r.statusNote,r.status_note)?{statusNote:ke(r.statusNote,r.status_note)}:{},...ke(r.createdAt,r.created_at)?{createdAt:ke(r.createdAt,r.created_at)}:{},...ke(r.startedAt,r.started_at)?{startedAt:ke(r.startedAt,r.started_at)}:{}}]}function yw(e){const t=nt(e.connection);return Object.keys(t).length>0?t:void 0}function vw(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 yi(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 rc(e){var n,a,o,i,c,u;let t=0;const r=e.git;return yi(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+=gi(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),((u=e.connection)==null?void 0:u.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 ww(e,t){var b,x,j,k;const r=rc(e),a=rc(t)>r?t:e,o=a===t?e:t,i=a.git??o.git,c=(((b=a.providers)==null?void 0:b.length)??0)>0?a.providers:o.providers,u=(((x=a.activeSessions)==null?void 0:x.length)??0)>0?a.activeSessions:o.activeSessions,m=(((j=a.activeSessionDetails)==null?void 0:j.length)??0)>0?a.activeSessionDetails:o.activeSessionDetails,d=(((k=a.providerPriority)==null?void 0:k.length)??0)>0?a.providerPriority:o.providerPriority,h=a.connection??o.connection,f={...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")?Qn(i):a.health,providers:c??[],activeSessions:u??[],...m&&m.length>0?{activeSessionDetails:m}:{},...d&&d.length>0?{providerPriority:d}:{},...h?{connection:h}:{},...i?{git:i}:{}},y=nt(a.branchConvergence);return Object.keys(y).length>0?Object.assign(f,{branchConvergence:y}):delete f.branchConvergence,i&&(delete f.gitProbePending,delete f.error),f}function Ju(e){const t=nt(e),r=ke(t.nodeId,t.id);if(!r)return null;const n=nt(t.cachedStatus),a=pw(t),o=a?void 0:An(nt(t.git),t)??An(t,t),i=a??o,c=i?void 0:An(nt(n.git),t),u=i??c,m=ke(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),d=ke(t.health),h=a?Qn(u):bw(d,i)||(u?Qn(u):void 0)||ke(n.health)||m||ke(t.status)||"unknown",y=(a?void 0:ke(t.error))??(i?void 0:ke(n.error)),b=gw(t),x=Ga(t.activeSessions),j=(b==null?void 0:b.map(I=>I.sessionId))??[],k=Ga(t.providerPriority),p=St(t.gitProbePending,t.git_probe_pending),w=i?void 0:p,S=yw(t),v=nt(t.branchConvergence??t.branch_convergence),g=S==null?void 0:S.state,C=a&&(!(S!=null&&S.reported)||g==="unknown")?vw(S):S;return{nodeId:r,machineLabel:ke(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:ke(t.workspace,u==null?void 0:u.workspace)||"",...ke(t.repoRoot,t.repo_root,u==null?void 0:u.repoRoot)?{repoRoot:ke(t.repoRoot,t.repo_root,u==null?void 0:u.repoRoot)}:{},...ke(t.daemonId,t.daemon_id)?{daemonId:ke(t.daemonId,t.daemon_id)}:{},...ke(t.machineId,t.machine_id)?{machineId:ke(t.machineId,t.machine_id)}:{},...m?{machineStatus:m}:{},...St(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:St(t.isLocalWorktree,t.is_local_worktree)}:{},...ke(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:ke(t.worktreeBranch,t.worktree_branch)}:{},...ke(t.clonedFromNodeId,t.cloned_from_node_id)?{clonedFromNodeId:ke(t.clonedFromNodeId,t.cloned_from_node_id)}:{},health:h,...u?{git:u}:{},...w!==void 0?{gitProbePending:w}:{},providers:Ga(t.providers),activeSessions:x.length>0?x:j,...b&&b.length>0?{activeSessionDetails:b}:{},...k.length>0?{providerPriority:k}:{},...St(t.launchReady)!==void 0?{launchReady:St(t.launchReady)}:a?{launchReady:!0}:{},...ke(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:ke(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},...ke(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:ke(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...C?{connection:C}:{},...Object.keys(v).length>0?{branchConvergence:v}:{},...y?{error:y}:{}}}function nc(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 Qu(e,t){const r=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],n=r.map(Xu).filter(a=>a!==null);return n.length===0?t:t.map(a=>{const o=n.filter(c=>{const u=nt(r.find(f=>{const y=nt(f);return ke(y.sessionId,y.session_id,y.id)===c.sessionId})),m=ke(u.nodeId,u.node_id),d=ke(u.daemonId,u.daemon_id),h=ke(u.workspace);return m&&m===a.nodeId?!0:d&&a.daemonId&&d===a.daemonId?!h||!a.workspace||h===a.workspace:!!(h&&a.workspace&&h===a.workspace)});if(o.length===0)return a;const i=nc([...a.activeSessionDetails??[],...o]);return{...a,activeSessionDetails:i,activeSessions:nc([...a.activeSessionDetails??[],...o,...(a.activeSessions??[]).map(c=>({sessionId:c}))]).map(c=>c.sessionId)}})}function jw(e){const t=nt(e);return Array.isArray(t.sessions)||Array.isArray(t.active_session_details)||ke(t.daemon_id,t.machine_id,t.repo_root,t.worktree_branch,t.cloned_from_node_id)!==void 0||St(t.is_local_worktree)!==void 0}function Zu(e){const t=new Map,r=[];for(const n of e){const a=jw(n)?Ju(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=ww(o,a);t.set(a.nodeId,i);const c=r.findIndex(u=>u.nodeId===a.nodeId);c>=0&&(r[c]=i)}return r}function em(e){const t=Zu(e.nodes??[]);return{...e,nodes:Qu(e,t)}}function kw(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:yi(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 Sw(e){const t=ke(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(u=>Ju(u)).filter(u=>u!==null):null;if(!t||!n)return null;const a=Qu(e,Zu(n)),o=ke(e.meshName,e.mesh_name,e.name),i=ke(e.repoIdentity,e.repo_identity),c=ke(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 Nw(e){var o;let t=0;const r=nt(e.sourceOfTruth),n=nt(r.directPeerTruth);ke(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+=gi(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 ac(e){let t=null;for(const r of e){const n=Sw(nt(r));if(!n)continue;const a=Nw(n);(!t||a>t.score)&&(t={status:n,score:a})}return(t==null?void 0:t.status)??null}function tm(e){const r=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,n=ac([r==null?void 0:r.status,r]);return n||ac([e==null?void 0:e.status,e])}const Cw=5*60*1e3;function sm(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function rm(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function Iw(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"||sm(e)||rm(e)?"remote":"unknown"}function Mw(e){return yi(e)}function nm(e){var t;return Mw(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function Aw(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function Tw(e){return e.activeSessionDetails&&e.activeSessionDetails.length>0?e.activeSessionDetails:(e.activeSessions??[]).map(t=>({sessionId:t,workspace:e.workspace,isCached:!0}))}function am(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function om(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function vi(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function _w(e){return vi(e)?"degraded":om(e)?"dirty":"online"}function Lw(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function oc(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 Va(e){return e.length===0?"unknown":e.reduce((t,r)=>oc(r)>oc(t)?r:t)}function Rw(e){var o,i,c,u,m;const t=new Map,r=new Map;for(const d of e){const h=(i=(o=d.git)==null?void 0:o.branch)==null?void 0:i.trim();h&&(r.set(h,(r.get(h)??0)+1),(c=d.git)!=null&&c.upstream&&t.set(h,(t.get(h)??0)+1))}const n=[...t.entries()].sort((d,h)=>{if(h[1]!==d[1])return h[1]-d[1];const f=["main","master","develop","dev"],y=f.indexOf(d[0]),b=f.indexOf(h[0]);return y!==-1||b!==-1?y===-1?1:b===-1?-1:y-b:d[0].localeCompare(h[0])});return(u=n[0])!=null&&u[0]?n[0][0]:((m=[...r.entries()].sort((d,h)=>h[1]-d[1])[0])==null?void 0:m[0])??null}function Pw(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 ic(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 Dw(e){return e.reduce((t,r)=>ic(r.status)>ic(t.status)?r:t)}function Ew(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 $w(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 Bw(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 Ow(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 Fw(e,t){if(nm(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=am(a)||om(a),i=!!(a!=null&&a.hasConflicts)||vi(a),c=(a==null?void 0:a.ahead)??0,u=(a==null?void 0:a.behind)??0,m=(a==null?void 0:a.branch)??null,d=(a==null?void 0:a.upstream)??null,h=(a==null?void 0:a.upstreamStatus)??null,f=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??m,defaultBranch:f,upstream:r.upstream??d,upstreamStatus:r.upstreamStatus??h,ahead:r.ahead??c,behind:r.behind??u,dirty:r.dirty??o,hasConflicts:r.hasConflicts??i}}function Hw(e,t){const r=Fw(e,t);return r?{...r,defaultBranch:r.defaultBranch??t}:null}function Ww(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function Kw(e){var u,m,d;const{nodeStatus:t,expectedSubmodulePaths:r,refreshedAtMs:n}=e,a=[],o=t.machineLabel||t.nodeId,i=t.git;if(!i){if(nm(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const h=t.health==="online"||t.machineStatus==="online"||((u=t.connection)==null?void 0:u.state)==="connected"||((m=t.connection)==null?void 0:m.state)==="self";return a.push(h?`${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(h=>h.path));if(r.size>0){const h=[...r].filter(f=>!c.has(f));h.length>0&&a.push(`${o} is missing submodule visibility for ${h.join(", ")} even though another peer reported it.`)}return((d=t.connection)==null?void 0:d.state)!=="self"&&n!==null&&typeof i.lastCheckedAt=="number"&&n-i.lastCheckedAt>Cw&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(h=>h.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(h=>h.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function Uw(e){const t=em(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??Rw(t.nodes),a=Aw(t.refreshedAt),o=new Set(t.nodes.flatMap(M=>{var R;return(((R=M.git)==null?void 0:R.submodules)??[]).map(z=>z.path)})),i=[],c=[],u=$w(t),m=new Map;for(const M of t.nodes){const R=M.git,z=(R==null?void 0:R.branch)??null,T=_w(R),L=am(R)||T==="dirty",B=Pw(M,n),O=Hw(M,n),$=Kw({nodeStatus:M,expectedSubmodulePaths:o,refreshedAtMs:a}),E=typeof M.clonedFromNodeId=="string"?M.clonedFromNodeId:null,W=Tw(M),J={id:M.nodeId,type:B.length>0?"orphanNode":"worktreeNode",label:M.machineLabel||M.nodeId.slice(0,8),workspace:M.workspace,branch:z,upstream:(R==null?void 0:R.upstream)??null,upstreamStatus:(R==null?void 0:R.upstreamStatus)??null,daemonId:sm(M),machineId:rm(M),machineLabel:M.machineLabel||null,locality:Iw(M),health:Va([M.health,T]),ahead:(R==null?void 0:R.ahead)??0,behind:(R==null?void 0:R.behind)??0,dirty:L,dirtyFiles:Lw(R),hasConflicts:(R==null?void 0:R.hasConflicts)??!1,activeSessionCount:W.length,activeSessions:W.map(Q=>Q.sessionId),sessionDetails:W,providers:M.providers??[],isOrphan:B.length>0,orphanReasons:B,error:M.error,nextStepHint:$.snapshotWarnings[0]??B[0]??(O==null?void 0:O.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:E,worktreeBranch:M.worktreeBranch??null,submodulePath:null,submoduleCommit:(R==null?void 0:R.headCommit)??null,outOfSync:vi(R),snapshotCompleteness:$.snapshotCompleteness,snapshotWarnings:$.snapshotWarnings,branchConvergence:O,source:M};if(i.push(J),z){const Q=m.get(z)??[];Q.push(J.id),m.set(z,Q)}for(const Q of(R==null?void 0:R.submodules)??[]){const ee=`${J.id}::submodule::${Q.path}`,me=Q.path.split("/").filter(Boolean).pop()||Q.path;i.push({id:ee,type:"submoduleNode",label:me,workspace:Q.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:J.daemonId,machineId:J.machineId,machineLabel:J.machineLabel,locality:J.locality,health:Ww(Q),ahead:0,behind:0,dirty:Q.dirty,dirtyFiles:Q.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],error:Q.error,nextStepHint:Q.error||(Q.outOfSync?`${Q.path} is out of sync with the parent checkout`:Q.dirty?`${Q.path} has local changes`:`${Q.path} is in sync with the parent checkout`),parentNodeId:J.id,submodulePath:Q.path,submoduleCommit:Q.commit,outOfSync:Q.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:J.id,parentWorkspace:M.workspace,submodule:Q}}),c.push({id:`${J.id}--${ee}`,source:J.id,target:ee,type:"submoduleLink",label:Q.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const d=n?`__branch_${n}`:null;if(d&&n){const R=(m.get(n)??[]).map(E=>i.find(W=>W.id===E)).filter(Boolean),z=R.map(E=>E.branchConvergence).filter(Boolean),T=Ew(t),L=R.length>0&&R.every(E=>Bw(E,n)),B=(T==null?void 0:T.length)===0&&L?Ow(n,R):z.length>0?Dw(z):null,O=(T==null?void 0:T.length)===0&&L?0:z.filter(E=>E.needsConvergence).length,$={id:d,type:"defaultBranchNode",label:n,workspace:t.repoIdentity,branch:n,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:"default branch",locality:"unknown",health:Va(R.map(E=>E.health)),ahead:0,behind:0,dirty:R.some(E=>E.dirty),dirtyFiles:R.reduce((E,W)=>E+W.dirtyFiles,0),hasConflicts:R.some(E=>E.hasConflicts),activeSessionCount:R.reduce((E,W)=>E+W.activeSessionCount,0),activeSessions:R.flatMap(E=>E.activeSessions),sessionDetails:R.flatMap(E=>E.sessionDetails),providers:[...new Set(R.flatMap(E=>E.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:O>0?`${O} workspace(s) on ${n} still need follow-up`:R.length>0?`${R.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:B,source:{nodeId:d,machineLabel:n,workspace:t.repoIdentity,health:Va(R.map(E=>E.health)),providers:[],activeSessions:[],activeSessionDetails:[]}};i.push($);for(const E of i)if(!(E.id===d||E.type==="submoduleNode")){if(E.branch===n){c.push({id:`${d}--${E.id}`,source:d,target:E.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(E.branch){c.push({id:`${d}--${E.id}`,source:d,target:E.id,type:E.isOrphan?"orphanLink":"parentBranch",label:E.branch,direction:"undirected"});continue}E.isOrphan&&c.push({id:`${d}--${E.id}`,source:d,target:E.id,type:"orphanLink",label:"detached",direction:"undirected"})}}for(const[M,R]of m){if(R.length<2)continue;const z=R.map(T=>i.find(L=>L.id===T)).filter(Boolean);z.sort((T,L)=>T.label.localeCompare(L.label));for(let T=1;T<z.length;T+=1)c.push({id:`wt_${z[T-1].id}--${z[T].id}`,source:z[T-1].id,target:z[T].id,type:"worktreeLink",label:T===1?`${M} peers`:void 0,direction:"undirected"})}const h=new Set(i.map(M=>M.id)),f=new Set;for(const M of i){if(!M.clonedFromNodeId||M.type==="submoduleNode"||!h.has(M.clonedFromNodeId))continue;const R=`clone_${M.clonedFromNodeId}--${M.id}`;if(f.has(R))continue;f.add(R);const z=M.worktreeBranch??M.branch??void 0;c.push({id:R,source:M.clonedFromNodeId,target:M.id,type:"cloneLink",label:z?`cloned · ${z}`:"cloned",direction:"directed"})}const y=i.filter(M=>M.type!=="defaultBranchNode"),b=y.filter(M=>M.isOrphan).length,x=y.filter(M=>M.hasConflicts).length,j=y.filter(M=>M.health==="offline").length,k=y.filter(M=>M.type==="submoduleNode"&&M.outOfSync).length,p=y.filter(M=>{var R;return M.type!=="submoduleNode"&&((R=M.branchConvergence)==null?void 0:R.needsConvergence)}).length,w=y.filter(M=>{var R;return((R=M.branchConvergence)==null?void 0:R.status)==="blocked_review"}).length,S=y.filter(M=>{var R;return((R=M.branchConvergence)==null?void 0:R.status)==="pushed_feature_branch_needs_merge"}).length,v=y.filter(M=>{var R;return((R=M.branchConvergence)==null?void 0:R.status)==="cleanup_candidate"}).length,g=y.filter(M=>{var R;return((R=M.branchConvergence)==null?void 0:R.status)==="not_mergeable"}).length,C=y.filter(M=>M.snapshotWarnings.length>0).length,I=y.filter(M=>M.snapshotCompleteness==="pending_git").length,N=y.filter(M=>M.snapshotCompleteness==="missing_git").length,_=y.filter(M=>M.snapshotCompleteness==="missing_submodule_report").length,D=y.filter(M=>M.snapshotCompleteness==="stale").length,A=[I>0?`${I} node(s) are still waiting for a live peer git snapshot`:null,N>0?`${N} node(s) have no visible peer git snapshot`:null,_>0?`${_} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,D>0?`${D} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return p>0&&u.push(`${p} workspace(s) still need follow-up before the mesh is converged`),b>0&&u.push(`${b} workspace(s) need attention before safe coordination`),w>0&&u.push(`${w} workspace(s) are blocked on branch convergence or upstream sync`),S>0&&u.push(`${S} clean feature branch workspace(s) still need merge follow-up`),v>0&&u.push(`${v} worktree workspace(s) are ready for refine / cleanup`),g>0&&u.push(`${g} workspace(s) have local changes or conflicts blocking convergence`),x>0&&u.push(`${x} workspace(s) report merge conflicts`),j>0&&u.push(`${j} node(s) are currently offline`),k>0&&u.push(`${k} submodule(s) are out of sync with their parent checkout`),u.push(...A),n||u.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:y.length,onlineNodes:y.filter(M=>M.health==="online").length,dirtyNodes:y.filter(M=>M.dirty).length,orphanNodes:b,errorNodes:y.filter(M=>!!M.error||M.outOfSync).length,offlineNodes:j,followUpNodes:p,blockedReviewNodes:w,mergeReadyNodes:S,cleanupCandidateNodes:v,notMergeableNodes:g,incompleteSnapshotNodes:C,missingGitSnapshotNodes:N,missingSubmoduleSnapshotNodes:_,staleGitSnapshotNodes:D,totalActiveSessions:y.reduce((M,R)=>M+R.activeSessionCount,0)},warnings:u,snapshotWarnings:A}}const zw={recentFailures:0,taskCompleted:0,taskFailed:0,sessionLaunched:0},wi=l.createContext(Ys("dark"));function Ve({label:e,tone:t="default"}){const r=l.useContext(wi);return s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${r.badge(t)}`,children:e})}function jt({label:e,value:t}){const r=l.useContext(wi);return s.jsxs("div",{className:r.rowClass,children:[s.jsx("span",{className:r.rowLabelClass,children:e}),s.jsx("span",{className:r.rowValueClass,children:t})]})}function Gw(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 qa(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 fn(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 Vw(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function qw(e){return e.startedAt||e.createdAt||null}function Yw(e){const t=qw(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 Xw(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function Jw(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 Qw(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 Zw(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 ej(e){return e.assignedNodeId||e.targetNodeId||null}function lc(e){return e?e.slice(0,7):null}function tj(e,t){var o,i,c;const r=lc((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?[lc(a.commit),a.message].filter(Boolean).join(" · "):null}function sj(e,t){const r=tj(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function rj(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 nj(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 u=((c=e.selectedNodeStatus)==null?void 0:c.daemonId)||e.coordinatorDaemonId;return u?{daemonId:u,workspace:t}:null}if(t&&e.selectedNodeStatus){const u=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return u?{daemonId:u,workspace:t}:null}return null}function aj(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":Qw(e.connection)}function oj(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 ij(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function lj(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,u,m,d,h,f,y,b,x,j,k,p,w,S,v,g,C,I,N,_,D;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)??"",((u=o.connection)==null?void 0:u.source)??"",o.health,o.gitProbePending?1:0,((m=o.git)==null?void 0:m.branch)??"",((d=o.git)==null?void 0:d.upstream)??"",((h=o.git)==null?void 0:h.upstreamStatus)??"",((f=o.git)==null?void 0:f.ahead)??"",((y=o.git)==null?void 0:y.behind)??"",((b=o.git)==null?void 0:b.headCommit)??"",((x=o.git)==null?void 0:x.staged)??"",((j=o.git)==null?void 0:j.modified)??"",((k=o.git)==null?void 0:k.untracked)??"",((p=o.git)==null?void 0:p.deleted)??"",((w=o.git)==null?void 0:w.renamed)??"",(S=o.git)!=null&&S.hasConflicts?1:0,((v=o.git)==null?void 0:v.lastCheckedAt)??"",((g=o.activeSessions)==null?void 0:g.join(","))??"",((C=o.activeSessionDetails)==null?void 0:C.length)??"",((I=o.activeSessionDetails)==null?void 0:I.map(A=>[A.sessionId,A.providerType??"",A.state??"",A.chatStatus??"",A.lifecycle??"",A.role??"",A.isSelfCoordinator?1:0,A.statusNote??"",A.startedAt??"",A.createdAt??""].join("/")).join(","))??"",((N=o.providers)==null?void 0:N.join(","))??"",((_=o.providerPriority)==null?void 0:_.join(","))??"",o.error??"",(((D=o.git)==null?void 0:D.submodules)??[]).map(A=>[A.path,A.commit,A.dirty?1:0,A.outOfSync?1:0,A.error??""].join("/")).join(",")].join("|")})].join("::")}function im({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null}){var ee,me,je,Me,q;const{theme:a}=qs(),o=l.useMemo(()=>Ys(a),[a]),i=l.useMemo(()=>em(e),[e]),c=l.useMemo(()=>lj(i),[i]),u=l.useMemo(()=>Uw(i),[c]),[m,d]=l.useState(null),[h,f]=l.useState(null),[y,b]=l.useState({}),[x,j]=l.useState(null),[k,p]=l.useState(null),w=l.useMemo(()=>new Map(i.nodes.map(G=>[G.nodeId,G])),[i.nodes]),S=l.useMemo(()=>new Map(u.nodes.map(G=>[G.id,G])),[u.nodes]),v=((ee=i.queue)==null?void 0:ee.summary)??null,g=((me=i.ledger)==null?void 0:me.summary)??zw,C=l.useMemo(()=>Zw(i),[i]),I=l.useMemo(()=>{const G=new Map;for(const he of C){const ue=fn(he.session);G.set(ue,(G.get(ue)??0)+1)}return[...G.entries()].sort((he,ue)=>ue[1]-he[1])},[C]);l.useEffect(()=>{m&&(S.has(m)||(d(null),f(G=>!G||"nodeId"in G&&G.nodeId===m?null:G)))},[S,m]);const N=m?w.get(m)??null:null,_=ij(u,m);l.useEffect(()=>{var G,he,ue;if(m)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:i.meshId,selectedNodeId:m,canonicalNode:kw(N),graphNode:_?{id:_.id,branch:_.branch,upstream:_.upstream,headCommit:_.submoduleCommit,submoduleCount:((he=(G=N==null?void 0:N.git)==null?void 0:G.submodules)==null?void 0:he.length)??0,snapshotCompleteness:_.snapshotCompleteness,snapshotWarnings:_.snapshotWarnings,branchConvergence:((ue=_.branchConvergence)==null?void 0:ue.status)??null}:null})}catch{}},[i.meshId,_,m,N]);const D=(h==null?void 0:h.kind)==="session"?C.find(G=>G.nodeId===h.nodeId&&G.session.sessionId===h.sessionId)??null:null,A=l.useMemo(()=>C.filter(G=>G.nodeId===m),[m,C]),M=nj({coordinatorDaemonId:r,selectedNodeStatus:N,selectedSessionEntry:D}),R=(M==null?void 0:M.workspace)??null,z=R?y[R]??null:null,T=sj(N,(z==null?void 0:z.entries)??[]),L=(_==null?void 0:_.daemonId)??(N==null?void 0:N.daemonId)??r??null,B=!!(_&&n&&L&&_.type!=="submoduleNode"&&_.behind>0&&_.ahead===0&&_.dirtyFiles===0&&!_.dirty&&!_.hasConflicts&&_.upstreamStatus==="fresh"),O=l.useCallback(()=>{d(null),f(null),j(null)},[]);l.useEffect(()=>{j(null)},[m]);const $=l.useCallback(async()=>{if(!(!_||!L||!n||!B)){p(_.id),j(null);try{const G=await n(L,"fast_forward_mesh_node",{meshId:i.meshId,nodeId:_.id,dryRun:!0,execute:!1});if(j({phase:"dry_run",code:typeof(G==null?void 0:G.code)=="string"?G.code:void 0,error:typeof(G==null?void 0:G.operationError)=="string"?G.operationError:null,executed:(G==null?void 0:G.executed)===!0}),!(G!=null&&G.success)||G.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${_.label}?`))return;const ue=await n(L,"fast_forward_mesh_node",{meshId:i.meshId,nodeId:_.id,dryRun:!1,execute:!0});j({phase:"execute",code:typeof(ue==null?void 0:ue.code)=="string"?ue.code:void 0,error:typeof(ue==null?void 0:ue.operationError)=="string"?ue.operationError:null,executed:(ue==null?void 0:ue.executed)===!0})}catch(G){j({phase:"dry_run",error:G instanceof Error?G.message:"fast-forward failed"})}finally{p(null)}}},[B,i.meshId,_,L,n]);l.useEffect(()=>{if(!_)return;const G=he=>{he.key==="Escape"&&O()};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[O,_]),l.useEffect(()=>{if(!M||!n)return;const{daemonId:G,workspace:he}=M,ue=y[he];if(ue!=null&&ue.loading||ue&&(ue.entries.length>0||ue.error))return;let ce=!1;return b(ve=>{var X;return{...ve,[he]:{loading:!0,error:null,entries:((X=ve[he])==null?void 0:X.entries)??[]}}}),n(G,"git_log",{workspace:he,limit:5}).then(ve=>{ce||b(X=>({...X,[he]:{loading:!1,error:null,entries:rj(ve)}}))}).catch(ve=>{ce||b(X=>({...X,[he]:{loading:!1,error:ve instanceof Error?ve.message:"git_log failed",entries:[]}}))}),()=>{ce=!0}},[y,M,n]);const E=[...u.warnings??[],...i.nodes.filter(G=>G.machineStatus&&G.machineStatus!=="online").map(G=>`${G.machineLabel}: ${G.machineStatus}`)],W=u.stats.incompleteSnapshotNodes>0,J=u.stats.followUpNodes>0?`${u.stats.followUpNodes} need follow-up`:W?"mesh visibility incomplete":"mesh converged",Q=u.stats.followUpNodes>0?"danger":W?"warn":"good";return s.jsx(wi.Provider,{value:o,children:s.jsx("div",{className:"flex min-h-0 flex-col gap-4",children:s.jsx("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-4",children:s.jsxs("div",{className:`${o.cardClass} relative min-h-0 flex-1 rounded-[28px] p-3 sm:p-4`,style:{minHeight:420},children:[s.jsxs("div",{className:`absolute inset-x-4 top-4 z-30 flex max-h-[42dvh] flex-wrap items-start justify-between gap-3 overflow-y-auto rounded-2xl px-3.5 py-3 backdrop-blur-xl sm:static sm:mb-3 sm:max-h-none sm:overflow-visible sm:backdrop-blur-none ${o.isDark?"border border-white/10 bg-slate-950/85 sm:bg-slate-950/45":"border border-slate-200 bg-white/95 shadow-lg shadow-slate-900/10 sm:bg-white/95 sm:shadow-sm"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-wrap gap-2 text-xs ${o.textSecondary}`,children:[s.jsx(Ve,{label:J,tone:Q}),u.stats.blockedReviewNodes>0&&s.jsx(Ve,{label:`${u.stats.blockedReviewNodes} blocked review`,tone:"danger"}),u.stats.notMergeableNodes>0&&s.jsx(Ve,{label:`${u.stats.notMergeableNodes} not mergeable`,tone:"danger"}),u.stats.mergeReadyNodes>0&&s.jsx(Ve,{label:`${u.stats.mergeReadyNodes} need merge`,tone:"warn"}),u.stats.cleanupCandidateNodes>0&&s.jsx(Ve,{label:`${u.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),u.stats.offlineNodes>0&&s.jsx(Ve,{label:`${u.stats.offlineNodes} offline`,tone:"danger"}),u.stats.incompleteSnapshotNodes>0&&s.jsx(Ve,{label:`${u.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),u.stats.missingGitSnapshotNodes>0&&s.jsx(Ve,{label:`${u.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),u.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Ve,{label:`${u.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),u.stats.staleGitSnapshotNodes>0&&s.jsx(Ve,{label:`${u.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((v==null?void 0:v.active)??0)>0&&s.jsx(Ve,{label:`${(v==null?void 0:v.active)??0} active queue`,tone:"info"}),s.jsx(Ve,{label:`${u.stats.totalNodes} nodes`,tone:"default"}),u.stats.totalActiveSessions>0&&s.jsx(Ve,{label:`${u.stats.totalActiveSessions} attached chats`,tone:"info"})]}),s.jsxs("details",{className:`max-w-full rounded-xl px-3 py-2 text-xs ${o.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${o.textSecondary} [&::-webkit-details-marker]:hidden`,children:"Legend & secondary details"}),s.jsxs("div",{className:"mt-3 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ve,{label:`${u.stats.dirtyNodes} dirty`,tone:u.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Ve,{label:`${u.stats.orphanNodes} orphan`,tone:u.stats.orphanNodes>0?"warn":"good"}),s.jsx(Ve,{label:`${g.recentFailures} recent failures`,tone:g.recentFailures>0?"danger":"good"}),I.length===0?s.jsx(Ve,{label:"no session metadata"}):I.slice(0,2).map(([G,he])=>s.jsx(Ve,{label:`${he} ${G}`,tone:qa(G)},G))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ve,{label:"Anchor = default branch",tone:"info"}),s.jsx(Ve,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Ve,{label:"Submodule link = child checkout",tone:"warn"})]}),E.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:E.map(G=>s.jsx("span",{className:o.isDark?"rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1 text-xs text-amber-100":"rounded-full border border-amber-300 bg-amber-50 px-3 py-1 text-xs text-amber-700",children:G},G))}),s.jsx("div",{className:`text-xs ${o.textMuted}`,children:"Click a node only when you want drill-down details. The graph itself now carries the convergence state."})]})]})]}),u.nodes.length>0?s.jsx(cw,{data:u,selectedNodeId:m,onNodeClick:G=>{if((h==null?void 0:h.kind)==="node"&&m===G.id){d(null),f(null);return}d(G.id),f({kind:"node",nodeId:G.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}),_&&(h==null?void 0:h.kind)==="node"&&s.jsx("div",{className:"absolute inset-x-3 bottom-3 top-20 z-20 flex items-end justify-center p-2 sm:inset-5 sm:top-24 sm:items-start sm:justify-end",onClick:O,role:"presentation",children:s.jsxs("section",{role:"dialog","aria-modal":"false","aria-label":"Selected node",className:o.isDark?"max-h-[min(72vh,540px)] w-full max-w-[min(28rem,calc(100vw-2.5rem))] overflow-y-auto rounded-2xl border border-white/12 bg-slate-950/96 p-4 shadow-2xl shadow-black/40 backdrop-blur-xl":"max-h-[min(72vh,540px)] w-full max-w-[min(28rem,calc(100vw-2.5rem))] overflow-y-auto rounded-2xl border border-slate-200 bg-white/96 p-4 shadow-2xl shadow-slate-900/15 backdrop-blur-xl",onClick:G=>G.stopPropagation(),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:`truncate text-sm font-semibold ${o.textPrimary}`,children:_.label}),s.jsx("div",{className:`mt-1 font-mono text-[11px] ${o.textMuted}`,children:_.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[_.behind>0&&s.jsx("button",{type:"button",onClick:()=>{$()},disabled:!B||k===_.id,className:o.isDark?"rounded-full border border-emerald-400/25 bg-emerald-500/10 px-2.5 py-1 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.5 py-1 text-xs font-semibold text-emerald-700 transition hover:bg-emerald-100 disabled:cursor-not-allowed disabled:opacity-45",children:k===_.id?"Checking":"Heal"}),s.jsx("button",{type:"button",onClick:O,className:o.isDark?"rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-xs text-slate-200 transition hover:bg-white/[0.08]":"rounded-full border border-slate-200 bg-white px-2.5 py-1 text-xs text-slate-600 transition hover:bg-slate-50",children:"Close"})]})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[s.jsx(Ve,{label:(N==null?void 0:N.health)??_.health,tone:Gw((N==null?void 0:N.health)??_.health)}),_.branch&&s.jsx(Ve,{label:_.branch,tone:"default"}),_.ahead>0&&s.jsx(Ve,{label:`ahead ${_.ahead}`,tone:"warn"}),_.behind>0&&s.jsx(Ve,{label:`behind ${_.behind}`,tone:"warn"}),_.dirtyFiles>0&&s.jsx(Ve,{label:`${_.dirtyFiles} dirty`,tone:"warn"}),(N==null?void 0:N.connection)&&s.jsx(Ve,{label:aj(N),tone:Jw(N.connection)}),A.length>0&&s.jsx(Ve,{label:`${A.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[s.jsx(jt,{label:"Machine",value:_.machineLabel??"not reported"}),s.jsx(jt,{label:"Locality",value:_.locality}),s.jsx(jt,{label:"Machine id",value:_.machineId??(N==null?void 0:N.machineId)??"not reported"}),s.jsx(jt,{label:"Daemon id",value:_.daemonId??(N==null?void 0:N.daemonId)??"not reported"}),s.jsx(jt,{label:"Workspace",value:(N==null?void 0:N.workspace)??_.workspace}),s.jsx(jt,{label:"Branch",value:_.branch??"unknown"}),s.jsx(jt,{label:"HEAD",value:T??(N!=null&&N.gitProbePending?"Pending live git probe":"not reported")}),s.jsx(jt,{label:"Upstream",value:_.upstream??"none"}),s.jsx(jt,{label:"Dirty/ahead/behind",value:`${_.dirtyFiles} dirty · ↑${_.ahead}/↓${_.behind}`}),s.jsx(jt,{label:"Source",value:String(((je=N==null?void 0:N.connection)==null?void 0:je.source)??oj(_))}),s.jsx(jt,{label:"Transport",value:((Me=N==null?void 0:N.connection)==null?void 0:Me.transport)??"unknown"}),s.jsx(jt,{label:"Sessions",value:A.length>0?A.map(G=>fn(G.session)).join(", "):"none active"})]}),A.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${o.textMuted}`,children:"Active Sessions"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:A.map(G=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${o.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono select-text ${o.textMuted}`,title:G.session.sessionId,children:Xw(G.session.sessionId)}),s.jsx(Ve,{label:fn(G.session),tone:qa(fn(G.session))})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 ${o.textMuted}`,children:[s.jsx("span",{className:"truncate",children:G.session.providerType||"provider unknown"}),s.jsx("span",{children:Vw(G.session)}),s.jsx("span",{children:Yw(G.session)})]}),G.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${o.textMuted}`,children:G.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${o.textMuted}`,title:G.session.workspace||G.workspace,children:[(G.session.workspace||G.workspace).slice(0,42),G.branch?` · ${G.branch}`:""]})]},G.session.sessionId))})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${o.textMuted}`,children:"Ledger (mesh-wide)"}),s.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[s.jsx(jt,{label:"Completed",value:String(g.taskCompleted)}),s.jsx(jt,{label:"Failed",value:s.jsx("span",{className:g.taskFailed>0?o.isDark?"text-rose-300":"text-rose-600":"",children:g.taskFailed})}),s.jsx(jt,{label:"Launched",value:String(g.sessionLaunched)}),s.jsx(jt,{label:"Recent failures",value:s.jsx("span",{className:g.recentFailures>0?o.isDark?"text-amber-300":"text-amber-600":"",children:g.recentFailures})})]})]}),(()=>{var ue,ce;const G=((ue=i.queue)==null?void 0:ue.tasks)??((ce=i.queue)==null?void 0:ce.items)??null;if(!Array.isArray(G)||G.length===0)return null;const he=G.filter(ve=>ej(ve)===m).slice(0,3);return he.length===0?null:s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${o.textMuted}`,children:"Queue tasks"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:he.map(ve=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${o.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`font-mono ${o.textMuted}`,children:ve.id.slice(0,12)}),s.jsx(Ve,{label:ve.status??"unknown",tone:qa(ve.status)})]}),ve.message&&s.jsx("div",{className:`mt-0.5 truncate ${o.textMuted}`,children:ve.message.slice(0,48)})]},ve.id))})]})})(),_.snapshotWarnings.length>0&&s.jsxs("div",{className:o.isDark?"mt-3 rounded-xl border border-amber-400/20 bg-amber-500/10 p-3 text-xs text-amber-100":"mt-3 rounded-xl border border-amber-300 bg-amber-50 p-3 text-xs text-amber-800",children:[s.jsx("div",{className:"font-medium",children:"Key warning"}),s.jsx("div",{className:"mt-1",children:_.snapshotWarnings[0]})]}),((q=_.branchConvergence)==null?void 0:q.nextStep)&&s.jsxs("div",{className:o.isDark?"mt-3 rounded-xl border border-sky-400/20 bg-sky-500/10 p-3 text-xs text-sky-100":"mt-3 rounded-xl border border-sky-300 bg-sky-50 p-3 text-xs text-sky-800",children:[s.jsx("div",{className:"font-medium",children:"Follow-up"}),s.jsx("div",{className:"mt-1",children:_.branchConvergence.nextStep})]}),x&&s.jsxs("div",{className:o.isDark?"mt-3 rounded-xl border border-emerald-400/20 bg-emerald-500/10 p-3 text-xs text-emerald-100":"mt-3 rounded-xl border border-emerald-300 bg-emerald-50 p-3 text-xs text-emerald-800",children:[s.jsx("div",{className:"font-medium",children:x.phase==="execute"?"Heal result":"Heal preview"}),s.jsx("div",{className:"mt-1",children:x.code??x.error??"No result code returned."})]})]})})]})})})})}function ht(e){return typeof e=="string"?e.trim():""}function Lo(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function ji(...e){const t=new Set;for(const r of e){const n=ht(r);n&&t.add(n)}return[...t]}function cj(e,t){var h,f;const r=Lo(e==null?void 0:e.settings),n=ht((h=e==null?void 0:e.coordinator)==null?void 0:h.meshId)||ht(r.meshCoordinatorFor),a=ht(r.meshNodeFor),o=!!n||!!a,i=n===t||a===t;if(o&&!i)return null;const c=Lo(e==null?void 0:e.activeChat),u=ji(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),m=u[0]||"";if(!m)return null;const d=n===t?ht((f=e==null?void 0:e.coordinator)==null?void 0:f.role)||"coordinator":a===t?ht(r.meshNodeRole)||"worker":ht(e==null?void 0:e.role)||ht(r.meshNodeRole)||void 0;return{sessionId:m,aliases:u,meshId:t,nodeId:i&&ht(r.meshNodeId)||null,providerType:ht(e==null?void 0:e.providerType)||void 0,state:ht(e==null?void 0:e.status)||void 0,chatStatus:ht(c.status)||void 0,lifecycle:ht(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:ht(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:ht(e==null?void 0:e.runtimeRecoveryState)||void 0,...d?{role:d}:{},...i?{isSelfCoordinator:n===t}:{},workspace:ht(e==null?void 0:e.workspace)||null}}function lm(e,t){var n;return t?(Array.isArray((n=e.status)==null?void 0:n.sessions)?e.status.sessions:[]).map(a=>cj(a,t)).filter(a=>a!==null):[]}function Zn(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function dj(e,t){const r=new Set(Zn(t));return Zn(e).some(n=>r.has(n))}function uj(e,t){const r=t.filter(a=>!!a);return r.length===0?e:[...e.filter(a=>!r.some(o=>dj(a,o))),...r]}function mj(e,t){if(t.length===0)return e;const r=new Map;for(const o of t)for(const i of Zn(o))r.set(i,o);let n=!1;const a=(e.nodes??[]).map(o=>{const i=Array.isArray(o.activeSessionDetails)?o.activeSessionDetails:Array.isArray(o.sessions)?o.sessions:[],c=new Map;for(const m of i){const d=ji(m==null?void 0:m.sessionId,m==null?void 0:m.session_id,m==null?void 0:m.id,m==null?void 0:m.providerSessionId,m==null?void 0:m.provider_session_id),h=d[0]||"";if(!h)continue;const f=d.map(y=>r.get(y)).find(Boolean);f&&(n=!0),c.set(h,f?{...m,sessionId:h,providerType:f.providerType||m.providerType,state:f.state||m.state,chatStatus:f.chatStatus||m.chatStatus,lifecycle:f.lifecycle||m.lifecycle,surfaceKind:f.surfaceKind||m.surfaceKind,recoveryState:f.recoveryState||m.recoveryState,role:f.role||m.role,isSelfCoordinator:f.isSelfCoordinator??m.isSelfCoordinator,workspace:f.workspace||m.workspace}:{...m,sessionId:h})}for(const m of o.activeSessions??[])c.has(m)||c.set(m,{sessionId:m,workspace:o.workspace,isCached:!0});for(const m of t)Zn(m).some(h=>c.has(h))||m.nodeId===o.nodeId&&(n=!0,c.set(m.sessionId,{sessionId:m.sessionId,providerType:m.providerType,state:m.state,chatStatus:m.chatStatus,lifecycle:m.lifecycle,surfaceKind:m.surfaceKind,recoveryState:m.recoveryState,role:m.role,isSelfCoordinator:m.isSelfCoordinator,workspace:m.workspace||o.workspace}));const u=[...c.values()];return u.length===0?o:{...o,activeSessionDetails:u,activeSessions:u.map(m=>m.sessionId)}});return n?{...e,nodes:a}:e}function hj(e,t){const n=lm(e,t).map(a=>{var u;const o=(Array.isArray((u=e.status)==null?void 0:u.sessions)?e.status.sessions:[]).find(m=>ht(m==null?void 0:m.id)===a.sessionId),i=Lo(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??"",ht(i.status)||ht(i.kind)||ht(i.type),a.nodeId??"",a.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(a=>!!a).sort();return n.length>0?n.join(`
73
+ `):null}function cm({status:e,daemonId:t,meshId:r,sendData:n,extraLiveSessions:a=[]}){const[o,i]=l.useState([]),c=l.useRef(null);l.useEffect(()=>{c.current=null,i([])},[t,r]),l.useEffect(()=>{if(!t||!r||!n)return;const m=zt.subscribe({sendData:n},t,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${t}`,params:{includeSessions:!0}},d=>{if(d.topic!=="daemon.metadata")return;const h=hj(d,r);h!==c.current&&(c.current=h,i(lm(d,r)))});return()=>{m()}},[t,r,n]);const u=l.useMemo(()=>uj(o,a),[a,o]);return l.useMemo(()=>e?mj(e,u):null,[u,e])}const xn=new Map;function pj(e,t){return!e||!t?null:`${e}::${t}`}function fj(e,t){var o,i,c,u;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((u=e.settings)==null?void 0:u.meshNodeId)=="string"?e.settings.meshNodeId:null;return{sessionId:e.sessionId,aliases:ji(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 xj({activeConv:e,sendDaemonCommand:t,onClose:r}){var T,L,B,O,$,E;const n=((T=e.coordinator)==null?void 0:T.meshId)??(typeof((L=e.settings)==null?void 0:L.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),a=e.daemonId??null,o=pj(a,n),i=o?xn.get(o)??null:null,c=pu(),{sendData:u}=ot(),{theme:m}=qs(),d=l.useMemo(()=>Ys(m),[m]),h=l.useMemo(()=>fj(e,n),[e.agentType,(B=e.coordinator)==null?void 0:B.meshId,e.sessionId,(O=e.settings)==null?void 0:O.meshCoordinatorFor,($=e.settings)==null?void 0:$.meshNodeFor,(E=e.settings)==null?void 0:E.meshNodeId,e.status,e.workspacePath,n]),[f,y]=l.useState(i),[b,x]=l.useState(!1),[j,k]=l.useState(!1),[p,w]=l.useState(null),[S,v]=l.useState((i==null?void 0:i.refreshedAt)??null),g=l.useRef(i!==null),C=l.useRef(!1),I=l.useRef(!1),N=l.useRef(!0);l.useEffect(()=>{g.current=f!==null},[f]),l.useEffect(()=>{const W=o?xn.get(o)??null:null;y(W),v((W==null?void 0:W.refreshedAt)??null),g.current=W!==null,I.current=!1,k(!1),w(null)},[o]);const _=l.useCallback(async(W=!1)=>{if(!a||!n){w("This coordinator does not expose a live mesh id."),y(null);return}if(C.current){W&&(I.current=!0);return}if(!W&&o){const Q=xn.get(o);if(Q){y(Q),v(Q.refreshedAt||null),g.current=!0,x(!1),w(null);return}}C.current=!0;const J=!g.current;x(J),k(W&&g.current),w(null);try{const Q=c!=null&&c.loadMeshStatus?await c.loadMeshStatus(a,n,{refresh:W,retryProfile:W?"settled":"interactive"}):await t(a,"mesh_status",{meshId:n,refresh:W}),ee=tm(Q);if(!ee){w("mesh_status returned an unexpected payload.");return}o&&xn.set(o,ee),y(ee),g.current=!0,v(ee.refreshedAt||new Date().toISOString())}catch(Q){w(Q instanceof Error?Q.message:"Failed to load live mesh status")}finally{C.current=!1,x(!1),k(!1),I.current&&N.current&&(I.current=!1,window.setTimeout(()=>{N.current&&_(!0)},0))}},[o,a,n,c,t]);l.useEffect(()=>(N.current=!0,_(!1),()=>{N.current=!1}),[_]),l.useEffect(()=>{const W=J=>{J.key==="Escape"&&r()};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[r]);const D=(f==null?void 0:f.meshName)||n||"Repo Mesh",A=l.useMemo(()=>h?[h]:[],[h]),M=cm({status:f,daemonId:a,meshId:n,sendData:u,extraLiveSessions:A}),R=S?new Date(S).toLocaleTimeString():null,z=l.useMemo(()=>b?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[b]);return s.jsx("div",{className:d.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:d.dialogShellClass,onClick:W=>W.stopPropagation(),children:[s.jsxs("div",{className:d.dialogHeaderClass,children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-400/20 bg-sky-500/12 text-sky-200 shadow-[0_12px_30px_rgba(14,165,233,0.18)]",children:s.jsx(ss,{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:d.dialogTitleClass,children:D}),s.jsx("span",{className:d.dialogKickerClass,children:"Mesh observability"})]}),s.jsxs("p",{className:d.dialogSubtitleClass,children:[at(e),e.workspaceName?` · ${e.workspaceName}`:"",f!=null&&f.repoIdentity?` · ${f.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[R&&s.jsx("span",{className:d.dialogRefreshedChipClass,children:j?"Refreshing mesh...":`Refreshed ${R}`}),!j&&f&&s.jsx("span",{className:d.dialogRefreshedChipClass,children:u&&!p?"Live daemon metadata":"Metadata subscription unavailable"}),s.jsx("button",{type:"button",onClick:()=>{_(!0)},disabled:b||j,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:b||j?"Refreshing...":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:d.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:s.jsx(gt,{size:16})})]})]}),p&&s.jsx("div",{className:d.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:p}),s.jsx("div",{className:d.dialogBodyClass,children:M?s.jsx(im,{status:M,emptyMessage:z,daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:d.dialogEmptyClass,children:z})})]})})}function bj(e,t){const{sendCommand:r}=ot(),[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(u=>{const m=(u==null?void 0:u.result)??u;a(typeof(m==null?void 0:m.remoteUrl)=="string"?m.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>i(!1))},[e,t,r]);const c=gj(n);return{remoteUrl:n,githubUrl:c,loading:o}}function gj(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 dm=5e3;function yj(e){return`git:${e}`}function vj({workspace:e,includeDiffSummary:t=!1,intervalMs:r=dm}){return{type:"subscribe",topic:"workspace.git",key:yj(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function ki(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 wj(e){const t=ki(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 jj(e){const t=ki(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 Ya(e){return e===void 0||typeof e=="boolean"}function kj(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Ya(t.binary)&&Ya(t.truncated)&&Ya(t.staged)}function Sj(e){const t=ki(e);return(t==null?void 0:t.success)===!1?{diff:null,error:js(t,"Git file diff request failed")}:kj(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 Nj({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=dm}){const{sendCommand:o,sendData:i}=ot(),c=typeof t=="string"?t.trim():"",u=!!(r&&e&&c),[m,d]=l.useState(null),[h,f]=l.useState(null),[y,b]=l.useState(!1),[x,j]=l.useState(null),k=l.useCallback(async()=>{if(!(!u||!e||!c)){b(!0),j(null);try{const w=wj(await o(e,"git_status",{workspace:c}));if(w.error){d(null),f(null),j(w.error);return}if(d(w.status),!n){f(null);return}const S=jj(await o(e,"git_diff_summary",{workspace:c}));if(S.error){f(null),j(S.error);return}f(S.diffSummary)}catch(w){j(js(w,"Git status request failed"))}finally{b(!1)}}},[u,e,n,o,c]),p=l.useMemo(()=>c?vj({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return l.useEffect(()=>{if(!u||!e||!c||!p){d(null),f(null),b(!1),j(null);return}const w=i?zt.subscribe({sendData:i},e,p,S=>{var v,g;S.workspace===c&&(d(S.status),f(S.diffSummary??null),j(((v=S.status)==null?void 0:v.error)||((g=S.diffSummary)==null?void 0:g.error)||null),b(!1))},{retryIntervalMs:1e3}):null;return k(),()=>{w==null||w()}},[u,e,k,p,i,c]),{status:m,diffSummary:h,loading:y,error:x,refresh:k}}const Cj={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},Ij={added:"text-emerald-400",modified:"text-orange-400",deleted:"text-red-400",renamed:"text-sky-400",copied:"text-sky-400",untracked:"text-zinc-400",conflict:"text-red-400 font-bold"};function cc(e){return e.split("/").pop()??e}function Mj(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function Aj({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=Cj[o.status]??"?",u=Ij[o.status]??"text-zinc-400",m=Mj(o.path),d=cc(o.path),h=o.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${i?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(o),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${u}`,title:o.status,children:c}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&s.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),s.jsx("span",{className:"text-text-primary",children:d}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",cc(o.oldPath)]}),h]}),!o.binary&&(o.insertions>0||o.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",o.insertions]}),o.insertions>0&&o.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),o.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",o.deletions]})]}),o.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${o.path}-${o.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function Tj(e,t){let r="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?r="bg-emerald-500/10 text-emerald-300":e.startsWith("-")&&!e.startsWith("---")?r="bg-red-500/10 text-red-300":e.startsWith("@@")?r="text-sky-400":(e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ "))&&(r="text-text-secondary"),s.jsx("div",{className:`px-3 ${r}`,children:s.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},t)}function _j({diff:e,binary:t,truncated:r,loading:n,error:a,className:o=""}){const i=l.useRef(null);if(l.useEffect(()=>{i.current&&(i.current.scrollTop=0)},[e]),n)return s.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${o}`,children:"Loading diff…"});if(a)return s.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${o}`,children:a});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"No diff available."});const c=e.split(`
74
+ `);return s.jsxs("div",{ref:i,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((u,m)=>Tj(u,m))}),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 Lj(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(`
75
+ `)}function um({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=ot(),{status:a,diffSummary:o,loading:i,error:c,refresh:u}=Nj({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,d]=l.useState(null),[h,f]=l.useState(null),[y,b]=l.useState(""),[x,j]=l.useState(!1),[k,p]=l.useState(!1),[w,S]=l.useState(null),[v,g]=l.useState(null),{githubUrl:C}=bj(e,t),I=l.useCallback(async R=>{if(!((m==null?void 0:m.path)===R.path&&!m.loading)){d({path:R.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const z=await n(e,"git_diff_file",{workspace:t,path:R.path,staged:R.staged}),T=Sj(z);if(T.error||!T.diff){d({path:R.path,diff:"",binary:!1,truncated:!1,loading:!1,error:T.error??"Failed to load diff"});return}d({path:R.path,diff:T.diff.diff,binary:T.diff.binary??!1,truncated:T.diff.truncated??!1,loading:!1,error:null})}catch(z){const T=z instanceof Error?z.message:"Failed to load diff";d({path:R.path,diff:"",binary:!1,truncated:!1,loading:!1,error:T})}}},[e,n,m,t]),N=l.useCallback(R=>{b(""),j(!1),S(null),g(null),f(R)},[]),_=l.useCallback(()=>{f(null),S(null),p(!1)},[]),D=l.useCallback(async()=>{var R,z,T;if(h){p(!0),S(null);try{let L;h==="checkpoint"?L=await n(e,"git_checkpoint",{workspace:t,message:y,includeUntracked:x}):h==="stash"?L=await n(e,"git_stash_push",{workspace:t,message:y,includeUntracked:x}):h==="stash_pop"?L=await n(e,"git_stash_pop",{workspace:t}):h==="checkout_files"&&m&&(L=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const B=(L==null?void 0:L.result)??L;if((B==null?void 0:B.success)===!1||B!=null&&B.error){S((B==null?void 0:B.error)??"Action failed"),p(!1);return}h==="checkpoint"?g(`Checkpoint created: ${((z=(R=B==null?void 0:B.checkpoint)==null?void 0:R.commit)==null?void 0:z.slice(0,7))??"done"}`):h==="stash"?g(`Stashed as ${((T=B==null?void 0:B.stash)==null?void 0:T.stashRef)??"stash@{0}"}`):h==="stash_pop"?g("Stash restored"):(g("File reverted"),d(null)),f(null),await u()}catch(L){S(L instanceof Error?L.message:"Action failed")}finally{p(!1)}}},[h,n,e,t,y,x,m,u]),A=!!(a!=null&&a.hasConflicts),M=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:R=>{R.target===R.currentTarget&&r()},children:s.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),C&&s.jsx("a",{href:`${C}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-sky-400 underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:u,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(gt,{className:"h-4 w-4"})})]}),a&&s.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[a.headCommit&&s.jsxs("span",{title:a.headMessage??void 0,children:[s.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&s.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&s.jsxs("span",{className:"text-orange-400",children:["↑",a.ahead," ahead"]}),a.behind>0&&s.jsxs("span",{className:"text-orange-400",children:["↓",a.behind," behind"]}),a.staged>0&&s.jsxs("span",{className:"text-emerald-400",children:[a.staged," staged"]}),a.modified>0&&s.jsxs("span",{children:[a.modified," modified"]}),a.untracked>0&&s.jsxs("span",{children:[a.untracked," untracked"]}),a.deleted>0&&s.jsxs("span",{className:"text-red-400",children:[a.deleted," deleted"]}),a.stashCount>0&&s.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&s.jsx("span",{className:"font-bold text-red-400",children:"conflicts"}),M===0&&!a.error&&s.jsx("span",{className:"text-emerald-500",children:"clean"}),o&&o.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[o.files.length," file",o.files.length!==1?"s":"",o.totalInsertions>0&&s.jsxs("span",{className:"text-emerald-500",children:[" +",o.totalInsertions]}),o.totalDeletions>0&&s.jsxs("span",{className:"text-red-400",children:[" -",o.totalDeletions]})]})]}),c&&s.jsx("div",{className:"shrink-0 border-b border-border/50 bg-red-500/10 px-4 py-2 text-xs text-red-400",children:c}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[i&&!o&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),o&&s.jsx(Aj,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:I}),!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:m?s.jsx(_j,{diff:m.diff,binary:m.binary,truncated:m.truncated,loading:m.loading,error:m.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"})})]}),v&&s.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-emerald-500/10 px-4 py-2 text-xs text-emerald-400 flex items-center justify-between",children:[s.jsx("span",{children:v}),s.jsx("button",{onClick:()=>g(null),className:"ml-2 text-emerald-400 hover:text-text-primary",children:"×"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[s.jsx("button",{onClick:()=>N("checkpoint"),disabled:A,title:A?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),s.jsx("button",{onClick:()=>N("stash"),disabled:A,title:A?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),s.jsx("button",{onClick:()=>N("stash_pop"),disabled:A||!(a!=null&&a.stashCount),title:A?"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:()=>N("checkout_files"),disabled:!m,title:m?`Revert changes to ${m.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 R=Lj((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(R),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"})]}),h&&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:[h==="checkpoint"&&"Create checkpoint commit",h==="stash"&&"Stash changes",h==="stash_pop"&&"Restore latest stash?",h==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(h==="checkpoint"||h==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:y,onChange:R=>b(R.target.value),maxLength:200,placeholder:"Message (required)",className:"rounded border border-border bg-surface-alt px-2 py-1 text-xs text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-border",autoFocus:!0}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:x,onChange:R=>j(R.target.checked)}),"Include untracked files"]})]}),w&&s.jsx("p",{className:"text-xs text-red-400",children:w}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:_,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:D,disabled:k||(h==="checkpoint"||h==="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 Rj({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=l.useState(!1),[o,i]=l.useState(!1),[c,u]=l.useState(!1),[m,d]=l.useState(!1),[h,f]=l.useState(!1),[y,b]=l.useState("quickstart"),[x,j]=l.useState("workspace"),k=l.useMemo(()=>!t&&!e,[t,e]),p=l.useCallback(I=>{a(I),I&&i(!1)},[]),w=l.useCallback(I=>{i(I),I&&a(!1)},[]),S=l.useCallback(()=>{b(r===0?"quickstart":"shortcuts"),j("workspace"),u(!0),a(!1),i(!1)},[r]),v=l.useCallback(()=>{u(!1)},[]),g=l.useCallback(()=>{d(!0)},[]),C=l.useCallback(()=>{d(!1)},[]);return l.useEffect(()=>{if(!k){f(!1);return}f(!0);const I=window.setTimeout(()=>{f(!1)},1e4);return()=>window.clearTimeout(I)},[k]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:m,guideNudgeVisible:h,guideTab:y,shortcutSection:x,isDesktopDashboard:k,setGuideTab:b,setShortcutSection:j,handleInboxOpenChange:p,handleHiddenOpenChange:w,handleOpenShortcutHelp:S,closeShortcutHelp:v,openNewSession:g,closeNewSession:C}}function Pj(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 Dj(e){return e instanceof Error?e.message:String(e||"")}function Ej(e){const t=Dj(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function $j({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:i,onStopCli:c,activeCliViewMode:u,onSetActiveCliViewMode:m,mobileChatConversations:d,hiddenConversations:h,ides:f,actionLogs:y,sendDaemonCommand:b,setActionLogs:x,setCliViewModeOverrides:j,isStandalone:k,initialDataLoaded:p,userName:w,requestedMobileTabKey:S,onRequestedMobileTabConsumed:v,requestedMachineId:g,onRequestedMachineConsumed:C,requestedMobileSection:I,onRequestedMobileSectionConsumed:N,containerRef:_,isSplitMode:D,numGroups:A,groupSizes:M,groupedConvs:R,clearedTabs:z,focusedGroup:T,focusGroup:L,moveTabToGroup:B,splitTabRelative:O,closeGroup:$,handleResizeStart:E,groupActiveTabIds:W,setGroupActiveTab:J,groupTabOrders:Q,setGroupTabOrder:ee,toggleHiddenTab:me,visibleConversations:je,requestedDesktopTabKey:Me,onRequestedDesktopTabConsumed:q,onDesktopActiveTabChange:G,onRequestScrollToBottom:he,onHideConversation:ue,onShowHiddenConversation:ce,onShowAllHiddenConversations:ve,scrollToBottomRequest:X,machineEntries:we,layoutProfile:de,onBrowseMachineDirectory:ye,onSaveMachineWorkspace:xe,onLaunchMachineIde:ge,onLaunchMachineProvider:le,onListMachineMeshes:be,onLaunchMeshCoordinator:ie,onListMachineSavedSessions:P,notifications:fe,notificationUnreadCount:Ce,liveSessionInboxState:_e,onMarkNotificationRead:se,onMarkNotificationUnread:De,onDeleteNotification:Te}){const Ee=bt.useRef(null),{inboxOpen:Oe,hiddenOpen:Je,shortcutHelpOpen:qe,newSessionOpen:Ze,guideNudgeVisible:et,guideTab:dt,shortcutSection:ut,isDesktopDashboard:xt,setGuideTab:Ae,setShortcutSection:He,handleInboxOpenChange:rt,handleHiddenOpenChange:Ye,handleOpenShortcutHelp:tt,closeShortcutHelp:K,openNewSession:U,closeNewSession:Y}=Rj({isMobile:t,showMobileChatMode:e,visibleConversationCount:je.length}),[re,H]=bt.useState(null),[V,te]=bt.useState(null),oe=bt.useCallback((ae,Pe)=>{H({daemonId:ae,workspace:Pe})},[]),Ne=bt.useCallback(ae=>{te(ae)},[]),Le=bt.useCallback(ae=>{var Pe;Nr.flushSync(()=>{ce(ae)}),(Pe=Ee.current)==null||Pe.restoreHiddenTabToSavedLocation(ae.tabKey)},[ce]),F=bt.useCallback(ae=>{var Nt;const Pe=d.find(Ct=>yo(Ct,ae))||h.find(Ct=>yo(Ct,ae));Pe&&(h.some(Ct=>Ct.tabKey===Pe.tabKey)&&Le(Pe),G(Pe.tabKey),(Nt=Ee.current)==null||Nt.activateConversationTab(Pe.tabKey),he(Pe.tabKey,"notification-open")),se(ae.id),rt(!1)},[Le,h,d,G,se,he]),ne=bt.useCallback(()=>{var Pe;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Pe=Ee.current)==null||Pe.resetAllPanelsToMain(),Ye(!1))},[Ye]),pe=bt.useCallback(async ae=>{var os;if(!r)return;const Pe=(os=r.modalButtons)==null?void 0:os[ae];if(!Pe)return;const Nt=ps(r);if(!Nt)return;const Ct=Pe.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Ns=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Ct);try{await b(Nt,"resolve_action",{button:Pe,action:Ns?"approve":"reject",buttonIndex:ae,...hs(r)})}catch(is){Ej(is)||console.error("[Shortcut approval] Failed:",is)}},[r,b]),{isMac:Se,actionDefinitions:Ie,actionShortcuts:We,shortcutListening:ze,shortcutListeningDraft:Be,setShortcutListening:mt,setShortcutListeningDraft:lt,saveShortcuts:pt}=U0({enabled:xt&&!qe,onTrigger:ae=>{var Pe,Nt,Ct,Ns,os,is,Fr,Hr,Wr,Kr,Ur,zr,Gr,Vr,qr,Yr;if(ae==="openShortcutHelp"){tt();return}if(ae==="openNewSession"){U();return}if(ae==="hideCurrentTab"){r&&ue(r);return}if(ae==="toggleHiddenTabs"){Ye(!Je);return}if(ae==="openHistoryForActiveTab"){r&&!Ge(r)&&o(r);return}if(ae==="openRemoteForActiveTab"){r&&!Xe(r)&&!Ge(r)&&i(r);return}if(ae==="splitActiveTabRight"){(Pe=Ee.current)==null||Pe.splitActiveTabRight();return}if(ae==="splitActiveTabDown"){(Nt=Ee.current)==null||Nt.splitActiveTabDown();return}if(ae==="floatActiveTab"){(Ct=Ee.current)==null||Ct.floatActiveTab();return}if(ae==="popoutActiveTab"){(Ns=Ee.current)==null||Ns.popoutActiveTab();return}if(ae==="dockActiveTab"){(os=Ee.current)==null||os.dockActiveTab();return}if(ae==="focusLeftPane"){(is=Ee.current)==null||is.focusLeftPane();return}if(ae==="focusRightPane"){(Fr=Ee.current)==null||Fr.focusRightPane();return}if(ae==="focusUpPane"){(Hr=Ee.current)==null||Hr.focusUpPane();return}if(ae==="focusDownPane"){(Wr=Ee.current)==null||Wr.focusDownPane();return}if(ae==="moveActiveTabToLeftPane"){(Kr=Ee.current)==null||Kr.moveActiveTabToLeftPane();return}if(ae==="moveActiveTabToRightPane"){(Ur=Ee.current)==null||Ur.moveActiveTabToRightPane();return}if(ae==="moveActiveTabToUpPane"){(zr=Ee.current)==null||zr.moveActiveTabToUpPane();return}if(ae==="moveActiveTabToDownPane"){(Gr=Ee.current)==null||Gr.moveActiveTabToDownPane();return}if(ae==="triggerPrimaryApprovalAction"){pe(0);return}if(ae==="triggerSecondaryApprovalAction"){pe(1);return}if(ae==="triggerTertiaryApprovalAction"){pe(2);return}if(ae==="setActiveTabShortcut"){(Vr=Ee.current)==null||Vr.setShortcutForActiveTab();return}if(ae==="selectPreviousGroupTab"){(qr=Ee.current)==null||qr.activatePreviousTabInGroup();return}if(ae==="selectNextGroupTab"){(Yr=Ee.current)==null||Yr.activateNextTabInGroup();return}!r||!Xe(r)||Ge(r)||ae==="toggleCliView"&&m(u==="chat"?"terminal":"chat")}}),Fe=bt.useCallback(()=>{K(),mt(null),lt([])},[K,mt,lt]),Qt=bt.useMemo(()=>ut==="all"?Ie:Ie.filter(ae=>Pj(ae)===ut),[Ie,ut]),Z=bt.useCallback(()=>{const ae=Object.fromEntries(Ie.map(Pe=>[Pe.id,""]));pt(ae)},[Ie,pt]),Re=bt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const ae=Object.fromEntries(Ie.map(Pe=>[Pe.id,Pe.defaultShortcut]));pt(ae)},[Ie,pt]);return bt.useEffect(()=>{const ae=Pe=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Pe.metaKey&&Pe.key.toLowerCase()==="w":Pe.ctrlKey&&Pe.key.toLowerCase()==="w")&&(Pe.preventDefault(),r&&ue&&ue(r))};return window.addEventListener("keydown",ae),()=>window.removeEventListener("keydown",ae)},[r,ue]),bt.useEffect(()=>{if(!qe||ze)return;const ae=Pe=>{Pe.key==="Escape"&&(Pe.preventDefault(),Fe())};return window.addEventListener("keydown",ae,!0),()=>window.removeEventListener("keydown",ae,!0)},[Fe,qe,ze]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(Ab,{activeConv:r,wsStatus:n,isConnected:a,conversations:je,hiddenConversations:h,onOpenHistory:o,onHideConversation:ue,onShowConversation:Le,onShowAllHidden:ve,onResetPanelsToMain:ne,notifications:fe,notificationUnreadCount:Ce,onOpenNotification:F,onMarkNotificationRead:se,onMarkNotificationUnread:De,onDeleteNotification:Te,inboxOpen:Oe,onInboxOpenChange:rt,hiddenOpen:Je,onHiddenOpenChange:Ye,onOpenNewSession:t?void 0:U,onOpenDashboardGuide:tt,guideNudgeVisible:et,actionShortcuts:We,onOpenRemote:()=>{!r||Xe(r)||Ge(r)||i(r)},onStopCli:c,activeCliViewMode:u,onSetCliViewMode:m,onOpenGitDialog:oe,onOpenMeshGraph:Ne}),e?s.jsx(L0,{conversations:d,hiddenConversations:h,ides:f,actionLogs:y,sendDaemonCommand:b,setActionLogs:x,setCliViewModeOverrides:j,isStandalone:k,userName:w,requestedActiveTabKey:S,onRequestedActiveTabConsumed:v,requestedMachineId:g,onRequestedMachineConsumed:C,requestedMobileSection:I,onRequestedMobileSectionConsumed:N,onOpenHistory:o,onOpenRemote:i,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:ve,onHideConversation:ue,onOpenMeshGraph:Ne,onOpenNewSession:U,liveSessionInboxState:_e}):t?s.jsx(F0,{containerRef:_,isSplitMode:D,numGroups:A,groupSizes:M,groupedConvs:R,clearedTabs:z,ides:f,actionLogs:y,sendDaemonCommand:b,setActionLogs:x,isStandalone:k,hasRegisteredMachines:we.length>0,userName:w,focusedGroup:T,focusGroup:L,moveTabToGroup:B,splitTabRelative:O,closeGroup:$,handleResizeStart:E,groupActiveTabIds:W,setGroupActiveTab:J,groupTabOrders:Q,setGroupTabOrder:ee,toggleHiddenTab:me,onOpenNewSession:U,allowTabShortcuts:!1,liveSessionInboxState:_e}):s.jsx(nv,{visibleConversations:je,clearedTabs:z,ides:f,actionLogs:y,sendDaemonCommand:b,setActionLogs:x,isStandalone:k,hasRegisteredMachines:we.length>0,initialDataLoaded:p,userName:w,toggleHiddenTab:me,actionShortcuts:We,registerActionHandlers:ae=>{Ee.current=ae},onActiveTabChange:G,requestedActiveTabKey:Me,onRequestedActiveTabConsumed:q,onRequestScrollToBottom:he,scrollToBottomRequest:X,onOpenNewSession:U,liveSessionInboxState:_e,layoutProfile:de}),Ze&&s.jsx(pv,{machines:we,ides:f,onClose:Y,onBrowseDirectory:ye,onSaveWorkspace:xe,onLaunchIde:ge,onLaunchProvider:le,onListMeshes:be,onLaunchMeshCoordinator:ie,onListSavedSessions:P}),V&&s.jsx(xj,{activeConv:V,sendDaemonCommand:b,onClose:()=>te(null)}),re&&s.jsx(um,{daemonId:re.daemonId,workspace:re.workspace,onClose:()=>H(null)}),qe&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:Fe,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:ae=>ae.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:Fe,"aria-label":"Close dashboard guide",children:s.jsx(gt,{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(ae=>s.jsx("button",{type:"button",className:`btn btn-sm ${dt===ae.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ae(ae.id),children:ae.label},ae.id))}),dt==="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 ",Se?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),dt==="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."]})]})]})]}),dt==="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(ae=>s.jsx("button",{type:"button",className:`btn btn-sm ${ut===ae.id?"btn-primary":"btn-secondary"}`,onClick:()=>He(ae.id),children:ae.label},ae.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Z,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:Re,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Qt.map(ae=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${ze===ae.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:ae.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ae.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:ae.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:ze===ae.id?Be.length>0?`${Be.join(" ")} ...`:"Listening...":We[ae.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{mt(ae.id),lt([])},children:ze===ae.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Pe={...We};Pe[ae.id]="",pt(Pe)},children:"Disable"})]})]})},ae.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Se?"⌘⇧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 Xa=[{icon:"🦦",title:"Welcome to ADHDev",desc:"Monitor and control your AI coding agents from anywhere — web, mobile, or CLI.",visual:"🎉"},{icon:"💬",title:"Real-time chat",desc:"See what your AI agent is doing in real-time. Send messages, approve or reject actions — all from your browser or phone.",visual:"📱"},{icon:"🖥️",title:"Remote desktop",desc:"View and control your IDE screen via P2P connection. Click, type, scroll — just like being there.",visual:"🖱️"},{icon:"🚀",title:"Get started",desc:"Install the daemon and link it to your dashboard. It connects automatically.",code:"npm install -g @adhdev/daemon-standalone && adhdev-standalone"}];function Bj({onClose:e}){const[t,r]=l.useState(0),n=Xa[t],a=t===Xa.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:o=>{o.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(gt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Xa.map((o,i)=>s.jsx("div",{style:{width:i===t?24:8,height:8,borderRadius:4,background:i===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},i))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx("span",{children:n.icon})," ",n.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&s.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>a?e():r(o=>o+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
76
+ @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
77
+ @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
78
+ `})]})}function Oj({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",u=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)":u?"var(--accent-primary)":"var(--text-muted)",boxShadow:u?"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 Fj({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,i]=l.useState(()=>a||"native"),c=l.useMemo(()=>Fd(t),[t]),u=l.useMemo(()=>e?ri(e,{machineNames:c,connectionStates:r,defaultConnectionState:"new"}):[],[e,c,r]),m=l.useMemo(()=>u.find(x=>x.streamSource==="native"),[u]),d=l.useMemo(()=>u.filter(x=>x.streamSource==="agent-stream"),[u]),h=l.useMemo(()=>e?Bt(u,e.id):null,[u,e]);l.useEffect(()=>{a&&i(a)},[a]),l.useEffect(()=>{if(a||!h)return;const x=h.streamSource==="native"?"native":h.tabKey;!x||o===x||o==="native"&&i(x)},[o,h,a]),l.useEffect(()=>{var x;o!=="native"&&(d.some(j=>j.tabKey===o)||i(((x=d[0])==null?void 0:x.tabKey)||"native"))},[o,d]),l.useEffect(()=>{o==="native"&&(m||d[0]&&i(d[0].tabKey))},[o,m,d]);const f=l.useMemo(()=>o==="native"&&m?m:d.find(x=>x.tabKey===o)||h||m||d[0],[o,m,h,d]),y=l.useMemo(()=>d.map(x=>({tabKey:x.tabKey,title:_d(x)||n,status:x.status})),[d,n]),b=l.useCallback(x=>{if(x)return u.find(j=>yo(j,{sessionId:x,routeId:x,tabKey:x,providerSessionId:x}))},[u]);return{activeChatTab:o,setActiveChatTab:i,activeConv:f,conversations:u,extensionTabs:y,hasExtensions:y.length>0,resolveConversationByTarget:b}}function Hj({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:i,isStandalone:c,userName:u,onOpenHistory:m,onConversationChange:d,onClose:h}){const[f,y]=l.useState("split"),[b,x]=l.useState(()=>as(e)?"native":e.tabKey),j=l.useRef(null),k=l.useMemo(()=>t||r.find(L=>L.id===e.routeId),[e.routeId,t,r]),p=l.useMemo(()=>yt((k==null?void 0:k.type)||""),[k==null?void 0:k.type]),{conversations:w,extensionTabs:S,hasExtensions:v}=Fj({ideData:k,allIdes:r,connectionStates:n,ideName:p||"IDE",preferredTabKey:as(e)?void 0:e.tabKey}),g=l.useMemo(()=>k?Bt(w,k.id):null,[k,w]);l.useEffect(()=>{const L=j.current,B={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(j.current=B,!(L&&L.routeId===B.routeId&&L.tabKey===B.tabKey&&L.streamSource===B.streamSource)){if(as(e)){x("native");return}x(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),l.useEffect(()=>{if(b==="native"){if(w.some(L=>L.streamSource==="native"))return;(g==null?void 0:g.streamSource)==="agent-stream"&&x(g.tabKey);return}if(!w.some(L=>L.tabKey===b)){if((g==null?void 0:g.streamSource)==="agent-stream"){x(g.tabKey);return}x("native")}},[w,b,g]);const C=l.useMemo(()=>b==="native"?w.find(L=>L.streamSource==="native")||e:w.find(L=>L.tabKey===b)||e,[e,w,b]),I=Qd(C),N=l.useMemo(()=>I.status||I.modalMessage||I.modalButtons?{...C,...I.status?{status:I.status}:{},...I.modalMessage!==void 0?{modalMessage:I.modalMessage}:{},...I.modalButtons!==void 0?{modalButtons:I.modalButtons}:{}}:C,[C,I]),_=Pr(N),D=ia({sendDaemonCommand:o,activeConv:N,setActionLogs:i,isStandalone:c}),{connScreenshot:A,screenshotUsage:M,handleRemoteAction:R}=Mu({doId:_,targetSessionId:pd(N),connState:N.connectionState||"new",viewMode:f}),z=l.useMemo(()=>a.filter(L=>L.routeId===N.tabKey),[a,N.tabKey]);l.useEffect(()=>{d==null||d(N)},[N,d]),l.useEffect(()=>{const L=B=>{B.key==="Escape"&&h()};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[h]);const T=l.useCallback(L=>{L.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:h,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:T,children:[s.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[s.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Ot,{size:16})}),s.jsx("span",{className:"truncate",children:Xo(C)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,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(L=>{const B=f===L;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${B?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>y(L),title:L==="split"?"Split view":"Remote only",children:L==="split"?s.jsx(Uh,{size:15}):s.jsx(Ot,{size:15})},L)})}),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:()=>m(C),title:"Chat History",children:[s.jsx(Fo,{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:h,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${f==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[f!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(Oj,{hasExtensions:v,ideName:p||"IDE",activeChatTab:b,extensionTabs:S,onSelectTab:x}),s.jsx(Zc,{activeConv:N,onModalButton:D.handleModalButton}),s.jsx(ko,{activeConv:N,ideEntry:k,showMetaChips:!1,handleSendChat:D.handleSendChat,handleForceSendChat:D.handleForceSendChat,isSendingChat:D.isSendingChat,sendFeedbackMessage:D.sendFeedbackMessage,handleFocusAgent:D.handleFocusAgent,isFocusingAgent:D.isFocusingAgent,actionLogs:z,userName:u})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${f==="split"?"order-1 md:order-2":""}`,children:s.jsx(Xc,{addLog:()=>{},connState:N.connectionState||"new",connScreenshot:A,screenshotUsage:M,transportType:N.transport,onAction:R})})]})]})})}function Wj({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=gb(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[s.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",o,"?"]}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:t?"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.":"This provider does not support graceful stop. Force Stop will end the runtime immediately."})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&s.jsx("button",{onClick:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),s.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:"Force Stop"}),s.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function Kj({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o,interactivePrompt:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(kb,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(Bd,{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(Hj,{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&&(Xe(r.targetConv)||Ge(r.targetConv))&&s.jsx(Wj,{activeConv:r.targetConv,canSaveAndStop:Xe(r.targetConv)&&!Ge(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(Od,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),s.jsx(Wp,{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(Bj,{onClose:o.onClose})]})}function Uj({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(ra,{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=Mt(i,{fallbackId:i.id}),u=n[i.id],m=i.version||i.daemonVersion||"unknown",d=i.versionUpdateRequired===!0,f=uu(i)==="preview"?"Update to preview":d?"Update now":"Upgrade";return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:c}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),d&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),u==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:d?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):u==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):u==="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:d?"var(--status-danger)":"var(--status-warning)",background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(i.id),children:f})]},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(gt,{size:16})})]})}function zj(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function Gj(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 Vj(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>Gj(t)).map(t=>t.id)}}function qj(){var Ti,_i,Li,Ri;const{sendCommand:e}=ot(),t=Dr(),r=Jd(),n=$o(),a=_r(),[o,i]=ih(),c=o.get("activeTab"),u=((Ti=n.state)==null?void 0:Ti.openRemoteForTabKey)||null,m=((_i=n.state)==null?void 0:_i.openMachineId)||null,d=((Li=n.state)==null?void 0:Li.mobileSection)||null,h=Id(),f=h.ides||[],y=h.initialLoaded??!0,{updateRouteChats:b,setToasts:x}=h,[j,k]=l.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),p=h.toasts||[],w=h.wsStatus||"connected",S=h.isConnected??!0,v=h.connectionStates||{},g=h.showReconnected||!1,{layoutProfile:C,groupAssignments:I,updateGroupAssignments:N,focusedGroup:_,updateFocusedGroup:D,focusGroup:A,groupActiveTabIds:M,updateGroupActiveTabIds:R,setGroupActiveTab:z,groupTabOrders:T,updateGroupTabOrders:L,setGroupTabOrder:B,groupSizes:O,updateGroupSizes:$,isMobile:E,hasHydratedStoredLayout:W,hydrateStoredLayout:J,focusConversationTab:Q}=Cy(),[ee,me]=l.useState(()=>ii());l.useEffect(()=>Tg(me),[]);const je=l.useMemo(()=>zj({isMobile:E,mobileViewMode:ee}),[E,ee]),[Me,q]=l.useState([]),[G,he]=l.useState({}),[ue,ce]=l.useState({});Rr("Dashboard",{ideCount:f.length,toastCount:p.length,focusedGroup:_,groupCount:Object.keys(I).length,actionLogCount:Me.length});const ve=l.useMemo(()=>f.filter(Ke=>Ke.type==="adhdev-daemon").sort(Vo),[f]),X=ve[0],we=!!X;l.useEffect(()=>{const{metadataDaemonIds:Ke,runtimeDaemonIds:Rt}=Vj(ve);for(const Xs of Ke)t(Xs,{minFreshMs:3e4}).catch(()=>{});for(const Xs of Rt)r(Xs,{minFreshMs:3e4}).catch(()=>{})},[t,r,ve]);const de=(X==null?void 0:X.terminalBackend)||null,ye=X?Mt(X,{fallbackId:X.id}):null,xe=(X==null?void 0:X.id)||null,ge=l.useMemo(()=>Qg(f,G),[f,G]),{hiddenTabs:le,autoHiddenTabs:be,autoHideTarget:ie,hideTarget:P,toggleTarget:fe,showTarget:Ce,showAllTabs:_e}=Wg(),{conversations:se,visibleConversations:De,visibleTabKeys:Te,resolveConversationBySessionId:Ee,resolveConversationByTarget:Oe}=uy({ides:ge,connectionStates:v,clearedTabs:ue,hiddenTabs:le}),Je=l.useMemo(()=>new Map(se.map(Ke=>[Ke.tabKey,Ke])),[se]),qe=l.useMemo(()=>Hg(se,le,be),[se,le,be]);l.useEffect(()=>{for(const Ke of qe)ie(Ke)},[qe,ie]),Ux(De,je),l.useEffect(()=>{Object.keys(G).length!==0&&he(Ke=>Zg(Ke,f))},[f,G]);const Ze=l.useMemo(()=>Up(f),[f]),{notifications:et,unreadCount:dt}=Wy({conversations:se,liveSessionInboxState:Ze}),{handleMarkDashboardNotificationRead:ut,handleMarkDashboardNotificationUnread:xt,handleDeleteDashboardNotification:Ae}=Ky({notifications:et,sendDaemonCommand:e}),{containerRef:He,normalizedGroupAssignments:rt,numGroups:Ye,isSplitMode:tt,groupedConvs:K,moveTabToGroup:U,closeGroup:Y,handleResizeStart:re,splitTabRelative:H}=Ry({groupAssignments:I,updateGroupAssignments:N,updateFocusedGroup:D,updateGroupActiveTabIds:R,updateGroupTabOrders:L,groupSizes:O,updateGroupSizes:$,isMobile:E,visibleConversations:De,visibleTabKeys:Te}),{activeConv:V,openDesktopConversation:te,requestScrollToBottom:oe,scrollToBottomRequest:Ne,setDesktopActiveTab:Le}=r0({isMobile:E,conversations:se,visibleConversations:De,groupActiveTabIds:M,focusedGroup:_,groupedConvs:K,setSearchParams:i});o0({activeConv:V,isMobile:E,liveSessionInboxState:Ze,sendDaemonCommand:e});const{requestedDesktopTabKey:F,requestedMobileTabKey:ne,consumeRequestedActiveTab:pe}=my({isMobile:E,urlActiveTab:c,resolveConversationBySessionId:Ee,setSearchParams:i}),{remoteDialogConv:Se,remoteDialogIdeEntry:Ie,remoteDialogActiveConv:We,setRemoteDialogActiveConv:ze,openRemoteDialog:Be,closeRemoteDialog:mt,cliStopDialogOpen:lt,cliStopTargetConv:pt,requestCliStop:Fe,cancelCliStop:Qt,confirmCliStop:Z}=c0({isMobile:E,location:n,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:F,conversations:se,ides:f,resolveConversationByTarget:Oe,activeConv:V,sendDaemonCommand:e}),{historyModalOpen:Re,openHistoryModal:ae,closeHistoryModal:Pe,historyTargetConv:Nt,isSavedSessionHistoryTarget:Ct,isHistoryCreatingChat:Ns,isHistoryRefreshingHistory:os,handleHistorySwitchSession:is,handleHistoryNewChat:Fr,handleHistoryRefresh:Hr,savedHistorySessions:Wr,savedHistoryFilters:Kr,setSavedHistoryFilters:Ur,missingWorkspaceResumePath:zr,isSavedHistoryLoading:Gr,resumingSavedHistorySessionId:Vr,handleRefreshSavedHistory:qr,handleResumeSavedHistorySession:Yr}=i0({activeConv:V,remoteDialogConv:Se,remoteDialogActiveConv:We,ides:f,sendDaemonCommand:e,updateRouteChats:b,setToasts:x,setClearedTabs:ce,setSearchParams:i}),bm=l.useMemo(()=>De,[De]),Xr=E&&ee==="chat",gm=l.useMemo(()=>se.filter(Ke=>ca(le,Ke)),[se,le]),Ii=l.useCallback(Ke=>{const Rt=new URLSearchParams(o);Rt.set("activeTab",Ke),i(Rt,{replace:!0})},[o,i]),{trackPendingLaunch:ym}=Zy({ides:f,conversations:se,onOpenSession:Ii}),{handleBrowseMachineDirectory:vm,handleSaveMachineWorkspace:wm,handleLaunchMachineIde:jm,handleLaunchMachineProvider:km,handleListMachineMeshes:Sm,handleLaunchMeshCoordinator:Nm,handleListMachineSavedSessions:Cm,setActiveCliViewMode:Im}=e0({sendDaemonCommand:e,trackPendingLaunch:ym,onOpenSession:Ii,activeConv:V,ides:f,setCliViewModeOverrides:he});ey({visibleConversations:De,clearedTabs:ue,setClearedTabs:ce,setActionLogs:q}),hy({ides:f,sendDaemonCommand:e,setToasts:x,resolveConversationByTarget:Oe});const Mm=Yg(),{isRefreshingHistory:Am,handleRefreshHistory:Tm}=du({sendDaemonCommand:e,activeConv:V,chats:(Ri=f.find(Ke=>Ke.id===(V==null?void 0:V.routeId)))==null?void 0:Ri.chats,updateRouteChats:b,setToasts:x,setClearedTabs:ce});My({urlActiveTab:E&&!Xr?c:null,conversations:se,resolveConversationBySessionId:Ee,normalizedGroupAssignments:rt,hasHydratedStoredLayout:E&&!Xr?W:!0,hydrateStoredLayout:E&&!Xr?J:()=>{},focusConversationTab:Q,setSearchParams:i,historyModalOpen:Re,activeConv:V,isRefreshingHistory:Am,ides:f,handleRefreshHistory:Tm});const _m=l.useMemo(()=>!V||!Xe(V)||Ge(V)?null:Vs(V),[V]),{versionMismatchDaemons:Lm,hasRequiredVersionDaemons:Mi,targetVersion:Rm,versionBannerDismissed:Pm,setVersionBannerDismissed:Dm,upgradingDaemons:Em,handleBannerUpgrade:$m}=Dy({ides:f,sendDaemonCommand:e}),Ai=l.useCallback(Ke=>{Ce(Ke),te(Ke)},[te,Ce]),Bm=l.useCallback(Ke=>{P(Ke)},[P]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[s.jsx(Sb,{terminalBackend:de,isStandalone:we,machineLabel:ye,machineKey:xe}),(!Pm||Mi)&&s.jsx(Uj,{daemons:Lm,targetVersion:Rm,required:Mi,upgradingDaemons:Em,onUpgrade:$m,onDismiss:()=>Dm(!0)}),s.jsx($j,{showMobileChatMode:Xr,isMobile:E,activeConv:V,wsStatus:w,isConnected:S,onOpenHistory:Ke=>{Ke&&ze(Ke),ae()},onOpenRemote:Be,onStopCli:Fe,activeCliViewMode:_m,onSetActiveCliViewMode:Im,mobileChatConversations:bm,ides:f,actionLogs:Me,sendDaemonCommand:e,setActionLogs:q,setCliViewModeOverrides:he,isStandalone:we,initialDataLoaded:y,userName:h.userName,requestedMobileTabKey:ne,onRequestedMobileTabConsumed:pe,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:d,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:He,isSplitMode:tt,numGroups:Ye,groupSizes:O,groupedConvs:K,clearedTabs:ue,focusedGroup:_,focusGroup:A,moveTabToGroup:U,splitTabRelative:H,closeGroup:Y,handleResizeStart:re,groupActiveTabIds:M,setGroupActiveTab:z,groupTabOrders:T,setGroupTabOrder:B,toggleHiddenTab:Ke=>fe(Je.get(Ke)||{tabKey:Ke}),visibleConversations:De,hiddenConversations:gm,requestedDesktopTabKey:F,onRequestedDesktopTabConsumed:pe,onDesktopActiveTabChange:Le,onRequestScrollToBottom:oe,onHideConversation:Bm,onShowHiddenConversation:Ai,onShowAllHiddenConversations:_e,scrollToBottomRequest:Ne,machineEntries:ve,layoutProfile:C,onBrowseMachineDirectory:vm,onSaveMachineWorkspace:wm,onLaunchMachineIde:jm,onLaunchMachineProvider:km,onListMachineMeshes:Sm,onLaunchMeshCoordinator:Nm,onListMachineSavedSessions:Cm,notifications:et,notificationUnreadCount:dt,liveSessionInboxState:Ze,onMarkNotificationRead:ut,onMarkNotificationUnread:xt,onDeleteNotification:Ae}),s.jsx("style",{children:`
79
+ body { overflow: hidden; overscroll-behavior: none; }
80
+ `}),s.jsx(Kj,{historyModal:{open:Re,targetConv:Nt,ides:f,isCreatingChat:Ns,isRefreshingHistory:Ct?!1:os,savedSessions:Wr,savedHistoryFilters:Kr,missingWorkspaceResumePath:zr||null,onSavedHistoryFiltersChange:Ur,isSavedSessionsLoading:Gr,isResumingSavedSessionId:Vr,onClose:Pe,onNewChat:Fr,onSwitchSession:is,onRefreshHistory:Ct?qr:Hr,onResumeSavedSession:Yr},remoteDialog:{conversation:Se,ideEntry:Ie,ides:f,connectionStates:v,actionLogs:Me,sendDaemonCommand:e,setActionLogs:q,isStandalone:we,userName:h.userName,onOpenHistory:Ke=>{Ke&&ze(Ke),ae()},onConversationChange:ze,onClose:mt},cliStopDialog:{open:lt,targetConv:pt,onCancel:Qt,onStopNow:async()=>{await Z("hard")},onSaveAndStop:async()=>{await Z("save")}},connectionBanner:{wsStatus:w,showReconnected:g,loginUrl:h.connectionLoginUrl,onReconnect:h.retryServerConnection},toastOverlay:{toasts:p,onDismiss:Ke=>x(Rt=>Rt.filter(Xs=>Xs.id!==Ke)),onClick:Ke=>{if(Ke.targetKey){const Rt=Oe(Ke.targetKey);Rt&&(Q(Rt.tabKey,rt),Ai(Rt),oe(Rt.tabKey,"toast-open"))}}},onboarding:{open:j,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}k(!1)}},interactivePrompt:Mm})]})}function Yj({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const{launchCli:o}=ta(),[i,c]=l.useState([]),[u,m]=l.useState(null),[d,h]=l.useState(null),[f,y]=l.useState(!1),[b,x]=l.useState(null),[j,k]=l.useState(!1),[p,w]=l.useState(""),S=l.useRef(null),v=l.useCallback($=>{S.current=$},[]),g=l.useCallback(($,E,W=!1)=>{c(J=>[...J.slice(-100),{timestamp:Date.now(),level:$,message:E}]),setTimeout(()=>{var J;return(J=a.current)==null?void 0:J.scrollIntoView({behavior:"smooth"})},100),W&&Qe.showToast(E,$==="error"||$==="warn"?"warning":"success")},[a]),C=l.useCallback($=>{const E=$ instanceof Error?$.message:String($||"");return E.includes("P2P command timeout")||E.includes("P2P not connected")||E.includes("P2P not available")},[]),I=l.useCallback(async($,E)=>{var W;if(!e||u)return!1;m($),g("info",`Launching ${yt($)}${E!=null&&E.workspace?` in ${E.workspace}`:""}...`);try{const J={ideType:$,enableCdp:!0};(W=E==null?void 0:E.workspace)!=null&&W.trim()?J.workspace=E.workspace.trim():E!=null&&E.useDefaultWorkspace&&(J.useDefaultWorkspace=!0);const Q=await r(e,"launch_ide",J);return g(Q!=null&&Q.success?"info":"error",Q!=null&&Q.success?`${yt($)} launched`:`Failed: ${Q==null?void 0:Q.error}`,!0),!!(Q!=null&&Q.success)}catch(J){return g("error",`Launch error: ${J.message}`,!0),!1}finally{m(null)}},[e,u,g,r]),N=l.useCallback(async $=>{if(!e)return{success:!1};const{cliType:E,dir:W,workspaceId:J,useDefaultWorkspace:Q,useHome:ee,argsStr:me,model:je,resumeSessionId:Me}=$;if(!E)return g("warn","Select a CLI or ACP provider first",!0),{success:!1};const q=me?me.split(/\s+/).filter(Boolean):void 0,G=(W==null?void 0:W.trim())||(J?"(saved id)":Q?"(default workspace)":ee?"(home)":"");g("info",`Launching ${E}${G?` in ${G}`:""}${je?` (model: ${je})`:""}...`),h(E);try{const he={cliType:E,cliArgs:q,initialModel:je||void 0};W!=null&&W.trim()?he.dir=W.trim():J?he.workspaceId=J:Q?he.useDefaultWorkspace=!0:ee&&(he.useHome=!0),Me&&(he.resumeSessionId=Me);const ue=await o(e,he),ce=(ue==null?void 0:ue.result)||ue;return ue!=null&&ue.success?(g("info",`${E} launched`,!0),(ce==null?void 0:ce.launchSource)==="home"?g("info","📂 Running in home directory (explicit choice)"):(ce==null?void 0:ce.launchSource)==="defaultWorkspace"&&g("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ce==null?void 0:ce.sessionId}):(g("error",`Failed: ${(ue==null?void 0:ue.error)||(ce==null?void 0:ce.error)}`,!0),(ue==null?void 0:ue.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&x({cliType:E,argsStr:me,model:je}),{success:!1,sessionId:ce==null?void 0:ce.sessionId})}catch(he){return C(he)?(g("warn",`${E} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(g("error",`Launch error: ${he.message}`,!0),{success:!1})}finally{h(null)}},[e,g,C,r]),_=l.useCallback(async($,E,W,J)=>e?$?E.trim()?N({cliType:$,dir:E,argsStr:W,model:J}):(x({cliType:$,argsStr:W,model:J}),{success:!1}):(g("warn","Select a provider",!0),{success:!1}):{success:!1},[e,g,N]),D=l.useCallback(async($,E,W)=>{if(e&&window.confirm(`Stop ${$}?
81
+ This will terminate the process.`))try{const J=await r(e,"stop_cli",{cliType:$,dir:E,targetSessionId:W});J!=null&&J.success?g("info",`${$} stopped`,!0):g("error",`Stop failed: ${(J==null?void 0:J.error)||"Unknown error"}`,!0)}catch(J){g("error",`Stop failed: ${J.message}`,!0)}},[e,g,r]),A=l.useCallback(async $=>{try{await r($.daemonId,"restart_ide",{ideType:$.type}),g("info",`${yt($.type)} restart initiated`,!0)}catch(E){g("error",`Restart failed: ${E.message}`,!0)}},[g,r]),M=l.useCallback(async $=>{if(window.confirm(`Stop ${yt($.type)}?
82
+ This will disconnect CDP and optionally kill the process.`))try{const E=await r($.daemonId,"stop_ide",{ideType:$.type,killProcess:!0});E!=null&&E.success?g("info",`${yt($.type)} stopped`,!0):g("error",`Stop failed: ${(E==null?void 0:E.error)||"Unknown error"}`,!0)}catch(E){g("error",`Stop failed: ${E.message}`,!0)}},[g,r]),R=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]),z=l.useCallback(async $=>{if(!e||!$.trim())return!1;y(!0);try{const E=await r(e,"workspace_add",{path:$.trim()});return E!=null&&E.success?(g("info",`Workspace added: ${$.trim()}`),!0):(g("error",(E==null?void 0:E.error)||"workspace_add failed"),!1)}catch(E){return g("error",E.message),!1}finally{y(!1)}},[e,g,r]),T=l.useCallback(async $=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){y(!0);try{const E=await r(e,"workspace_remove",{id:$});E!=null&&E.success?g("info","Workspace removed",!0):g("error",(E==null?void 0:E.error)||"workspace_remove failed",!0)}catch(E){g("error",E.message,!0)}finally{y(!1)}}},[e,g,r]),L=l.useCallback(async $=>{var E;if(e){y(!0);try{const W=await r(e,"workspace_set_default",$===null?{clear:!0}:{id:$});if(W!=null&&W.success){g("info",$?"Default workspace updated":"Default workspace cleared",!0);const J=typeof W.defaultWorkspacePath=="string"?W.defaultWorkspacePath:"";J&&((E=S.current)==null||E.call(S,J))}else g("error",(W==null?void 0:W.error)||"workspace_set_default failed",!0)}catch(W){g("error",W.message,!0)}finally{y(!1)}}},[e,g,r]),B=l.useCallback(async $=>{var W;if(!e||!$.trim())return;const E=$.trim();y(!0);try{const J=await r(e,"workspace_set_default",{path:E});J!=null&&J.success?(g("info","Default workspace set from history"),(W=S.current)==null||W.call(S,E)):g("error",(J==null?void 0:J.error)||"Could not set default (path missing on disk?)")}catch(J){g("error",J.message)}finally{y(!1)}},[e,g,r]),O=l.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:p}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:p})}catch($){g("warn",`Live nickname updated, but account sync failed: ${$.message}`)}g("info",`Nickname set to "${p||"(cleared)"}"`),k(!1)}catch($){g("error",`Failed: ${$.message}`)}},[e,p,t,g,n,r]);return{logs:i,launchingIde:u,launchingAgentType:d,workspaceBusy:f,launchPick:b,setLaunchPick:x,editingNickname:j,setEditingNickname:k,nicknameInput:p,setNicknameInput:w,addLog:g,handleLaunchIde:I,runLaunchCliCore:N,handleLaunchCli:_,handleStopCli:D,handleRestartIde:A,handleStopIde:M,handleDetectIdes:R,handleWorkspaceAdd:z,handleWorkspaceRemove:T,handleWorkspaceSetDefault:L,handleWorkspaceResumePath:B,handleSaveNickname:O,setOnDefaultWorkspaceChanged:v}}function Xj({machine:e,ideSessions:t,cliSessions:r,acpSessions:n}){var u;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=((u=e.loadavg)==null?void 0:u[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(Zr,{icon:s.jsx(Bc,{size:16}),label:"Uptime",value:typeof e.uptime=="number"?Xp(e.uptime):"Waiting…"}),s.jsx(Zr,{icon:s.jsx(Ot,{size:16}),label:"IDEs",value:`${t.length}`}),s.jsx(Zr,{icon:s.jsx(Wo,{size:16}),label:"CLIs",value:`${r.length}`}),s.jsx(Zr,{icon:s.jsx(Gh,{size:16}),label:"ACPs",value:`${n.length}`})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),s.jsxs("div",{className:"flex gap-6",children:[s.jsx(Vi,{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(Vi,{value:i,max:100,label:"Memory",color:"#3b82f6",detail:a?`${ya(e.totalMem-o)} / ${ya(e.totalMem)}${e.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${ya(e.totalMem)} total`})]})]})]})}function Jj(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 Qj(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(u=>u.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 Ja(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 dc(e){if(!e||typeof e!="object")return null;if(Ja(e))return e;const t=e,r=t.result;return Ja(r)?r:Ja(t.sourceConfig)?t.sourceConfig:null}function Zj(e){const t=e.trim();return t||null}function ek({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var v;const o=t.filter(g=>g.category==="ide"),[i,c]=l.useState(((v=o[0])==null?void 0:v.type)||""),[u,m]=l.useState(""),[d,h]=l.useState(""),[f,y]=l.useState(!1),[b,x]=l.useState(""),[j,k]=l.useState(!1),p=g=>{const C=g.toLowerCase().replace(/[^a-z0-9-]/g,"");m(C),(!d||d===w(u))&&h(w(C))},w=g=>g.split("-").map(C=>C.charAt(0).toUpperCase()+C.slice(1)).join(" "),S=async()=>{if(!(!u||!d||!i)){y(!0),x("");try{const g=await r(e,"provider_clone",{type:u,name:d,category:"ide",location:"user",cloneFrom:i});g!=null&&g.success||g!=null&&g.created?(k(!0),a==null||a(u)):x((g==null?void 0:g.error)||"Failed to create provider")}catch(g){x((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:j?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:u})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",u,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",u]})," 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:u,onChange:g=>p(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/",u||"...","/"]})]})]}),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:d,onChange:g=>h(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"})]}),b&&s.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:b})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:j?s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:S,disabled:!u||!d||f,className:"machine-btn",style:{background:u&&d?"rgba(34,197,94,0.12)":void 0,borderColor:u&&d?"rgba(34,197,94,0.3)":void 0,color:u&&d?"#86efac":void 0,opacity:!u||!d||f?.4:1},children:f?"⏳ Creating...":"✨ Create Provider"})]})})]})})}const uc={"user-custom":"Custom",trusted:"Official","trusted-with-scripts":"Official · runs JS","external-safe":"External · spec-only","external-untrusted":"⚠ External · untrusted JS"},tk={"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 sk({trust:e,sourceName:t,description:r}){const n=t&&(e==="external-safe"||e==="external-untrusted")?`${uc[e]} · ${t}`:uc[e];return s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded border whitespace-nowrap ${tk[e]}`,title:r,children:n})}function rk(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 nk={detected:"Detected",not_detected:"Not detected",enabled_unchecked:"Enabled (unchecked)",disabled:"Disabled"},mc={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"},ak={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 hc(e){if(!e)return"—";const t=e.ok?"OK":"Failed",r=e.message||e.path||e.command||"";return r?`${t} — ${r}`:t}function ok(e){return e==="cli"||e==="acp"}function ik({prov:e,providerInfo:t,savingKey:r,onSetSetting:n,onEnableToggle:a,onDetect:o,onResetCommand:i}){const[c,u]=l.useState(!1),m=(t==null?void 0:t.enabled)===!0||e.values.enabled===!0,d=t==null?void 0:t.machineStatus,h=m&&d==="disabled"?"enabled_unchecked":d||(m?"enabled_unchecked":"disabled"),f=ok(e.category);return s.jsxs("div",{className:"rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("button",{onClick:()=>u(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 ${ak[e.category]??"border-border-subtle text-text-muted"}`,children:e.category.toUpperCase()}),(t==null?void 0:t.trust)&&s.jsx(sk,{trust:t.trust,sourceName:t.sourceName??null,description:t.trustDescription}),f&&s.jsx("span",{className:`text-[9px] font-semibold px-1.5 py-px rounded border ${mc[h]??mc.disabled}`,children:nk[h]??h}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[f&&s.jsx("button",{onClick:y=>{y.stopPropagation(),a(e.type,!m)},disabled:r===`${e.type}.enabled`,className:`machine-btn text-[10px] px-2 py-0.5 ${m?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:m?"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 b=Object.entries(y).map(([x,j])=>({k:x,href:rk(j)})).filter(x=>x.href!==null);return b.length===0?null:s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Links:"})," ",b.map(({k:x,href:j})=>s.jsx("a",{href:j,target:"_blank",rel:"noopener noreferrer",className:"text-violet-400 hover:underline mr-2",children:x},x))]})})()]}),f&&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:"})," ",hc(t==null?void 0:t.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Verification:"})," ",hc(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:b=>{const x=parseInt(b.target.value)||0;y.min!==void 0&&x<y.min||y.max!==void 0&&x>y.max||n(e.type,y.key,x)},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:b=>void n(e.type,y.key,b.target.value),className:"machine-input text-[11px]",children:y.options.map(b=>s.jsx("option",{value:b,children:b},b))}):s.jsx("input",{type:"text",defaultValue:String(e.values[y.key]??y.default??""),onBlur:b=>void n(e.type,y.key,b.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:f&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>void o(e.type),disabled:!m||r===`${e.type}.detect`,className:`machine-btn text-[10px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${m?"":"opacity-40 cursor-not-allowed"}`,title:m?"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 bn(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function lk({machineId:e,sendDaemonCommand:t,onChange:r}){const[n,a]=l.useState([]),[o,i]=l.useState([]),[c,u]=l.useState(!1),[m,d]=l.useState(null),[h,f]=l.useState(!1),[y,b]=l.useState(""),[x,j]=l.useState("main"),[k,p]=l.useState(""),[w,S]=l.useState(!1),[v,g]=l.useState(null),[C,I]=l.useState(null),N=l.useCallback(async()=>{if(e){u(!0),d(null);try{const M=bn(await t(e,"list_provider_sources",{}));if(!(M!=null&&M.success)){d((M==null?void 0:M.error)||"Failed to load sources");return}a(M.sources||[]),i(M.conflicts||[])}catch(M){d((M==null?void 0:M.message)||String(M))}finally{u(!1)}}},[e,t]);l.useEffect(()=>{N()},[N]);const _=async()=>{if(y.trim()){S(!0),d(null);try{const M=bn(await t(e,"add_provider_source",{url:y.trim(),ref:x.trim()||"main",...k.trim()?{name:k.trim()}:{}}));M!=null&&M.success?(f(!1),b(""),j("main"),p(""),await N(),r==null||r()):d((M==null?void 0:M.error)||"Failed to add source")}catch(M){d((M==null?void 0:M.message)||String(M))}finally{S(!1)}}},D=async M=>{if(confirm(`Remove provider source ${M}? This deletes the cloned manifests and clears any active-source entries that pointed here.`)){g(M),d(null);try{const R=bn(await t(e,"remove_provider_source",{name:M}));R!=null&&R.success?(await N(),r==null||r()):d((R==null?void 0:R.error)||"Failed to remove source")}catch(R){d((R==null?void 0:R.message)||String(R))}finally{g(null)}}},A=async(M,R)=>{I(`${M}:${R}`),d(null);try{const z=bn(await t(e,"set_active_provider_source",{type:M,sourceName:R}));z!=null&&z.success?(await N(),r==null||r()):d((z==null?void 0:z.error)||"Failed to set active source")}catch(z){d((z==null?void 0:z.message)||String(z))}finally{I(null)}};return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-sky-400",children:"External sources"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"3rd-party git URLs you've added. Providers here may ship JavaScript the daemon will execute — activation requires a confirmation."})]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsxs("button",{onClick:()=>void N(),disabled:c,className:"machine-btn text-[10px]",children:[c?"⏳":"↻"," Refresh"]}),s.jsx("button",{onClick:()=>f(!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"})]})]}),m&&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:m}),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(M=>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:M.name}),s.jsxs("div",{className:"text-[10px] text-text-muted truncate",children:[M.url," ",s.jsxs("span",{className:"opacity-60",children:["@ ",M.ref]})]})]}),s.jsx("button",{type:"button",onClick:()=>void D(M.name),disabled:v===M.name,className:"machine-btn text-[10px] text-red-400 hover:bg-red-500/[0.10]",children:v===M.name?"…":"Remove"})]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:Object.entries(M.providers).map(([R,z])=>s.jsxs("span",{className:"mr-3",children:[s.jsxs("span",{className:"text-text-secondary",children:[R,":"]})," ",z.length]},R))})]},M.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(M=>s.jsxs("li",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"font-mono text-[11px]",children:[M.type," ",s.jsxs("span",{className:"text-text-muted",children:["(",M.category,")"]})]}),s.jsx("div",{className:"flex gap-1.5 flex-wrap",children:M.candidates.map(R=>s.jsxs("button",{type:"button",onClick:()=>void A(M.type,R),disabled:C===`${M.type}:${R}`,className:`text-[10px] px-2 py-0.5 rounded border ${M.active===R?"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:M.active===R?"Active":`Switch active to ${R}`,children:[M.active===R?"● ":"",R]},R))})]},M.type))})]}),h&&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:M=>b(M.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:x,onChange:M=>j(M.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:M=>p(M.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:()=>f(!1),className:"machine-btn text-[10px]",children:"Cancel"}),s.jsx("button",{type:"button",onClick:()=>void _(),disabled:w||!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:w?"Cloning…":"Clone + register"})]})]})]})}function ck({machineId:e,providers:t,sendDaemonCommand:r}){var L;const[n,a]=l.useState([]),[o,i]=l.useState(!1),[c,u]=l.useState(null),[m,d]=l.useState("all"),[h,f]=l.useState(!1),[y,b]=l.useState(!1),[x,j]=l.useState(!1),[k,p]=l.useState(null),[w,S]=l.useState("normal"),[v,g]=l.useState(""),[C,I]=l.useState(!1),N=l.useCallback(async()=>{if(e)try{const B=await r(e,"get_provider_source_config",{}),O=dc(B);O&&(p(O),S(O.sourceMode),g(O.explicitProviderDir||""))}catch{}},[e,r]),_=l.useCallback(async()=>{if(e){i(!0);try{const B=await r(e,"get_provider_settings",{}),O=Jj(B);if(O){const $=Qj(O,t,{filterSchema:E=>E.filter(W=>W.key!=="enabled")});$.sort((E,W)=>E.category.localeCompare(W.category)||E.displayName.localeCompare(W.displayName)),a($)}}catch{}i(!1)}},[e,t,r]);l.useEffect(()=>{n.length===0&&_(),k||N()},[]);const D=async(B,O,$)=>{u(`${B}.${O}`),a(E=>E.map(W=>W.type===B?{...W,values:{...W.values,[O]:$}}:W));try{const E=await r(e,"set_provider_setting",{providerType:B,key:O,value:$});E!=null&&E.success||_()}catch{_()}u(null)},A=async(B,O)=>{await D(B,"enabled",O),await _()},M=async B=>{u(`${B}.detect`);try{await r(e,"detect_provider",{providerType:B})}finally{await _(),u(null)}},R=async B=>{await D(B,"executablePath",""),await D(B,"executableArgs",""),await _()},z=async()=>{I(!0);try{const B=await r(e,"set_provider_source_config",{providerSourceMode:w,providerDir:Zj(v)}),O=dc(B);O?(p(O),S(O.sourceMode),g(O.explicitProviderDir||"")):await N(),await _()}catch{await N()}I(!1)},T=n.filter(B=>m==="all"||B.category===m);return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[s.jsxs("div",{className:"flex gap-1 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(B=>s.jsx("button",{onClick:()=>d(B),className:`machine-btn text-[10px] px-2 py-0.5 ${m===B?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:B.toUpperCase()},B))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>b(B=>!B),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:()=>f(!0),className:"machine-btn text-[10px]",title:"Create a new provider from an existing one",children:"✨ Create"}),s.jsxs("button",{onClick:_,disabled:o,className:"machine-btn text-[10px]",children:[o?"⏳":"↻"," Refresh"]}),s.jsx("button",{onClick:()=>j(B=>!B),className:"machine-btn text-[10px]",title:"Show source configuration (advanced)",children:"⚙ Advanced"})]})]}),y&&s.jsx(lk,{machineId:e,sendDaemonCommand:r,onChange:()=>{_()}}),x&&s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Where the daemon looks for provider manifests. Affects resolution and reloads."})]}),s.jsx("button",{onClick:N,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:w,onChange:B=>S(B.target.value),className:"machine-input text-[11px]",children:[s.jsx("option",{value:"normal",children:"normal"}),s.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),s.jsx("input",{type:"text",value:v,onChange:B=>g(B.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void z(),disabled:C,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:C?"Applying…":"Apply + Reload"})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"User root:"})," ",(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:"})," ",((L=k==null?void 0:k.providerRoots)==null?void 0:L.join(" → "))||"—"]})]})]}),o&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings…"}):T.length===0?s.jsx("div",{className:"px-4.5 py-8 rounded-xl border border-border-subtle bg-bg-secondary text-center",children:s.jsx("div",{className:"text-[12px] text-text-muted",children:m==="all"?'No providers installed yet. Open "Add provider" above to install one.':`No ${m.toUpperCase()} providers installed.`})}):s.jsx("div",{className:"flex flex-col gap-1.5",children:T.map(B=>s.jsx(ik,{prov:B,providerInfo:t.find(O=>O.type===B.type),savingKey:c,onSetSetting:D,onEnableToggle:A,onDetect:M,onResetCommand:R},B.type))}),h&&s.jsx(ek,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>f(!1),onCreated:()=>{f(!1),_()}})]})}const dk=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function uk({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function mk(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function hk(e){return e.trim().toLowerCase()}function ua(e,t){const r=hk(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function Si(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function zs(e,t=220){const r=Si(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function pk(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 fk(e,t){return e.filter(r=>ua([r.level,r.message],t))}function pc(e){return`${e.timestamp}:${e.level}:${e.message}`}function xk(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const i of e.entries)n.set(pc(i),i);for(const i of t.entries)n.set(pc(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 bk(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 gk(e,t){return e.split(`
83
+ `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>ua([r],t))}function yk(e,t){return e.filter(r=>ua([r.level,r.category,r.stage,r.interactionId,Si(r.payload)],t))}function vk(e,t){return e.filter(r=>ua([r.kind,r.topic,r.interactionId,Si(r.payload)],t))}function fc(e){return e==="warn"||e==="error"}function wk({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=>fc(a.level)).length+r.filter(a=>fc(a.level)).length}}function jk({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(`
84
+ `)):t.length>0&&a.push(["[daemon logs]",...t].join(`
85
+ `)),r.length>0&&a.push(["[trace]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${zs(o.payload,500)}`.trim())].join(`
86
+ `)),n.length>0&&a.push(["[browser events]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${zs(o.payload,500)}`.trim())].join(`
87
+ `)),a.join(`
88
+
89
+ `)}function kk({machineId:e,sendDaemonCommand:t}){const[r,n]=l.useState([]),[a,o]=l.useState("empty"),[i,c]=l.useState(""),[u,m]=l.useState([]),[d,h]=l.useState([]),[f,y]=l.useState(null),[b,x]=l.useState(!0),[j,k]=l.useState("info"),[p,w]=l.useState("all"),[S,v]=l.useState(!0),[g,C]=l.useState(!0),[I,N]=l.useState(""),[_,D]=l.useState(""),[A,M]=l.useState(0),R=l.useRef(0),z=l.useRef(0),T=l.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),L=l.useRef([]),B=l.useCallback(()=>{const ee={entries:[],kind:"empty",rawText:"",lastTs:0};T.current=ee,R.current=0,n([]),c(""),o("empty"),v(!0)},[]),O=l.useCallback(()=>{L.current=[],z.current=0,m([]),C(!0)},[]),$=l.useCallback(ee=>{ee!==j&&(B(),k(ee))},[j,B]),E=l.useCallback(ee=>{w(me=>me===ee?me:ee)},[]),W=l.useCallback(()=>{B(),O(),h([]),y(null),N(""),D(""),$s.clear()},[B,O]),J=l.useCallback(()=>{M(ee=>ee+1)},[]),Q=l.useCallback(async()=>{if(!e)return;const ee=R.current,me=z.current,[je,Me]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:j,since:ee}),t(e,"get_debug_trace",uk({count:120,since:me,category:p}))]);if(je.status==="fulfilled"){const q=je.value,G=(q==null?void 0:q.result)||q,he=pk(G),ue=xk(T.current,he,300);T.current=ue,R.current=ue.lastTs,v(!1),N((q==null?void 0:q.success)===!1?String((q==null?void 0:q.error)||"Could not load daemon logs"):""),o(ue.kind),c(ue.rawText),n(ue.entries)}else v(!1),N(je.reason instanceof Error?je.reason.message:"Could not load daemon logs");if(Me.status==="fulfilled"){const q=Me.value,G=(q==null?void 0:q.result)||q;if((q==null?void 0:q.success)===!1)D(String((q==null?void 0:q.error)||"Could not load daemon trace"));else if(Array.isArray(G==null?void 0:G.trace)){const he=G.trace,ue=bk(L.current,he,120),ce=he.reduce((ve,X)=>Math.max(ve,Number(X.ts||0)),me);L.current=ue,ce>me&&(z.current=ce),D(""),m(ue)}else D("");C(!1)}else C(!1),D(Me.reason instanceof Error?Me.reason.message:"Could not load daemon trace");h($s.list({limit:120})),y(Date.now())},[j,e,t,p]);return l.useEffect(()=>{O()},[O,p]),l.useEffect(()=>{if(!e||(Q(),!b))return;const ee=setInterval(()=>{Q()},3e3);return()=>clearInterval(ee)},[b,Q,e,A]),{daemonLogs:r,daemonLogKind:a,daemonRawText:i,debugTrace:u,webEvents:d,lastUpdatedAt:f,autoRefresh:b,logLevel:j,traceCategory:p,daemonLoading:S,traceLoading:g,daemonFetchError:I,traceFetchError:_,setAutoRefresh:x,setLogLevel:$,setTraceCategory:E,refresh:J,clear:W}}function Sk({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:i,traceCount:c,webEventCount:u}){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:u>0?"ok":"empty",detail:u>0?`${u} local browser event(s)`:"No browser events captured"}]}function xc(e){return e==="warn"||e==="error"}function Nk(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 Ck(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 bc(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function Ik(e){const t=zs(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function Mk(e){const t=zs(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function Ak({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:Mk(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:Ik(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:Ck(o,i),severity:Nk(o),message:o,raw:o})}),a.sort((o,i)=>o.ts!==i.ts?o.ts-i.ts:bc(o.source)-bc(i.source))}function Tk(e){return`${e.source}:${e.severity}:${e.message}`}function _k(e){const t=e.filter(n=>xc(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!xc(n.severity))continue;const a=Tk(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 Lk(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function gc(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${Lk(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function Rk({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
90
+ `)),a.push(["[source status]",...r.map(i=>`${i.label}: ${i.status} - ${i.detail}`)].join(`
91
+ `)),t.latestIssue&&a.push(["[latest issue]",gc(t.latestIssue)].join(`
92
+ `)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(i=>`${i.count}x ${i.severity.toUpperCase()} ${i.source} ${i.message}`)].join(`
93
+ `));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(gc):["No diagnostic events captured."]].join(`
94
+ `)),a.join(`
95
+
96
+ `)}function Pk(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Dk(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Ek({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:i,searchQuery:c,daemonLoading:u,traceLoading:m,daemonFetchError:d,traceFetchError:h}){const f=mk(n,o),y=fk(e,c),b=gk(t,c),x=yk(f,c),j=vk(a,c),k=Pk(y,i),p=i==="all"?b:[],w=Dk(x,i),S=i==="issues"?[]:j,v=wk({daemonLogs:y,daemonRawLines:b,trace:x,webEvents:j}),g=Ak({daemonLogs:k,daemonRawLines:p,trace:w,webEvents:S}),C=_k(g),I=Sk({daemonLoading:u,traceLoading:m,daemonFetchError:d,traceFetchError:h,daemonLogKind:r,daemonLogsCount:y.length,daemonRawLineCount:b.length,traceCount:x.length,webEventCount:j.length});return{filteredDaemonLogs:y,filteredDaemonRawLines:b,filteredTraceEntries:x,filteredWebEvents:j,visibleDaemonLogs:k,visibleDaemonRawLines:p,visibleTraceEntries:w,visibleWebEvents:S,quickFilterCounts:v,diagnosticEvents:g,diagnosticsSummary:C,sourceStates:I}}function $k(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function mm(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Ro(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 Qa(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 Ni(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function Bk({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ro(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:mm(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:Ni(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 Ok({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:i,onCopyVisible:c,onToggleAutoRefresh:u,onRefresh:m,onClear:d}){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(h=>s.jsx("button",{type:"button",onClick:()=>a(h.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===h.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:h.label},h.id))}),s.jsx("input",{value:r,onChange:h=>o(h.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),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:u,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:d,className:"machine-btn",children:"Clear"})]})]})}function Fk({logLevel:e,traceCategory:t,onLogLevelChange:r,onTraceCategoryChange:n}){return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-3",children:s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(a=>s.jsxs("button",{onClick:()=>r(a),className:`machine-btn text-[10px] px-2 py-0.5 ${e===a?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",a.toUpperCase(),"+"]},a))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:dk.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 Hk({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:i,traceFetchError:c}){var d,h;const u=((d=e.latestIssue)==null?void 0:d.severity)==="error"?"danger":((h=e.latestIssue)==null?void 0:h.severity)==="warn"?"warning":"good",m=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 ${Qa(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 ${Qa(u)}`,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:[Ni(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:mm(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 ${Qa(m)}`,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: ",$k(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(f=>s.jsxs("div",{children:[f.label,": ",f.status]},f.id))})]})]})}function Wk({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()," · ",Ni(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function Kk({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:i,visibleWebEvents:c,quickFilter:u,searchQuery:m}){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(d=>({...d,timeline:!d.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(d=>s.jsx(Bk,{event:d},d.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(d=>({...d,daemon:!d.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:u==="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((d,h)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:d},`raw-${h}`)),e.daemonLogKind!=="text"&&a.map((d,h)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Ro(d.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(d.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:d.level==="error"?"ERR":d.level==="warn"?"WRN":d.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:d.message})]},`log-${h}`))]})]}),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(d=>({...d,trace:!d.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:m.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(d=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ro(d.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.level.toUpperCase()}),s.jsxs("span",{children:[d.category,".",d.stage]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:zs(d.payload,360)||"No payload"})]},d.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(d=>({...d,web:!d.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:m.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),c.map(d=>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(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.kind}),d.topic&&s.jsxs("span",{children:["topic=",d.topic]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:zs(d.payload,360)||"No payload"})]},d.id))]})]})]})}function Uk({machineId:e,sendDaemonCommand:t}){const r=kk({machineId:e,sendDaemonCommand:t}),[n,a]=l.useState("info"),[o,i]=l.useState(""),[c,u]=l.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=l.useRef(null),d=l.useRef(!1),h=l.useMemo(()=>Ek({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&&h.diagnosticEvents.length>0){const b=d.current?"smooth":"instant";setTimeout(()=>{var x;(x=m.current)==null||x.scrollIntoView({behavior:b}),d.current=!0},50)}},[h.diagnosticEvents.length,r.autoRefresh]);const f=l.useCallback(async()=>{var x;const b=jk({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!b.trim()){Qe.showToast("No visible logs to copy.","info");return}try{await((x=navigator.clipboard)==null?void 0:x.writeText(b)),Qe.showToast("Copied visible logs to clipboard.","success")}catch(j){Qe.showToast(j instanceof Error?j.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),y=l.useCallback(async()=>{var x;const b=Rk({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((x=navigator.clipboard)==null?void 0:x.writeText(b)),Qe.showToast("Copied diagnostic bundle to clipboard.","success")}catch(j){Qe.showToast(j instanceof Error?j.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(Ok,{quickFilter:n,quickFilterCounts:h.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:()=>{y()},onCopyVisible:()=>{f()},onToggleAutoRefresh:()=>r.setAutoRefresh(b=>!b),onRefresh:r.refresh,onClear:r.clear}),s.jsx(Fk,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(Hk,{diagnosticsSummary:h.diagnosticsSummary,diagnosticEventsCount:h.diagnosticEvents.length,sourceStates:h.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(Wk,{patterns:h.diagnosticsSummary.repeatedPatterns}),s.jsx(Kk,{streams:r,sectionsOpen:c,setSectionsOpen:u,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:m})]})}function zk(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 hm(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 Gk(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=hm((o==null?void 0:o.meta)||void 0),u=((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")&&(u||c)?r.push(o):n.push(o)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function Vk(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Za(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 eo(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function to(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function yc(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 qk(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Yk(e){switch(e){case"running":return"bg-green-500/[0.08] text-green-500";case"starting":return"bg-sky-500/[0.08] text-sky-400";case"stopping":return"bg-orange-500/[0.08] text-orange-400";case"interrupted":return"bg-amber-500/[0.08] text-amber-400";case"failed":return"bg-red-500/[0.08] text-red-500";default:return"bg-[#ffffff0a] text-text-muted"}}function Xk(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 Jk({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=l.useState(""),[o,i]=l.useState(null),[c,u]=l.useState(!1),m=$g(e,{enabled:!!e,includeSessions:!0,limit:ul,intervalMs:bx}),d=m.diagnostics,h=m.loading,f=m.applyDiagnostics,y=l.useMemo(()=>zk({diagnostics:d,loading:h,refreshing:c,error:n}),[d,h,c,n]),b=l.useMemo(()=>new Map(t.map(D=>[D.sessionId||D.id,D])),[t]),x=l.useCallback(async()=>{if(e){u(!0);try{const D=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:ul}),A=eo(D);if(!(A!=null&&A.success))throw new Error((A==null?void 0:A.error)||"Could not load hosted runtime diagnostics");f(A.diagnostics||A.result||null),a("")}catch(D){const A=D instanceof Error?D.message:"Could not load hosted runtime diagnostics";a(A)}finally{u(!1)}}},[f,e,r]);l.useEffect(()=>{!e||d||h||c||x()},[d,h,e,x,c]);const j=l.useCallback(async(D,A)=>{const M=`${D}:${A.sessionId}`;if(!(D==="session_host_stop_session"&&!window.confirm(`Stop ${A.displayName}?
97
+ This will terminate the hosted runtime.`))){i(M);try{const R=await r(e,D,{sessionId:A.sessionId}),z=eo(R);if(!(z!=null&&z.success))throw new Error((z==null?void 0:z.error)||"Session host action failed");const T=D==="session_host_resume_session"?"resumed":D==="session_host_restart_session"?"restarted":"stopped";Qe.showToast(`Session host ${T}: ${A.displayName}`,"success"),await x()}catch(R){const z=R instanceof Error?R.message:"Session host action failed";Qe.showToast(z,"warning"),a(z)}finally{i(R=>R===M?null:R)}}},[e,x,r]),k=l.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
98
+ 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 A=await r(e,"session_host_prune_duplicate_sessions",{}),M=eo(A);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Duplicate prune failed");const R=M.result||{},z=Array.isArray(R.prunedSessionIds)?R.prunedSessionIds.length:0,T=typeof R.duplicateGroupCount=="number"?R.duplicateGroupCount:0;Qe.showToast(`Pruned ${z} duplicate runtime(s) across ${T} group(s)`,"success"),await x()}catch(A){const M=A instanceof Error?A.message:"Duplicate prune failed";Qe.showToast(M,"warning"),a(M)}finally{i(A=>A==="session_host_prune_duplicate_sessions"?null:A)}}},[e,x,r]),p=l.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((D,A)=>(A.lastActivityAt||0)-(D.lastActivityAt||0)),[d==null?void 0:d.sessions]),w=l.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:Gk(p),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,p]),S=w.liveRuntimes,v=w.recoverySnapshots,g=w.inactiveRecords,C=l.useMemo(()=>Xk(S),[S]),I=l.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),N=l.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(D=>D.level==="warn"||D.level==="error")||null,[d==null?void 0:d.recentLogs]),_=(D,A)=>{var E;const M=o===`session_host_resume_session:${D.sessionId}`,R=o===`session_host_restart_session:${D.sessionId}`,z=o===`session_host_stop_session:${D.sessionId}`,T=hm(D.meta),L=b.get(D.sessionId),B=D.attachedClients.length===1?"1 client":`${D.attachedClients.length} clients`,O=A==="recovery"?"Recover":"Resume",$=Vk(A);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:D.displayName||(L==null?void 0:L.cliName)||D.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Yk(D.lifecycle)}`,children:D.lifecycle}),T&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:T})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:D.workspaceLabel||(L==null?void 0:L.runtimeWorkspaceLabel)||D.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:D.runtimeKey}),D.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",D.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((E=D.writeOwner)==null?void 0:E.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:qk(D.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(Pc,{size:11})," ",B]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",yc(D.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:[A==="recovery"&&(D.lifecycle==="interrupted"||D.lifecycle==="failed"||D.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{j("session_host_resume_session",D)},children:M?`${O}ing…`:O}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{j("session_host_restart_session",D)},children:R?"Restarting…":"Restart"}),A==="live"&&(D.lifecycle==="running"||D.lifecycle==="starting"||D.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{j("session_host_stop_session",D)},children:z?"Stopping…":"Stop"})]})]})},D.sessionId)};return s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(ns,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Eb()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[C>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 (${C})`}),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:()=>{x()},disabled:h||c,children:[s.jsx(ra,{size:13}),h||c?"Refreshing…":"Refresh"]})]})]}),n&&!d&&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(Fs,{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})]})]})}),d&&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:d.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:v.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:d.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:yc(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:to(d.hostStartedAt)})]})]}),N&&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(Fs,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:N.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[to(N.timestamp),N.sessionId?` · ${N.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(Wo,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Za("live")}),S.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:S.map(D=>_(D,"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(ns,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Za("recovery")}),v.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:v.map(D=>_(D,"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:Za("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:g.map(D=>_(D,"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"}),I.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:I.map(D=>{var M;const A=p.find(R=>R.sessionId===D.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:(A==null?void 0:A.displayName)||((M=b.get(D.sessionId))==null?void 0:M.cliName)||D.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[D.action,D.lifecycle?` · ${D.lifecycle}`:"",D.detail?` · ${D.detail}`:"",D.error?` · ${D.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${D.success===!1?"text-red-300":"text-text-secondary"}`,children:to(D.timestamp)})]},`${D.sessionId}:${D.timestamp}:${D.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Qk({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(o=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{a(null),n({cliType:t.cliType,workspaceId:o.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:o.label||o.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:o.path})]},o.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function Zk(e,t){const r=uu(e),n=Ls(e,t),a=ni(e,n),o=wr(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 so({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 ro({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function e1({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:i}){const c=n.slice(0,6),u=r.slice(0,4),d=Zk(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(so,{icon:s.jsx(ks,{size:13}),children:"Current Chats"}),s.jsx(ro,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(h=>{const f=Ao(h);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(h),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:at(h)}),f>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:na(f)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ws(h)})]},h.tabKey)})})})]}),u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(so,{icon:s.jsx(Bc,{size:13}),children:"Recent Launches"}),s.jsx(ro,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const{metaText:f,updatedLabel:y}=Su(h);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>o(h),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:h.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:f})]},h.id)})})})]}),d.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(so,{icon:s.jsx(Fs,{size:13}),children:"Daemon Update"}),s.jsx(ro,{className:d.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":d.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:d.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[d.description,d.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",d.targetVersion,d.channel?` (${d.channel})`:""]})]}),d.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(ra,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:d.buttonLabel})]}):s.jsx("div",{className:d.tone==="good"?"text-xs font-medium text-emerald-300":"text-xs font-medium text-sky-300",children:"No preview update action is needed."})]})})]})]})}function t1({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:u,handleWorkspaceRemove:m,handleWorkspaceSetDefault:d}=o,[h,f]=l.useState(!1),[y,b]=l.useState(""),[x,j]=l.useState([]),[k,p]=l.useState(!1),[w,S]=l.useState(""),v=l.useCallback(async C=>{p(!0),S("");try{const I=await mi(i,e,C);b(I.path),j(I.directories)}catch(I){S(I instanceof Error?I.message:"Could not load folder")}finally{p(!1)}},[e,i]),g=l.useCallback(()=>{f(!0);const C=[...r.map(N=>N.workspace),...n.map(N=>N.workspace),...a.map(N=>N.workspace)],I=ui(t.platform,di(C,t.defaultWorkspacePath,(t.workspaces||[]).map(N=>N.path)));v(I)},[a,n,r,v,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-4 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(Os,{size:14})," Workspaces"]}),s.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick: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(C=>{const I=C.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${I?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:I?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void d(I?null:C.id),className:`text-base leading-none shrink-0 transition-colors ${I?"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:ed(C.path,C.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:C.path,children:C.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void m(C.id),children:"Remove"})]},C.id)})})]}),h&&s.jsx(pi,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:y,directories:x,busy:k,error:w,confirmLabel:"Add workspace",onClose:()=>f(!1),onNavigate:C=>{v(C)},onConfirm:C=>{(async()=>{if(!C)return;await u(C)&&f(!1)})()}})]})}function s1({machine:e,machineId:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i}){return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspaces"}),s.jsx("div",{className:"text-sm text-text-secondary",children:'Save folders as workspaces on this machine. Use the dashboard "+" button to launch a session.'})]}),i&&s.jsx(t1,{machineId:t,machine:e,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function r1({onNicknameSynced:e}={}){var ve,X,we,de,ye,xe,ge,le,be,ie;const{id:t}=lh(),r=_r(),n=$o(),{sendCommand:a}=ot(),o=Dr(),i=Jd(),c=Id(),u=c.ides||[],m=c.initialLoaded??!0,d=u.find(P=>P.id===t&&P.type==="adhdev-daemon"),h=u.some(P=>P.type==="adhdev-daemon"),f=t?(ve=c.connectionRetryStatuses)==null?void 0:ve[t]:void 0,y=!!(f!=null&&f.blocked),[b,x]=l.useState("workspace"),[j,k]=l.useState(null);l.useCallback((P,fe)=>{k({daemonId:P,workspace:fe})},[]);const[,p]=l.useState("ide"),w=l.useRef(null),[S,v]=l.useState(null),g=l.useRef("__home__"),[C,I]=l.useState("__home__"),[N,_]=l.useState(!1),D=l.useRef(null);l.useEffect(()=>{!t||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||o(t,{minFreshMs:3e4}).catch(()=>{})},[o,d,t]),l.useEffect(()=>{if(!t||!d||b!=="overview")return;const P=d.machine;(typeof(P==null?void 0:P.cpus)!="number"||typeof(P==null?void 0:P.totalMem)!="number"||typeof(P==null?void 0:P.arch)!="string"||typeof(P==null?void 0:P.release)!="string")&&i(t,{minFreshMs:3e4}).catch(()=>{})},[b,i,d,t]),Eg(t&&b==="overview"?[t]:[],{enabled:b==="overview",intervalMs:hx});const A=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},M=Yj({machineId:t,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:D});l.useEffect(()=>Qe.onToast(fe=>{c.setToasts(_e=>{if(_e.some(Te=>Te.message===fe.message&&fe.timestamp-Te.timestamp<3e3))return _e;const De={id:fe.id,message:fe.message,type:fe.type,timestamp:fe.timestamp,targetKey:fe.targetKey,actions:fe.actions};return[..._e.slice(-4),De]});const Ce=fe.duration||5e3;setTimeout(()=>c.setToasts(_e=>_e.filter(se=>se.id!==fe.id)),Ce)}),[c]);const R=(d==null?void 0:d.availableProviders)||[],z={};for(const P of R)z[P.type]=P.icon;const T=d?{id:d.id,hostname:td(d,{fallbackId:d.id}),platform:((X=d.machine)==null?void 0:X.platform)||"unknown",arch:((we=d.machine)==null?void 0:we.arch)||"",cpus:((de=d.machine)==null?void 0:de.cpus)||0,totalMem:((ye=d.machine)==null?void 0:ye.totalMem)||0,freeMem:(xe=d.machine)==null?void 0:xe.freeMem,availableMem:(ge=d.machine)==null?void 0:ge.availableMem,loadavg:(le=d.machine)==null?void 0:le.loadavg,uptime:(be=d.machine)==null?void 0:be.uptime,release:((ie=d.machine)==null?void 0:ie.release)||"",cdpConnected:!!d.cdpConnected,machineNickname:d.machineNickname||null,p2p:d.p2p?{screenshotActive:!1,...d.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:d.detectedIdes||[],workspaces:d.workspaces||[],defaultWorkspaceId:d.defaultWorkspaceId??d.activeWorkspaceId??null,defaultWorkspacePath:d.defaultWorkspacePath??d.activeWorkspacePath??null}:null,L=u.filter(P=>P.daemonId===t&&P.type!=="adhdev-daemon").filter(P=>!Ir(P)&&!Ds(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,version:P.version||"",instanceId:P.instanceId||"",status:P.status,workspace:P.workspace||null,terminals:P.terminals||0,aiAgents:nf(P.aiAgents||(P.agents||[]).map(fe=>({id:fe.name,name:fe.name,status:fe.status,version:fe.version}))),activeChat:P.activeChat||null,chats:P.chats||[],childSessions:P.childSessions||[],cdpConnected:P.cdpConnected||!1,daemonId:t,lastMessageAt:P.lastMessageAt})),B=u.filter(P=>P.daemonId===t&&Ir(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,cliName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,mode:P.mode,runtimeKey:P.runtimeKey,runtimeDisplayName:P.runtimeDisplayName,runtimeWorkspaceLabel:P.runtimeWorkspaceLabel,runtimeWriteOwner:P.runtimeWriteOwner||null,runtimeAttachedClients:P.runtimeAttachedClients||[],daemonId:t,lastMessageAt:P.lastMessageAt})),O=u.filter(P=>P.daemonId===t&&Ds(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,acpName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,daemonId:t,lastMessageAt:P.lastMessageAt})),$=d?Mt(d,{fallbackId:t}):"",E="workspace",W=n.state,J=W==null?void 0:W.initialMachineTab,Q=W==null?void 0:W.initialWorkspaceCategory;W==null||W.initialWorkspaceId,W==null||W.initialWorkspacePath;const ee=J==="ides"||J==="clis"||J==="acps"?"workspace":J||E,me=J==="ides"?"ide":J==="clis"?"cli":J==="acps"?"acp":Q,je=[...L.map(P=>{var fe;return{id:`ide:${P.type}:${P.workspace||""}`,label:((fe=P.activeChat)==null?void 0:fe.title)||P.type,kind:"ide",providerType:P.type,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:P.lastMessageAt||0}}),...B.map(P=>{var fe;return{id:`cli:${P.type}:${P.workspace||""}`,label:((fe=P.activeChat)==null?void 0:fe.title)||P.cliName,kind:"cli",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:P.lastMessageAt||0}}),...O.map(P=>{var fe;return{id:`acp:${P.type}:${P.workspace||""}`,label:((fe=P.activeChat)==null?void 0:fe.title)||P.acpName,kind:"acp",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:vs(P.summaryMetadata)||P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:P.lastMessageAt||0}})].sort((P,fe)=>(fe.lastLaunchedAt||0)-(P.lastLaunchedAt||0)),Me=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(P=>({id:P.id,label:P.title||P.providerName||P.providerType,kind:P.kind,providerType:P.providerType,providerSessionId:P.providerSessionId,subtitle:vs(P.summaryMetadata)||P.workspace||void 0,workspace:P.workspace,summaryMetadata:P.summaryMetadata,lastLaunchedAt:P.lastLaunchedAt})):je,q=l.useMemo(()=>{var fe;const P=((fe=c.connectionStates)==null?void 0:fe[t||""])||void 0;return u.filter(Ce=>Ce.daemonId===t&&Ce.type!=="adhdev-daemon").flatMap(Ce=>ri(Ce,{connectionStates:t&&P?{[t]:P}:void 0,defaultConnectionState:P})).filter(Ce=>!(Ce.transport==="pty"&&Ce.mode==="terminal")).sort((Ce,_e)=>Ao(_e)-Ao(Ce))},[u,c.connectionStates,t]),G=l.useCallback(P=>{const fe=xu(P);fe&&r(Ar(fe))},[r]),he=l.useCallback(()=>{w.current&&(_(!0),w.current().finally(()=>{w.current=null,_(!1),v(null)}))},[]),ue=l.useCallback(P=>{if(!T)return;const{options:fe,selectedKey:Ce}=ku({machine:T,currentWorkspacePath:P.workspace}),_e=async()=>{p(P.kind),x("workspace")};w.current=async()=>{const se=fe.find(Ee=>Ee.key===g.current),De=(se==null?void 0:se.workspacePath)??null,Te=(se==null?void 0:se.workspaceId)??null;if(P.kind==="ide"&&P.providerType){await M.handleLaunchIde(P.providerType,De?{workspace:De}:void 0);return}if((P.kind==="cli"||P.kind==="acp")&&P.providerType){await M.runLaunchCliCore({cliType:P.providerType,dir:Te?void 0:De||"",workspaceId:Te||void 0,model:P.kind==="acp"&&rd(P.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:P.providerSessionId});return}await _e()},g.current=Ce,I(Ce),v({title:P.kind==="ide"?Wn("restart-ide",P.label):P.providerSessionId?Ed(P.label):Wn("start-fresh",P.label),description:P.kind==="ide"?Kn("restart-ide"):P.providerSessionId?$d():Kn("start-fresh"),confirmLabel:P.kind==="ide"?Un("restart-ide"):P.providerSessionId?Hn(!0):Un("start-fresh"),busyLabel:P.kind==="ide"?zn("restart-ide"):P.providerSessionId?ti(!0):zn("start-fresh"),workspaceOptions:fe,details:[{label:"Mode",value:P.kind.toUpperCase()},...P.providerType?[{label:"Provider",value:P.providerType}]:[]]})},[M,T]);if(l.useEffect(()=>{x(ee)},[E,ee,t]),l.useEffect(()=>{me&&p(me)},[me,t]),!T)return m?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:A,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 ce=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ot,{size:14})," Workspace"]}),count:L.length+B.length+O.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ns,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(sa,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Kh,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Fh,{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:A,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[M.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:M.nicknameInput,onChange:P=>M.setNicknameInput(P.target.value),onKeyDown:P=>{P.key==="Enter"&&M.handleSaveNickname(),P.key==="Escape"&&M.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:M.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:()=>M.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:()=>{M.setEditingNickname(!0),M.setNicknameInput(T.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:[T.platform," · ",T.arch]}),s.jsxs("span",{children:[T.cpus," cores"]}),(d==null?void 0:d.version)&&s.jsxs("span",{children:["v",d.version]}),T.p2p.available&&s.jsxs("span",{children:["P2P ",T.p2p.state==="connected"?"connected":T.p2p.state]}),T.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:T.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ce.map(P=>s.jsxs("button",{onClick:()=>x(P.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${b===P.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[P.label,P.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${b===P.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:P.count})]},P.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[b==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(e1,{machineEntry:d,providers:R,recentLaunches:Me,currentConversations:q,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",mu(d))}catch{}},onOpenRecent:ue,onOpenConversation:G}),s.jsx(s1,{machine:T,machineId:t,ideSessions:L,cliSessions:B,acpSessions:O,actions:M,sendDaemonCommand:a})]}),b==="providers"&&s.jsx(ck,{machineId:t,providers:R,sendDaemonCommand:a}),b==="overview"&&s.jsx(Xj,{machine:T,ideSessions:L,cliSessions:B,acpSessions:O}),b==="session-host"&&s.jsx(Jk,{machineId:t,cliSessions:B,sendDaemonCommand:a}),b==="logs"&&s.jsx(Uk,{machineId:t,sendDaemonCommand:a})]})})}),M.launchPick&&T&&s.jsx(Qk,{machine:T,launchPick:M.launchPick,actions:M}),S&&s.jsx(ju,{title:S.title,description:S.description,details:S.details,workspaceOptions:S.workspaceOptions,selectedWorkspaceKey:C,onWorkspaceChange:P=>{g.current=P,I(P)},confirmLabel:S.confirmLabel,busyLabel:S.busyLabel,busy:N,onConfirm:he,onCancel:()=>{w.current=null,v(null)}}),j&&s.jsx(um,{daemonId:j.daemonId,workspace:j.workspace,onClose:()=>k(null)}),s.jsx(Od,{toasts:c.toasts||[],onDismiss:P=>c.setToasts(fe=>fe.filter(Ce=>Ce.id!==P)),onClickToast:P=>{P.targetKey&&r(Ar(P.targetKey))}}),s.jsx("style",{children:`
99
+ @keyframes toast-in {
100
+ from { opacity: 0; transform: translateX(40px); }
101
+ to { opacity: 1; transform: translateX(0); }
102
+ }
103
+ `})]})}const gn=[{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."}],n1={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function Tn(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 a1(e){const t=Tn(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"launch not ready unless an explicit provider is selected"}}function o1(e){return e.isLocalWorktree===!0}function i1(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function l1(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 c1(e,t){return[...Array.isArray(t==null?void 0:t.cliSessions)?t.cliSessions:[],...Array.isArray(t==null?void 0:t.acpSessions)?t.acpSessions:[],...Array.isArray(t==null?void 0:t.sessions)?t.sessions:[]].filter(n=>{var a;return((a=n==null?void 0:n.settings)==null?void 0:a.meshNodeId)===e.id||(n==null?void 0:n.workspace)===e.workspace}).map(n=>{var a;return{id:n.sessionId||n.id||n.instanceId||"unknown",provider:n.providerType||n.cliType||n.acpType||n.type||"unknown",status:n.status||((a=n.activeChat)==null?void 0:a.status)||"unknown"}})}function no(e){return{...n1,...(e==null?void 0:e.policy)||{}}}function d1({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const o=a.id.toLowerCase(),i=a.name.toLowerCase();return o==="hermes-cli"||o.includes("hermes")||i.includes("hermes")}),n=fu(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(ct,{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(Bu,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function u1({hideHostPairing:e=!1}={}){var V,te,oe,Ne,Le;const{sendCommand:t,sendData:r}=ot(),{ides:n}=Xt(),a=n.find(F=>F.daemonMode||F.type==="adhdev-daemon"),o=(a==null?void 0:a.id)||"",i=[];let c=[];if(a){const F=a.availableProviders||[];c=qb(F);for(const ne of F)ne.category==="cli"&&i.push({id:ne.type||ne.id,name:ne.displayName||ne.name||ne.type,meshCoordinator:ne.meshCoordinator})}const[u,m]=l.useState([]),[d,h]=l.useState(null),[f,y]=l.useState(!0),[b,x]=l.useState(null),[j,k]=l.useState(!1),[p,w]=l.useState(null),[S,v]=l.useState({}),[g,C]=l.useState({override:"",append:""}),[I,N]=l.useState(!1),[_,D]=l.useState({}),[A,M]=l.useState(null),[R,z]=l.useState([]),[T,L]=l.useState(null),[B,O]=l.useState(null),[$,E]=l.useState(!1),[W,J]=l.useState(null),[Q,ee]=l.useState(null),[me,je]=l.useState(!1),[Me,q]=l.useState(!1),[G,he]=l.useState(!1),[ue,ce]=l.useState(""),[ve,X]=l.useState(""),[we,de]=l.useState(!1),[ye,xe]=l.useState(""),[ge,le]=l.useState(""),[be,ie]=l.useState(""),[P,fe]=l.useState(!1),[Ce,_e]=l.useState(""),[se,De]=l.useState([]),Te=u.find(F=>F.id===d)||null,Ee=cm({status:B,daemonId:o,meshId:d,sendData:r});l.useEffect(()=>{v(Object.fromEntries(((Te==null?void 0:Te.nodes)||[]).map(F=>[F.id,Tn(F)])))},[Te]),l.useEffect(()=>{const F=(Te==null?void 0:Te.coordinator)||{};C({override:typeof F.systemPromptOverride=="string"?F.systemPromptOverride:"",append:typeof F.systemPromptAppend=="string"?F.systemPromptAppend:typeof F.systemPromptSuffix=="string"?F.systemPromptSuffix:""}),D(Object.fromEntries(((Te==null?void 0:Te.nodes)||[]).map(ne=>[ne.id,typeof ne.systemPrompt=="string"?ne.systemPrompt:""])))},[Te]),l.useEffect(()=>{const F=Yb(c);P&&se.length===0&&F.length>0&&De(F)},[P,c,se.length]),l.useEffect(()=>{const F=new Set(((Te==null?void 0:Te.nodes)||[]).map(ne=>ne.id));T&&!F.has(T)&&L(null)},[Te,T]);const Oe=l.useCallback(async()=>{if(o){y(!0);try{const F=await t(o,"list_meshes");F!=null&&F.success?(m(F.meshes||[]),x(null)):x((F==null?void 0:F.error)||"Failed to load meshes")}catch(F){x((F==null?void 0:F.message)||"Failed to load meshes")}finally{y(!1)}}},[o,t]),Je=l.useCallback(async F=>{if(!o||!F){z([]);return}try{const ne=await t(o,"get_mesh_queue",{meshId:F});ne!=null&&ne.success?z(Array.isArray(ne.queue)?ne.queue:[]):z([])}catch{z([])}},[o,t]),qe=l.useCallback(async F=>{var ne;if(!o||!F){ee(null),ce(""),X("");return}je(!0);try{const pe=await t(o,"get_mesh_host_pairing",{meshId:F});pe!=null&&pe.success?(ee(pe),ce(pe.hostAddress||((ne=pe.meshHost)==null?void 0:ne.hostAddress)||"")):ee({success:!1,error:(pe==null?void 0:pe.error)||"Failed to load Mesh Host pairing"}),X("")}catch(pe){ee({success:!1,error:(pe==null?void 0:pe.message)||"Failed to load Mesh Host pairing"}),X("")}finally{je(!1)}},[o,t]);l.useEffect(()=>{Oe()},[Oe]),l.useEffect(()=>{Je(d)},[Je,d]),l.useEffect(()=>{e||qe(d)},[qe,d,e]);async function Ze(){if(!(!o||!d))try{E(!0),J(null);const F=await t(o,"mesh_status",{meshId:d});if((F==null?void 0:F.success)===!1){O(null),J((F==null?void 0:F.error)||"mesh_status failed");return}const ne=tm(F);ne?O(ne):(O(null),J("mesh_status returned an unexpected payload."))}catch(F){O(null),J((F==null?void 0:F.message)||"Failed to load mesh graph")}finally{E(!1)}}l.useEffect(()=>{d&&(O(null),J(null),Ze())},[d]);async function et(){var pe;if(!o||!ye.trim())return;const F=be.trim(),ne=ge.trim();if(!(!F&&!ne))try{const Se=await t(o,"create_mesh",{name:ye.trim(),repoRemoteUrl:F||void 0,repoIdentity:ne||void 0});Se!=null&&Se.success?(de(!1),xe(""),le(""),ie(""),await Oe(),h(((pe=Se.mesh)==null?void 0:pe.id)||null)):x((Se==null?void 0:Se.error)||"Create failed")}catch(Se){x((Se==null?void 0:Se.message)||"Create failed")}}async function dt(F){if(!(!o||!confirm("Delete this mesh?")))try{await t(o,"delete_mesh",{meshId:F}),h(null),await Oe()}catch(ne){x((ne==null?void 0:ne.message)||"Delete failed")}}async function ut(){if(!(!o||!d||!Ce.trim()))try{const F=await t(o,"add_mesh_node",{meshId:d,workspace:Ce.trim(),providerPriority:So(se,c)});F!=null&&F.success?(fe(!1),_e(""),De([]),await Oe(),await Je(d)):x((F==null?void 0:F.error)||"Add node failed")}catch(F){x((F==null?void 0:F.message)||"Add node failed")}}async function xt(F){var Se;if(!o||!d)return;const ne=no(Te),pe=((Se=gn.find(Ie=>Ie.value===ne.sessionCleanupOnNodeRemove))==null?void 0:Se.label)||"Preserve history and runtimes";if(confirm(`Remove this node?
104
+
105
+ Node removal cleanup policy: ${pe}`))try{await t(o,"remove_mesh_node",{meshId:d,nodeId:F}),T===F&&L(null),await Oe(),await Je(d)}catch(Ie){x((Ie==null?void 0:Ie.message)||"Remove node failed")}}async function Ae(F){if(!o||!d)return;const ne={...no(Te),...F};try{k(!0),x(null);const pe=await t(o,"update_mesh",{meshId:d,policy:ne});if((pe==null?void 0:pe.success)===!1){x(pe.error||"Policy update failed");return}await Oe()}catch(pe){x((pe==null?void 0:pe.message)||"Policy update failed")}finally{k(!1)}}async function He(){if(!o||!d)return;const ne={...(Te==null?void 0:Te.coordinator)||{}};g.override.trim()?ne.systemPromptOverride=g.override:delete ne.systemPromptOverride,g.append.trim()?ne.systemPromptAppend=g.append:delete ne.systemPromptAppend,delete ne.systemPromptSuffix;try{N(!0),x(null);const pe=await t(o,"update_mesh",{meshId:d,coordinator:ne});if((pe==null?void 0:pe.success)===!1){x(pe.error||"Coordinator prompt save failed");return}await Oe()}catch(pe){x((pe==null?void 0:pe.message)||"Coordinator prompt save failed")}finally{N(!1)}}async function rt(F){if(!o||!d)return;const ne=(_[F.id]||"").trim();try{M(F.id),x(null);const pe=await t(o,"update_mesh_node",{meshId:d,nodeId:F.id,systemPrompt:ne});if((pe==null?void 0:pe.success)===!1){x(pe.error||"Node instruction save failed");return}await Oe()}catch(pe){x((pe==null?void 0:pe.message)||"Node instruction save failed")}finally{M(null)}}async function Ye(){var F;if(!(!o||!d||!ue.trim()||!ve.trim())){q(!0);try{const ne=await t(o,"configure_mesh_host_pairing",{meshId:d,hostAddress:ue.trim(),token:ve.trim()});ne!=null&&ne.success?(ee(ne),ce(ne.hostAddress||((F=ne.meshHost)==null?void 0:F.hostAddress)||ue.trim()),await Oe()):ee({success:!1,error:(ne==null?void 0:ne.error)||"Failed to save Mesh Host pairing"})}catch(ne){ee({success:!1,error:(ne==null?void 0:ne.message)||"Failed to save Mesh Host pairing"})}finally{q(!1)}}}async function tt(){if(!(!o||!d||!ve.trim())){he(!0);try{const F=await t(o,"join_mesh_host_pairing",{meshId:d,token:ve.trim()});F!=null&&F.success?(ee(F),X(""),await Oe(),await qe(d),await Ze()):ee({success:!1,meshHost:F==null?void 0:F.meshHost,manualPairing:F==null?void 0:F.manualPairing,error:(F==null?void 0:F.error)||"Failed to apply Mesh Host join"})}catch(F){ee({success:!1,error:(F==null?void 0:F.message)||"Failed to apply Mesh Host join"})}finally{he(!1)}}}async function K(F){if(!o||!d)return;const ne=S[F.id]||Tn(F),pe=c.length>0?So(ne,c):Br(ne),Se={...F.policy||{}};delete Se.provider_priority,pe.length?Se.providerPriority=pe:delete Se.providerPriority;try{w(F.id),x(null);const Ie=await t(o,"update_mesh_node",{meshId:d,nodeId:F.id,policy:Se,providerPriority:pe});if((Ie==null?void 0:Ie.success)===!1){x(Ie.error||"Node policy update failed");return}await Oe()}catch(Ie){x((Ie==null?void 0:Ie.message)||"Node policy update failed")}finally{w(null)}}if(!o)return s.jsx(vr,{icon:s.jsx(ss,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})});if(!Te)return s.jsxs(vr,{icon:s.jsx(ss,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>de(!0),children:"+ Create Mesh"}),children:[b&&s.jsx(Ps,{variant:"error",className:"mb-4",children:b}),we&&s.jsx(ct,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(ft,{label:"Name",children:s.jsx(Is,{value:ye,onChange:F=>xe(F.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(ft,{label:"Repo remote URL (optional)",hint:"Provide a remote URL OR a stable identity. Mesh nodes use this to match the same project across machines.",children:s.jsx(Is,{value:be,onChange:F=>ie(F.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(ft,{label:"Repo identity (optional)",hint:"Provide a remote URL OR a stable identity. Mesh nodes use this to match the same project across machines.",children:s.jsx(Is,{value:ge,onChange:F=>le(F.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:et,disabled:!ye.trim()||!be.trim()&&!ge.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>{de(!1),xe(""),le(""),ie("")},children:"Cancel"})]})]})}),f?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):u.length===0?s.jsx(Gn,{icon:s.jsx(ss,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:u.map(F=>s.jsxs("button",{className:"text-left w-full p-4 rounded-xl border border-border-subtle bg-bg-panel hover:border-accent-primary/40 transition-colors",onClick:()=>h(F.id),children:[s.jsx("div",{className:"font-semibold text-sm",children:F.name}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:F.repoIdentity||"No repo identity"}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[F.nodes.length," node(s)"]})]},F.id))})]});const U=no(Te),Y=(Q==null?void 0:Q.meshHost)||Te.meshHost||{},re=((V=Q==null?void 0:Q.manualPairing)==null?void 0:V.status)||((te=Y.pairing)==null?void 0:te.status)||"not_configured",H=((oe=Q==null?void 0:Q.manualPairing)==null?void 0:oe.description)||"Manual address/token config is saved locally; Apply join sends the token once to the Mesh Host command endpoint. P2P runtime signaling remains outside this slice.";return s.jsxs(vr,{icon:s.jsx(ss,{}),title:Te.name,subtitle:Te.repoIdentity||"Repo Mesh",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(null),children:"← Back"}),s.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>dt(Te.id),children:"Delete"})]}),children:[b&&s.jsx(Ps,{variant:"error",className:"mb-4",children:b}),!e&&s.jsx(ct,{title:"Mesh Host pairing",description:"Standalone manual pairing. Save a Mesh Host address/token, apply the join to the host command endpoint, then check persisted status.",children:s.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(280px,420px)]",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-4 text-sm",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"text-text-muted",children:"Local role"}),s.jsx("span",{className:"rounded-full border border-accent-primary/25 bg-accent-primary/10 px-2 py-0.5 text-xs font-semibold text-accent-primary",children:Y.role||"host"}),s.jsx("span",{className:"text-text-muted",children:"Pairing"}),s.jsx("span",{className:"rounded-full border border-border-subtle px-2 py-0.5 text-xs font-mono text-text-primary",children:me?"loading":re})]}),s.jsxs("div",{className:"mt-3 grid gap-2 text-xs text-text-muted",children:[s.jsxs("div",{children:["Host address: ",s.jsx("code",{className:"text-text-primary",children:Y.hostAddress||"not configured"})]}),s.jsxs("div",{children:["Token id: ",s.jsx("code",{className:"text-text-primary",children:((Ne=Y.pairing)==null?void 0:Ne.tokenId)||"not configured"})]}),s.jsxs("div",{children:["Can own coordinator: ",s.jsx("code",{className:"text-text-primary",children:String(Y.canOwnCoordinator??Y.role!=="member")})]}),s.jsxs("div",{children:["Can own queue: ",s.jsx("code",{className:"text-text-primary",children:String(Y.canOwnQueue??Y.role!=="member")})]})]}),s.jsx("p",{className:"mt-3 text-xs leading-relaxed text-text-secondary",children:H}),(Q==null?void 0:Q.error)&&s.jsx("div",{className:"mt-3 rounded-lg border border-red-500/25 bg-red-500/10 px-3 py-2 text-xs text-red-300",children:Q.error})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-panel p-4",children:[s.jsx(ft,{label:"Mesh Host address",hint:"Example: http://127.0.0.1:3847 or a reachable HTTPS/WSS host endpoint.",children:s.jsx(Is,{value:ue,onChange:F=>ce(F.target.value),placeholder:"http://127.0.0.1:3847",disabled:Me||G})}),s.jsx(ft,{label:"Pairing token",hint:"The raw token is used once to derive a local token id; it is not displayed after save.",children:s.jsx(Is,{value:ve,onChange:F=>X(F.target.value),placeholder:"paste Mesh Host pairing token",type:"password",disabled:Me||G})}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:Ye,disabled:Me||G||!ue.trim()||!ve.trim(),children:Me?"Saving...":"Save manual pairing"}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:tt,disabled:G||Me||!ve.trim(),children:G?"Applying...":"Apply join"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>qe(d),disabled:me||Me||G,children:me?"Checking...":"Check saved config"})]})]})]})}),s.jsxs(ct,{title:"Policy",description:"Coordinator safety defaults and node-removal session cleanup behavior for this local mesh.",children:[s.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[s.jsx(ft,{label:"Checkpoint before task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:U.requirePreTaskCheckpoint?"yes":"no",onChange:F=>Ae({requirePreTaskCheckpoint:F.target.value==="yes"}),disabled:j,children:[s.jsx("option",{value:"no",children:"No"}),s.jsx("option",{value:"yes",children:"Yes"})]})}),s.jsx(ft,{label:"Checkpoint after task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:U.requirePostTaskCheckpoint?"yes":"no",onChange:F=>Ae({requirePostTaskCheckpoint:F.target.value==="yes"}),disabled:j,children:[s.jsx("option",{value:"yes",children:"Yes"}),s.jsx("option",{value:"no",children:"No"})]})}),s.jsx(ft,{label:"Push approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:U.requireApprovalForPush?"required":"not_required",onChange:F=>Ae({requireApprovalForPush:F.target.value==="required"}),disabled:j,children:[s.jsx("option",{value:"required",children:"Require approval before push"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(ft,{label:"Submodule main auto-publish",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:U.allowAutoPublishSubmoduleMainCommits?"enabled":"disabled",onChange:F=>Ae({allowAutoPublishSubmoduleMainCommits:F.target.value==="enabled"}),disabled:j,children:[s.jsx("option",{value:"disabled",children:"Require explicit approval"}),s.jsx("option",{value:"enabled",children:"Allow Refinery non-force publish"})]})}),s.jsx(ft,{label:"Destructive git approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:U.requireApprovalForDestructiveGit?"required":"not_required",onChange:F=>Ae({requireApprovalForDestructiveGit:F.target.value==="required"}),disabled:j,children:[s.jsx("option",{value:"required",children:"Require approval"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(ft,{label:"Dirty workspace behavior",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:U.dirtyWorkspaceBehavior||"warn",onChange:F=>Ae({dirtyWorkspaceBehavior:F.target.value}),disabled:j,children:[s.jsx("option",{value:"warn",children:"Warn and continue"}),s.jsx("option",{value:"block",children:"Block task"}),s.jsx("option",{value:"checkpoint_then_continue",children:"Checkpoint then continue"})]})}),s.jsx(ft,{label:"Max parallel tasks",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:String(U.maxParallelTasks??2),onChange:F=>Ae({maxParallelTasks:Number(F.target.value)}),disabled:j,children:[1,2,3,4,5,6,7,8].map(F=>s.jsx("option",{value:F,children:F},F))})})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(ft,{label:"Node removal session cleanup",hint:"Separate transcript cleanup from runtime/process cleanup. Preserve is safest when completed work may need review.",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:U.sessionCleanupOnNodeRemove||"preserve",onChange:F=>Ae({sessionCleanupOnNodeRemove:F.target.value}),disabled:j,children:gn.map(F=>s.jsx("option",{value:F.value,children:F.label},F.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((Le=gn.find(F=>F.value===U.sessionCleanupOnNodeRemove))==null?void 0:Le.description)||gn[0].description})]}),j&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),s.jsxs(ct,{title:"Coordinator prompt",description:"Customize the system prompt for mesh coordinator sessions. Leave both fields empty to use the daemon's built-in prompt. Supports placeholders: {{meshName}}, {{repo}}, {{defaultBranch}}, {{cliType}}, {{nodes}}, {{policy}}, {{tools}}, {{workflow}}, {{rules}}, {{toolExposurePreflight}}.",children:[s.jsx(ft,{label:"Override (replaces default)",hint:"When set, REPLACES the daemon's default base prompt for this mesh. Use placeholders if you still want node/policy/tools to render. 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:g.override,onChange:F=>C(ne=>({...ne,override:F.target.value})),disabled:I,placeholder:"(empty — daemon default applies)"})}),s.jsx(ft,{label:"Append (added after the base)",hint:"Always added after whichever base prompt wins. Use this for mesh-specific rules that should layer on top of 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:4,value:g.append,onChange:F=>C(ne=>({...ne,append:F.target.value})),disabled:I,placeholder:"(empty — nothing appended at mesh layer)"})}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void He(),disabled:I,children:I?"Saving…":"Save coordinator prompt"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>C({override:"",append:""}),disabled:I,title:"Clear both fields. Click Save to commit the reset.",children:"Clear"})]})]}),s.jsxs(ct,{title:"Visualization",description:"Live mesh topology: branches, worktrees, sessions, and orphan detection.",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500"}),"healthy"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-amber-500"}),"dirty"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-red-500"}),"error"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-gray-500"}),"offline"]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:Ze,disabled:$,children:$?"Loading...":"Refresh Graph"})]}),W&&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:W}),Ee?s.jsx(im,{status:Ee,emptyMessage:"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon.",daemonId:o,sendDaemonCommand:t}):s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:$?"Loading graph...":"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon."})]}),s.jsxs(ct,{title:"Nodes",description:"Workspaces participating in this mesh.",children:[s.jsx("div",{className:"flex justify-end mb-3",children:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>fe(!0),children:"+ Add Node"})}),P&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:"Add Node"}),s.jsx("button",{onClick:()=>fe(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(gt,{size:16})})]}),s.jsx(ft,{label:"Workspace Path",children:(()=>{var pe;const F=Array.isArray(a==null?void 0:a.workspaces)?a.workspaces:[],ne=`mesh-add-node-workspaces-${d||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(Is,{value:Ce,onChange:Se=>_e(Se.target.value),placeholder:((pe=F[0])==null?void 0:pe.path)||"/Users/dev/projects/myapp",list:F.length>0?ne:void 0,autoFocus:!0}),F.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:ne,children:F.map(Se=>s.jsx("option",{value:Se.path,children:Se.label||Se.path},Se.id||Se.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:F.slice(0,6).map(Se=>s.jsx("button",{type:"button",onClick:()=>_e(Se.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:Se.path,children:Se.label||Se.path.split("/").filter(Boolean).pop()||Se.path},Se.id||Se.path))})]})]})})()}),s.jsx(ft,{label:"Provider Priority",hint:"Order used when launching without an explicit provider. Empty means fail closed unless a provider is selected explicitly.",children:s.jsx(kl,{value:se,availableProviders:c,onChange:De})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:ut,disabled:!Ce.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>fe(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),Te.nodes.length===0?s.jsx(Gn,{icon:s.jsx(Os,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:Te.nodes.map(F=>{const ne=Tn(F),pe=a1(F),Se=i1(F,R),Ie=c1(F,a),We=T===F.id,ze=o1(F);return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary cursor-pointer transition-colors ${We?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`,role:"button",tabIndex:0,onClick:()=>L(We?null:F.id),onKeyDown:Be=>{(Be.key==="Enter"||Be.key===" ")&&(Be.preventDefault(),L(We?null:F.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"text-sm font-medium",children:F.workspace.split("/").pop()}),Se.length>0&&s.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-orange-500/15 text-orange-300 border border-orange-500/25",children:[Se.length," active task",Se.length===1?"":"s"]}),ze&&s.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-cyan-500/15 text-cyan-300 border border-cyan-500/25",children:"worktree"})]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:F.workspace}),ze&&s.jsxs("div",{className:"mt-2 rounded-lg border border-cyan-500/20 bg-cyan-500/10 px-3 py-2 text-[11px] text-cyan-200",children:["Worktree node",F.worktreeBranch?` · ${F.worktreeBranch}`:"",". Provider priority saved here is node-local and disappears when this worktree node is removed."]}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:Be=>Be.stopPropagation(),children:[s.jsxs(ft,{label:"Provider priority",hint:ze?"Worktree-local launch defaults. Configure the source node for durable defaults.":"Used when launches omit an explicit provider. Empty keeps fail-closed behavior until a provider is selected manually.",children:[s.jsx(kl,{value:S[F.id]??ne,availableProviders:c,onChange:Be=>v(mt=>({...mt,[F.id]:Be})),disabled:p===F.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:Be=>{Be.stopPropagation(),K(F)},disabled:p===F.id,children:p===F.id?"Saving...":"Save policy"})}),s.jsxs("div",{className:"mt-2 text-[12px]",children:[s.jsx("span",{className:"text-text-muted",children:"Effective provider priority: "}),s.jsx("span",{className:pe.configured?"text-text-primary font-mono":"text-amber-400",children:pe.label}),pe.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",pe.launchBlockedMessage,")"]})]})]}),s.jsxs(ft,{label:"Node instruction (optional)",hint:"Surfaced in the coordinator system prompt as 📌 Node instruction. The coordinator quotes it verbatim when delegating tasks to this node.",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:_[F.id]??"",onChange:Be=>{const mt=Be.target.value;D(lt=>({...lt,[F.id]:mt}))},onClick:Be=>Be.stopPropagation(),disabled:A===F.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:Be=>{Be.stopPropagation(),rt(F)},disabled:A===F.id,children:A===F.id?"Saving…":"Save instruction"})})]})]})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:Be=>{Be.stopPropagation(),xt(F.id)},children:s.jsx(gt,{size:14})})]}),We&&s.jsxs("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Node ID:"})," ",s.jsx("span",{className:"font-mono",children:F.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:pe.configured?"text-green-400":"text-amber-400",children:pe.configured?"yes":"provider priority not configured"})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Repo root:"})," ",s.jsx("span",{className:"font-mono",children:F.repoRoot||F.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",Ie.length]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Branch / git:"})," not loaded in standalone list view"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Health:"})," ",Se.length>0||Ie.length>0?"active":"idle/unknown"]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),Se.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:Se.map(Be=>s.jsx("li",{className:"font-mono",children:l1(Be)},Be.id))})]}),Ie.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:Ie.map(Be=>s.jsxs("li",{className:"font-mono",children:[Be.provider," / ",Be.status," / ",Be.id]},Be.id))})]})]})]},F.id)})})]}),s.jsx(d1,{meshId:Te.id,availableCliAgents:i})]})}function Ci(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function m1(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=Ci();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 Ht(e,t){return await fetch(m1(e),{credentials:"same-origin",...t})}function pm(){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 h1{constructor(){Ue(this,"adapters",new Map);Ue(this,"states",new Map);Ue(this,"runtimeListeners",new Map);Ue(this,"screenshotCallbacks",new Map);Ue(this,"statusCallbacks",new Set);Ue(this,"stateChangeCallbacks",new Set);Ue(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 Ht(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const u=await o.json();u!=null&&u.error&&(c=u.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 Ft=new h1;function p1(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Ci();return r?`${t}?token=${encodeURIComponent(r)}`:t}const yn=p1(),vc=3e3,f1=3e4;let Et=null,x1=0;const ea=new Map;let ds=null,kr=null;function wc(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function dr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function b1(e){return e==="connected"?"connected":e}async function Sr(e,t,r){const n=Kd(e,r||{}),a=Et;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++x1}_${Date.now()}`;return new Promise((i,c)=>{const u=setTimeout(()=>{ea.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);ea.set(o,{resolve:m=>{clearTimeout(u),i(m)},reject:m=>{clearTimeout(u),c(m)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Po(e,t){const r=Et;if(!r||r.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(t)),!0}catch{return!1}}function fm(e,t,r){const n=Et;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Kd(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}}Ft.registerPtyInputSender(fm);class g1{constructor(t){Ue(this,"daemonId");Ue(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Et==null?void 0:Et.readyState)===WebSocket.OPEN}get connectionState(){return(Et==null?void 0:Et.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Sr(this.daemonId,t,r)}async sendInput(t,r){return Sr(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,ds&&(clearInterval(ds),ds=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Sr(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());Ft.emitScreenshot(this.daemonId,a)}}catch{}};r(),ds=setInterval(r,2e3)}stopScreenshots(t){ds&&(clearInterval(ds),ds=null)}}let _t=null;function y1(e){return(!_t||_t.daemonId!==e)&&(_t=new g1(e)),_t}function v1({children:e}){const t=l.useRef(Cr()),r=Cr();t.current=r;const{setUserName:n}=Xt(),a=l.useRef(n);a.current=n;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),u=l.useCallback((x,j)=>{c(x),kr==null||kr(x,j)},[]),m=l.useRef(null),d=l.useRef(),h=l.useRef(vc),f=l.useRef(!0),y=l.useRef(!1),b=l.useRef("initial_connect");return l.useEffect(()=>{f.current=!0,y.current=!1;function x(){var p,w;if(!f.current||((p=m.current)==null?void 0:p.readyState)===WebSocket.OPEN||((w=m.current)==null?void 0:w.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${yn}...`),dr("connect_attempt",{url:yn,reason:b.current,delayMs:h.current});let k;try{k=new WebSocket(yn)}catch(S){console.error("[Standalone WS] Failed to create WebSocket:",S),j();return}m.current=k,k.onopen=()=>{if(!f.current){k.close();return}u("connected"),h.current=vc,dr("open",{url:yn,reason:b.current}),zt.resubscribeAll({sendData:Po}),console.log("[Standalone WS] Connected")},Et=k,k.onmessage=S=>{var v,g;try{const C=JSON.parse(S.data);if((C.type==="command_result"||C.type==="error")&&C.requestId){const I=ea.get(C.requestId);I&&(ea.delete(C.requestId),C.type==="error"?I.reject(new Error(((v=C.data)==null?void 0:v.message)||"Command failed")):I.resolve(C.data));return}if(C.type==="session_output"){const I=C.sessionId||C.cliId||C.cliType;I&&Ft.emitSessionOutput(I,typeof C.data=="string"?C.data:"",typeof C.seq=="number"?C.seq:void 0);return}if(C.type==="runtime_snapshot"){Ft.emitRuntimeSnapshot(C.sessionId,typeof C.text=="string"?C.text:"",typeof C.seq=="number"?C.seq:0,!!C.truncated,typeof C.cols=="number"?C.cols:void 0,typeof C.rows=="number"?C.rows:void 0);return}if(C.type==="topic_update"){const I=C.update;I&&zt.publish(I);return}if(C.type==="status"||C.type==="initial_state"){const I=C.data;if(!I)return;const{injectEntries:N,markLoaded:_,getIdes:D}=t.current,A=I.instanceId||"standalone",M=D().find(T=>T.id===A),R=y1(A);Ft.register(A,R),Ft.setState(A,"connected"),u("connected",A),Ft.emitStatus(A,I);const z=Bn(I,{daemonId:A,existingDaemon:M,existingEntries:D()});wc("ws_status",{type:C.type,daemonId:A,sessions:(I.sessions||[]).map(T=>({id:T.id,parentId:T.parentId,providerType:T.providerType,kind:T.kind,transport:T.transport,unread:T.unread,inboxBucket:T.inboxBucket,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,title:T.title})),recentLaunches:(I.recentLaunches||[]).map(T=>({id:T.id,providerType:T.providerType,kind:T.kind,workspace:T.workspace,lastLaunchedAt:T.lastLaunchedAt}))}),wc("entries",{daemonId:A,entries:z.filter(T=>T.type!=="adhdev-daemon").map(T=>({id:T.id,type:T.type,unread:T.unread,inboxBucket:T.inboxBucket,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,sessionId:T.sessionId}))}),z.length>0&&N(z,{authoritativeDaemonIds:[A]}),_(),i.current!==A&&((g=o.current)==null||g.call(o),i.current=A,o.current=zt.subscribe({sendData:Po},A,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${A}`,params:{includeSessions:!0}},T=>{if(T.topic!=="daemon.metadata")return;const L=t.current.getIdes(),B=L.find($=>$.id===A),O=Bn(T.status,{daemonId:A,existingDaemon:B,existingEntries:L,timestamp:T.timestamp});O.length>0&&t.current.injectEntries(O,{authoritativeDaemonIds:[A]}),T.userName&&a.current&&a.current(T.userName)}))}}catch(C){console.error("[Standalone WS] Parse error:",C)}},k.onclose=S=>{f.current&&(_t==null||_t.stopScreenshots(),_t&&Ft.setState(_t.daemonId,"disconnected"),u("disconnected"),m.current=null,b.current=`close:${S.code}${S.wasClean?":clean":":unclean"}`,dr("close",{code:S.code,reason:S.reason||"",wasClean:S.wasClean}),j())},k.onerror=S=>{y.current||!f.current||(b.current="error",dr("error",{message:S instanceof Event?"event":String(S),readyState:k.readyState}),console.warn("[Standalone WS] Error, will reconnect:",S))}}function j(){if(!f.current)return;clearTimeout(d.current);const k=h.current;console.log(`[Standalone WS] Reconnecting in ${k}ms...`),dr("schedule_reconnect",{reason:b.current,delayMs:k}),d.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,f1),x()},k)}return x(),()=>{var k;f.current=!1,y.current=!0,(k=o.current)==null||k.call(o),o.current=null,i.current=null,clearTimeout(d.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,Et=null),_t&&(_t.stopScreenshots(),Ft.unregister(_t.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function w1({children:e}){const[t,r]=l.useState("disconnected"),[n,a]=l.useState(null);l.useEffect(()=>(kr=(i,c)=>{r(i),c&&a(c)},()=>{kr=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=b1(t),u={};return n&&(u[n]=c),u.standalone=c,{wsStatus:t,isConnected:i,connectionStates:u}},[t,n]);return s.jsx(Nh,{connectionOverrides:o,children:s.jsx(v1,{children:e})})}const xm="adhdev_standalone_font_preferences",ys={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},ma=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],Tr=[{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"}],j1=new Set(ma.map(e=>e.id)),k1=new Set(Tr.map(e=>e.id));function Kt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:_n("chat",t.chat),code:_n("code",t.code),terminal:_n("terminal",t.terminal)}}function _n(e,t){const r=ys[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"?j1:k1).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Ln(e,t){var a;const r=_n(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?ma:Tr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function S1(e){const t=Kt(e),r=Ln("chat",t.chat),n=Ln("code",t.code),a=Ln("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function ms(e,t=document.documentElement){const r=Kt(e),n=S1(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function Do(e){const t=Kt(e);try{localStorage.setItem(xm,JSON.stringify(t))}catch{}return t}function N1(){try{const e=localStorage.getItem(xm);if(e)return Kt(JSON.parse(e))}catch{}return ys}function C1(){return ms(N1())}function ur(e,t){var n;const r=e==="chat"?ma:Tr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const I1=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Rc,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(ns,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(Hs,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(sa,{}),label:"Settings"}];function M1({children:e}){const t=_r(),r=$o(),n=l.useMemo(()=>I1.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(Dc,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Ec,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(og,{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 A1=[{icon:s.jsx(ns,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(ks,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx($c,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Ot,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Hs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Dc,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],T1=[{icon:s.jsx(zh,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Rc,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Lr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Oh,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Pc,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Hh,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],_1=[{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 L1(){return s.jsxs(vr,{icon:s.jsx(Ec,{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(ct,{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(ct,{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:A1.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(ct,{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:Ud.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Gd.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:zd.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(ct,{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:T1.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(ct,{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:_1.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(Gn,{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(ep,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function ao(e,t,r){return{...e,[t]:r}}function oo({surface:e,title:t,description:r,value:n,options:a,onChange:o}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:i=>{const c=i.target.value;o(c==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:c})},children:a.map(i=>s.jsx("option",{value:i.id,children:i.label},i.id))}),n.preset==="custom"&&s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:i=>o({preset:"custom",customFamily:i.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:Ln(e,n)})]})]})]})}function R1({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:u}){const m=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&s.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&s.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(oo,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:ma,onChange:d=>o(ao(e,"chat",d))}),s.jsx(oo,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Tr,onChange:d=>o(ao(e,"code",d))}),s.jsx(oo,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Tr,onChange:d=>o(ao(e,"terminal",d))})]}),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: ",ur("chat",e.chat.preset)," · Code: ",ur("code",e.code.preset)," · Terminal: ",ur("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",ur("chat",ys.chat.preset)," / ",ur("code",ys.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:i,disabled:r||!m,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),s.jsx("button",{type:"button",onClick:c,disabled:r||!m,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),s.jsx("button",{type:"button",onClick:u,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function P1(){const{ides:e}=Xt(),t=e.find(q=>q.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=ot(),{userName:a}=Xt(),[o,i]=l.useState(a||""),[c,u]=l.useState(null),[m,d]=l.useState(null),[h,f]=l.useState(ys),[y,b]=l.useState(!1),[x,j]=l.useState(""),[k,p]=l.useState(""),[w,S]=l.useState("127.0.0.1"),[v,g]=l.useState(""),[C,I]=l.useState(""),[N,_]=l.useState(""),[D,A]=l.useState(""),[M,R]=l.useState(""),[z,T]=l.useState(!1),L=async()=>{const G=await(await Ht("/auth/session")).json();u(G)},B=async()=>{const G=await(await Ht("/api/v1/standalone/preferences")).json();d(G),S(G.standaloneBindHost);const he=Kt(G.standaloneFontPreferences);f(he),ms(he),Do(he)};l.useEffect(()=>{a!==void 0&&i(a)},[a]),l.useEffect(()=>{Promise.all([L(),B()]).catch(q=>{A(q instanceof Error?q.message:String(q))})},[]),l.useEffect(()=>{ms(h)},[h]);const O=q=>{const G=q.target.value.trim();t!=null&&t.id&&G!==a&&n(t.id,"set_user_name",{userName:G}).catch(console.error)},[$,E]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),W=q=>{E(q);try{localStorage.setItem("adhdev_sound",q?"1":"0")}catch{}},J=async()=>{j(""),p(""),b(!0);try{const q=Kt(h),G=await Ht("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:q})}),he=await G.json();if(!G.ok)throw new Error((he==null?void 0:he.error)||"Failed to save standalone font preferences");const ue=Kt(he.standaloneFontPreferences);d(he),f(ue),ms(ue),Do(ue),p("Standalone chat fonts saved for this self-hosted dashboard.")}catch(q){j(q instanceof Error?q.message:String(q))}finally{b(!1)}},Q=()=>{const q=Kt(m==null?void 0:m.standaloneFontPreferences);j(""),p(""),f(q),ms(q)},ee=()=>{j(""),p(""),f(ys),ms(ys)},me=async()=>{A(""),R(""),T(!0);try{const q=await Ht("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:w})}),G=await q.json();if(!q.ok)throw new Error((G==null?void 0:G.error)||"Failed to save standalone network preference");d(G),S(G.standaloneBindHost),R(G.standaloneBindHost==="0.0.0.0"?"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.":"Default standalone network mode set to localhost only. Restart standalone to apply it.")}catch(q){A(q instanceof Error?q.message:String(q))}finally{T(!1)}},je=async()=>{if(A(""),R(""),C.trim().length<4){A("Password must be at least 4 characters.");return}if(C!==N){A("New password and confirmation do not match.");return}T(!0);try{const q=await Ht("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:C})}),G=await q.json();if(!q.ok)throw new Error((G==null?void 0:G.error)||"Failed to save password");u(G),await B(),g(""),I(""),_(""),R(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),pm()}catch(q){A(q instanceof Error?q.message:String(q))}finally{T(!1)}},Me=async()=>{A(""),R(""),T(!0);try{const q=await Ht("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),G=await q.json();if(!q.ok)throw new Error((G==null?void 0:G.error)||"Failed to clear password");u(G),await B(),g(""),I(""),_(""),R("Standalone password disabled.")}catch(q){A(q instanceof Error?q.message:String(q))}finally{T(!1)}};return s.jsxs(vr,{icon:s.jsx(sa,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Ps,{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(Ps,{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(ct,{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:(m==null?void 0:m.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:(m==null?void 0:m.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(ct,{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:w==="127.0.0.1",onChange:()=>S("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:w==="0.0.0.0",onChange:()=>S("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:()=>{me()},disabled:z,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:z?"Saving…":"Save default network mode"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(m==null?void 0:m.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(ct,{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."}),D&&s.jsx(Ps,{variant:"error",children:D}),M&&s.jsx(Ps,{variant:"success",children:M}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:c!=null&&c.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:v,onChange:q=>g(q.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:c!=null&&c.hasPasswordAuth?"New password":"New standalone password",value:C,onChange:q=>I(q.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:N,onChange:q=>_(q.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{je()},disabled:z,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:z?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{Me()},disabled:z,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),s.jsx(ct,{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(q=>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 ${q.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:q.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:q.type})]},q.type))})}),s.jsx(ct,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(fg,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(ct,{title:"Coordinator prompts",description:"User-level overrides for the mesh coordinator system prompt. Per-mesh overrides live in the Repo Mesh page.",children:s.jsx(yg,{daemonId:t==null?void 0:t.id})}),s.jsx(ct,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(wg,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI."}),s.jsx(Ag,{})]}),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(R1,{value:h,savedValue:Kt(m==null?void 0:m.standaloneFontPreferences),saving:y,error:x,notice:k,onChange:f,onSave:()=>{J()},onResetToSaved:Q,onResetToDefaults:ee})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),s.jsx(Lg,{})]})]})}),s.jsx(ct,{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(mg,{}),s.jsx(us,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zh,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:$,onChange:W})]})}),s.jsx(ct,{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(Bh,{size:16,className:"text-text-secondary"})," Display Name"]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:o,onChange:q=>i(q.target.value),onBlur:O,onKeyDown:q=>{q.key==="Enter"&&q.currentTarget.blur()}})]})})})]})}const D1=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],fr="adhdev_onboarding_done",E1=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],$1={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function B1({onDone:e}){const[t,r]=l.useState([]),[n,a]=l.useState(new Set(D1)),[o,i]=l.useState(!0),[c,u]=l.useState(null),[m,d]=l.useState(!1),[h,f]=l.useState(null),[y,b]=l.useState("all");l.useEffect(()=>{let v=!1;const g=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${g}/providers?sort=popular&limit=100`).then(C=>{if(!C.ok)throw new Error(`HTTP ${C.status}`);return C.json()}).then(C=>{v||r(C.providers??[])}).catch(C=>{v||u(C instanceof Error?C.message:String(C))}).finally(()=>{v||i(!1)}),()=>{v=!0}},[]);const x=t.filter(v=>y==="all"||v.category===y),j=["cli","ide","extension","acp"].map(v=>({category:v,items:x.filter(g=>g.category===v)})).filter(v=>v.items.length>0),k=l.useCallback(v=>{a(g=>{const C=new Set(g);return C.has(v)?C.delete(v):C.add(v),C})},[]),p=l.useCallback(async()=>{if(n.size===0){localStorage.setItem(fr,"1"),e();return}d(!0);const v=[];for(const g of n)try{const I=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:g})})).json().catch(()=>({}));v.push({type:g,ok:!!I.success,error:I.error})}catch(C){v.push({type:g,ok:!1,error:C instanceof Error?C.message:String(C)})}f(v),d(!1),v.every(g=>g.ok)&&localStorage.setItem(fr,"1")},[n,e]),w=l.useCallback(()=>{localStorage.setItem(fr,"1"),e()},[e]),S=l.useCallback(()=>{h&&h.every(v=>v.ok)?e():m||w()},[h,m,e,w]);return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60",onClick:S,children:s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-2xl max-w-2xl w-full p-6 flex flex-col gap-5 max-h-[85vh] overflow-y-auto",onClick:v=>v.stopPropagation(),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Welcome to ADHDev"}),s.jsxs("div",{className:"text-[12px] text-text-muted mt-1",children:["Pick the providers you want to use. Defaults to the four officially supported CLI providers; you can install IDE, ACP, or extension providers from the tabs below or later from ",s.jsx("span",{className:"text-text-secondary",children:"Burrow → Providers → Add provider"}),"."]})]}),!o&&!c&&t.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:E1.map(v=>{const g=v.key==="all"?t.length:t.filter(C=>C.category===v.key).length;return g===0&&v.key!=="all"?null:s.jsxs("button",{onClick:()=>b(v.key),className:`machine-btn text-[10px] px-2 py-0.5 ${y===v.key?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:[v.label," ",s.jsxs("span",{className:"opacity-60",children:["(",g,")"]})]},v.key)})}),o&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"Loading registry…"}),!o&&c&&s.jsxs("div",{className:"rounded-xl border border-red-500/30 bg-red-500/5 px-3 py-2 text-[12px] text-red-400",children:["Failed to load registry: ",c]}),!o&&!c&&x.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"No providers in this category."}),!o&&!c&&x.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:j.map(v=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:$1[v.category]??v.category}),s.jsx("div",{className:"grid gap-1.5",children:v.items.map(g=>{var D,A;const C=n.has(g.type),I=h==null?void 0:h.find(M=>M.type===g.type),N=((D=g.manifest)==null?void 0:D.icon)??"📦",_=((A=g.manifest)==null?void 0:A.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${C?"bg-violet-500/[0.06] border-violet-500/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:C,onChange:()=>k(g.type),disabled:m,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:N}),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}),_&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:_})]}),I&&s.jsx("span",{className:`text-[10px] font-semibold ${I.ok?"text-green-400":"text-red-400"}`,children:I.ok?"✓ installed":`✗ ${I.error??"failed"}`})]},g.type)})})]},v.category))}),s.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-border-subtle",children:[s.jsxs("div",{className:"text-[11px] text-text-muted",children:[n.size," provider",n.size!==1?"s":""," selected"]}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx("button",{onClick:w,disabled:m,className:"machine-btn text-[11px] px-3 py-1",children:"Skip"}),s.jsx("button",{onClick:()=>{h?(localStorage.setItem(fr,"1"),e()):p()},disabled:m||!h&&n.size===0,className:"machine-btn text-[11px] px-3 py-1 bg-violet-500/15 border-violet-500/40 text-violet-400 hover:bg-violet-500/25",children:m?"Installing…":h?"Done":`Install ${n.size}`})]})]})]})})}function O1(){try{return localStorage.getItem(fr)==="1"}catch{return!1}}ng();Ig();C1();const F1=Ac({baseUrl:"",getToken:Ci});function H1({children:e}){const[t,r]=l.useState(null),[n,a]=l.useState(!0),[o,i]=l.useState(""),[c,u]=l.useState(""),[m,d]=l.useState(!1),h=async()=>{a(!0),u("");try{const b=await(await Ht("/auth/session")).json();r(b)}catch(y){u(y instanceof Error?y.message:String(y))}finally{a(!1)}};l.useEffect(()=>{h()},[]),l.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let y=!1;return(async()=>{try{const b=await Ht("/api/v1/standalone/preferences");if(!b.ok)return;const x=await b.json();if(y)return;const j=Kt(x.standaloneFontPreferences);ms(j),Do(j)}catch{}})(),()=>{y=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const f=async y=>{y.preventDefault(),d(!0),u("");try{const b=await Ht("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),x=await b.json();if(!b.ok)throw new Error((x==null?void 0:x.error)||"Login failed");r(x),i(""),pm()}catch(b){u(b instanceof Error?b.message:String(b))}finally{d(!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:f,children:[s.jsx("input",{type:"password",value:o,onChange:y=>i(y.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled:m||!o,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:m?"Signing in…":"Unlock dashboard"})]}):s.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),c&&s.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:c})]})}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",c||"unknown error"]})}function jc(){const{ides:e,initialLoaded:t}=Xt();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(co,{to:`/machines/${r.id}`,replace:!0}):s.jsx(co,{to:"/dashboard",replace:!0})}function W1(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let r=!1;if(!O1())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(B1,{onDone:()=>t(!1)}):null}function K1(){const e=l.useMemo(()=>({sendCommand:Sr,sendData:Po,sendPtyInput:fm}),[]);return s.jsx(ch,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Mh,{client:F1,children:s.jsx(H1,{children:s.jsx(w1,{children:s.jsx(Th,{value:e,children:s.jsx(Ph,{sendDaemonCommand:Sr,children:s.jsxs(M1,{children:[s.jsx(W1,{}),s.jsxs(dh,{children:[s.jsx(es,{path:"/dashboard",element:s.jsx(qj,{})}),s.jsx(es,{path:"/machine",element:s.jsx(jc,{})}),s.jsx(es,{path:"/machines/:id",element:s.jsx(r1,{})}),s.jsx(es,{path:"/machines",element:s.jsx(jc,{})}),s.jsx(es,{path:"/about",element:s.jsx(L1,{})}),s.jsx(es,{path:"/settings",element:s.jsx(P1,{})}),s.jsx(es,{path:"/mesh",element:s.jsx(u1,{hideHostPairing:!0})}),s.jsx(es,{path:"*",element:s.jsx(co,{to:"/dashboard",replace:!0})})]})]})})})})})})})}db({connectionManager:Ft});uh(document.getElementById("root")).render(s.jsx(K1,{}));