@adhdev/daemon-standalone 0.9.82-rc.211 → 0.9.82-rc.213

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,112 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-DN8I8rbd.js","assets/vendor-BwuWgaJI.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
+ var rp=Object.defineProperty;var np=(e,t,r)=>t in e?rp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ue=(e,t,r)=>np(e,typeof t!="symbol"?t+"":t,r);import{r as l,j as s,M as Wo,a as ap,b as op,c as ip,R as gt,d as Cr,t as lp,e as cp,u as Dr,D as dp,f as ho,g as fo,E as up,i as mp,C as pp,h as hp,B as fp,k as xp,l as bp,m as gp,n as yp,H as en,P as es,o as vp,p as wp,q as jp,s as kp,v as Sp,w as Ko,x as Np,y as Cp,z as Ip,A as Mp,F as ts,N as xo,G as Ap}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 Tp(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 Es=Tp();function Wi(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 _p(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Ki(e){return Array.isArray(e)?[...e]:[]}function Bc(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?Ki(e.messages):i?[]:t.messages,activeModal:n?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...r?{messages:Ki(e.messages)}:{},...n?{activeModal:e.activeModal??null}:{}}}function pr(e,t){const r=_p(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:Bc(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 Oc(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?pr(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 Ui(e){return!!e&&typeof e=="object"&&"text"in e}function Uo(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:Ui(o)?String(o.text||""):"").join(r):Ui(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Bs(e){return Uo(e,{normalizeWhitespace:!0})}const Fc=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}),Hc=l.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function zi(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 Wc(e,t,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=t.version??r.version??e.version,o=t.serverVersion??e.serverVersion??r.serverVersion,i=t.versionMismatch===!0||e.versionMismatch===!0,c=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,d=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),o&&(n.serverVersion=o),d&&(n.versionUpdateReason=d),a&&o&&a===o?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||i&&a&&o&&a!==o)&&(n.versionMismatch=!0),c&&(n.versionUpdateRequired=!0),n)}function Lp(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 ba(e){if(!e||typeof e!="object")return"";const t=e,r=Lp(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 Pp(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=ba(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:ba(e[0]),last:ba(e[e.length-1])}}function bo(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function go(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(bo(e)&&bo(t)){const i=e.messages;Array.isArray(i)&&i===t.messages&&r.add(i)}if(Array.isArray(e)&&Array.isArray(t)){const i=Math.min(e.length,t.length);for(let c=0;c<i;c+=1)go(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"&&go(n[i],a[i],r)}function br(e,t){return Array.isArray(e)?e.map(r=>br(r,t)):!e||typeof e!="object"?e:bo(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Pp(a,t):br(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,br(n,t)]))}function Rp(e,t){try{const r=new WeakSet;return go(e,t,r),JSON.stringify(br(e,r))===JSON.stringify(br(t,r))}catch{return!1}}function yo(e,t,r){return Rp(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Kc(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Dp(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Gi(e,t,r,n){var c;const a=(c=t.chats)!=null&&c.length?t.chats:e.chats,o=Oc(e.childSessions,t.childSessions,{preserveMissing:n}),i=Bc(t.activeChat,e.activeChat);return Wc(e,t,{...e,...t,chats:a,childSessions:o,activeChat:i,_lastUpdate:r})}function $p(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=Oc(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"])Dp(n,t,i);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function Ep(e,t,r,n){const a=$p(e,t,n),o=Object.keys(a).length>0?Wc(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return yo(e,o,r)}function Bp(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=Kc(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 Op(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 Fp(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function Hp(e,t,r){var u,p;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:d,daemonIdsWithAuthoritativeSessionList:m}=Bp(e);for(const f of e){const y=o.get(f.id);if(!y){o.set(f.id,{...f,_lastUpdate:n});continue}const g=zi(f),x=zi(y),k=Kc(f),j=!a.has(k);if(g>x){const I=Gi(y,f,n,j);o.set(f.id,yo(y,I,n));continue}if(g<x){o.set(f.id,Ep(y,f,n,j));continue}const h=f.timestamp||n,v=y._lastUpdate||y.timestamp||0;if(h>=v){const I=Gi(y,f,n,j);o.set(f.id,yo(y,I,n));continue}(u=f.chats)!=null&&u.length&&!((p=y.chats)!=null&&p.length)&&o.set(f.id,{...y,chats:f.chats})}for(const[f,y]of o){const g=y.daemonId||f.split(":")[0];if(!c.has(g))continue;if(a.has(g)&&m.has(g)&&!i.has(f)){o.delete(f);continue}const x=n-(y._lastUpdate||y.timestamp||0);Op(y,g,x,i,a,d)&&o.delete(f)}for(const[f,y]of o){const g=y.daemonId||f.split(":")[0];if(Fp(y,g,c,d,o))continue;n-(y._lastUpdate||y.timestamp||0)>3e5&&y.status!=="online"&&o.delete(f)}return Array.from(o.values())}function Wp(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 Kp({children:e,connectionOverrides:t}){const[r,n]=l.useState([]),[a,o]=l.useState(!1),[i,c]=l.useState([]),[d,m]=l.useState(void 0),u=l.useRef(r);l.useEffect(()=>{u.current=r},[r]);const p=l.useCallback((j,h)=>{n(v=>{let I=!1;const w=v.map(b=>b.id!==j||b.chats===h?b:(I=!0,{...b,chats:h}));return I?w:v})},[]),f=l.useCallback((j,h)=>{n(v=>{const I=v.length===0?j:Hp(j,v,h),w=!Wp(v,I);return w&&Es.record({kind:"dashboard.entries_applied",payload:{incoming:Wi(j),next:Wi(I)}}),w?I:v})},[]),y=l.useCallback(()=>o(!0),[]),g=l.useMemo(()=>({injectEntries:f,markLoaded:y,getIdes:()=>u.current}),[f,y]),x=t,k=l.useMemo(()=>({ides:r,updateRouteChats:p,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:d,setUserName:m}),[r,p,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,d]);return s.jsx(Hc.Provider,{value:g,children:s.jsx(Fc.Provider,{value:k,children:e})})}function qt(){return l.useContext(Fc)}function Ir(){return l.useContext(Hc)}function Uc(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(c){return c.startsWith("http")?c:`${t}${c.startsWith("/")?"":"/"}${c}`}function o(c){const d=r==null?void 0:r(),m=a(c),u=c.startsWith("http")?new URL(m):new URL(m,typeof window<"u"?window.location.origin:"http://localhost");return d&&u.searchParams.set("token",d),!c.startsWith("http")&&!t?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function i(c,d={}){const m={"Content-Type":"application/json",...d.headers||{}},u=r==null?void 0:r();u&&(m.Authorization=`Bearer ${u}`);const p=a(c),f=new AbortController,y=setTimeout(()=>f.abort(),15e3);try{const g=await fetch(p,{...d,headers:m,signal:f.signal});if(g.status===401)throw n==null||n(),new Error("Unauthorized");if(!g.ok){const x=await g.json().catch(()=>({error:g.statusText}));throw new Error(x.error||`API Error: ${g.status}`)}return g.json()}finally{clearTimeout(y)}}return{getDaemons:()=>i("/api/v1/daemons"),getDaemonStatus:c=>i(`/api/v1/daemons/${c}/status`),sendCommand:(c,d,m={})=>i(`/api/v1/daemons/${c}/command`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),execTerminal:(c,d,m)=>i(`/api/v1/daemons/${c}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:m})}),sendAgentMessage:(c,d,m)=>i(`/api/v1/shortcuts/${c}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:m})}),getAgentStatus:c=>i(`/api/v1/shortcuts/${c}/status`),approveAgent:(c,d,m)=>i(`/api/v1/shortcuts/${c}/approve`,{method:"POST",body:JSON.stringify({agentType:d,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,d,m={})=>i(`/api/v1/mux/${encodeURIComponent(c)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),getMuxEventsUrl:c=>o(`/api/v1/mux/${encodeURIComponent(c)}/events`),getRuntimeEventsUrl:c=>o(`/api/v1/runtime/${encodeURIComponent(c)}/events`),request:i}}const Up=Uc({baseUrl:"http://localhost:3847"}),zp=l.createContext(Up);function Gp({client:e,children:t}){return s.jsx(zp.Provider,{value:e,children:t})}const Vp={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},zc=l.createContext(Vp);function qp({value:e,children:t}){return s.jsx(zc.Provider,{value:e,children:t})}function it(){return l.useContext(zc)}function Gc(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function Yp(e){const t=Gc(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 Xp(e){const[t,r]=l.useState(null),n=l.useCallback(async(i,c)=>{const d=p=>e(i,"launch_cli",{...c,...p}),m=await d({}),u=Yp(m);return u?new Promise(p=>{r({providerType:u.providerType||String(c.cliType??"?"),sourceName:u.sourceName,description:u.description,retry:()=>d({confirmExternalUntrusted:!0}),resolve:f=>{f.cancelled?p({success:!1,error:"user_cancelled_untrusted_launch"}):p(f.response)}})}):m},[e]),a=l.useCallback(async()=>{const i=t;if(i){r(null);try{const c=await i.retry(),d=Gc(c);d!=null&&d.success?i.resolve({ok:!0,response:c}):i.resolve({ok:!1,error:(d==null?void 0:d.error)||"launch failed after confirm",response:c})}catch(c){i.resolve({ok:!1,error:(c==null?void 0:c.message)||String(c)})}}},[t]),o=l.useCallback(()=>{const i=t;i&&(r(null),i.resolve({ok:!1,cancelled:!0}))},[t]);return{launchCli:n,pending:t,confirm:a,cancel:o}}function Jp({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 Vc=l.createContext(null);function Qp({sendDaemonCommand:e,children:t}){const r=Xp(e),n=l.useMemo(()=>({launchCli:r.launchCli}),[r.launchCli]);return s.jsxs(Vc.Provider,{value:n,children:[t,r.pending&&s.jsx(Jp,{providerType:r.pending.providerType,sourceName:r.pending.sourceName,description:r.pending.description,onConfirm:r.confirm,onCancel:r.cancel})]})}function na(){const e=l.useContext(Vc);return e||{launchCli:async()=>{throw new Error("useLaunchCli must be used inside <LaunchCliProvider>")}}}function Zp(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 th(e){return e?Zp([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),eh(e.content)]):""}const Ee={size:18};function qc({size:e=Ee.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 zo({size:e=Ee.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 as({size:e=Ee.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 Yc({size:e=Ee.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 sh({size:e=Ee.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 rh({size:e=Ee.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 Xc({size:e=Ee.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 nh({size:e=Ee.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 aa({size:e=Ee.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 Jc({size:e=Ee.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 ah({size:e=Ee.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 Ns({size:e=Ee.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 Ft({size:e=Ee.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 Go({size:e=Ee.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=Ee.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 oa({size:e=Ee.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=Ee.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=Ee.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 Jt({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"5",r:"2"}),s.jsx("circle",{cx:"5",cy:"19",r:"2"}),s.jsx("circle",{cx:"19",cy:"19",r:"2"}),s.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),s.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),s.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function oh({size:e=Ee.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 Qc({size:e=Ee.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 Vo({size:e=Ee.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 Zc({size:e=Ee.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 ih({size:e=Ee.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 qo({size:e=Ee.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 lh({size:e=Ee.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 ed({size:e=Ee.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 td({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function yt({size:e=Ee.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 ch({size:e=Ee.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 dh({size:e=Ee.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),s.jsx("path",{d:"M12 2v6"}),s.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function uh({size:e=Ee.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 mh({size:e=Ee.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 $r({size:e=Ee.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 ph({size:e=Ee.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 hh({size:e=Ee.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 fh({size:e=Ee.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 sd({size:e=Ee.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 xh({size:e=Ee.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 bh({size:e=Ee.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 gh({size:e=Ee.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 yh({size:e=Ee.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 vh({size:e=Ee.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 wh({size:e=Ee.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 jh({size:e=Ee.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 kh({size:e=Ee.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 rd="adhdev_chat_activity_visible",Vi=new Set(["hidden","debug","internal"]),qi=new Set(["visible","user","chat"]),Sh=new Set(["debug","trace","internal"]),Nh=new Set(["tool_call","terminal_command","runtime_activity"]),Ch=new Set(["runtime_status","provider_chrome","control"]),Ih=new Set(["thought","tool","terminal"]);function nd(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Ts(e){return typeof e=="string"?e.trim().toLowerCase():""}function ga(e,t,r){return e[r]??(t==null?void 0:t[r])}function Yi(e,t,r){const n=e;return r.some(a=>n[a]===!0||(t==null?void 0:t[a])===!0)}function Mh(e,t){const r=Ts(e.kind);return r||(t==="tool"?"tool":"standard")}function ya(e,t,r){const n=nd(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 Ah(e){const t=e.content;return Array.isArray(t)&&t.some(r=>!!r&&typeof r=="object"&&r.type!=="text")}function Yo(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=nd(e),r=Ts(e.role),n=Mh(e,r),a=Ts(ga(e,t,"visibility")),o=Ts(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),i=Ts(ga(e,t,"audience")),c=Ts(ga(e,t,"source")),d=Vi.has(a)||Vi.has(o)||Sh.has(i)||Yi(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),m=qi.has(a)||qi.has(o)||i==="chat"||Yi(e,t,["userFacing"]),u=Ih.has(n)||Nh.has(c);if(d)return{surface:u?"activity":"internal",isUserFacing:!1,isActivityFacing:u,isInternal:!u,role:r,kind:n,label:ya(e,n,c)};if(m)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:ya(e,n,c)};if((r==="system"||n==="system")&&Ah(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:"Chat"};if(Ch.has(c)||r==="system"||n==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:r,kind:n,label:"Internal"};if(u)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:r,kind:n,label:ya(e,n,c)};const p=(r==="user"||r==="human"||r==="assistant")&&(n==="standard"||n==="");return{surface:p?"chat":"internal",isUserFacing:p,isActivityFacing:!1,isInternal:!p,role:r,kind:n,label:p?"Chat":"Internal"}}function Th(e){return(Array.isArray(e)?e:[]).filter(t=>Yo(t).isUserFacing)}function ad(e){return(Array.isArray(e)?e:[]).filter(t=>Yo(t).isActivityFacing)}function _h(e,t,r){return!r||t.length===0?e:[...e,...t].sort((n,a)=>{const o=Number(n.receivedAt??n.timestamp??0)||0,i=Number(a.receivedAt??a.timestamp??0)||0;if(o!==i)return o-i;const c=Number(n.index??0)||0,d=Number(a.index??0)||0;return c-d})}function Xi(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(rd))==="1"}catch{return!1}}const od=[ap,{singleTilde:!1}],id=[od,op,ip],Lh=[od],Xo=200,Ph=80,Ji=650,Js=new Map;function En(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function Rh(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}:${th(n)}`}function Dh(e,t,r,n){return e||!t?!1:En(r,n)}function $h({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=Ph,bottomThresholdPx:a=Xo}){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 Eh(e){return $h({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function hr(e,t=Xo){return!!e&&e.fromBottom>=t}function Bh(e,t){return En(e,t)?!hr(e):!0}function Oh({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function Fh({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function va(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function ld(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Hh(e,t,r){return Number(e.receivedAt||r[Bn(e,t)]||0)||0}function cd(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Wh(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 wa(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 tn(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 Qi(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):cd(e)?s.jsx(Wo,{remarkPlugins:id,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:Qi(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=wa(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:tn("Image",o,r.mimeType)},`image-fallback-${n}`)}if(r.type==="audio"){const a=wa(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:tn("Audio",Qs(r.uri,"audio"),r.transcript||r.mimeType)},`audio-fallback-${n}`)}if(r.type==="video"){const a=wa(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"}):tn("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}):tn("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}),Qi(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 Bn(e,t){const r=e,n=Uo(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 Kh=l.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(Wo,{remarkPlugins:Lh,children:t.text}),s.jsx("span",{className:"action-time",children:ld(t.timestamp)})]})},(e,t)=>e.log===t.log),Uh=l.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:i,onToggleTextExpanded:c}){var N,S,T;const d=(t.role||"").toLowerCase(),m=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),p=Yo(t),f=Wh(t.content)?t.content:null,y=!!(f!=null&&f.some(_=>_.type!=="text")),g=Uo(t.content,{joiner:`
6
+ `});if(p.isActivityFacing&&u!=="thought"&&u!=="tool"&&u!=="terminal"){const _=p.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:_})]}),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:g})]})}if(u==="thought"){const _=typeof((N=t.meta)==null?void 0:N.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":p.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(uh,{size:13}),s.jsx("span",{children:_})]}),s.jsx("div",{className:"chat-msg-body",children:g})]})}if(u==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":p.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:g})]});if(u==="terminal"){const _=(S=t.meta)!=null&&S.isRunning?"⏳":"✅",L=typeof((T=t.meta)==null?void 0:T.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":p.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:_}),s.jsx("span",{children:L})]}),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:g})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:y&&f?s.jsx(Zs,{parts:f,renderAsPreformatted:!1}):g.slice(0,100)});const x=t.meta,j=(typeof(x==null?void 0:x.renderMode)=="string"?x.renderMode.trim():"")==="preformatted",h=g,v=!1,I=h,w=j,b=!m&&!w&&cd(I),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:(h||y||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${h||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:ld(r)})]}),(h||y)&&s.jsx("div",{className:"chat-markdown",children:y&&f?s.jsx(Zs,{parts:f,renderAsPreformatted:w}):w?s.jsx("pre",{className:"chat-preformatted",children:I}):b?s.jsx(Wo,{remarkPlugins:id,children:I}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:I})}),v]})})},(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),zh=l.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:o=!1,isWorking:i=!1,contextKey:c="",receivedAtMap:d={},lastMessageHash:m,showActivityMessages:u=!1,emptyState:p,onLoadMore:f,isLoadingMore:y,hasMoreHistory:g,hiddenLiveCount:x=0,loadError:k,scrollToBottomRequestNonce:j,isVisible:h=!0},v){const I=l.useRef(null),w=l.useRef(null),b=l.useRef(null),C=l.useRef(0),N=l.useRef(""),S=l.useRef(""),T=l.useRef(!1),_=l.useRef(null),L=l.useRef(!1),M=l.useRef(null),A=l.useRef(!1),[H,P]=l.useState(new Set),[D,O]=l.useState({showTop:!1,showBottom:!1}),R=l.useRef(!1),B=l.useRef(!1),E=l.useRef(h),F=l.useRef(h),Q=l.useRef(null);F.current=h;const Z=()=>{const q=I.current;return q?q.scrollHeight-q.scrollTop-q.clientHeight<Xo:!0},Y=l.useCallback(()=>{const q=I.current,$=q?Eh(q):{showTop:!1,showBottom:!1};O(re=>re.showTop===$.showTop&&re.showBottom===$.showBottom?re:$)},[]),te=l.useCallback((q="auto")=>{var re;const $=I.current;$&&($.scrollTo({top:$.scrollHeight,behavior:q}),(re=$.ownerDocument.defaultView)==null||re.requestAnimationFrame(()=>Y()))},[Y]),fe=l.useCallback((q="auto")=>{var re;const $=I.current;$&&($.scrollTo({top:0,behavior:q}),(re=$.ownerDocument.defaultView)==null||re.requestAnimationFrame(()=>Y()))},[Y]),Ne=l.useCallback(()=>{var je;const q=I.current,$=(je=window.getSelection)==null?void 0:je.call(window);if(!q||!$||$.rangeCount===0||$.isCollapsed){A.current=!1;return}const re=$.anchorNode,xe=$.focusNode;A.current=!!(re&&xe&&q.contains(re)&&q.contains(xe))},[]),X=l.useMemo(()=>{const q=Th(t),$=ad(t);return _h(q,$,u)},[t,u]),we=X.length===t.length?m:void 0,ge=Rh(X,we),be=l.useCallback(()=>{const q=I.current;if(!q||!c||!F.current)return;const $={top:q.scrollTop,fromBottom:Math.max(0,q.scrollHeight-q.scrollTop-q.clientHeight),messageFingerprint:ge};Q.current={contextKey:c,snapshot:$},Js.set(c,$)},[c,ge]),de=l.useCallback((q="auto")=>{_.current!=null&&cancelAnimationFrame(_.current),_.current=requestAnimationFrame(()=>{_.current=null,te(q)})},[te]),Ie=l.useCallback(()=>{R.current=!1,L.current=!0,B.current=!0,M.current!=null&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{L.current=!1,M.current=null},Ji)},[]);l.useEffect(()=>{const q=!T.current,$=S.current!==c;if(S.current=c,q||$){T.current=!0;const xe=c?Js.get(c):null,je=!!xe&&En(xe,ge);R.current=je?hr(xe):!1,L.current=Bh(xe,ge),A.current||(je?requestAnimationFrame(()=>{const ae=I.current;ae&&(va(ae,xe),R.current=hr(xe),Y(),B.current=!0)}):de("auto")),C.current=X.length,N.current=ge;return}X.length>C.current;const re=ge!==N.current;Oh({hasSelection:A.current,userScrolledUp:R.current,hasChatContentChanged:re})&&de("auto"),C.current=X.length,N.current=ge},[ge,c,X.length,de,Y]),l.useEffect(()=>{j&&(Ie(),A.current||de("auto"))},[Ie,de,j]),l.useEffect(()=>{const q=E.current;q&&!h&&be(),F.current=h,E.current=h;const $=c?Js.get(c):null;if(Dh(q,h,$,ge)){if(!$)return;R.current=hr($),L.current=!1,A.current||requestAnimationFrame(()=>{const re=I.current;re&&(va(re,$),Y())});return}},[h,c,ge,Ie,be,de,Y]),l.useEffect(()=>()=>{const q=Q.current;q&&Js.set(q.contextKey,q.snapshot),_.current!=null&&cancelAnimationFrame(_.current),M.current!=null&&window.clearTimeout(M.current)},[]),l.useEffect(()=>{const q=w.current,$=I.current;if(!q||!$)return;const re=()=>{M.current!=null&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{L.current=!1,M.current=null},Ji)},xe=new ResizeObserver(()=>{Y();const je=L.current;Fh({hasSelection:A.current,userScrolledUp:R.current,contextAutoScrollActive:je})&&(de("auto"),je&&re())});return xe.observe(q),$!==q&&xe.observe($),()=>{xe.disconnect(),M.current!=null&&(window.clearTimeout(M.current),M.current=null)}},[de,c,Y]),l.useImperativeHandle(v,()=>({scrollToBottom:(q="smooth")=>{te(q)}}),[te]),l.useEffect(()=>{const q=I.current;if(!q)return;let $;const re=()=>{be(),clearTimeout($),$=setTimeout(()=>{R.current=!Z(),Y()},50)};return q.addEventListener("scroll",re,{passive:!0}),()=>{q.removeEventListener("scroll",re),clearTimeout($)}},[be,Y]),l.useEffect(()=>(document.addEventListener("selectionchange",Ne),()=>document.removeEventListener("selectionchange",Ne)),[Ne]);const ee=l.useRef(0),ve=l.useRef(!1);l.useEffect(()=>{const q=I.current;if(!q||!ve.current||ee.current===0)return;const $=q.scrollHeight-ee.current;$>0&&(q.scrollTop=$),Y(),be(),ee.current=0,ve.current=!1},[X.length,be,Y]),l.useEffect(()=>{if(B.current||!c)return;const q=Js.get(c),$=I.current;if(!(!q||!$)){if(!En(q,ge)){te("auto"),B.current=!0;return}va($,q),R.current=hr(q),Y(),B.current=!0}},[c,ge,X.length,te,Y]);const ce=()=>{const q=I.current;q&&(ee.current=q.scrollHeight),ve.current=!0,f==null||f()},W=()=>{R.current=!0,fe("smooth"),be()},ne=()=>{Ie(),te("smooth"),be()},ue=l.useMemo(()=>{const q=X.map((je,ae)=>({type:"message",data:je,index:ae,ts:Hh(je,ae,d)}));if(!r||r.length===0)return q;const $=[...r].sort((je,ae)=>je.timestamp-ae.timestamp).map((je,ae)=>({type:"action",data:je,index:ae,ts:je.timestamp})),re=[];let xe=0;for(const je of q){for(;xe<$.length&&je.ts>0&&$[xe].ts<je.ts;)re.push($[xe++]);re.push(je)}for(;xe<$.length;)re.push($[xe++]);return re},[X,r,d]),me=x>0||!!g,J=x>0?`↑ Show ${Math.min(x,80)} earlier messages${x>80?` (${x} hidden)`:""}`:k?`↻ ${k}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:I,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:w,className:"chat-container-content",children:[y&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),me&&!y&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:ce,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${k&&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:J})}),ue.length===0&&!me&&(p||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),ue.map(q=>{if(q.type==="action"){const $e=q.data;return s.jsx(Kh,{log:$e},`action-${q.index}`)}const $=q.data,re=q.index,xe=Bn($,re),je=$.receivedAt||d[xe],ae=`${c}-${xe}`,Pe=H.has(ae);return s.jsx(Uh,{message:$,receivedAt:je,agentName:n,userName:a,isCliMode:o,isTextExpanded:Pe,onToggleTextExpanded:()=>P($e=>{const Re=new Set($e);return Pe?Re.delete(ae):Re.add(ae),Re})},`msg-${xe}`)}),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:b})]})}),(D.showTop||D.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[D.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:W,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),D.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:ne,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Gh=l.memo(zh,(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),Vh="modulepreload",qh=function(e){return"/"+e},Zi={},Yh=function(t,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),c=(i==null?void 0:i.nonce)||(i==null?void 0:i.getAttribute("nonce"));a=Promise.allSettled(r.map(d=>{if(d=qh(d),d in Zi)return;Zi[d]=!0;const m=d.endsWith(".css"),u=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const p=document.createElement("link");if(p.rel=m?"stylesheet":Vh,m||(p.as="script"),p.crossOrigin="",p.href=d,c&&p.setAttribute("nonce",c),document.head.appendChild(p),m)return new Promise((f,y)=>{p.addEventListener("load",f),p.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return a.then(i=>{for(const c of i||[])c.status==="rejected"&&o(c.reason);return t().catch(o)})};let el=!1;const dd=l.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:o="measured"},i)=>{const c=l.useRef(null),[d,m]=l.useState(null),u=l.useRef([]),p=l.useRef(!1),f=l.useRef(!1),y=l.useRef(!1),g=l.useRef(!1),x=()=>{const k=c.current;if(k){p.current&&(k.clear(),p.current=!1);for(const j of u.current)k.write(j.data,j.onProcessed);u.current=[],f.current&&(k.fit(),f.current=!1),y.current&&(k.bumpResize(),y.current=!1),g.current&&(k.scrollToTop(),g.current=!1)}};return l.useImperativeHandle(i,()=>({write:(k,j)=>{c.current?c.current.write(k,j):u.current.push({data:k,onProcessed:j})},clear:()=>{c.current?c.current.clear():(u.current=[],p.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(u.current=[],p.current=!0)},resize:(k,j)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(k,j)},fit:()=>{c.current?c.current.fit():f.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():y.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():g.current=!0},getSelection:()=>{var k,j;return((j=(k=c.current)==null?void 0:k.getSelection)==null?void 0:j.call(k))||""},getVisibleText:()=>{var k,j;return((j=(k=c.current)==null?void 0:k.getVisibleText)==null?void 0:j.call(k))||""}}),[]),l.useEffect(()=>{d&&x()},[d]),l.useEffect(()=>{let k=!1;return Yh(()=>import("./terminal-DN8I8rbd.js"),__vite__mapDeps([0,1,2])).then(j=>{el||(el=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),k||m(()=>j.GhosttyTerminalView)}).catch(j=>{console.error("[CliTerminal] failed to load terminal renderer",j)}),()=>{k=!0}},[]),d?s.jsx(d,{ref:c,onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:o,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});dd.displayName="CliTerminal";function sn({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 tl({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 Xh({cursorPos:e,viewportRef:t,imgRef:r}){var h;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(h=t.current)==null?void 0:h.getBoundingClientRect();if(!o)return null;const i=n.naturalWidth||a.width,c=n.naturalHeight||a.height,d=i/c,m=a.width/a.height;let u,p,f,y;d>m?(u=a.width,p=a.width/d,f=0,y=(a.height-p)/2):(p=a.height,u=a.height*d,f=(a.width-u)/2,y=0);const g=a.left-o.left+f+u*e.nx,x=a.top-o.top+y+p*e.ny,k=Math.max(8,Math.min(o.width-8,g)),j=Math.max(8,Math.min(o.height-8,x));return s.jsxs("div",{style:{position:"absolute",left:k-8,top:j-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 Jh({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:i,setImeText:c,handleImeSubmit:d,isConnActive:m,zoom:u,isMobile:p,mobileFillZoom:f,onZoomOut:y,onZoomReset:g,onZoomIn:x,transportType:k,screenshotUsage:j,lastActionStatus:h}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:v=>v.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[s.jsxs("div",{onClick:t,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{n(v=>!v),o(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&s.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:s.jsx("input",{type:"text",placeholder:"Type & Enter...",value:i,autoFocus:!0,onTouchStart:v=>v.stopPropagation(),onChange:v=>c(v.target.value),onKeyDown:v=>{d(v)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{o(v=>!v),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background: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"})]}),u>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),k==="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"}),k==="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"}),j&&j.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:j.budgetExhausted?"#ef4444":"#c4b5fd",background:j.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:j.budgetExhausted?"TURN blocked":`TURN ${j.dailyUsedMinutes}/${j.dailyBudgetMinutes}m`}),h&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:h})]})]}),a&&s.jsxs("div",{onTouchStart:v=>v.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",u<=(p?f:1)+.01?p?"FILL":"FIT":`${Math.round(u*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:v=>{v.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:v=>{v.stopPropagation(),g()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:p?"FILL":"FIT"}),s.jsx("button",{onClick:v=>{v.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 Qh({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 Zh(){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 sl(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 Er(e,t){const r=l.useRef(null),n=l.useRef(0);l.useEffect(()=>{if(!Zh())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,sl(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,sl(t[i])]))}),r.current=t})}function ef({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:i,panXRef:c,panYRef:d,setPanX:m,setPanY:u,setZoom:p,lastWheelTimeRef:f,onAction:y,setLastActionStatus:g,spawnRippleFromNormalized:x,clampPan:k,isMobile:j,mobileFillZoom:h}){const[v,I]=l.useState(null),w=l.useRef(null),b=l.useRef(null),C=l.useRef(null),N=l.useRef(!1),S=l.useRef(null),T=l.useRef(0),_=l.useRef(null),L=l.useRef(1),M=l.useRef({x:0,y:0}),A=l.useRef(!1),H=l.useRef(n),P=l.useRef(y),D=30,O=550,R=18,B=60,E=400,F=12,Q=()=>{if(w.current)return;const te={nx:.5,ny:.5};w.current=te,I(te)};return l.useEffect(()=>{H.current=n,n==="mouse"&&Q()},[n]),l.useEffect(()=>{P.current=y},[y]),l.useEffect(()=>{const te=e.current;if(!te)return;const fe=de=>{if(!r.current)return null;const Ie=r.current.getBoundingClientRect();return!Ie.width||!Ie.height?null:{nx:Math.max(0,Math.min(1,(de.clientX-Ie.left)/Ie.width)),ny:Math.max(0,Math.min(1,(de.clientY-Ie.top)/Ie.height))}},Ne=(de,Ie)=>{if(!r.current)return{dnx:0,dny:0};const ee=r.current,ve=ee.getBoundingClientRect(),ce=ee.naturalWidth||ve.width,W=ee.naturalHeight||ve.height,ne=ce/W,ue=ve.width/ve.height;let me,J;return ne>ue?(me=ve.width,J=ve.width/ne):(J=ve.height,me=ve.height*ne),{dnx:de/me,dny:Ie/J}},X=(de,Ie,ee)=>{if(ee<=1.05)return;const ve=-(de-.5)*100,ce=-(Ie-.5)*100,W=k(ve,ce,ee);(Math.abs(W.x-c.current)>.1||Math.abs(W.y-d.current)>.1)&&(m(W.x),u(W.y),c.current=W.x,d.current=W.y)},we=de=>{const Ie=t.current;if(Ie&&de.target instanceof Node&&Ie.contains(de.target))de.preventDefault();else return;if(de.touches.length===1){const ee=de.touches[0];b.current={x:ee.clientX,y:ee.clientY,time:Date.now()},C.current={x:ee.clientX,y:ee.clientY},A.current||(N.current=!1),S.current=setTimeout(()=>{if(!N.current&&!A.current)if(N.current=!0,H.current==="mouse"){const ve=w.current||{nx:.5,ny:.5};g("Right Click"),x(ve.nx,ve.ny,"right"),P.current("input_click",{...ve,button:"right"}).catch(()=>{})}else{const ve=fe(ee);ve&&(g("Right Click"),x(ve.nx,ve.ny,"right"),P.current("input_click",{...ve,button:"right"}).catch(()=>{}))}},500);return}if(de.touches.length===2){S.current&&clearTimeout(S.current),N.current=!0,A.current=!0;const ee=de.touches[1].clientX-de.touches[0].clientX,ve=de.touches[1].clientY-de.touches[0].clientY;_.current=Math.sqrt(ee*ee+ve*ve),L.current=i.current,M.current={x:(de.touches[0].clientX+de.touches[1].clientX)/2,y:(de.touches[0].clientY+de.touches[1].clientY)/2}}},ge=de=>{const Ie=t.current;if(Ie&&de.target instanceof Node&&Ie.contains(de.target)&&de.preventDefault(),de.touches.length===1&&C.current){const ee=de.touches[0],ve=ee.clientX-C.current.x,ce=ee.clientY-C.current.y;if(!N.current&&b.current){const W=ee.clientX-b.current.x,ne=ee.clientY-b.current.y;Math.sqrt(W*W+ne*ne)>8&&(N.current=!0,S.current&&clearTimeout(S.current))}if(N.current)if(H.current==="mouse"){const W=Ne(ve,ce),ne=w.current||{nx:.5,ny:.5},ue=Math.max(0,Math.min(1,ne.nx+W.dnx)),me=Math.max(0,Math.min(1,ne.ny+W.dny));w.current={nx:ue,ny:me},I({nx:ue,ny:me}),g(`Cursor: ${Math.round(ue*100)}%, ${Math.round(me*100)}%`),X(ue,me,i.current);const J=Date.now();J-f.current>=30&&(f.current=J,P.current("input_mouseMoved",{nx:ue,ny:me}).catch(()=>{}))}else if(i.current>1){const W=t.current;if(W){const ne=W.clientWidth,ue=W.clientHeight,me=c.current+ve/ne*100,J=d.current+ce/ue*100,q=k(me,J,i.current);m(q.x),u(q.y),c.current=q.x,d.current=q.y}}else{const W=fe(ee);if(W){const ne=Date.now();ne-f.current>=40&&(f.current=ne,g("Scroll"),P.current("input_wheel",{nx:W.nx,ny:W.ny,deltaX:Math.round(-ve*2.5),deltaY:Math.round(-ce*2.5)}).catch(()=>{}))}}C.current={x:ee.clientX,y:ee.clientY};return}if(de.touches.length===2&&_.current!==null){const ee=de.touches[1].clientX-de.touches[0].clientX,ve=de.touches[1].clientY-de.touches[0].clientY,W=Math.sqrt(ee*ee+ve*ve)/_.current,ne=(de.touches[0].clientX+de.touches[1].clientX)/2,ue=(de.touches[0].clientY+de.touches[1].clientY)/2,me=ne-M.current.x,J=ue-M.current.y,q=Math.abs(W-1)>.03;if(H.current==="mouse"){if(q){const $=Math.max(o,Math.min(5,L.current*W));p($),i.current=$}else if(Math.abs(me)>2||Math.abs(J)>2){const $=w.current||{nx:.5,ny:.5},re=Date.now();re-f.current>=30&&(f.current=re,g("Scroll"),P.current("input_wheel",{nx:$.nx,ny:$.ny,deltaX:Math.round(-me*3),deltaY:Math.round(-J*3)}).catch(()=>{}))}}else{const $=Math.max(o,Math.min(5,L.current*W));p($),i.current=$;const re=t.current;if(re&&$>1){const xe=re.clientWidth,je=re.clientHeight,ae=c.current+me/xe*100,Pe=d.current+J/je*100,$e=k(ae,Pe,$);m($e.x),u($e.y),c.current=$e.x,d.current=$e.y}}M.current={x:ne,y:ue}}},be=de=>{var Ie;if(S.current&&clearTimeout(S.current),_.current=null,de.touches.length===1&&A.current){const ee=de.touches[0];b.current={x:ee.clientX,y:ee.clientY,time:Date.now()},C.current={x:ee.clientX,y:ee.clientY},N.current=!0;return}if(de.touches.length===0){if(A.current){A.current=!1,N.current=!1;return}if(de.changedTouches.length===1){const ee=de.changedTouches[0],ve=Date.now(),ce=ve-(((Ie=b.current)==null?void 0:Ie.time)||0),W=b.current?ee.clientX-b.current.x:0,ne=b.current?ee.clientY-b.current.y:0,ue=Math.sqrt(W*W+ne*ne);if(H.current==="mouse"){if(ce<D||ce>O||ue>R){N.current=!1;return}const me=w.current||fe(ee);me&&(g(`Click: ${Math.round(me.nx*100)}%, ${Math.round(me.ny*100)}%`),x(me.nx,me.ny,"left"),P.current("input_click",{...me}).catch(()=>{}))}else{if(N.current){N.current=!1;return}if(ce<B||ce>E||ue>F){N.current=!1;return}const me=fe(ee);if(!me)return;ve-T.current<300?(g("Double tap"),x(me.nx,me.ny,"double"),P.current("input_click",{...me,clickCount:2}).catch(()=>{}),T.current=0):(g(`Tap: ${Math.round(me.nx*100)}%, ${Math.round(me.ny*100)}%`),x(me.nx,me.ny,"left"),P.current("input_click",{...me}).catch(()=>{}),T.current=ve)}}N.current=!1}};return te.addEventListener("touchstart",we,{passive:!1}),te.addEventListener("touchmove",ge,{passive:!1}),te.addEventListener("touchend",be,{passive:!1}),()=>{te.removeEventListener("touchstart",we),te.removeEventListener("touchmove",ge),te.removeEventListener("touchend",be),S.current&&clearTimeout(S.current)}},[e,t,r,o,i,c,d,m,u,p,f,g,x,k]),{cursorPos:v,cursorPosRef:w,handleToggleInputMode:()=>{a(te=>{const fe=te==="touch"?"mouse":"touch";return fe==="mouse"&&Q(),fe})},handleZoomReset:()=>{const te=j?h:1;p(te),i.current=te,m(0),u(0),c.current=0,d.current=0}}}function ud({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:o}){const i=l.useRef(null),c=l.useRef(null),d=l.useRef(null),[m,u]=l.useState(null),[p,f]=l.useState(""),[,y]=l.useState(!1),[g,x]=l.useState([]),k=l.useRef(0),[j,h]=l.useState(!1),[v,I]=l.useState(!1),w=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[b,C]=l.useState(w?"mouse":"touch"),[N,S]=l.useState(1),T=l.useRef(!1),[_,L]=l.useState(1),[M,A]=l.useState(0),[H,P]=l.useState(0);Er("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:b,zoom:_,panX:M,panY:H,isMenuOpen:j,isImeOpen:v});const D=l.useRef(0),O=l.useRef(_),R=l.useRef(M),B=l.useRef(H);l.useEffect(()=>{O.current=_},[_]),l.useEffect(()=>{R.current=M},[M]),l.useEffect(()=>{B.current=H},[H]),l.useEffect(()=>{var ce;(ce=i.current)==null||ce.focus()},[]);const E=r==="connected",F=n,Q=E?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",Z=E?"The remote stream is warming up":"Waiting for the remote stream to catch up";l.useEffect(()=>{if(!w||T.current||!F)return;const ce=d.current,W=c.current;if(!ce||!W)return;const ne=()=>{const ue=W.clientWidth,me=W.clientHeight,J=ce.naturalWidth,q=ce.naturalHeight;if(!J||!q||!ue||!me)return;const $=Math.min(ue/J,me/q),xe=Math.max(ue/J,me/q)/$;xe>1.01&&(S(xe),L(xe),O.current=xe),T.current=!0};ce.complete&&ce.naturalWidth?ne():ce.addEventListener("load",ne,{once:!0})},[F,w]);const Y=.5;l.useEffect(()=>{_<=Y&&(A(0),P(0))},[_,Y]);const te=(ce,W,ne)=>{if(ne<=Y)return{x:0,y:0};const ue=(ne-1)/(2*ne)*100,me=(ne-1)/(2*ne)*100;return{x:Math.max(-ue,Math.min(ue,ce)),y:Math.max(-me,Math.min(me,W))}},fe=(ce,W)=>{if(!d.current)return null;const ne=d.current.getBoundingClientRect();return!ne.width||!ne.height?null:{nx:Math.max(0,Math.min(1,(ce-ne.left)/ne.width)),ny:Math.max(0,Math.min(1,(W-ne.top)/ne.height))}},Ne=(ce,W,ne)=>{const ue=c.current;if(!ue)return;const me=ue.getBoundingClientRect(),J=++k.current;x(q=>[...q,{id:J,x:ce-me.left,y:W-me.top,type:ne}]),setTimeout(()=>x(q=>q.filter($=>$.id!==J)),600)},X=(ce,W,ne)=>{const ue=d.current,me=c.current;if(!ue||!me)return;const J=ue.getBoundingClientRect(),q=me.getBoundingClientRect(),$=ue.naturalWidth||J.width,re=ue.naturalHeight||J.height,xe=$/re,je=J.width/J.height;let ae,Pe,$e,Re;xe>je?(ae=J.width,Pe=J.width/xe,$e=0,Re=(J.height-Pe)/2):(Pe=J.height,ae=J.height*xe,$e=(J.width-ae)/2,Re=0);const Ge=J.left-q.left+$e+ae*ce,Ye=J.top-q.top+Re+Pe*W,Xe=++k.current;x(at=>[...at,{id:Xe,x:Ge,y:Ye,type:ne}]),setTimeout(()=>x(at=>at.filter(Je=>Je.id!==Xe)),600)},we=async ce=>{var ne;const W=fe(ce.clientX,ce.clientY);if(W){u(`Click: ${Math.round(W.nx*100)}%, ${Math.round(W.ny*100)}%`),Ne(ce.clientX,ce.clientY,"left"),(ne=i.current)==null||ne.focus();try{const ue=await e("input_click",{nx:W.nx,ny:W.ny});ue!=null&&ue.success||t(`❌ Click failed: ${ue==null?void 0:ue.error}`)}catch(ue){t(`❌ Click error: ${ue.message||ue}`)}}},ge=async(ce,W,ne,ue=0)=>{try{await e("input_key",{type:ne?"char":"keyDown",key:ce,code:W,text:ne?ce:void 0,unmodifiedText:ne?ce:void 0,modifiers:ue})}catch(me){t(`❌ Key error: ${me.message||me}`)}},be=async ce=>{if(ce.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ce.key)&&ce.preventDefault();let ne=0;ce.altKey&&(ne|=1),ce.ctrlKey&&(ne|=2),ce.metaKey&&(ne|=4),ce.shiftKey&&(ne|=8),u(`Key: ${ce.key}`),await ge(ce.key,ce.code,ce.key.length===1,ne)},de=async ce=>{if(ce.key==="Enter"){if(ce.nativeEvent.isComposing)return;if(p){const W=p;f(""),u(`IME Sent: ${W}`);try{const ne=await e("input_type",{text:W});ne!=null&&ne.success||t(`❌ IME error: ${ne==null?void 0:ne.error}`)}catch(ne){t(`❌ IME error: ${ne.message}`)}}else u("Key: Enter"),await ge("Enter","Enter",!1)}};l.useEffect(()=>{const ce=i.current;if(!ce)return;const W=ne=>{var ue;if((ue=d.current)!=null&&ue.contains(ne.target)){ne.preventDefault();const me=Date.now();if(me-D.current<40)return;D.current=me;const J=fe(ne.clientX,ne.clientY);if(!J)return;u(`Scroll: ${Math.round(ne.deltaY)}`),e("input_wheel",{nx:J.nx,ny:J.ny,deltaX:Math.round(ne.deltaX),deltaY:Math.round(ne.deltaY)}).catch(()=>{})}};return ce.addEventListener("wheel",W,{passive:!1}),()=>ce.removeEventListener("wheel",W)},[e]);const{cursorPos:Ie,handleToggleInputMode:ee,handleZoomReset:ve}=ef({containerRef:i,viewportRef:c,imgRef:d,inputMode:b,setInputMode:C,minZoom:Y,zoomRef:O,panXRef:R,panYRef:B,setPanX:A,setPanY:P,setZoom:L,lastWheelTimeRef:D,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:X,clampPan:te,isMobile:w,mobileFillZoom:N});return s.jsxs("div",{ref:i,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:be,onContextMenu:ce=>ce.preventDefault(),onFocus:()=>y(!0),onBlur:()=>y(!1),tabIndex:0,children:[s.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[F?s.jsx("img",{ref:d,src:F,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${_}) translate(${M}%, ${H}%)`,transformOrigin:"center center",cursor:b==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:we,onContextMenu:ce=>ce.preventDefault(),onDragStart:ce=>ce.preventDefault()}):s.jsx(Qh,{waitingLabel:Q,waitingHint:Z,transportType:o}),b==="mouse"&&F&&s.jsx(Xh,{cursorPos:Ie,viewportRef:c,imgRef:d}),g.map(ce=>{const ne={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ce.type];return s.jsxs("div",{style:{position:"absolute",left:ce.x,top:ce.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ne}, 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(${ne}, 0.9)`,boxShadow:`0 0 12px rgba(${ne}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ce.id)})]}),s.jsx(Jh,{inputMode:b,onToggleInputMode:ee,isImeOpen:v,setIsImeOpen:I,isMenuOpen:j,setIsMenuOpen:h,imeText:p,setImeText:f,handleImeSubmit:de,isConnActive:E,zoom:_,isMobile:w,mobileFillZoom:N,onZoomOut:()=>L(ce=>Math.max(.5,ce-.25)),onZoomReset:ve,onZoomIn:()=>L(ce=>Math.min(5,ce+.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 rl(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 tf(e){var t;return rl(e.activeInteractivePrompt)||rl((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function sf(e){return e.sessionId||e.instanceId||e.id}function rf(e,t){const r=typeof t=="string"?t.trim():"";for(const n of e){const a=tf(n);if(!a)continue;const o=sf(n);if(r&&r!==o&&r!==n.id)continue;return{daemonId:n.daemonId||n.id.split(":")[0]||n.id,sessionId:o,routeId:n.id,providerType:n.type,title:n.title||n.cliName||n.type,prompt:a}}return null}function md(e,t){var n;const r={};for(const a of e.questions){const o=t[a.questionId]||{},i=Array.from(new Set((o.selectedLabels||[]).map(d=>d.trim()).filter(Boolean))),c=(n=o.freeformText)==null?void 0:n.trim();r[a.questionId]={selectedLabels:i,...c?{freeformText:c}:{}}}return{promptId:e.promptId,answers:r}}function nl(e){const t={};for(const r of(e==null?void 0:e.prompt.questions)||[])t[r.questionId]={selectedLabels:[],freeformText:""};return t}function al(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 nf({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(sd,{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 pd({promptSession:e,isSubmitting:t=!1,error:r,onSubmit:n,onCancel:a}){var C;const[o,i]=l.useState(()=>nl(e)),[c,d]=l.useState(0);l.useEffect(()=>{i(nl(e)),d(0)},[e==null?void 0:e.prompt.promptId]);const m=(e==null?void 0:e.prompt.questions)||[],u=m.length,p=c===u-1,f=u===1,y=m[c],g=y?o[y.questionId]:void 0,x=y?al(y,g):!1,k=l.useMemo(()=>e?e.prompt.questions.every(N=>al(N,o[N.questionId])):!1,[e,o]);if(!e)return null;const j=(N,S)=>{i(T=>{const _=T[N.questionId]||{selectedLabels:[]},L=_.selectedLabels||[],M=N.multiSelect?L.includes(S)?L.filter(A=>A!==S):[...L,S]:[S];return{...T,[N.questionId]:{..._,selectedLabels:M}}})},h=(N,S)=>{i(T=>({...T,[N]:{...T[N]||{selectedLabels:[]},freeformText:S}}))},v=()=>{c<u-1&&d(N=>N+1)},I=()=>{c>0&&d(N=>N-1)},w=()=>{!k||t||n(o)},b=md(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.jsxs("div",{className:"flex items-center gap-2",children:[!f&&s.jsxs("span",{className:"text-xs text-text-muted",children:[c+1," / ",u]}),s.jsx("button",{type:"button",onClick:a,className:"btn btn-ghost btn-sm h-8 w-8 p-0","aria-label":"Cancel interactive prompt",children:s.jsx(yt,{size:16})})]})]}),!f&&s.jsx("div",{className:"flex gap-1.5 px-5 pt-3",children:m.map((N,S)=>s.jsx("div",{className:`h-1.5 flex-1 rounded-full transition-colors ${S<c?"bg-accent-primary":S===c?"bg-accent-primary/60":"bg-border-primary"}`},N.questionId))}),s.jsxs("div",{className:"space-y-4 px-5 py-4",children:[y&&s.jsxs("section",{className:"space-y-3",children:[s.jsxs("div",{children:[y.header&&s.jsx("div",{className:"mb-1 text-xs font-semibold uppercase tracking-normal text-text-muted",children:y.header}),s.jsxs("div",{className:"text-sm font-semibold text-text-primary",children:[f?"":`${c+1}. `,y.question]})]}),s.jsx("div",{className:"grid gap-2",children:y.options.map(N=>{var S;return s.jsx(nf,{label:N.label,description:N.description||N.preview,selected:(((S=b.answers[y.questionId])==null?void 0:S.selectedLabels)||[]).includes(N.label),disabled:t,onClick:()=>j(y,N.label)},N.label)})}),y.allowFreeform&&s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-semibold text-text-muted",children:"Other"}),s.jsx("textarea",{value:((C=o[y.questionId])==null?void 0:C.freeformText)||"",disabled:t,onChange:N=>h(y.questionId,N.currentTarget.value),className:"w-full min-h-20 rounded-md border border-border-primary bg-surface-secondary px-3 py-2 text-sm text-text-primary outline-none focus:border-accent-primary"})]})]}),r&&s.jsx("div",{className:"rounded-md border border-status-error/30 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:r})]}),s.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-border-primary px-5 py-4",children:[s.jsx("div",{children:!f&&c>0&&s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:I,disabled:t,children:"Back"})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:a,disabled:t,children:"Cancel"}),f||p?s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:w,disabled:!k||t,children:t?"Submitting...":"Submit"}):s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:v,disabled:!x||t,children:"Next"})]})]})]})})}function ia(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,o=Date.now()-e,i=Math.floor(o/1e3);if(i<a)return n;const c=Math.floor(i/60);if(c<60)return`${c}m${r}`;const d=Math.floor(c/60);if(d<24)return`${d}h${r}`;const m=Math.floor(d/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const hd=e=>ia(e);function af(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 of(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...af(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 On(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 la(e,t,r){const n=On(e,t),a=Gs(e),o=a.isReconnecting,i=a.isConnecting,c=a.isGenerating,d=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d,u=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:u,isReconnecting:o,isConnecting:i,isGenerating:c,isWaiting:d,inboxBucket:m?"needs_attention":u?"working":f?"task_complete":"idle"}}function lf(e,t,r){return la(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function fd({activeConv:e,onModalButton:t}){const[r,n]=l.useState(null);if(l.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!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,d)=>{const m=i(c).toLowerCase(),u=/^(run|approve|accept|yes|allow|always)/.test(m),p=/^(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 ${u?"font-extrabold":p?"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:u?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:p?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)},d)})})]})]})}const Jo="adhdev_controls_bar_visible",vo="adhdev:controlsbarvisibilitychange";function ja(e){if(!e)return!1;try{return e.getItem(Jo)==="1"}catch{return!1}}function cf(e,t){if(t)try{t.setItem(Jo,e?"1":"0")}catch{}}function df(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(vo,{detail:{visible:e}}))}function Qo(){const[e,t]=l.useState(()=>typeof window>"u"?!1:ja(window.localStorage)),r=l.useRef(e),n=l.useCallback((i,c=!0)=>{r.current=i,t(i),typeof window<"u"&&cf(i,window.localStorage),c&&df(i)},[]);l.useEffect(()=>{const i=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:ja(window.localStorage);r.current=u,t(u)},c=d=>{if(d.key!==Jo)return;const m=ja(window.localStorage);r.current=m,t(m)};return window.addEventListener(vo,i),window.addEventListener("storage",c),()=>{window.removeEventListener(vo,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 uf=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function mf(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function Lt(e,t){if(mf(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":r==="waiting_choice"?"waiting_choice":uf.has(r)?"generating":r==="error"?"error":r==="stopped"?"stopped":r==="starting"?"starting":r==="panel_hidden"?"panel_hidden":r==="not_monitored"?"not_monitored":r==="disconnected"?"disconnected":"idle"}function wo(e){return Lt(e)==="generating"}function ol(e,t){return Lt(e,t)==="waiting_approval"}function wt(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function pf(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 ka(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function xd(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 hf(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 ff(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function xf(e){return hf(e.trim().replace(/\.local$/i,""))}function bf(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function bd(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&&!ff(i));if(r&&r!=="Unknown")return xf(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Pt(e,t={}){return bf(e)||bd(e,t)}function gd(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 yd(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 js(e,t){return gd(e).join(" · ")}function Mr(e){return e.transport==="pty"}function Ds(e){return e.transport==="acp"}function gf(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:wt(e)}function il(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),i=wt(r||"").trim().toLowerCase();return n===a||n===o||n===i}function yf(e,t=[],r=[]){var d,m,u,p;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==="waiting_choice")return"waiting_choice";if(n==="generating")return"generating";const a=t.find(f=>ol(f.status,{activeModal:f.activeModal})||wo(f.status));if(a)return Lt(a.status,{activeModal:a.activeModal});const o=r.find(f=>ol(f.status,{activeModal:f.activeModal})||wo(f.status));if(o)return Lt(o.status,{activeModal:o.activeModal});if(n&&n!=="idle")return n;const i=Lt((d=t[0])==null?void 0:d.status,{activeModal:(m=t[0])==null?void 0:m.activeModal});if(i!=="idle")return i;const c=Lt((u=r[0])==null?void 0:u.status,{activeModal:(p=r[0])==null?void 0:p.activeModal});return c!=="idle"?c:"idle"}function vf(e){return Lt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function wf(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,r=["generating","waiting_approval","waiting_choice","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),o=t.get(a),i=Lt(n.status);if(!o){t.set(a,{...n,status:i});continue}const c=r.indexOf(o.status||"idle"),d=r.indexOf(i||"idle");d>=0&&(c<0||d<c)&&t.set(a,{...n,status:i})}return Array.from(t.values())}function jf(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 kf(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&&jf(t.receivedAt)||0}function Sf(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function jo(e){return Math.max(Sf(e),kf(e.activeChat))}function Nf(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 Zo(e,t){return Nf(jo(e),jo(t),Pt(e,{fallbackId:e.id}),Pt(t,{fallbackId:t.id}),e.id,t.id)}const vd="adhdev_notification_prefs",ll={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Cf(){try{const e=localStorage.getItem(vd);if(e){const t=JSON.parse(e);return{...ll,...t}}}catch{}return{...ll}}function If(e){try{localStorage.setItem(vd,JSON.stringify(e))}catch{}}let Yt=Cf(),kn=[];function Mf(){kn.forEach(e=>e())}function Af(e){Yt={...Yt,...e},If(Yt),Mf()}function Tf(){const[,e]=l.useState(0);l.useEffect(()=>{const r=()=>e(n=>n+1);return kn.push(r),()=>{kn=kn.filter(n=>n!==r)}},[]);const t=l.useCallback(r=>{Af(r)},[]);return[{...Yt},t]}function gr(e){if(!Yt.globalEnabled)return!1;switch(e){case"disconnect":return Yt.disconnectAlert;case"completion":return Yt.completionAlert;case"approval":return Yt.approvalAlert;case"browser":return Yt.browserNotifications;default:return!0}}const _f={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function wd(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function jd(){return"Notification"in window&&Notification.permission==="granted"}let ds=null;function Lf(e){return e!==!1}async function Pf(){if(ds!==null)return ds;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return ds=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(ds=!!await e.pushManager.getSubscription(),ds):(ds=!1,!1)}catch{return ds=!1,!1}}function ko(e,t,r){if(jd())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 Rf(e,t={}){const r={..._f,...t},n=l.useRef(new Map),a=l.useRef(0),[o,i]=l.useState(null);l.useEffect(()=>{let d=!1;return Pf().then(m=>{d||i(m)}),()=>{d=!0}},[]);const c=l.useCallback((d,m,u)=>{const p=Date.now();p-a.current<r.throttleMs||(a.current=p,ko(d,m,u))},[r.throttleMs]);l.useEffect(()=>{var d;if(!(!r.enabled||!jd())&&gr("browser")&&!Lf(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 u=n.current.get(m.id),p=Lt(m.status,{activeModal:m.activeModal}),f=m.name||m.id;if(r.onApproval&&gr("approval")&&p==="waiting_approval"&&u!=="waiting_approval"){const y=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${f} — Approval needed`,y.slice(0,120),`approval-${m.id}`)}r.onComplete&&gr("completion")&&wo(u)&&p==="idle"&&c(`✅ ${f} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&p==="error"&&u!=="error"&&c(`⚠️ ${f} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,p)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,c])}const Df=/^(run|approve|accept|yes|allow|always)/,$f=/^(run|approve|accept|yes|allow|always|proceed|save)/,Ef=/^(reject|deny|delete|remove|abort|cancel|no)/;function ei(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Bf(e){const t=ei(e).toLowerCase();return Df.test(t)?"primary":Ef.test(t)?"danger":"default"}function Of(e){return $f.test(ei(e).toLowerCase())?"approve":"reject"}function Ff(e){return e.map((t,r)=>({label:ei(t),variant:Bf(t),action:Of(t),button:t,buttonIndex:r}))}function Hf(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Wf(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 Kf{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 g;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),o=n||t.daemonId||"",i=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),c=`${o}:${t.event}:${i}`;if(this.isDuplicate(c))return;for(const x of this.statusEventCallbacks)x(t);const d=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(d==null?void 0:d.type)||"";let u=wt(m);const p=this.resolveOwningDaemon(t);if(p){const x=Pt(p,{fallbackId:p.id});x&&(u=!m||m==="adhdev-daemon"?x:`${x}/${u}`)}let f="",y="info";if(t.event==="agent:generating_completed"){const x=t.duration?` (${t.duration}s)`:"";f=`✅ ${u} 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=`⚡ ${u} approval needed`,y="warning",(g=t.modalButtons)!=null&&g.length&&this.resolveActionFn){const x=this.resolveActionRouteTarget(t);if(!x)return;const k=this.resolveActionFn,j=Ff(t.modalButtons).map(I=>({label:I.label,variant:I.variant,onClick:()=>{k(x,"resolve_action",{action:I.action,button:I.button,buttonIndex:I.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),h=Hf(u,t.modalMessage,f),v=Date.now();this.emitToast({id:v,message:h,type:y,timestamp:v,targetKey:n||x,actions:j,duration:15e3}),f=""}}else if(t.event==="monitor:long_generating"){const x=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";f=`⚠️ ${u} agent is taking a long time${x}`,y="warning",gr("browser")&&!document.hasFocus()&&ko(`⚠️ ${u} — 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",k=t.requestId,j=t.orgId;if(f=`👁️ ${x} wants to view your session`,y="warning",k&&j&&this.viewRequestRespondFn){const h=Date.now(),v=Wf(j,k,this.viewRequestRespondFn,(I,w)=>console.error(`[EventManager] ${I} view request failed:`,w));this.emitToast({id:h,message:f,type:y,timestamp:h,actions:v,duration:3e4}),f=""}gr("browser")&&!document.hasFocus()&&ko("👁️ View Request",`${x} wants to view your session`,`view-request-${k}`)}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 tt=new Kf,cl=new Map;function Fn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function $s(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function ca(e){return Fn(e)?Fn(e.result)?e.result:e:null}function Uf(e){const t=ca(e);return!t||!Fn(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function rn(e){const t=ca(e);return!t||!Fn(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function er(e){const t=ca(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function nn(e){const t=ca(e);return!!t&&t.success===!1}function zf(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";tt.showToast(n.toast.message,a);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const a=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";tt.showToast(n.notification.body,a)}}}function Gf(e,t){return e&&$s(e.currentValue)?e.currentValue:t}function Vf(e,t){return $s(t)?$s(e)?typeof e=="string"&&e.trim()==="":!0:!1}function qf(e,t){var o,i;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if($s(c))return c}const n=(o=t.controlValues)==null?void 0:o[e];if($s(n))return n;const a=(i=t.defaultValues)==null?void 0:i[e];return $s(a)?a:void 0}function Sn(e,t){return e.options||t[e.id]||[]}const Yf={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 Xf(e,t,r){var n;return((n=Yf[t])==null?void 0:n.has(r.id))===!0}function ti(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Xf(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function Sa(e,t){return{value:t}}function Jf(e,t,r){var a;return r?((a=Sn(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const Qf={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Zf({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:i}){const{sendCommand:c}=it(),d=`${e}:${t||n}`,m=Qf[n]||"#94a3b8",[u,p]=l.useState({}),f=l.useRef({}),y=l.useRef(i);f.current=u,y.current=i;const g=l.useRef(0),x={};for(const D of o||[])D.defaultValue!==void 0&&(x[D.id]=D.defaultValue);const k={...x,...i||{},...Date.now()<g.current?u:{}};l.useEffect(()=>{i&&Date.now()>g.current&&p({})},[i]);const[j,h]=l.useState(cl.get(d)||{}),[v,I]=l.useState(null),[w,b]=l.useState(null),C=l.useCallback(async(D,O={})=>{const R={...O,...t&&{targetSessionId:t}};return await c(e,D,R)},[e,t,c]),N=l.useCallback(async(D,O={})=>{const R=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await C("invoke_provider_script",{...R,scriptName:D,...O})},[C,n,r,t]),S=l.useCallback((D,O,R)=>{const B=Gf(R,O);p(E=>({...E,[D.id]:B})),zf(R==null?void 0:R.effects)},[]),T=l.useCallback((D,O)=>{p(R=>{const B={...R};return O===void 0?delete B[D.id]:B[D.id]=O,B}),g.current=0},[]);if(!o||o.length===0)return null;const _=ti(o,{hostIdeType:r,providerType:n});if(_.length===0)return null;const L=async D=>{if(v===D.id){I(null);return}if(Sn(D,j).length>0){I(D.id);return}if(D.dynamic&&D.listScript){b(D.id);try{const R=await N(D.listScript,{}),B=Uf(R);if(!B){const Q=er(R);Q&&tt.showToast(Q,"warning");return}const E=B.options;h(Q=>{const Z={...Q,[D.id]:E};return cl.set(d,Z),Z});const F=qf(D.id,{localOverrideUntil:g.current,localValues:f.current,controlValues:y.current,defaultValues:x});if(Vf(F,B.currentValue)){const Q=B.currentValue;p(Z=>({...Z,[D.id]:Q}))}I(D.id)}catch(R){const B=R instanceof Error?R.message:`Could not load ${D.label}`;tt.showToast(B,"warning")}finally{b(null)}}},M=async(D,O)=>{I(null);const R=(i==null?void 0:i[D.id])??x[D.id];p(B=>({...B,[D.id]:O})),g.current=Date.now()+5e3;try{if(!D.setScript)return;const B=await N(D.setScript,Sa(D,O)),E=rn(B);if(E&&!E.ok||nn(B))throw new Error((E==null?void 0:E.error)||er(B)||`Could not update ${D.label}`);S(D,O,E)}catch(B){T(D,R);const E=B instanceof Error?B.message:`Could not update ${D.label}`;tt.showToast(E,"warning")}},A=async D=>{const O=Sn(D,j).map(Z=>Z.value);if(O.length===0)return;const R=String(k[D.id]||""),E=(O.indexOf(R)+1)%O.length,F=O[E];if(typeof F!="string")return;const Q=(i==null?void 0:i[D.id])??x[D.id];p(Z=>({...Z,[D.id]:F})),g.current=Date.now()+5e3;try{if(!D.setScript)return;const Z=await N(D.setScript,Sa(D,F)),Y=rn(Z);if(Y&&!Y.ok||nn(Z))throw new Error((Y==null?void 0:Y.error)||er(Z)||`Could not update ${D.label}`);S(D,F,Y)}catch(Z){T(D,Q);const Y=Z instanceof Error?Z.message:`Could not update ${D.label}`;tt.showToast(Y,"warning")}},H=async D=>{const R=!k[D.id],B=(i==null?void 0:i[D.id])??x[D.id];p(E=>({...E,[D.id]:R})),g.current=Date.now()+5e3;try{if(!D.setScript)return;const E=await N(D.setScript,Sa(D,R)),F=rn(E);if(F&&!F.ok||nn(E))throw new Error((F==null?void 0:F.error)||er(E)||`Could not update ${D.label}`);S(D,R,F)}catch(E){T(D,B);const F=E instanceof Error?E.message:`Could not update ${D.label}`;tt.showToast(F,"warning")}},P=async D=>{if(!D.invokeScript)return;if(D.confirmMessage){const R=[D.confirmTitle,D.confirmMessage,D.confirmLabel].filter(E=>typeof E=="string"&&E.trim().length>0);if(!window.confirm(R.join(`
30
+
31
+ `)))return}const O=(i==null?void 0:i[D.id])??x[D.id];try{const R=await N(D.invokeScript),B=rn(R);if(B&&!B.ok||nn(R))throw new Error((B==null?void 0:B.error)||er(R)||`Could not run ${D.label}`);B&&S(D,O??!0,B)}catch(R){T(D,O);const B=R instanceof Error?R.message:`Could not run ${D.label}`;tt.showToast(B,"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}),_.map(D=>{const O=String(k[D.id]||""),R=Jf(D,j,O),B=v===D.id,E=w===D.id,F=Sn(D,j),Q="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium transition-colors whitespace-nowrap";switch(D.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${Q} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:B?`${m}55`:"var(--border-default)",background:B?`${m}10`:"var(--surface-tertiary)",color:O?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void L(D),title:D.label,children:[D.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:D.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:E?"Loading…":R||D.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),B&&F.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>I(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:D.label}),F.map(Z=>s.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-[12px] transition-colors",style:{background:Z.value===O?`${m}14`:"transparent",color:Z.value===O?"var(--text-primary)":"var(--text-secondary)",borderLeft:Z.value===O?`2px solid ${m}`:"2px solid transparent"},title:Z.description||Z.label,onMouseEnter:Y=>{Y.currentTarget.style.background=`${m}10`},onMouseLeave:Y=>{Y.currentTarget.style.background=Z.value===O?`${m}14`:"transparent"},onClick:()=>void M(D,Z.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:Z.label}),Z.value===O&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},Z.value))]})]})]},D.id);case"cycle":return s.jsxs("button",{type:"button",className:`${Q} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:O?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void A(D),title:`Click to cycle: ${F.map(Z=>Z.label).join(" → ")}`,children:[D.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:D.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:R||D.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},D.id);case"toggle":return s.jsxs("button",{type:"button",className:`${Q} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:O?`${m}44`:"var(--border-default)",background:O?`${m}14`:"var(--surface-tertiary)",color:O?m:"var(--text-muted)"},onClick:()=>void H(D),"aria-pressed":!!O,children:[D.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:D.icon}),D.label]},D.id);case"action":return s.jsxs("button",{type:"button",className:`${Q} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void P(D),children:[D.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:D.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:D.resultDisplay==="inline"&&O?`${D.label}: ${O}`:D.label})]},D.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:O?"var(--text-primary)":"var(--text-muted)"},children:[D.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:D.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:O?`${D.label}: ${O}`:D.label})]},D.id);default:return null}})]})})}function ex({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:c,controlValues:d}){const{isVisible:m}=Qo(),u=ti(c,{hostIdeType:a,providerType:o});return!e||t||u.length===0||!m?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(Zf,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:u,controlValues:d})})}const tr=5,kd=10*1024*1024;function tx({hasDraft:e,isBusy:t=!1}){return!e||t}function sx(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 rx(e){if(e.size>kd)return null;const t=await sx(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 nx(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const Sd=l.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,onSend:i,onForceSend:c,canForceSend:d=!1,isActive:m=!0,showControlsToggle:u=!1,animateVisibility:p=!0,onControlsToggle:f,messageInput:y}){const g=l.useRef(null),x=l.useRef(null),[k,j]=l.useState(""),[h,v]=l.useState([]),[I,w]=l.useState(null),[b,C]=l.useState(!1),N=l.useRef(!1),{isVisible:S,toggleVisibility:T}=Qo(),_=nx(y),L=!!k.trim()||h.length>0;l.useEffect(()=>{j(""),v([]),w(null)},[t]),l.useEffect(()=>{var B;m&&((B=g.current)==null||B.focus({preventScroll:!0}))},[t,m]),l.useEffect(()=>{const B=g.current;B&&(B.style.height="auto",B.style.height=`${Math.min(B.scrollHeight,160)}px`)},[k]);const M=l.useCallback(async B=>{w(null);const E=Array.from(B).filter(fe=>fe.type.startsWith("image/"));if(E.length===0)return;const F=tr-h.length;if(F<=0){w(`Max ${tr} images`);return}const Q=E.slice(0,F);if(Q.filter(fe=>fe.size>kd).length>0){w("Image too large (max 10 MB)");return}const te=(await Promise.all(Q.map(rx))).filter(fe=>fe!==null);v(fe=>[...fe,...te])},[h.length]),A=l.useCallback(B=>{v(E=>E.filter((F,Q)=>Q!==B))},[]),H=l.useCallback(async()=>{const B=k.trim();if(!B&&h.length===0||a||N.current)return;N.current=!0;const E=h.length>0?[...h]:void 0;try{await i(B,E)!==!1&&(j(""),v([]),w(null))}finally{N.current=!1}},[k,h,a,i]),P=l.useCallback(async()=>{if(!d||!c)return;const B=k.trim();if(!B&&h.length===0||N.current)return;N.current=!0;const E=h.length>0?[...h]:void 0;try{await c(B,E)!==!1&&(j(""),v([]),w(null))}finally{N.current=!1}},[h,d,k,c]),D=l.useCallback(B=>{_&&(B.preventDefault(),C(!0))},[_]),O=l.useCallback(()=>C(!1),[]),R=l.useCallback(B=>{_&&(B.preventDefault(),C(!1),B.dataTransfer.files.length>0&&M(B.dataTransfer.files))},[_,M]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",p?"transition-all duration-200 ease-out":"",b?"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:D,onDragLeave:O,onDrop:R,children:[h.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:h.map((B,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:B.previewUrl,alt:B.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>A(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 ${B.name}`,children:"✕"})]},E))}),s.jsxs("div",{className:"flex gap-2 items-center",title:m?`Send message to ${r}`:void 0,children:[u&&s.jsx("button",{type:"button",onClick:()=>{T(),f==null||f()},"aria-label":S?"Hide controls":"Show controls","aria-pressed":S,title:S?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:s.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),_&&s.jsxs(s.Fragment,{children:[s.jsx("input",{ref:x,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:B=>{B.target.files&&M(B.target.files),B.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var B;return(B=x.current)==null?void 0:B.click()},disabled:h.length>=tr,title:h.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:g,rows:1,placeholder:o||(_&&h.length>0?"Add a message (optional)...":`Send message to ${r}... (Shift+Enter for newline)`),value:k,onChange:B=>j(B.target.value),onPaste:B=>{_&&B.clipboardData.files.length>0&&Array.from(B.clipboardData.files).some(F=>F.type.startsWith("image/"))&&(B.preventDefault(),M(B.clipboardData.files))},onKeyDown:B=>{B.key==="Enter"&&(B.nativeEvent.isComposing||B.shiftKey||(B.preventDefault(),H()))},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:()=>{H()},disabled:tx({hasDraft:L,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${L&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:L&&!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:L?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})}),d&&s.jsx("button",{type:"button",onClick:()=>{P()},disabled:!L,className:`h-10 px-3 rounded-full text-[11px] font-medium border border-border-subtle shrink-0 transition-colors ${L?"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"})]}),(I||_&&b)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${I?"text-red-400":"text-[var(--accent-primary)]"}`,children:I||"Drop image here"}),o&&!I&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:o})]})});function dl(e){if(!e||!Number.isFinite(e))return"—";try{return`${new Date(e).toLocaleString()} (${e})`}catch{return String(e)}}function ul(e){if(!e)return"";const t=Date.now()-e;if(t<0)return"";const r=Math.floor(t/1e3);if(r<60)return`${r}s ago`;const n=Math.floor(r/60);if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function ax({sessionId:e,daemonId:t,onClose:r}){const{sendCommand:n}=it(),[a,o]=l.useState(!0),[i,c]=l.useState(null),[d,m]=l.useState(null),u=l.useCallback(async()=>{o(!0),m(null);try{const p=await n(t,"get_session_info",{targetSessionId:e}),f=p&&typeof p=="object"?p:{},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(p){m((p==null?void 0:p.message)||String(p)),c(null)}finally{o(!1)}},[n,t,e]);return l.useEffect(()=>{u()},[u]),l.useEffect(()=>{const p=f=>{f.key==="Escape"&&r()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[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:p=>p.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-border-subtle px-4 py-3",children:[s.jsx("h2",{className:"text-base font-semibold",children:"Session info"}),s.jsx("button",{type:"button",onClick:r,className:"text-text-secondary hover:text-text-primary px-2 py-1 rounded","aria-label":"Close",children:"×"})]}),s.jsxs("div",{className:"overflow-y-auto px-4 py-3 text-sm space-y-4",children:[a&&s.jsx("div",{className:"text-text-secondary",children:"Loading…"}),d&&s.jsx("div",{className:"text-red-500",children:d}),(i==null?void 0:i.session)&&s.jsxs(ml,{title:"Session",children:[s.jsx(Dt,{k:"Session ID",v:s.jsx(sr,{children:i.session.sessionId})}),s.jsx(Dt,{k:"Provider",v:`${i.session.providerName||i.session.providerType} (${i.session.providerType})`}),i.session.transport&&s.jsx(Dt,{k:"Transport",v:i.session.transport}),i.session.workspace&&s.jsx(Dt,{k:"Workspace",v:s.jsx(sr,{children:i.session.workspace})}),s.jsx(Dt,{k:"Spawned at",v:s.jsxs(s.Fragment,{children:[dl(i.session.spawnedAtMs),i.session.spawnedAtMs?s.jsx("span",{className:"text-text-secondary ml-2",children:ul(i.session.spawnedAtMs)}):null]})}),i.session.providerSessionId&&s.jsx(Dt,{k:"Provider session ID",v:s.jsx(sr,{children:i.session.providerSessionId})})]}),(i==null?void 0:i.coordinator)&&s.jsxs(ml,{title:"Mesh coordinator",children:[s.jsx(Dt,{k:"Mesh ID",v:s.jsx(sr,{children:i.coordinator.meshId})}),i.coordinator.cliType&&s.jsx(Dt,{k:"Coordinator CLI",v:i.coordinator.cliType}),s.jsx(Dt,{k:"Started at",v:s.jsxs(s.Fragment,{children:[dl(i.coordinator.startedAt),i.coordinator.startedAt?s.jsx("span",{className:"text-text-secondary ml-2",children:ul(i.coordinator.startedAt)}):null]})}),i.coordinator.injection&&s.jsx(Dt,{k:"Prompt injection",v:`${i.coordinator.injection.mode}${i.coordinator.injection.target?` → ${i.coordinator.injection.target}`:""}`}),i.coordinator.mcpConfigPath&&s.jsx(Dt,{k:"MCP config",v:s.jsx(sr,{children:i.coordinator.mcpConfigPath})}),i.coordinator.extraSystemPrompt&&s.jsx(pl,{title:"Per-launch extra prompt",body:i.coordinator.extraSystemPrompt,defaultOpen:!0}),i.coordinator.systemPrompt&&s.jsx(pl,{title:"Final system prompt (click to expand)",body:i.coordinator.systemPrompt})]}),i&&!i.coordinator&&s.jsx("div",{className:"text-text-secondary italic",children:"This isn't a mesh coordinator session, so no coordinator-specific prompt was injected. The agent runs with whatever defaults its CLI ships with."})]}),s.jsxs("div",{className:"border-t border-border-subtle px-4 py-2 flex justify-end gap-2",children:[s.jsx("button",{type:"button",onClick:()=>void u(),className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:"px-3 py-1 text-sm rounded bg-accent text-white hover:opacity-90",children:"Close"})]})]})})}function ml({title:e,children:t}){return s.jsxs("div",{children:[s.jsx("h3",{className:"text-xs uppercase tracking-wide text-text-secondary mb-1",children:e}),s.jsx("div",{className:"space-y-1",children:t})]})}function Dt({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 pl({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 ox({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(ax,{sessionId:e,daemonId:t,onClose:()=>n(!1)})]})}const Qe=e=>e.transport==="pty",Vs=(e,t)=>Qe(e)?e.mode||"terminal":"chat",Nd=(e,t)=>Qe(e)&&Vs(e)==="terminal",qe=e=>e.transport==="acp",ix=180;function os(e){return e.streamSource!=="agent-stream"}function Cs(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Cd(e){return e.machineName||""}function Br(e){return Cs(e)}function Gt(e){return e.agentType||""}function Hn(e){return e.hostIdeType||""}function si(e){return e.displayPrimary||e.agentName||"Agent"}function Id(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function lx(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Md(e){const t=lx(e),r=Bs(t==null?void 0:t.content),n=Bs(e.lastMessagePreview);return r||n||""}function cx(e,t=ix){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 dx(e){return cx(Md(e)||e.displaySecondary||"")}function Ad(e){return[e.displaySecondary,Cd(e)].filter(Boolean)}function Ws(e){return e.agentName||wt(Gt(e))}function ux(e){var t,r;if(!os(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return wt(Hn(e)||Gt(e))}function Td(e){return os(e)?e.sessionId:e.nativeSessionId}function hl(e){return os(e)?"native":e.tabKey}function mx(e){return e.sessionId}function px(e,t){if(t)return os(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function hx(e,t){const r=Gt(e),n=os(e),a=Qe(e)||qe(e),o=n?a?Ws(e)||(t==null?void 0:t.cliName)||wt(Hn(e)||r):t!=null&&t.type?wt(t.type):wt(Hn(e)||r):Ws(e);return{isNativeConversation:n,isCli:Qe(e),isAcp:qe(e),isCliTerminal:Nd(e),providerType:r,displayLabel:o,targetEntry:px(e,t)}}function fs(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:Qe(e)||qe(e)?{agentType:Gt(e)}:e.streamSource==="agent-stream"?{agentType:Gt(e)}:t}function xs(e){return e?Br(e):""}function rr(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function ri(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function fl(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 _d(){return"select_session"}function fx(){return"open_panel"}function xx({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function xl(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function an(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function yr(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function ni(e){return e instanceof Error?e.message:String(e||"")}function bl(e){const t=ni(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function gl(e,t){const r=ni(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function yl(e,t,r,n={}){const a=fs(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 da({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,o]=l.useState(!1),[i,c]=l.useState(!1),[d,m]=l.useState(null),u=l.useRef(!1),p=l.useRef(null);l.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const f=l.useCallback(async(j,h)=>{if(!t||u.current)return!1;const v=j.trim(),I=ri(t);if(xx({hasMessage:!!v,blockedMessage:I,sendInFlight:u.current}))return I&&m(I),!1;const w=Date.now(),b={tabKey:t.tabKey,message:v,timestamp:w};if(xl(p.current,b))return m(null),!0;u.current=!0,c(!0),m(null),p.current=b;try{const C=xs(t);if(!C)return p.current=an(p.current,b),m("Unable to send message right now."),!1;const N=await e(C,"send_chat",yl(v,h,t)),S=yr(N);if(S!=null&&S.deduplicated)return m(null),!0;if((S==null?void 0:S.sent)===!1)throw new Error((S==null?void 0:S.error)||"Send failed");if((S==null?void 0:S.success)===!1)throw new Error((S==null?void 0:S.error)||"Send failed");return m(null),!0}catch(C){const N=ni(C);return N.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",N):console.warn("Send blocked/failed",C),p.current=an(p.current,b),m(fl(C)),!1}finally{u.current=!1,c(!1)}},[t,e]),y=l.useCallback(async(j,h)=>{if(!t||u.current)return!1;const v=j.trim();if(!v&&(!h||h.length===0))return!1;const I=Date.now(),w={tabKey:t.tabKey,message:`force:${v}`,timestamp:I};if(xl(p.current,w))return m(null),!0;u.current=!0,c(!0),m(null),p.current=w;try{const b=xs(t);if(!b)return p.current=an(p.current,w),m("Unable to send message right now."),!1;const C=await e(b,"send_chat",yl(v,h,t,{force:!0})),N=yr(C);if((N==null?void 0:N.success)===!1||(N==null?void 0:N.sent)===!1)throw new Error((N==null?void 0:N.error)||"Send failed");return m(null),!0}catch(b){return console.warn("Force send blocked/failed",b),p.current=an(p.current,w),m(fl(b)),!1}finally{u.current=!1,c(!1)}},[t,e]),g=l.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(j){console.error("Relaunch failed",j)}},[t,e]),x=l.useCallback(async j=>{if(t)try{const v=(t.modalButtons||[]).indexOf(j),I=j.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),w=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(I),b=xs(t);if(!b)return;const C=await e(b,"resolve_action",{button:j,action:w?"approve":"reject",...v>=0&&{buttonIndex:v},...fs(t)}),N=yr(C);N.success||r(S=>[...S,{routeId:t.tabKey,text:gl(j,N==null?void 0:N.error),timestamp:Date.now()}])}catch(h){bl(h)||console.error("[ModalButton] Error:",h),r(v=>[...v,{routeId:t.tabKey,text:bl(h)?gl(j,h):`❌ **${j}** error`,timestamp:Date.now()}])}},[t,e,r]),k=l.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,fx(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(j){console.error("Focus agent failed",j)}finally{o(!1)}}},[t,a,e]);return{isSendingChat:i,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:f,handleForceSendChat:y,handleRelaunch:g,handleModalButton:x,handleFocusAgent:k}}const bx=10,gx=8e3,yx=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function vx(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 So(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(yx.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=vx(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=>So(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,So(a,n,r+1)]))}function nr(e,t){return Array.isArray(e)?e.slice(-t):[]}function wx(e,t=Date.now()){const r=e&&t-e.firstAt<=gx,n=r?e.count+1:1;return n>=bx?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function Ld(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 So(r)}function Pd(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 Rd(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 Dd(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 Na(e,t){return`${e}:${t}`}function jx(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function kx(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Ms(e,t){kx()&&console.debug(`[subscription-manager] ${e}`,t)}class Sx{constructor(){Ue(this,"active",new Map);Ue(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var u,p;const i=Na(n.topic,n.key),c=this.active.get(i);let d=!0;if(c)c.handlers.add(a),(!jx(c.request,n)||c.daemonId!==r)&&(c.daemonId=r,c.request=n,d=((u=t.sendData)==null?void 0:u.call(t,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)?this.scheduleRetry(i,t,o.retryIntervalMs):d&&this.clearRetry(i),Ms("subscribe_update",{daemonId:r,topic:n.topic,key:n.key,accepted:d})),c.lastUpdate&&a(c.lastUpdate);else{const f={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,f),Ms("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((p=t.sendData)==null?void 0:p.call(t,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(i,t,o.retryIntervalMs)}const m=()=>{var g;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};Ms("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(g=t.sendData)==null||g.call(t,r,y)};return m.initialSendAccepted=d,m}publish(t){const r=Na(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Es.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),Es.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=Na(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;Ms("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);Ms("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;Ms("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 Vt=new Sx;function Nx(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 Cx(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 Ca(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function Ix(){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){Ix()&&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 Wn(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:i}=t,c=i||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:m,childrenByParent:u}=Cx(d),p=Nx(o,n),f=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,y=m.filter(k=>k.kind==="workspace"&&k.transport==="cdp-page"),g=m.filter(k=>k.kind==="agent"&&k.transport==="pty"),x=m.filter(k=>k.kind==="agent"&&k.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(k=>!!k.cdpConnected)});for(const k of y){const j=p.get(k.id),h=pr(k,j),v=(u.get(k.id)||[]).map(I=>pr(I,p.get(I.id)));r.push({id:`${n}:ide:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,status:h.cdpConnected?"online":"detected",daemonId:n,instanceId:Ca(n,k.id),workspace:h.workspace,terminals:0,childSessions:v,agents:v.map(I=>({id:I.id,name:I.providerName||I.providerType,type:I.providerType,status:I.status})),activeChat:h.activeChat,...h.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:h.activeInteractivePrompt},chats:[],cdpConnected:h.cdpConnected,...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},...h.settings!==void 0&&{settings:h.settings},...h.messageInput!==void 0&&{messageInput:h.messageInput},timestamp:c})}for(const k of g){const j=p.get(k.id),h=pr(k,j);r.push({id:`${n}:cli:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:Ca(n,k.id),cliName:h.providerName||h.providerType,mode:h.mode||(j==null?void 0:j.mode)||"terminal",workspace:h.workspace||"",activeChat:h.activeChat,...h.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:h.activeInteractivePrompt},...h.resume!==void 0&&{resume:h.resume},...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},...h.settings!==void 0&&{settings:h.settings},...h.messageInput!==void 0&&{messageInput:h.messageInput},timestamp:c,_isCli:!0})}for(const k of x){const j=p.get(k.id),h=pr(k,j);r.push({id:`${n}:acp:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:Ca(n,k.id),cliName:h.providerName||h.providerType,mode:"chat",workspace:h.workspace||"",activeChat:h.activeChat,...h.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:h.activeInteractivePrompt},...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},...h.settings!==void 0&&{settings:h.settings},...h.messageInput!==void 0&&{messageInput:h.messageInput},timestamp:c,_isAcp:!0})}return Mx(r),r}const Ax=15e3,Tx=15e3,_x=6e4,Lx=1200,vl=12,Px=8e3,Rx=4e3,Ia=new Map,Ma=new Map,on=new Set,vr=new Map;function Dx(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 wl(e,t){const r=vr.get(e);!r||r.size===0||(vr.delete(e),r.forEach(n=>n(t)))}function $x(e,t){return new Promise(r=>{const n=vr.get(e)||new Set;vr.set(e,n);const a=i=>{clearTimeout(o),n.delete(a),n.size===0&&vr.delete(e),r(i)},o=setTimeout(()=>a(!1),t);n.add(a)})}function Or(){const{sendCommand:e,sendData:t}=it(),{injectEntries:r,getIdes:n}=Ir();return l.useCallback(async(a,o)=>{if(!a)return;const i=(o==null?void 0:o.minFreshMs)??_x,c=Ma.get(a)||0;if(!(o!=null&&o.force)&&on.has(a)&&c>0||!(o!=null&&o.force)&&c>0&&Date.now()-c<i)return;const d=Ia.get(a);if(d)return d;const m=(async()=>{if(t&&!on.has(a)){const x=Vt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},k=>{const j=n(),h=j.find(I=>I.id===a),v=Wn(k.status,{daemonId:a,existingDaemon:h,existingEntries:j,timestamp:k.timestamp});v.length>0&&r(v),Ma.set(a,Date.now()),wl(a,!0)});if(x.initialSendAccepted?on.add(a):on.delete(a),!(o!=null&&o.force)&&x.initialSendAccepted&&await $x(a,Lx))return}const u=await e(a,"get_status_metadata"),p=Dx(u);if(!p)return;const f=n(),y=f.find(x=>x.id===a),g=Wn(p,{daemonId:a,existingDaemon:y,existingEntries:f,timestamp:p.timestamp||Date.now()});g.length>0&&r(g,{authoritativeDaemonIds:[a]}),Ma.set(a,Date.now()),wl(a,!0)})().finally(()=>{Ia.delete(a)});return Ia.set(a,m),m},[n,r,e,t])}function Ex(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const Bx=60,Ox=50;function $d(e={}){return e.isCliLike?Ox:Bx}function Fx(e={}){return $d(e)}function kt(e){return(typeof e=="string"?e.trim():"")||void 0}function Xt(e,t){const r=kt(t);return r?`${e}:${r}`:void 0}function rs(e,t,r){const n=Xt(t,r),a=kt(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 Ed(e){return kt(e.providerSessionId)||kt(e.sessionId)||kt(e.tabKey)||kt(e.routeId)}function ua(e){return Rs([kt(e.historySessionId),kt(e.providerSessionId),kt(e.sessionId)])}function Qt(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 Hx(e){const t=[];return kt(e.providerSessionId)?(rs(t,"provider",e.providerSessionId),Rs(t)):kt(e.sessionId)?(rs(t,"session",e.sessionId),Rs(t)):kt(e.tabKey)?(rs(t,"tab",e.tabKey),Rs(t)):kt(e.routeId)?(rs(t,"route",e.routeId),Rs(t)):[]}function Ar(e){return Xt("provider",e.providerSessionId)||Xt("session",e.sessionId)||Xt("tab",e.tabKey)||Xt("route",e.routeId)||"unknown:"}function Fr(e){return ua(e)[0]}function Wx(e){const t=kt(e.providerSessionId),r=kt(e.sessionId),n=kt(e.tabKey),a=kt(e.routeId),o=[Xt("provider",t),Xt("session",r),Xt("tab",n),Xt("route",a)].filter(d=>typeof d=="string"),i=Qt({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),c=Ar({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:c,targetKey:c,targetValue:Ed({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:Fr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:i}}function No(e,t){const r=Wx(e);return Hx(t).some(n=>r.lookupKeys.includes(n))}const Hr=60,Kx=1e3,ai=12e4,Ux=new Set(["generating","waiting_approval","starting","streaming","working"]),Co=new Map;function oi(e,t,r){return`${e}::${t}::${r||t}`}function Kn(e=Hr){return{liveMessages:[],hasLiveSnapshot:!1,cursor:zx([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function zx(e,t=Hr){return{tailLimit:t}}function jl(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 Io(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(Io).join(`
41
+ `);if(typeof e=="object"){const t=e;return Io(t.text??t.content??t.value??"")}return String(e)}function Gx(e){return Io(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function Vx(e){return e.length===0||e.every(Gx)}function qx(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="generating"||t==="long_generating"||t==="streaming"||t==="working"||t==="starting"}function Bd(e,t){return Math.max(Math.max(0,t),Array.isArray(e.liveMessages)?e.liveMessages.length:0)}function Yx(e,t,r,n,a){if(!qx(n))return!1;const o=Bd(e,t);if(o<=0)return!1;if(Vx(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 Xx(e,t,r,n){if(r.length!==0||Bd(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 Jx(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}function kl(e,t){const r=e[t];return typeof r=="string"?r:""}class Qx{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||Vt,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=Kn(Math.max(0,t.tailLimit??Hr))}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={...Kn(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:Kx}))}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=kl(t,"sessionId");if(r&&r!==this.sessionId)return;const n=kl(t,"historySessionId");if(n&&this.historySessionId&&n!==this.historySessionId)return;const a=Jx(t),o=t.messageSource;if(Yx(this.snapshot,this.fallbackRecentCount,a,t.status,o)||Xx(this.snapshot,this.fallbackRecentCount,a,o))return;const i={tailLimit:this.snapshot.cursor.tailLimit};jl(this.snapshot.liveMessages)===jl(a)&&this.snapshot.cursor.tailLimit===i.tailLimit||(this.snapshot={...this.snapshot,liveMessages:a,hasLiveSnapshot:!0,cursor:i,messageSource:o},this.emit())}}function Od(e){const t=oi(e.daemonId,e.sessionId,e.historySessionId),r=Co.get(t);if(r)return r.updateOptions(e),r;const n=new Qx(e);return Co.set(t,n),n}function Zx(e,t,r){if(!e||!t)return;const n=`${e}::${t}::`,a=oi(e,t,r);for(const[o,i]of Co.entries())(o===a||o.startsWith(n))&&i.clearLiveSnapshot()}function eb(e,t){return{...e,loadHistoryPage:t}}function tb(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function sb(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Ux.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??ai)),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 rb(e=ai){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function nb(e,t={}){const r=new Set,n=[];for(const a of e){if(!sb(a,t))continue;const o=Br(a),i=a.sessionId||"";if(!o||!i)continue;const c=Fr(a),d=oi(o,i,c||i);r.has(d)||(r.add(d),n.push({daemonId:o,sessionId:i,historySessionId:c||i,subscriptionKey:`daemon:${o}:session:${i}`}))}return n.sort(tb),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function ab(e,t){const{sendData:r,sendCommand:n}=it(),a=(t==null?void 0:t.enabled)!==!1,o=Br(e),i=e.sessionId||"",c=Fr(e)||i,d=`daemon:${o}:session:${i}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??Hr),u=l.useMemo(()=>!a||!o||!i?null:Od({daemonId:o,sessionId:i,historySessionId:c,subscriptionKey:d,sendData:r,tailLimit:m,fallbackRecentCount:e.messages.length}),[e.messages.length,o,a,c,r,i,d,m]),[p,f]=l.useState(()=>(u==null?void 0:u.getSnapshot())||Kn(m));l.useEffect(()=>{if(!u){f(Kn(m));return}u.retain(),f(u.getSnapshot());const g=u.subscribe(x=>{f(x)});return()=>{g(),u.release()}},[u,m]);const y=l.useCallback(async()=>{!u||!o||!i||await u.loadHistoryPage(async({offset:g,excludeRecentCount:x})=>{const k=e.agentType,j=await n(o,"chat_history",{agentType:k,offset:g,limit:30,targetSessionId:i,historySessionId:c,excludeRecentCount:x}),h=j&&typeof j=="object"&&"result"in j?j.result||{}:j||{};return{messages:Array.isArray(h.messages)?h.messages:[],hasMore:h.hasMore===!0}})},[e.agentType,u,o,c,n,i]);return l.useMemo(()=>eb(p,y),[y,p])}function ob(e,t){const{sendData:r}=it(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??Hr),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??ai)),i=rb(o),[c,d]=l.useState(0);l.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(p=>p+1)},i);return()=>{clearInterval(u)}},[e.length,n,i]);const m=l.useMemo(()=>nb(e,{recentActivityMs:o}),[e,o,c]);l.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const u=m.descriptors.map(p=>Od({...p,sendData:r,tailLimit:a}));return u.forEach(p=>{p.retain()}),()=>{u.forEach(p=>p.release())}},[m.signature,n,r,a])}function ib(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function Sl(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 lb(e,t){if(e.length===0)return[];if(t.some(Sl))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||!Sl(o))continue;const i=String(o.role||"").toLowerCase();n.has(i)||(n.add(i),r.unshift(o))}return r}function cb(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=lb(o,i),d=c.length>0?[...c,...i]:i;return t.length===0?d:[...t,...d]}function db(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function ub(e){return db(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Nn=new Map,Mo=new Set;function Nl(e,t){!e||Nn.get(e)===t||(t?Nn.set(e,!0):Nn.delete(e),Mo.forEach(n=>n(e,t)))}function mb(e){return e?Nn.get(e)===!0:!1}function pb(e){return Mo.add(e),()=>{Mo.delete(e)}}function hb(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function fb(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function xb(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Fd(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function Hd(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 bb(e){return Fd(e)?!1:e.inboxBucket==="task_complete"&&Hd(e).length>0}function Cl(e){return e.branch||"detached HEAD"}function gb(e){if(e.error)return`${Cl(e)} · Git error: ${e.error}`;const t=[Cl(e)];return e.changedFiles>0?t.push(hb(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 yb(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${gb(t)}`}function vb(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function wb(e,t={}){if(t.enabled===!1)return[];if(!xb(e))return[];const r=Fd(e)?"working":bb(e)?"complete":null;if(!r)return[];const n=r==="complete"?Hd(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${fb(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:yb(r,e.git),timestamp:vb(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 jb=60;function kb(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 Ao({activeConv:e,ideEntry:t,handleSendChat:r,handleForceSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:d,userName:m,scrollToBottomRequestNonce:u,isInputActive:p=!0,isVisible:f=!0}){var ee,ve,ce,W,ne,ue,me;const y=l.useRef(new Map),g=l.useRef(void 0),x=Or(),{sendCommand:k}=it(),{isVisible:j}=Qo();Er("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:d.length,isSendingChat:a});const h=gt.useMemo(()=>Gs(e),[e.status,e.connectionState]);gt.useEffect(()=>{const J=e.sessionId;if(J)return Nl(J,h.isGenerating),()=>{Nl(J,!1)}},[e.sessionId,h.isGenerating]);const v=l.useMemo(()=>hx(e,t),[e,t]),I=l.useMemo(()=>{var J;return ti((J=v.targetEntry)==null?void 0:J.providerControls,{hostIdeType:e.hostIdeType,providerType:v.providerType})},[e.hostIdeType,v.providerType,(ee=v.targetEntry)==null?void 0:ee.providerControls]),w=$d({isCliLike:v.isCli||v.isAcp}),b=Fx({isCliLike:v.isCli||v.isAcp}),C=ab(e,{enabled:f&&!!e.sessionId,tailLimit:b}),[N,S]=l.useState(w),[T,_]=l.useState(()=>Xi()),L=e.tabKey,M=C.historyMessages,A=C.hasMoreHistory,H=C.historyError,P=ib(e,C),D=ad(P).length;l.useEffect(()=>{S(w)},[w,L]);const O=Math.max(0,P.length-N),R=si(e),B=Br(e),E=ub(e),F=ri(e),Q=kb(e),Z=o||F||Q,Y=!!F,[te,fe]=l.useState(!1);l.useEffect(()=>{const J=v.targetEntry;B&&(!J||J.providerControls===void 0||J.controlValues===void 0)&&x(B,{minFreshMs:3e4}).catch(()=>{})},[B,v.isAcp,(ve=v.targetEntry)==null?void 0:ve.providerControls,(ce=v.targetEntry)==null?void 0:ce.controlValues,x]);const Ne=l.useCallback(async()=>{if(!te){if(P.length>N){S(J=>Math.min(P.length,J+jb));return}fe(!0);try{await C.loadHistoryPage()}finally{fe(!1)}}},[C,te,P.length,N]),{allMessages:X,receivedAtMap:we}=l.useMemo(()=>{const J=cb({historyMessages:M,liveMessages:P,visibleLiveCount:N}),q=wb(e),$=q.length>0?[...J,...q]:J,re={};return $.forEach((xe,je)=>{const ae=`${e.tabKey}:${Bn(xe,je)}`;let Pe=Ex(xe)||y.current.get(ae)||0;Pe||(Pe=Date.now(),y.current.set(ae,Pe)),re[Bn(xe,je)]=Pe}),{allMessages:$,receivedAtMap:re}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,O,M,P,N]),ge=l.useMemo(()=>d.filter(J=>J.routeId===e.tabKey).sort((J,q)=>J.timestamp-q.timestamp),[d,e.tabKey]),be=l.useCallback(async()=>{var je,ae;if(!B)return;const J=Ld({activeConv:e,visibleMessages:X,actionLogs:d,controls:(je=v.targetEntry)==null?void 0:je.providerControls,controlValues:(ae=v.targetEntry)==null?void 0:ae.controlValues,visibleBarControlCount:I.length,chatTailState:{liveMessages:C.liveMessages,hasLiveSnapshot:C.hasLiveSnapshot,hasMoreHistory:A,historyError:H,historyMessages:M},ui:{controlsVisible:j,visibleLiveCount:N,activityVisible:T,activityCount:D,hiddenLiveCount:O,isInputActive:p,isVisible:f}}),q=await k(B,"get_chat_debug_bundle",{agentType:v.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:J}),$=yr(q),re=Dd($),xe=await Rd(re);xe==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),tt.showToast(Pd($,{locatorCopyStatus:xe}),xe==="failed"?"warning":"success")},[e,d,D,X,j,C.hasLiveSnapshot,C.liveMessages,v.providerType,(W=v.targetEntry)==null?void 0:W.controlValues,(ne=v.targetEntry)==null?void 0:ne.providerControls,B,A,O,M,p,f,H,k,T,I.length,N]);l.useEffect(()=>{const J=q=>{q.key===rd&&_(Xi())};return window.addEventListener("storage",J),()=>window.removeEventListener("storage",J)},[]);const de=l.useCallback(()=>{const J=wx(g.current);g.current=J.state,J.shouldCollect&&be().catch(q=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",q),tt.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[be]),Ie=l.useMemo(()=>{if(P.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((h.isGenerating||e.status==="streaming")&&fe(!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 ",R," 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(Qc,{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 ",R," 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"&&!te)return!A&&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,A,M.length,c,te,P.length,R,h.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(ox,{sessionId:e.sessionId,daemonId:e.daemonId})})}),s.jsx(Gh,{messages:X,actionLogs:ge,agentName:Ws(e)||R||"Agent",userName:m,isCliMode:v.isCli||v.isAcp,isWorking:h.isGenerating,contextKey:e.tabKey,receivedAtMap:we,lastMessageHash:e.lastMessageHash,showActivityMessages:T,onLoadMore:Ne,isLoadingMore:te,hasMoreHistory:A,hiddenLiveCount:O,loadError:H??void 0,emptyState:Ie,scrollToBottomRequestNonce:u,isVisible:f}),s.jsx(ex,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:v.providerType,displayLabel:v.displayLabel,controls:(ue=v.targetEntry)==null?void 0:ue.providerControls,controlValues:(me=v.targetEntry)==null?void 0:me.controlValues,isActive:p,isCliTerminal:v.isCliTerminal}),!v.isCliTerminal&&s.jsx(Sd,{contextKey:e.tabKey,panelLabel:R,isSending:a,isBusy:Y,statusMessage:Z,onSend:r,onForceSend:n,canForceSend:!!n&&h.isGenerating&&!Y,isActive:p,showControlsToggle:I.length>0,onControlsToggle:de,messageInput:e.messageInput})]})}let Wd=qt;function Kd(){return Wd()}class Sb{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 Ud=new Sb;class Nb{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 pt=new Nb;function Cb(e){e.dashboardWS&&(Ud=e.dashboardWS),e.connectionManager&&(pt=e.connectionManager),e.useDaemonsHook&&(Wd=e.useDaemonsHook)}const Ib=.5,Mb=1.25;function ot(e){return si(e)}function ks(e){return Ad(e).join(" · ")}function Ab(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 Tb(e){var i,c,d;const t=[],r=typeof((i=e.settings)==null?void 0:i.meshNodeFor)=="string"?e.settings.meshNodeFor.trim():"",n=typeof((c=e.coordinator)==null?void 0:c.meshId)=="string"?e.coordinator.meshId.trim():"",a=typeof((d=e.settings)==null?void 0:d.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor.trim():"",o=n||a;if(r&&t.push(`메시 노드: ${r}`),o&&t.push(`코디네이터: ${o}`),e.meshQueueStats){const{pending:m,assigned:u,completed:p,failed:f}=e.meshQueueStats;t.push(`Queue: ${m} pending, ${u} assigned, ${p} completed, ${f} failed`)}return t.join(" · ")}function zd(e){const t=Md(e);return t||(e.title?e.title:ks(e)||"No messages yet")}function Gd(e,t){const{isReconnecting:r,isConnecting:n}=Gs(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function _b(e,t){const r=["Chat",...Ad(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function bs(e){return Gd(e)||ks(e)}function Lb(e){return`${ot(e)} · ${zd(e)}`}function Pb(e){const t=Hn(e),r=t?wt(t):Ws(e);return`${ot(e)} — ${r||"Agent"}`}function Rb(e){return Ws(e)||"CLI"}function Vd(e){return Id(e)}function qd(e){return e?`Remote · ${ot(e)||e.workspaceName||"Session"}`:"Remote"}function ar(e){const t=Date.now()-e;if(t<0)return"just now";if(t<2e3)return`${t}ms ago`;if(t<6e4)return`${(t/1e3).toFixed(1)}s ago`;const r=Math.floor(t/6e4);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}function Db(e){return e<=0?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}const $b={busy_hold_expired:"text-amber-200 bg-amber-500/20 border border-amber-500/30",idle_hold_committed:"text-green-200 bg-green-500/20 border border-green-500/30",completion_idle_after:"text-sky-200 bg-sky-500/20 border border-sky-500/30",forced_completion:"text-orange-200 bg-orange-500/20 border border-orange-500/30",forceEmit:"text-purple-200 bg-purple-500/20 border border-purple-500/30",spec_reload:"text-purple-200 bg-purple-500/20 border border-purple-500/30",eval_match:"text-zinc-300 bg-zinc-500/15 border border-zinc-500/20"},Eb={idle:"text-green-100 bg-green-600/30 border border-green-500/40",busy:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",generating:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",waiting_approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",picker:"text-sky-100 bg-sky-600/30 border border-sky-500/40",signing_in:"text-sky-100 bg-sky-600/30 border border-sky-500/40"};function Aa(e){return Eb[e]??"text-zinc-200 bg-zinc-600/20 border border-zinc-500/30"}function Ta({children:e}){return s.jsx("div",{className:"text-zinc-400 text-[10px] uppercase tracking-widest font-semibold mb-1.5 mt-0.5",children:e})}function _a(){return s.jsx("div",{className:"border-t border-white/8 my-2"})}function Bb({activeConv:e,onClose:t}){var w,b,C,N;const{sendCommand:r}=it(),[n,a]=l.useState(!0),[o,i]=l.useState(null),[c,d]=l.useState(null),[m,u]=l.useState(!1),[p,f]=l.useState(new Set(["footer"])),[y,g]=l.useState("Snapshot"),x=e.daemonId||((w=e.routeId)==null?void 0:w.split(":")[0])||e.routeId||"",k=e.sessionId||"",j=l.useCallback(async()=>{a(!0),d(null);try{const S=await r(x,"get_spec_debug",{targetSessionId:k}),T=S&&typeof S=="object"?S:{},_=T.result&&typeof T.result=="object"?T.result:T;_!=null&&_.success?i(_):(d((_==null?void 0:_.error)||"Failed to load spec debug"),i(null))}catch(S){d((S==null?void 0:S.message)||String(S)),i(null)}finally{a(!1)}},[r,x,k]);l.useEffect(()=>{j()},[j]),l.useEffect(()=>{const S=T=>{T.key==="Escape"&&t()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[t]);const h=o==null?void 0:o.snapshot,v=async()=>{var H,P,D;let S=o;S||(await j(),S=o);const T=S==null?void 0:S.snapshot,_=[];if(_.push("# Spec Debug Snapshot"),_.push(`Generated: ${new Date().toISOString()}`),_.push(`Session: ${(S==null?void 0:S.sessionId)??""} (${(S==null?void 0:S.providerType)??""})`),_.push(`Spec: ${(T==null?void 0:T.spec_id)??""} (${(T==null?void 0:T.specPath)??""})`),_.push(`Provider: ${(T==null?void 0:T.name)??""} (${(T==null?void 0:T.cliType)??""})`),_.push(`Working dir: ${(T==null?void 0:T.workingDir)??""}`),_.push(`Spawned: ${T!=null&&T.spawnedAtMs?new Date(T.spawnedAtMs).toISOString():""}`),_.push(""),_.push("## Current State"),_.push(`State: ${((H=T==null?void 0:T.current_state)==null?void 0:H.id)??"none"} (${((P=T==null?void 0:T.current_state)==null?void 0:P.label)??""})`),_.push(`Status: ${(T==null?void 0:T.status)??""}`),_.push(`Idle hold pending: ${(T==null?void 0:T.idleHoldPending)??!1}`),_.push(`Exited: ${(T==null?void 0:T.exited)??!1}`),_.push(`Last busy: ${T!=null&&T.lastBusyAt?ar(T.lastBusyAt):""}`),_.push(`Cursor: ${(T==null?void 0:T.cursorPosition)!=null?`(${T.cursorPosition.row},${T.cursorPosition.col})`:"n/a"}`),(D=T==null?void 0:T.completionIdleDebounce)!=null&&D.active){const O=T.completionIdleDebounce;_.push(`completion_idle_after: age=${O.ageMs}ms hold=${O.holdMs}ms force=${O.forceAfterMs}ms remaining=${Math.max(0,O.holdMs-O.ageMs)}ms`)}if(_.push(""),_.push("## Modal"),T!=null&&T.current_modal){const O=T.current_modal.buttons.map(R=>R.label).join(" / ");_.push(`${T.current_modal.title??""} [${O}]`)}else _.push("none");_.push(""),_.push("## State History (last 20)");const L=T!=null&&T.stateHistory?[...T.stateHistory].reverse().slice(0,20):[];for(const O of L){const R=O.reason!=null?typeof O.reason=="string"?O.reason:JSON.stringify(O.reason):"",B=O.debounceKind!=null?typeof O.debounceKind=="string"?O.debounceKind:JSON.stringify(O.debounceKind):"",E=O.matchedStateId!=null?String(O.matchedStateId):"",F=(O.matchedRules??[]).map(Q=>typeof Q=="string"?Q:JSON.stringify(Q)).join(", ");_.push(`- ${O.stateId} @ ${new Date(O.at).toISOString()} held ${O.durationMs}ms | reason: ${R} | debounce: ${B} | eval→${E} | rules: ${F}`)}if(_.push(""),_.push("## Sections"),T!=null&&T.sections)for(const[O,R]of Object.entries(T.sections)){const B=R.split(`
42
+ `).slice(0,3).join(`
43
+ `);_.push(`${O}: ${B}`)}_.push(""),_.push("## Last Assistant Message");const A=[...(T==null?void 0:T.messages)??(T==null?void 0:T.committedMessages)??[]].reverse().find(O=>O.role==="assistant");_.push(A?A.content.slice(0,400):""),_.push(""),_.push("## Screen (first 50 lines)"),_.push(T!=null&&T.screen?T.screen.split(`
44
+ `).slice(0,50).join(`
45
+ `):"");try{await navigator.clipboard.writeText(_.join(`
46
+ `)),g("Copied!"),setTimeout(()=>g("Snapshot"),1500)}catch(O){console.error("[SpecDebugPanel] clipboard write failed",O)}},I=S=>{f(T=>{const _=new Set(T);return _.has(S)?_.delete(S):_.add(S),_})};return s.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Spec debug",className:"fixed inset-0 z-50 flex items-end justify-center bg-black/60 p-0 sm:items-center sm:p-4",onClick:t,style:{pointerEvents:"auto"},children:s.jsxs("div",{className:"bg-zinc-900 text-zinc-100 border border-zinc-700 rounded-t-xl sm:rounded-lg shadow-2xl max-w-2xl w-full max-h-[92vh] sm:max-h-[88vh] flex flex-col",onClick:S=>S.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-zinc-700 px-4 py-2.5 shrink-0 gap-2 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 overflow-hidden",children:[s.jsx("span",{className:"text-sm font-semibold text-zinc-100 shrink-0",children:"Spec Debug"}),h&&s.jsx("span",{className:"text-[11px] text-zinc-400 font-mono bg-zinc-800 px-1.5 py-0.5 rounded truncate",children:h.spec_id})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[s.jsx("button",{type:"button",className:"text-[11px] text-zinc-300 hover:text-white transition-colors px-2 py-1 rounded hover:bg-zinc-700 border border-transparent hover:border-zinc-600",onClick:()=>{v()},disabled:n,children:y}),s.jsx("button",{type:"button",className:"text-[11px] text-zinc-300 hover:text-white transition-colors px-2 py-1 rounded hover:bg-zinc-700 border border-transparent hover:border-zinc-600",onClick:()=>{j()},disabled:n,children:n?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"text-zinc-400 hover:text-zinc-100 transition-colors text-xl leading-none w-7 h-7 flex items-center justify-center rounded hover:bg-zinc-700",onClick:t,"aria-label":"Close",children:"×"})]})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3 space-y-3 text-[12px]",children:[c&&s.jsx("div",{className:"text-red-300 bg-red-900/40 border border-red-700/50 rounded p-2",children:c}),n&&!o&&s.jsx("div",{className:"text-zinc-500 text-center py-6",children:"Loading…"}),o&&!o.isSpecProvider&&s.jsxs("div",{className:"text-zinc-500 text-center py-6",children:["Not a spec-driven provider (",o.providerType||"unknown",")."]}),h&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-[11px] bg-zinc-800/60 rounded-md px-3 py-2 border border-zinc-700/50",children:[h.name&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Provider"}),s.jsxs("span",{className:"font-mono text-zinc-200",children:[h.name," ",s.jsxs("span",{className:"text-zinc-500",children:["(",h.cliType,")"]})]})]}),h.workingDir&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Dir"}),s.jsx("span",{className:"font-mono text-zinc-300 truncate",title:h.workingDir,children:h.workingDir})]}),h.spawnedAtMs?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Spawned"}),s.jsx("span",{className:"text-zinc-400",children:ar(h.spawnedAtMs)})]}):null,h.providerSessionId&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Session"}),s.jsx("span",{className:"font-mono text-zinc-500 text-[10px] truncate",title:h.providerSessionId,children:h.providerSessionId})]})]}),s.jsxs("div",{className:"flex items-center gap-2 flex-wrap bg-zinc-800/40 rounded-md px-3 py-2 border border-zinc-700/50",children:[s.jsx("span",{className:`font-semibold font-mono text-[12px] px-2 py-0.5 rounded ${h.current_state?Aa(h.current_state.id):"text-zinc-500"}`,children:h.current_state?h.current_state.id:"none"}),((b=h.current_state)==null?void 0:b.label)&&h.current_state.label!==h.current_state.id&&s.jsx("span",{className:"text-zinc-400 text-[11px]",children:h.current_state.label}),h.status&&h.status!==((C=h.current_state)==null?void 0:C.id)&&s.jsxs("span",{className:"text-zinc-500 text-[11px]",children:["engine: ",s.jsx("span",{className:`font-mono ${Aa(h.status)} px-1 py-0.5 rounded text-[10px]`,children:h.status})]}),h.idleHoldPending&&s.jsx("span",{className:"text-yellow-200 text-[10px] bg-yellow-600/25 border border-yellow-500/35 px-1.5 py-0.5 rounded font-mono",children:"idle hold pending"}),h.exited&&s.jsx("span",{className:"text-red-200 text-[10px] bg-red-600/25 border border-red-500/35 px-1.5 py-0.5 rounded font-mono",children:"exited"}),h.cursorPosition!=null&&s.jsxs("span",{className:"text-zinc-500 text-[11px] font-mono",children:["cursor: ",s.jsxs("span",{className:"text-zinc-300",children:[h.cursorPosition.row,",",h.cursorPosition.col]})]}),h.lastBusyAt>0&&s.jsxs("span",{className:"text-zinc-500 text-[11px] ml-auto",children:["last busy: ",s.jsx("span",{className:"text-zinc-400",children:ar(h.lastBusyAt)})]})]}),((N=h.completionIdleDebounce)==null?void 0:N.active)&&s.jsxs("div",{className:"flex items-center gap-2 text-[11px] bg-sky-900/20 border border-sky-700/30 rounded-md px-3 py-1.5 font-mono",children:[s.jsx("span",{className:"text-sky-400",children:"completion_idle_after"}),s.jsxs("span",{className:"text-zinc-400",children:["age: ",s.jsxs("span",{className:"text-sky-200",children:[h.completionIdleDebounce.ageMs,"ms"]})]}),s.jsx("span",{className:"text-zinc-500",children:"/"}),s.jsxs("span",{className:"text-zinc-400",children:["hold: ",s.jsxs("span",{className:"text-zinc-300",children:[h.completionIdleDebounce.holdMs,"ms"]})]}),s.jsxs("span",{className:"text-zinc-400",children:["force: ",s.jsxs("span",{className:"text-zinc-300",children:[h.completionIdleDebounce.forceAfterMs,"ms"]})]}),s.jsx("span",{className:"text-zinc-500 ml-auto",children:h.completionIdleDebounce.ageMs<h.completionIdleDebounce.holdMs?s.jsxs("span",{className:"text-amber-300",children:["hold remaining: ",h.completionIdleDebounce.holdMs-h.completionIdleDebounce.ageMs,"ms"]}):h.completionIdleDebounce.ageMs<h.completionIdleDebounce.forceAfterMs?s.jsxs("span",{className:"text-orange-300",children:["force in: ",h.completionIdleDebounce.forceAfterMs-h.completionIdleDebounce.ageMs,"ms"]}):s.jsx("span",{className:"text-red-300",children:"overdue"})})]}),h.current_modal&&s.jsxs("div",{className:"bg-orange-900/30 border border-orange-600/40 rounded-md p-2.5",children:[s.jsx("span",{className:"text-orange-200 font-semibold",children:"Modal: "}),s.jsx("span",{className:"text-zinc-300",children:h.current_modal.title||""}),h.current_modal.buttons.length>0&&s.jsxs("span",{className:"text-zinc-400 ml-2",children:["[",h.current_modal.buttons.map(S=>S.label).join(" / "),"]"]})]}),s.jsx(_a,{}),h.sections&&Object.keys(h.sections).length>0&&s.jsxs("div",{children:[s.jsx(Ta,{children:"Sections"}),s.jsx("div",{className:"space-y-1",children:Object.entries(h.sections).map(([S,T])=>{var A;const _=p.has(S),L=T.split(`
47
+ `),M=((A=L[0])==null?void 0:A.slice(0,80))||"(empty)";return s.jsxs("div",{className:"border border-zinc-700 rounded overflow-hidden bg-zinc-800/30",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2.5 py-1.5 hover:bg-zinc-700/40 transition-colors text-left",onClick:()=>I(S),children:[s.jsx("span",{className:"text-[10px] text-zinc-500 w-3",children:_?"▾":"▸"}),s.jsx("span",{className:"font-mono text-sky-300 w-20 shrink-0 text-[11px]",children:S}),!_&&s.jsx("span",{className:"text-zinc-400 truncate font-mono text-[11px]",children:M}),s.jsxs("span",{className:"ml-auto text-zinc-600 text-[10px] shrink-0",children:[L.length,"L"]})]}),_&&s.jsx("pre",{className:"px-3 pb-2.5 pt-1 font-mono text-[11px] text-zinc-300 whitespace-pre-wrap break-all bg-black/30 max-h-40 overflow-y-auto border-t border-zinc-700/50",children:T||"(empty)"})]},S)})})]}),s.jsx(_a,{}),h.stateHistory&&h.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs(Ta,{children:["State History (",h.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...h.stateHistory].reverse().slice(0,20).map((S,T)=>s.jsxs("div",{className:"rounded px-2 py-1 hover:bg-zinc-800/60 transition-colors",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:`font-mono text-[11px] font-semibold px-1.5 py-0.5 rounded shrink-0 ${Aa(S.stateId)}`,children:S.stateId}),s.jsx("span",{className:"text-zinc-400 text-[11px] shrink-0 tabular-nums",children:ar(S.at)}),S.durationMs>0&&s.jsxs("span",{className:"text-zinc-500 text-[11px]",children:["held ",s.jsx("span",{className:"text-zinc-400",children:Db(S.durationMs)})]}),S.reason&&s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${$b[String(S.reason)]??"text-zinc-400 bg-zinc-700/50 border border-zinc-600/30"}`,children:String(S.reason)}),S.debounceKind&&String(S.debounceKind)!=="none"&&s.jsxs("span",{className:"text-zinc-500 text-[10px] font-mono",children:["debounce:",String(S.debounceKind)]}),S.matchedStateId&&String(S.matchedStateId)!==S.stateId&&s.jsxs("span",{className:"text-zinc-500 text-[10px] font-mono",children:["eval→",s.jsx("span",{className:"text-zinc-300",children:String(S.matchedStateId)})]})]}),S.matchedRules&&S.matchedRules.length>0&&s.jsxs("div",{className:"flex items-start gap-1 flex-wrap mt-0.5 ml-1 pl-1 border-l border-zinc-700",children:[S.matchedRules.slice(0,3).map((_,L)=>s.jsx("span",{className:"font-mono text-[10px] text-sky-200 bg-sky-900/40 border border-sky-700/40 px-1.5 py-0.5 rounded break-all",children:typeof _=="string"?_:JSON.stringify(_)},L)),S.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-zinc-500",children:["+",S.matchedRules.length-3," more"]})]})]},T))})]}),s.jsx(_a,{}),(()=>{const S=h.messages??h.committedMessages??[];if(S.length===0)return null;const T=S.filter(M=>M.role==="user").length,_=S.filter(M=>M.role==="assistant").length,L=[...S].reverse().find(M=>M.role==="assistant");return s.jsxs("div",{children:[s.jsxs(Ta,{children:["Transcript (",S.length," — ",T,"u / ",_,"a)"]}),L&&s.jsxs("div",{className:"bg-zinc-800/50 border border-zinc-700 rounded-md p-2.5 text-[11px]",children:[s.jsxs("div",{className:"text-zinc-500 mb-1 text-[10px]",children:["Last assistant ",L.receivedAt?ar(L.receivedAt):""]}),s.jsxs("div",{className:"text-zinc-300 font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[L.content.slice(0,400),L.content.length>400?"…":""]})]})]})})(),h.specPath&&s.jsx("div",{className:"text-[10px] text-zinc-600 font-mono truncate border-t border-zinc-800 pt-2 mt-1",title:h.specPath,children:h.specPath}),s.jsxs("div",{children:[s.jsxs("button",{type:"button",className:"text-[11px] text-zinc-400 hover:text-zinc-200 transition-colors flex items-center gap-1.5",onClick:()=>u(S=>!S),children:[s.jsx("span",{className:"text-zinc-600",children:m?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",h.screen?h.screen.split(`
48
+ `).length:0," lines)"]})]}),m&&s.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-[11px] text-zinc-300 whitespace-pre bg-black/40 rounded-md border border-zinc-700 max-h-64 overflow-auto",children:h.screen||"(empty)"})]})]})]})]})})}function Ob({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var ke;qt();const{sendPtyInput:d}=it(),[m,u]=l.useState(!1),p=l.useRef(!1);p.current=m;const[f,y]=l.useState("Runtime terminal unavailable"),[g,x]=l.useState(!1),[k,j]=l.useState(null),[h,v]=l.useState(!1),[I,w]=l.useState(!1),[b,C]=l.useState(1),[N,S]=l.useState(!1),[T,_]=l.useState(!1),[L,M]=l.useState({width:0,height:0}),[A,H]=l.useState({width:0,height:0}),[P,D]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[O,R]=l.useState(null),B=l.useRef(null),E=l.useRef(null),F=l.useRef(!1),Q=l.useRef(!1),Z=l.useRef(i),Y=l.useRef(0),te=l.useRef(!1),fe=l.useRef(""),Ne=l.useRef(null),X=l.useRef(!1),we=l.useRef(!1),ge=l.useRef(null),be=l.useRef(null),de=l.useRef(null),Ie=32*1024,ee=()=>{var z,G,le,Ce;return((G=(z=B.current)==null?void 0:z.ownerDocument)==null?void 0:G.defaultView)||((Ce=(le=E.current)==null?void 0:le.ownerDocument)==null?void 0:Ce.defaultView)||window},ve=z=>{const G=ee();return{ownerWindow:G,frameId:G.requestAnimationFrame(z)}},ce=()=>{const z=ge.current;if(z){try{z.ownerWindow.cancelAnimationFrame(z.frameId)}catch{}ge.current=null}},W=()=>{const z=be.current;if(z){try{z.ownerWindow.clearTimeout(z.timeoutId)}catch{}be.current=null}},ne=()=>{const z=de.current;if(z){try{z.ownerWindow.clearTimeout(z.timeoutId)}catch{}de.current=null}},ue=()=>{i&&ge.current===null&&(ge.current=ve(()=>{dt()}))},me=e.tabKey,J=e.sessionId||"",q=e.daemonId||((ke=e.routeId)==null?void 0:ke.split(":")[0])||e.routeId||"",$=ri(e),re=m?o||$:f,xe=Ib,je=Mb,ae=.05,Pe=()=>{const z=A.width,G=A.height;if(!Number.isFinite(L.width)||L.width<=0||!Number.isFinite(L.height)||L.height<=0||!Number.isFinite(z)||z<=0||!Number.isFinite(G)||G<=0)return 1;const le=L.width/z,Ce=L.height/G;return Number(Math.min(je,Math.max(xe,Math.min(le,Ce))).toFixed(2))},$e=Pe(),Re=F.current&&b>$e,Ge=Number.isFinite(A.width)&&A.width>0?Math.max(L.width,Math.round(A.width*b)):L.width,Ye=Number.isFinite(A.height)&&A.height>0?Math.max(L.height,Math.round(A.height*b)):L.height,Xe=()=>{ve(()=>{const z=E.current;z&&(z.scrollLeft=0,z.scrollTop=z.scrollHeight-z.clientHeight)})},at=()=>{var z,G;Y.current=0,te.current=!1,fe.current="",Ne.current=null,X.current=!1,we.current=!1,F.current||(Q.current=!1,C(1)),ge.current!==null&&ce(),u(!1),y("Runtime terminal unavailable"),ne(),W(),j(null),R(null),S(!1),x(!1),v(!1),w(!1),(G=(z=r.current)==null?void 0:z.reset)==null||G.call(z)},Je=()=>{var z,G;Y.current=0,te.current=!1,fe.current="",Ne.current=null,X.current=!1,we.current=!1,ge.current!==null&&ce(),u(!0),y(""),ne(),W(),j(null),R(null),S(!1),x(!1),v(!1),w(!1),(G=(z=r.current)==null?void 0:z.reset)==null||G.call(z)},Ze=()=>{we.current&&(we.current=!1,ve(()=>{var z,G;(G=(z=r.current)==null?void 0:z.scrollToTop)==null||G.call(z)}))},dt=()=>{if(ge.current=null,!i)return;const z=fe.current;if(!z)return;const G=z.slice(0,Ie);fe.current=z.slice(G.length);const le=r.current;if(!le){fe.current=G+fe.current,ue();return}le.write(G,()=>{if(fe.current.length>0){ue();return}Ze()})},ft=z=>{z&&(fe.current+=z,ue())},he=(z,G=0,le,Ce,Te={})=>{var _e,De,Ae,He;const Me=!!Te.force;!Me&&G>0&&Y.current>=G||!Me&&G===0&&te.current||(Y.current=G,G>0&&v(!0),u(!0),y(""),typeof le=="number"&&typeof Ce=="number"&&le>0&&Ce>0&&((De=(_e=r.current)==null?void 0:_e.resize)==null||De.call(_e,le,Ce)),fe.current="",(He=(Ae=r.current)==null?void 0:Ae.reset)==null||He.call(Ae),z?ft(z):Ze())};l.useEffect(()=>{at()},[J]),l.useEffect(()=>{var G;if(!J)return;const z=((G=pt.onRuntimeEvent)==null?void 0:G.call(pt,J,le=>{if(!(!le||le.sessionId!==J)){if(le.type==="runtime_snapshot"){if(!i){Ne.current={text:le.text||"",seq:le.seq||0,cols:le.cols,rows:le.rows,force:!!le.force};return}he(le.text||"",le.seq||0,le.cols,le.rows,{force:!!le.force});return}if(le.type==="session_output"){te.current=!0,typeof le.seq=="number"&&(Y.current=Math.max(Y.current,le.seq),le.seq>0&&v(!0)),p.current||u(!0),p.current||y(""),typeof le.data=="string"&&ft(le.data);return}if(le.type==="session_cleared"){if(!i){X.current=!0,fe.current="",Ne.current=null;return}Je();return}if(le.type==="session_io_error"){const Ce=typeof le.error=="string"&&le.error?le.error:typeof le.reason=="string"&&le.reason?le.reason:"unknown error";u(!1),y(`Runtime input failed: ${Ce}`);return}}},q))||(()=>{});return()=>{z()}},[q,J,r,i]);const Oe=async(z={})=>{var G;if(!q||!J)return{success:!1,error:"daemonId and sessionId are required"};z.preserveStatus||y(z.loadingMessage||"Loading runtime terminal...");try{const le=await((G=pt.requestRuntimeSnapshot)==null?void 0:G.call(pt,q,J,{sinceSeq:z.sinceSeq,force:z.force}));return le&&le.success===!1?(z.preserveStatus||(u(!1),y(`Runtime terminal unavailable: ${le.error}`)),le):le||{success:!0}}catch(le){const Ce=(le==null?void 0:le.message)||String(le);return z.preserveStatus||(u(!1),y(`Runtime terminal unavailable: ${Ce}`)),{success:!1,error:Ce}}},et=async z=>{var Me,_e;const G=((Me=B.current)==null?void 0:Me.ownerDocument)||document,le=G.defaultView||window,Ce=(_e=le.navigator)==null?void 0:_e.clipboard;if(Ce!=null&&Ce.writeText&&le.isSecureContext)try{return await Ce.writeText(z),!0}catch{}let Te=null;try{return Te=G.createElement("textarea"),Te.value=z,Te.setAttribute("readonly","true"),Te.style.position="fixed",Te.style.left="-9999px",Te.style.top="0",G.body.appendChild(Te),Te.focus(),Te.select(),G.execCommand("copy")}catch{return!1}finally{Te==null||Te.remove()}},ze=z=>{W(),R(z);const G=ee();be.current={ownerWindow:G,timeoutId:G.setTimeout(()=>{be.current=null,R(le=>le===z?null:le)},2200)}},ht=z=>{ne(),j(z);const G=ee();de.current={ownerWindow:G,timeoutId:G.setTimeout(()=>{de.current=null,j(le=>le===z?null:le)},2200)}},K=async()=>{var Te,Me,_e,De;const z=((Me=(Te=r.current)==null?void 0:Te.getSelection)==null?void 0:Me.call(Te))||"",G=((De=(_e=r.current)==null?void 0:_e.getVisibleText)==null?void 0:De.call(_e))||"",le=z.trimEnd()||G.trimEnd();if(!le){ze("Nothing to copy");return}if(!await et(le)){ze("Copy failed");return}ze(z.trimEnd()?"Copied selection":"Copied visible terminal")},U=z=>{if(!m||!i)return;((d==null?void 0:d(q,J,z))??!1)||ze("Terminal input failed")},V=async()=>{if(g)return;x(!0),j("Loading older terminal output..."),we.current=!0;const z=await Oe({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(x(!1),(z==null?void 0:z.success)===!1){we.current=!1,j(`Older terminal output unavailable: ${z.error}`);return}w(!0),ht("Older terminal output loaded"),ve(()=>{var G;(G=r.current)==null||G.bumpResize()})};l.useEffect(()=>{var G,le;if(!J)return;q&&((G=pt.getState)==null?void 0:G.call(pt,q))==="connected"&&Oe();const z=(le=pt.onStateChange)==null?void 0:le.call(pt,(Ce,Te)=>{Ce!==q||Te!=="connected"||Oe()});return()=>{z==null||z()}},[q,J,r]),l.useEffect(()=>{t&&at()},[t,me,r]),l.useEffect(()=>{var Ce,Te;const z=B.current,G=(Te=(Ce=z==null?void 0:z.ownerDocument)==null?void 0:Ce.defaultView)==null?void 0:Te.ResizeObserver;if(!z||!G)return;const le=new G(Me=>{const _e=Me[0];if(!_e)return;const{width:De,height:Ae}=_e.contentRect;M(He=>{const Ve=Math.round(De),ut=Math.round(Ae);return He.width===Ve&&He.height===ut?He:{width:Ve,height:ut}})});return le.observe(z),()=>le.disconnect()},[]),l.useEffect(()=>{if(F.current)return;const z=Pe();!Number.isFinite(z)||z<=0||C(G=>Q.current?z<G-ae?z:G:(Q.current=!0,z))},[A.height,A.width,L.height,L.width]),l.useEffect(()=>{Re&&Xe()},[Re,Ye,Ge]),l.useEffect(()=>{var le;const z=Z.current;if(Z.current=i,!i)return;z||w(!1),X.current&&(X.current=!1,Je());const G=Ne.current;G&&(Ne.current=null,he(G.text,G.seq,G.cols,G.rows,{force:!!G.force})),q&&J&&((le=pt.getState)==null?void 0:le.call(pt,q))==="connected"&&Oe(),fe.current&&ge.current===null&&ue(),ve(()=>{var Ce;(Ce=r.current)==null||Ce.bumpResize()})},[q,i,J]),l.useEffect(()=>()=>{ge.current!==null&&ce(),W(),ne()},[]),l.useEffect(()=>{const z=Ce=>{var Me;const Te=Ce.detail;Te!=null&&Te.sessionId&&Te.sessionId!==J||m&&((Me=r.current)==null||Me.bumpResize())},G=ee(),le=G===window?[window]:[window,G];for(const Ce of le)Ce.addEventListener("adhdev:fit-cli-terminal",z);return()=>{for(const Ce of le)Ce.removeEventListener("adhdev:fit-cli-terminal",z)}},[m,J,r]);const pe=m&&h&&!I&&(P.atTop||!P.canScroll)||g||!!k;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:B,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[pe&&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:()=>{V()},disabled:!J||g,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:g?"Loading older...":"Load older terminal output"}),k&&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:k})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[O&&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:O}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>_(z=>!z),title:"Spec debug — inspect current state, sections, and transition history",children:"Debug"}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{K()},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:()=>S(z=>!z),disabled:!m,"aria-label":"Open terminal control keys","aria-expanded":N,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),N&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":"Terminal control keys",className:"absolute right-0 top-10 w-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:()=>S(!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:()=>U("\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:()=>U(" "),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:()=>U("\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:()=>U("\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:()=>U("\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:()=>U("\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:()=>U("\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:()=>U(""),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:()=>U(""),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:()=>U(""),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:()=>{F.current=!0,C(z=>{const G=Math.max($e,Number((z-.1).toFixed(2)));return G>$e&&Xe(),G})},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:()=>{F.current=!0,C(z=>{const G=Math.min(je,Number((z+.1).toFixed(2)));return G>$e&&Xe(),G})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:E,className:Re?"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:Ge>0?`${Ge}px`:"100%",height:Ye>0?`${Ye}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:b},children:s.jsx(dd,{ref:r,readOnly:!m||!i,sizingMode:"measured",onViewportMetrics:H,onScrollMetrics:D,onInput:z=>{!m||(d==null||d(q,J,z))}})})})}),!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(Sd,{contextKey:e.tabKey,panelLabel:ot(e),isSending:a,isBusy:!!$,statusMessage:re,onSend:async z=>$?!1:n(z),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),T&&s.jsx(Bb,{activeConv:e,onClose:()=>_(!1)})]})}const Fb=5e3,Hb=12e3;function Wb(e){return e==="disconnected"||e==="reconnecting"}function Kb({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=Fb,reconnectActionDelayMs:o=Hb}){const i=Wb(e),[c,d]=l.useState(()=>!i||a<=0),[m,u]=l.useState(()=>!i||o<=0),p=l.useRef(!1);l.useEffect(()=>{if(!i){d(!1);return}if(p.current=!1,a<=0){p.current=!0,d(!0);return}d(!1);const w=setTimeout(()=>{p.current=!0,d(!0)},a);return()=>clearTimeout(w)},[a,i]),l.useEffect(()=>{if(!i){u(!1);return}if(o<=0){u(!0);return}u(!1);const w=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(w)},[o,i]);const f=i?c:e==="offline"||e==="auth_failed",y=!!(n&&e!=="auth_failed"&&(!i||m)),g=l.useMemo(()=>!t||e!=="connected"?!1:a<=0||p.current,[a,t,e]),x=e==="auth_failed"?"red":e==="offline"?"orange":"accent",k={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))"},j={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)"},h={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},v="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",I={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[f&&s.jsx("div",{className:v,style:I,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:k[x],border:j[x],color:h[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"})]})}),g&&s.jsx("div",{className:v,style:I,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 Yd({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(qo,{size:n}):s.jsx(Ns,{size:n})})}const Ut="New session",Xd="A connected machine is ready. Start a new session with any installed provider — CLI, ACP, or IDE.";function Ub(e){if(!e||e.isGitRepo===!1||e.reason==="not_git_repo")return null;if(e.hasConflicts)return`${e.branch||"Git"} · conflicts${e.changedFiles>0?` ${e.changedFiles}`:""}`;const t=[e.branch||"Git"];return e.changedFiles>0&&t.push(`±${e.changedFiles}`),e.ahead>0&&t.push(`↑${e.ahead}`),e.behind>0&&t.push(`↓${e.behind}`),t.length===1&&e.dirty&&t.push("dirty"),t.join(" ")}function zb(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 Gb(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 Un({git:e,className:t="",compact:r=!1}){const n=Ub(e),a=zb(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 ${Gb(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 Vb({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 Il({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Ml({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const i=ia(e.updatedAt),c=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${c?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",i].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[c?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),o()},children:"Delete"})]})]})}function qb({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:p,onShowAllHidden:f,onResetPanelsToMain:y,inboxOpen:g,onInboxOpenChange:x,hiddenOpen:k,onHiddenOpenChange:j,onOpenNewSession:h,onOpenDashboardGuide:v,guideNudgeVisible:I=!1,actionShortcuts:w,notifications:b,notificationUnreadCount:C,onOpenNotification:N,onMarkNotificationRead:S,onMarkNotificationUnread:T,onDeleteNotification:_,onOpenGitDialog:L,onOpenMeshGraph:M}){var Ie;const{ides:A,p2pStates:H={}}=qt(),P=!!e&&Qe(e)&&!qe(e),D=!!e&&qe(e),O=!!(e!=null&&e.daemonId)&&!!((Ie=e==null?void 0:e.coordinator)!=null&&Ie.meshId),R=c||(e?Nd(e)?"terminal":"chat":null),[B,E]=l.useState(!1),F=l.useRef(null),Q=l.useRef(null),Z=A.filter(ee=>ee.type==="adhdev-daemon"),Y=Vb({wsStatus:t,isConnected:r,daemonCount:Z.length,p2pStates:H}),te=Y.subtitle,fe=Y.tone==="connected"?"#22c55e":Y.tone==="limited"?"#eab308":"#ef4444",Ne=Y.tone==="connected"?"0 0 4px #22c55e80":Y.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",X=l.useMemo(()=>b.filter(ee=>!ee.readAt),[b]),we=l.useMemo(()=>b.filter(ee=>!!ee.readAt),[b]),ge=l.useMemo(()=>X.slice(0,9),[X]),be=C;l.useEffect(()=>{if(!g)return;const ee=ve=>{var ce;(ce=F.current)!=null&&ce.contains(ve.target)||x(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[g,x]),l.useEffect(()=>{if(!k)return;const ee=ve=>{var ce;(ce=Q.current)!=null&&ce.contains(ve.target)||j(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[k,j]),l.useEffect(()=>{if(!k&&!g)return;const ee=ve=>{if(!ve.altKey)return;const ce=ve.code.match(/^Digit([1-9])$/);if(!ce)return;const W=Number(ce[1])-1,ne=k?u[W]:void 0,ue=g?ge[W]:void 0;if(!(!ne&&!ue)){if(ve.preventDefault(),ve.stopPropagation(),ne){p==null||p(ne),j(!1);return}ue&&(N(ue),x(!1))}};return window.addEventListener("keydown",ee,!0),()=>window.removeEventListener("keydown",ee,!0)},[u,k,g,ge,j,x,N,p]);const de=ee=>{if(!ee)return;const ve=n.find(ce=>ce.tabKey===ee);ve&&(m==null||m(ve))};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(Ns,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?ot(e):"Dashboard"}),s.jsx("span",{title:Y.title,"aria-label":Y.title,className:"header-title-status-dot",style:{background:fe,boxShadow:Ne}}),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:fe,boxShadow:Ne}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[te&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",te]}),h&&s.jsx("button",{type:"button",onClick:h,className:"btn btn-secondary btn-sm ml-2",title:`${Ut}${w!=null&&w.openNewSession?` (${w.openNewSession})`:""}`,"aria-label":Ut,children:s.jsx(td,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[v&&s.jsxs("button",{type:"button",onClick:v,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:"Dashboard guide","aria-label":"Open dashboard guide",children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),I&&s.jsx("span",{children:"Guide"})]}),e&&(P||D||!qe(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:ks(e)||ot(e),children:ot(e)}),L&&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:()=>L(e.daemonId,e.workspacePath),children:s.jsx(Un,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Un,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),O&&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(Jt,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:"Mesh graph"})]}),(P||D)&&i&&s.jsxs(s.Fragment,{children:[P&&d&&R&&s.jsx(Yd,{mode:R,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:D?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(yt,{size:14})})]}),!qe(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(Go,{size:14})}),!P&&!qe(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Ft,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:F,children:[s.jsxs("div",{className:`dashboard-header-hidden${B?" is-drop-target":""}`,ref:Q,onDragEnter:ee=>{ee.dataTransfer.types.includes("text/tab-key")&&(ee.preventDefault(),E(!0))},onDragOver:ee=>{ee.dataTransfer.types.includes("text/tab-key")&&(ee.preventDefault(),ee.dataTransfer.dropEffect="move",E(!0))},onDragLeave:ee=>{ee.currentTarget.contains(ee.relatedTarget)||E(!1)},onDrop:ee=>{const ve=ee.dataTransfer.getData("text/tab-key");ee.preventDefault(),E(!1),de(ve)},children:[s.jsxs("button",{type:"button",onClick:()=>j(!k),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${w!=null&&w.toggleHiddenTabs?` (${w.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(Vo,{size:16}),u.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),k&&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(Il,{value:w==null?void 0:w.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[y&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:y,children:"Reset panels"}),u.length>0&&f&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),j(!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(Il,{value:w==null?void 0:w.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:ot(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(ee=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{p==null||p(ee),j(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:ot(ee)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(ee)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(ee)+1]}):null,ks(ee)]})]},ee.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>x(!g),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx($r,{size:16}),be>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:be})]}),g&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[X.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),X.map(ee=>s.jsx(Ml,{notification:ee,shortcutIndex:ge.indexOf(ee)>=0?ge.indexOf(ee)+1:void 0,onOpen:()=>N(ee),onMarkRead:()=>S(ee.id),onMarkUnread:()=>T(ee.id),onDelete:()=>_(ee.id)},ee.id))]}),we.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),we.map(ee=>s.jsx(Ml,{notification:ee,onOpen:()=>N(ee),onMarkRead:()=>S(ee.id),onMarkUnread:()=>T(ee.id),onDelete:()=>_(ee.id)},ee.id))]}),b.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function Nt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Yb(e,t){return String(e||"")!==String(t||"")}function Xb(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.resumableOnly;return!r&&!n&&!a&&!o?e:e.filter(i=>!(o&&!i.canResume||r&&![i.title,i.preview].map(d=>String(d||"").toLowerCase()).join(`
49
+ `).includes(r)||n&&!String(i.workspace||"").toLowerCase().includes(n)||a&&!gd(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
50
+ `).includes(a)))}function Jb(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 Jd(e,t={}){return Jb(Xb(e,t),t.sortMode||"recent")}function zn(e){return e?"Resume saved history":"Start fresh"}function ii(e){return e?"Resuming saved history…":"Starting fresh…"}function Qb(){return"Start fresh"}function Zb(e,t=!1){return e==="cli"?zn(t):e==="ide"?"Start IDE":"Start ACP session"}function eg(e,t=!1){return e==="cli"?ii(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function tg(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function sg(){return"Open saved history"}function rg(){return"Saved History"}function li(){return"Use saved history when you want continuity in the same provider conversation."}function ng(){return"No saved history found yet."}function ag(){return"Refresh saved history"}function og(){return"Refreshing saved history…"}function Gn(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function Vn(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 qn(e){return e==="start-fresh"?"Start fresh":"Restart"}function Yn(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Qd(e){return`Resume saved history with ${e}?`}function Zd(){return"Review or change the target workspace before resuming saved history."}function ig(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 eu({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:m,onClose:u,onNewChat:p,onSwitchSession:f,onRefreshHistory:y,onResumeSavedSession:g}){var _;const x=t.find(L=>L.id===e.routeId),k=(x==null?void 0:x.chats)||[],j=(_=x==null?void 0:x.activeChat)==null?void 0:_.id,h=Qe(e)&&!qe(e),[v,I]=l.useState(()=>Nt()),w=c||v,b=String(d||"").trim(),C=L=>{if(m){m(L);return}I(L)},N=l.useMemo(()=>a.map(L=>{const M=String(L.workspace||"").trim();return L.canResume||M||!b?L:{...L,workspace:b,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[b,a]),S=l.useMemo(()=>Jd(N,{textQuery:w.textQuery,workspaceQuery:w.workspaceQuery,modelQuery:w.modelQuery,resumableOnly:w.resumableOnly,sortMode:w.sortMode}),[N,w.modelQuery,w.resumableOnly,w.sortMode,w.textQuery,w.workspaceQuery]),T=s.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:h?rg():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Pb(e)}),h&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:li()})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(yt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!h&&s.jsx("button",{onClick:p,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"}),h?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:w.textQuery,onChange:L=>C({...w,textQuery:L.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:w.workspaceQuery,onChange:L=>C({...w,workspaceQuery:L.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:w.modelQuery,onChange:L=>C({...w,modelQuery:L.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:w.sortMode,onChange:L=>C({...w,sortMode:L.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:w.resumableOnly,onChange:L=>C({...w,resumableOnly:L.target.checked})}),"Resume-ready only"]})]}),S.map(L=>{const M=e.providerSessionId===L.providerSessionId,A=M||!L.canResume||!!i,H=L.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{A||!g||g(L)},disabled:A,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"} ${A?"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:L.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:L.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:ig(L.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:L.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:[L.workspace||"Workspace unknown",H?" · selected workspace":"",js(L.summaryMetadata)?` · ${js(L.summaryMetadata)}`:"",L.messageCount>0?` · ${L.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:M?"ACTIVE":L.canResume?H?"RESUME IN SELECTED WORKSPACE":i===L.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},L.id)})]}):k.map(L=>s.jsxs("div",{onClick:()=>{f(e.routeId,L.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${j===L.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 ${j===L.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:L.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:[L.id.substring(0,12),"..."]}),j===L.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},L.id)),(h&&!o&&S.length===0||!h&&k.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(mh,{size:32})}),s.jsx("div",{className:"text-[13px]",children:h?a.length>0?"No saved history matches these filters.":ng():"No recent chat sessions found."})]}),h&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:og()})})]}),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(oa,{size:13})," ",h?ag():"Refresh History"]})})})]})]});return typeof document>"u"?T:Cr.createPortal(T,document.body)}const Al={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 tu({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=Al[n.type]||Al.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var o;(o=n.actions)!=null&&o.length||r&&r(n)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:o=>{o.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(yt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((o,i)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${o.variant==="primary"||o.variant==="danger",""}`,style:o.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:o.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:c=>{c.stopPropagation(),o.onClick(),t(n.id)},children:o.label},i))})]})]},n.id)})})}const lg=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function cg(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function dg(e){return e.sessionId||e.instanceId||e.agentType}function La(e,t){return t||e||"unknown"}function su(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Pt(r,{fallbackId:r.id}));return t}function ru(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 ci(e,t={}){return ug(e,ru(e,t))}function ug(e,t={}){var p,f,y,g,x,k,j;const r=[],n=t.machineName,a=t.connectionState,o=cg(e),i=e.workspace||"",c=gf(e.type,{agentName:e.cliName}),d=Qe(e)||qe(e)?c:wt(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(h=>{var v,I,w;return{sessionId:h.id,instanceId:h.id,providerSessionId:h.providerSessionId,activeChatId:(v=h.activeChat)==null?void 0:v.id,transport:h.transport,sessionCapabilities:h.capabilities,agentType:h.providerType,agentName:h.providerName||wt(h.providerType),status:h.status,title:h.title,lastMessagePreview:h.lastMessagePreview,lastMessageRole:h.lastMessageRole,lastMessageAt:h.lastMessageAt,lastMessageHash:h.lastMessageHash,messages:((I=h.activeChat)==null?void 0:I.messages)||[],activeModal:((w=h.activeChat)==null?void 0:w.activeModal)||void 0,unread:h.unread,lastSeenAt:h.lastSeenAt,lastUpdated:h.lastUpdated,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,surfaceHidden:h.surfaceHidden,git:h.git,settings:h.settings,coordinator:h.coordinator,messageInput:h.messageInput}}):[],u=lg(e);if(u){const h=e.sessionId||e.instanceId,v=(p=e.settings)==null?void 0:p.meshCoordinatorFor,I=(f=e.settings)==null?void 0:f.meshNodeFor,w=v?" (Coordinator)":I?" (Mesh Node)":"",b=c+w,C=(y=e.activeChat)==null?void 0:y.activeModal,N=C&&Array.isArray(C.buttons)&&C.buttons.length>0,S=yf(e.activeChat,[{status:e.status,activeModal:(g=e.activeChat)==null?void 0:g.activeModal}],e.agents||[]),T=e.activeChat||{title:"",messages:[]};let _=T.title&&String(T.title).trim()?String(T.title).trim():"";const L=(x=e.activeChat)==null?void 0:x.id,M=e.chats;if(L&&Array.isArray(M)&&M.length>0){const E=M.find(F=>F.id===L||F.id&&String(F.id)===String(L));E!=null&&E.title&&String(E.title).trim()&&(_=String(E.title).trim())}const A=(Qe(e)||qe(e),e.type),H=(Qe(e)||qe(e))&&il(_,b,A)?"":_,P=T.messages||[],D=typeof L=="string"?L.trim():"",O=(Qe(e)||qe(e))&&D===String(e.type||"").trim(),R=D&&!O?D:e.providerSessionId,B=e.coordinator||(typeof((k=e.settings)==null?void 0:k.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:h,providerSessionId:e.providerSessionId,historySessionId:R,nativeSessionId:h,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:Qe(e)?e.mode||"terminal":"chat",agentName:b,agentType:A,status:S,title:H,messages:P,resume:e.resume,hostIdeType:!Qe(e)&&!qe(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:H||o||(Qe(e)?e.mode==="chat"?b:`Terminal${w}`:b),displaySecondary:Qe(e)&&o?b:d,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:N?C.buttons:void 0,modalMessage:N?C.message:void 0,streamSource:"native",tabKey:La(h,e.id),machineName:n,connectionState:a,settings:e.settings,coordinator:B,messageInput:e.messageInput})}if(u&&(Qe(e)||qe(e)))return r;for(const h of m){const v=h.activeModal&&Array.isArray(h.activeModal.buttons)&&h.activeModal.buttons.length>0,I=vf(h),w=dg(h),b=`${e.id}:${w}`,C=h.title&&String(h.title).trim()||"",N=il(C,h.agentName,h.agentType)?"":C,S=h.messages||[];if(!(h.transport==="cdp-webview"||!!h.sessionId||!!h.providerSessionId||S.length>0||v||!!N||!["idle","panel_hidden","disconnected","not_monitored"].includes(I)))continue;const _=h.coordinator||(typeof((j=h.settings)==null?void 0:j.meshCoordinatorFor)=="string"&&h.settings.meshCoordinatorFor?{meshId:h.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:h.sessionId||h.instanceId,providerSessionId:h.providerSessionId,historySessionId:h.activeChatId||h.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:h.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:h.sessionCapabilities,mode:"chat",agentName:h.agentName,agentType:h.agentType,status:I,title:N,messages:S,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:h.git||e.git,displayPrimary:N||o||h.agentName||d,displaySecondary:`${d} · ${h.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:h.lastMessagePreview,lastMessageRole:h.lastMessageRole,lastMessageAt:h.lastMessageAt,lastMessageHash:h.lastMessageHash,lastUpdated:h.lastUpdated||e.lastUpdated,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,modalButtons:v?h.activeModal.buttons:void 0,modalMessage:v?h.activeModal.message:void 0,streamSource:"agent-stream",tabKey:La(h.sessionId||h.instanceId,b),machineName:n,connectionState:a,settings:h.settings,coordinator:_,messageInput:h.messageInput})}return r.length===0&&r.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:La(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function nu(e){return String(e.type||e.id||"").trim()}function mg(e){var t;return e.category!=="cli"||!nu(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 Tr(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!mg(a))continue;const o=nu(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 Wr(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 Cn(e,t){const r=new Set(t.map(n=>n.type));return Wr(e).filter(n=>r.has(n))}function _r(e){return e.map(t=>t.type)}function pg(e,t){const r=Wr(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function hg(e,t){return Wr(e).filter(r=>r!==t)}function Tl(e,t,r){const n=Wr(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 _l({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 Ll({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]),d=l.useMemo(()=>Cn(e,t),[e,t]),m=e.length-d.length,u=t.filter(f=>!d.includes(f.type)),p=()=>{o&&(r(pg(d,o)),i(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:d.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):d.map((f,y)=>{const g=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]}),(g==null?void 0:g.icon)&&s.jsx("span",{"aria-hidden":"true",children:g.icon}),s.jsx("span",{className:"font-mono text-[12px] text-text-primary",children: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:g?`${g.label} · ${g.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(Tl(d,f,"up")),children:s.jsx(_l,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:n||y===d.length-1,title:"Move down",onClick:()=>r(Tl(d,f,"down")),children:s.jsx(_l,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(hg(d,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||u.length===0,children:[s.jsx("option",{value:"",children:u.length?"Select provider…":"No additional detected CLI providers"}),u.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:p,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 fg(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 au(e,t){const r=fg(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const ou=[{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:"🏄"}],iu=[{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:"🧩"}],lu=[{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:"🟠"}],xg=ou,bg=iu,gg=lu;function Zt(...e){return lp(cp(e))}function yg({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:Zt("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 Kr({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(yg,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Zt("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const To="adhdev:themechange";function vg(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function _s(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Ls(e){return e==="system"?vg():e}function cu(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function In(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(To,{detail:{preference:e,theme:t}}))}function wg(){const e=_s(),t=Ls(e);cu(t),In(e,t)}function qs(){const[e,t]=l.useState(_s),[r,n]=l.useState(()=>Ls(_s()));l.useEffect(()=>{cu(r)},[r]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const m=d.matches?"light":"dark";n(m),In("system",m)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=d=>{const m=d.detail||{},u=m.preference,p=m.theme;t(u==="dark"||u==="light"||u==="system"?u:_s()),n(p==="dark"||p==="light"?p:Ls(_s()))},c=d=>{if(d.key!=="theme")return;const m=_s(),u=Ls(m);t(m),n(u)};return window.addEventListener(To,i),window.addEventListener("storage",c),()=>{window.removeEventListener(To,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=Ls(i);t(i),n(c);try{localStorage.setItem("theme",i)}catch{}In(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=Ls(c);n(d);try{localStorage.setItem("theme",c)}catch{}return In(c,d),c})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const Pl={dark:"Dark",light:"Light",system:"System"};function jg({collapsed:e}){const{preference:t,cycleTheme:r}=qs(),n=t==="dark"?s.jsx(hh,{size:16}):t==="light"?s.jsx(ph,{size:16}):s.jsx(fh,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Pl[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:Pl[t]})]})}function Pa(e,t){return e?typeof e=="function"?e(t):e:null}function kg({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const[m,u]=l.useState(!1),[p,f]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),y=()=>u(!0),g=()=>u(!1),x=()=>{f(v=>{const I=!v;try{localStorage.setItem(d,I?"1":"0")}catch{}return I})},k=l.useMemo(()=>({collapsed:p,mobileMenuOpen:m,openMobileMenu:y,closeMobileMenu:g,toggleCollapsed:x}),[p,m]),j=v=>`nav-item${v.active?" active":""} cursor-pointer ${p?"justify-center py-2.5 px-0":""}${v.className?` ${v.className}`:""}`,h=v=>s.jsxs("div",{className:j(v),id:`nav-${v.id}`,onClick:()=>{v.onSelect(),g()},title:p?v.title??(typeof v.label=="string"?v.label:void 0):v.title,children:[s.jsx("span",{className:"nav-icon",children:v.icon}),!p&&v.label]},v.id);return s.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${p?" 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:g,onKeyDown:v=>v.key==="Escape"&&g()}),s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${p?"justify-center gap-0":""}`,children:Pa(t,k)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:g,children:s.jsx(yt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(h)}),n.map(v=>s.jsxs("div",{className:v.className??"border-t border-border-subtle pt-2 mt-2",children:[!p&&v.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:v.title}):null,v.items.map(h)]},v.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(h),Pa(o,k),s.jsx(jg,{collapsed:p}),Pa(i,k)]})]}),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:Zt("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 ma({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:Zt("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 Sg={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"},Ng={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function ns({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:Zt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Sg[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Ng[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 jt({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:Zt("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 wr(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:Zt("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"},Ig={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Mg({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:Zt("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:Zt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Ig[e])}),n]})}function ps({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 Ag({onPrefChange:e}){const[t,r]=Tf(),[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(ps,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx($r,{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(ps,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ft,{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:()=>{wd().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(ps,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(sd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:i=>o("completionAlert",i)}),s.jsx(ps,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xh,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:i=>o("approvalAlert",i)}),s.jsx(ps,{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 Xn(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Tg(e,t){const r=Xn(e),n=Xn(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 di(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function jr(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Tg(r,t)>=0)return!1;const n=Xn(r),a=Xn(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function _g(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Ra(e,t){return e instanceof Error?e.message:t}function Lg({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(ma,{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(Rg,{ide:i,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},i.id))})}function Rl({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 Cr.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 Pg(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...xg,...bg,...gg].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 Rg({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var A,H;const[o,i]=l.useState("idle"),[c,d]=l.useState(""),[m,u]=l.useState(null),[p,f]=l.useState("idle"),[y,g]=l.useState(""),x=e.version||null,k=((A=e.machine)==null?void 0:A.platform)||((H=e.system)==null?void 0:H.platform)||"",j=Pt(e,{fallbackId:e.id}),h=k==="win32"?"🪟":k==="darwin"?"🍎":"🐧",v=t.filter(P=>P.daemonId===e.id&&P.transport==="cdp-page"),I=t.filter(P=>P.daemonId===e.id&&P.transport==="pty"),w=t.filter(P=>P.daemonId===e.id&&P.transport==="acp"),b=e.p2p,C=async()=>{if(r){i("upgrading"),d("Starting upgrade...");try{const P=_g(await r(e.id,"daemon_upgrade",{}));P.alreadyLatest?(i("done"),d(`Already on v${P.version||"latest"}.`)):P.upgraded||P.success?(i("done"),d(`Upgrade to v${P.version||"latest"} started. Daemon is restarting...`)):(i("error"),d(P.error||"Upgrade failed"))}catch(P){i("error"),d(Ra(P,"Connection lost during upgrade"))}}},N=async()=>{if(u(null),!!n){f("loading");try{await n(e.id),f("done"),g("Machine disconnected.")}catch(P){f("error"),g(Ra(P,"Failed to disconnect"))}}},S=async()=>{if(u(null),!!a){f("loading");try{await a(e.id),f("done"),g("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(P){f("error"),g(Ra(P,"Failed to revoke token"))}}},T="0.9.82",_=di(e,T),L=jr(e,T),M=v.length+I.length+w.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:h}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:j}),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] ${_?"":"bg-bg-secondary"}`,style:_?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",x,!_&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&_&&s.jsx("button",{onClick:C,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${T}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${L?"↑ Update now":`↑ Update${` to v${T}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:p==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:p==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Mg,{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:[b&&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 ${b.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${b.state==="connecting"||b.state==="new"?"animate-pulse":""}`,style:b.state==="connecting"||b.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",b.state==="connected"?"connected":b.state==="connecting"||b.state==="new"?"connecting...":b.state||"off"]}),b.peers!==void 0&&b.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",b.peers," peer",b.peers!==1?"s":"",")"]})]}),b&&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:[v.map(P=>{const D=Pg(P.type),O=P.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:D.icon}),s.jsx("span",{children:D.name}),O!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${O?"bg-green-400":"animate-pulse"}`,style:O?void 0:{background:"var(--status-warning)"},title:O?"CDP connected":"CDP connecting..."})]},P.id)}),I.map(P=>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:P.cliName||"CLI"})]},P.id)),w.map(P=>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:P.cliName||"ACP"})]},P.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"||p==="error"?"text-red-400":o==="done"||p==="done"?"text-green-400":"text-text-muted"}`,children:y||c})]}),m==="disconnect"&&s.jsx(Rl,{title:"🔌 Disconnect Machine",message:`Disconnect "${j}" from ADHDev?
51
+
52
+ This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
53
+
54
+ Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:N,onCancel:()=>u(null)}),m==="revoke"&&s.jsx(Rl,{title:"⚠️ Remove Machine",message:`Remove "${j}" from your dashboard?
55
+
56
+ This will:
57
+ • Immediately disconnect the machine
58
+ • Delete the machine registration
59
+ • Require restarting ADHDev on that machine
60
+
61
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:S,onCancel:()=>u(null)})]})}const Dg=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function $g({daemonId:e,knownCliTypes:t=Dg}){const{sendCommand:r}=it(),[n,a]=l.useState({}),[o,i]=l.useState({}),[c,d]=l.useState(!0),[m,u]=l.useState(null),[p,f]=l.useState(null),[y,g]=l.useState(""),x=l.useCallback(async()=>{if(e){d(!0),f(null);try{const h=await r(e,"list_coordinator_prompts",{}),v=h!=null&&h.result&&typeof h.result=="object"?h.result:h;if(!(v!=null&&v.success)){f((v==null?void 0:v.error)||"Failed to load");return}const I=v.entries||{};g(v.dir||"");const w={};for(const b of t)w[b]=I[b]||{override:"",append:""};for(const b of Object.keys(I))w[b]||(w[b]=I[b]);a(w),i(JSON.parse(JSON.stringify(w)))}catch(h){f((h==null?void 0:h.message)||String(h))}finally{d(!1)}}},[r,e,t]);l.useEffect(()=>{x()},[x]);const k=l.useCallback(async(h,v)=>{var I;if(e){u(`${h}:${v}`),f(null);try{const w=((I=n[h])==null?void 0:I[v])||"",b=await r(e,"write_coordinator_prompt",{key:h,kind:v,content:w}),C=b!=null&&b.result&&typeof b.result=="object"?b.result:b;if(!(C!=null&&C.success)){f((C==null?void 0:C.error)||"Save failed");return}i(N=>({...N,[h]:{...N[h]||{override:"",append:""},[v]:w}}))}catch(w){f((w==null?void 0:w.message)||String(w))}finally{u(null)}}},[r,e,n]),j=l.useMemo(()=>(h,v)=>{var I,w;return(((I=n[h])==null?void 0:I[v])||"")!==(((w=o[h])==null?void 0:w[v])||"")},[n,o]);return e?s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",children:[s.jsxs("p",{children:["Customize the coordinator prompt this daemon's mesh coordinator sessions get. ",s.jsx("span",{className:"font-mono text-[11px]",children: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."]})]}),p&&s.jsx("div",{className:"text-[12px] text-red-400 bg-red-500/10 border border-red-500/20 rounded px-3 py-2",children:p}),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(([h,v])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-2",children:h}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Override"}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:4,value:v.override,onChange:I=>a(w=>({...w,[h]:{...w[h],override:I.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:m===`${h}: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 k(h,"override"),disabled:m===`${h}:override`||!j(h,"override"),children:m===`${h}:override`?"Saving…":j(h,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Append"}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:3,value:v.append,onChange:I=>a(w=>({...w,[h]:{...w[h],append:I.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:m===`${h}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void k(h,"append"),disabled:m===`${h}:append`||!j(h,"append"),children:m===`${h}:append`?"Saving…":j(h,"append")?"Save append":"Saved"})})]},h))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const Eg=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Bg(){const{preference:e,setPreference:t}=qs();return s.jsx("div",{className:"flex gap-2",children:Eg.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 Og(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 Fg(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Da(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Dl(e){const{r:t,g:r,b:n}=Fg(e);return .2126*Da(t)+.7152*Da(r)+.0722*Da(n)}function $l(e,t){const r=Dl(e),n=Dl(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function du(e){const t=Og(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return $l(t,r)>=$l(t,n)?r:n}const _o={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},Lo={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},Hg=[{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"}}}],uu="adhdev-chat-theme",mu="adhdev-chat-theme-custom";function Mn(){if(typeof window>"u")return"ember";try{return localStorage.getItem(uu)||"ember"}catch{return"ember"}}function Bt(e){try{const t=localStorage.getItem(mu);if(t){const r=JSON.parse(t);return{...e==="dark"?_o:Lo,...r[e]}}}catch{}return e==="dark"?_o:Lo}function ln(e,t){try{localStorage.setItem(mu,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 Jn(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 Wg={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function kr(e,t){var a;const r=(a=Wg[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",Jn(r,24)),n.style.setProperty("--accent-on-primary",du(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Jn(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 gs(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",Jn(e.accentColor,30)),t.style.setProperty("--accent-on-primary",du(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Jn(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 ui(){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 Kg(e){try{localStorage.setItem(uu,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ys()?"dark":"light";gs(Bt(t))}else ui(),kr(e,ys()?"dark":"light")}function Ug(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Mn();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ys()?"dark":"light";gs(Bt(t))}else ui(),kr(e,ys()?"dark":"light")}function ys(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function St({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 or({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 zg({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=l.useState(()=>Bt(r));l.useEffect(()=>{a(Bt(r))},[r]);const o=l.useCallback((i,c)=>{a(d=>{const m={...d,[i]:c},p=Bt(r==="dark"?"light":"dark");return r==="dark"?ln(m,p):ln(p,m),gs(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(or,{title:"App Background",children:[s.jsx(St,{label:"Background",value:n.bgPrimary,onChange:i=>o("bgPrimary",i)}),s.jsx(St,{label:"Surface",value:n.bgSecondary,onChange:i=>o("bgSecondary",i)}),s.jsx(St,{label:"Card",value:n.surfacePrimary,onChange:i=>o("surfacePrimary",i)})]}),s.jsxs(or,{title:"App Text",children:[s.jsx(St,{label:"Primary",value:n.textPrimary,onChange:i=>o("textPrimary",i)}),s.jsx(St,{label:"Secondary",value:n.textSecondary,onChange:i=>o("textSecondary",i)}),s.jsx(St,{label:"Muted",value:n.textMuted,onChange:i=>o("textMuted",i)})]}),s.jsxs(or,{title:"Borders & Accent",children:[s.jsx(St,{label:"Border subtle",value:n.borderSubtle,onChange:i=>o("borderSubtle",i)}),s.jsx(St,{label:"Border default",value:n.borderDefault,onChange:i=>o("borderDefault",i)}),s.jsx(St,{label:"Accent",value:n.accentColor,onChange:i=>o("accentColor",i)})]})]}),s.jsxs("div",{children:[s.jsxs(or,{title:"Chat Bubbles",children:[s.jsx(St,{label:"User bubble",value:n.userBubble,onChange:i=>o("userBubble",i)}),s.jsx(St,{label:"User text",value:n.userText,onChange:i=>o("userText",i)}),s.jsx(St,{label:"Agent bubble",value:n.assistantBubble,onChange:i=>o("assistantBubble",i)}),s.jsx(St,{label:"Agent text",value:n.assistantText,onChange:i=>o("assistantText",i)})]}),s.jsxs(or,{title:"Chat Layout",children:[s.jsx(St,{label:"Chat BG",value:n.containerBg,onChange:i=>o("containerBg",i)}),s.jsx(St,{label:"Send button",value:n.sendButton,onChange:i=>o("sendButton",i)}),s.jsx(St,{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?_o:Lo,d=Bt(e?"light":"dark");e?ln(i,d):ln(d,i),a(i),gs(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 Gg(){const[e,t]=l.useState(Mn),[r,n]=l.useState(!0),[a,o]=l.useState(()=>Bt("dark"));l.useEffect(()=>{n(ys());const d=new MutationObserver(()=>{const p=ys();n(p);const f=Mn();f==="custom"?gs(Bt(p?"dark":"light")):kr(f,p?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const p=ys();n(p);const f=Mn();f==="custom"?gs(Bt(p?"dark":"light")):kr(f,p?"dark":"light")};return m.addEventListener("change",u),()=>{d.disconnect(),m.removeEventListener("change",u)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?gs(Bt(r?"dark":"light")):(ui(),kr(e,r?"dark":"light"))},[e,r]),l.useEffect(()=>{o(Bt(r?"dark":"light"))},[r]);const i=d=>{t(d),Kg(d)},c=[...Hg,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:c.map(d=>{const m=e===d.id,u=r?d.preview.dark:d.preview.light,p=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>i(d.id),className:"text-left rounded-xl p-3 transition-all",style:{background: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:u.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:p},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[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:d.id==="custom"?"🎨 Custom":d.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:d.description})]})]})]},d.id)})}),e==="custom"&&s.jsx(zg,{dark:r,onColorsChange:d=>o(d)})]})}const mi="adhdev_mobileDashboardMode_v1",Po="adhdev:mobile-dashboard-mode-change";function pi(){try{return localStorage.getItem(mi)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Vg(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??pi())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==mi||t()};return window.addEventListener(Po,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Po,r),window.removeEventListener("storage",n)}}function qg(e){try{localStorage.setItem(mi,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Po,{detail:e}))}function Yg(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(pi()==="chat")},[]),s.jsx(ps,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ns,{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),qg(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const $a=new Map,El=new Map;function Xg(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 Jg(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 pu(){const{sendCommand:e}=it(),{injectEntries:t,getIdes:r}=Ir();return l.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??Tx,i=El.get(n)||0;if(!(a!=null&&a.force)&&i>0&&Date.now()-i<o)return;const c=$a.get(n);if(c)return c;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=Xg(m);if(!u)return;const p=r().find(y=>y.id===n),f=Jg(p,n,u.machine,u.timestamp||Date.now());t([f]),El.set(n,Date.now())})().finally(()=>{$a.delete(n)});return $a.set(n,d),d},[r,t,e])}function Qg(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 Zg(e,t){const{sendData:r}=it(),{injectEntries:n,getIdes:a}=Ir(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(d=>Vt.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const p=a().find(y=>y.id===d),f=Qg(p,d,u);n([f])}));return()=>{c.forEach(d=>d())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function ey(e,t){const{sendData:r}=it(),[n,a]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){a(null),i(!1);return}if(!(t!=null&&t.enabled)||!r){i(!1);return}a(null),i(!0);let c=null;const d=Vt.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 d.initialSendAccepted?c=setTimeout(()=>{i(!1)},Rx):i(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:o,applyDiagnostics:a}}function ty(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function hu(e){const{sendData:t}=it(),[r,n]=l.useState({});return l.useEffect(()=>{const a=ty(e);if(!a||!e.sessionId||!t){n({});return}const o=Vt.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}),Es.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 fu="adhdev_hiddenTabs",xu="adhdev_autoHiddenMeshTabs";function sy(){try{const e=localStorage.getItem(fu);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function us(e){try{localStorage.setItem(fu,JSON.stringify([...e]))}catch{}}function ry(){try{const e=localStorage.getItem(xu);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function Bl(e){try{localStorage.setItem(xu,JSON.stringify([...e]))}catch{}}function fr(e){return Ar(e)}function pa(e,t){return Qt(t).some(r=>e.has(r))}function bu(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 ny(e,t,r=new Set){return e.filter(n=>{if(!bu(n))return!1;const a=fr(n);return r.has(a)?!1:!pa(t,n)})}function ay(){const[e,t]=l.useState(sy),[r,n]=l.useState(ry),a=l.useCallback(f=>{const y=fr(f);t(g=>{const x=new Set(g);return x.has(y)?x.delete(y):x.add(y),us(x),x})},[]),o=l.useCallback(f=>{const y=fr(f);t(g=>{if(g.has(y))return g;const x=new Set(g);return x.add(y),us(x),x})},[]),i=l.useCallback(f=>{const y=fr(f);t(g=>{if(g.has(y))return g;const x=new Set(g);return x.add(y),us(x),x}),n(g=>{if(g.has(y))return g;const x=new Set(g);return x.add(y),Bl(x),x})},[]),c=l.useCallback(f=>{const y=fr(f);t(g=>{if(!g.has(y))return g;const x=new Set(g);return x.delete(y),us(x),x}),n(g=>{if(g.has(y))return g;const x=new Set(g);return x.add(y),Bl(x),x})},[]),d=l.useCallback(()=>{t(f=>{if(f.size===0)return f;const y=new Set;return us(y),y})},[]),m=l.useCallback((f,y)=>{t(g=>{const x=new Set(g);for(const k of y)x.add(k);return us(x),x})},[]),u=l.useCallback((f,y)=>{t(g=>{const x=new Set(g);for(const k of y)x.delete(k);return us(x),x})},[]),p=l.useCallback(f=>pa(e,f),[e]);return{hiddenTabs:e,autoHiddenTabs:r,toggleTarget:a,hideTarget:o,autoHideTarget:i,showTarget:c,showAllTabs:d,hideAllForDaemon:m,showAllForDaemon:u,isHidden:p}}const cn="adhdev_mutedConversations",Ea="adhdev_autoMutedMeshConversations";function Ol(e){try{const t=localStorage.getItem(e);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function ir(e,t){try{localStorage.setItem(e,JSON.stringify([...t]))}catch{}}function oy(e,t){return Qt(t).some(r=>e.has(r))}function iy(){const[e,t]=l.useState(()=>Ol(cn)),[r,n]=l.useState(()=>Ol(Ea)),a=l.useCallback(m=>{const u=Ar(m);t(p=>{if(p.has(u))return p;const f=new Set(p);return f.add(u),ir(cn,f),f})},[]),o=l.useCallback(m=>{const u=Qt(m);t(p=>{let f=!1;const y=new Set(p);for(const g of u)y.delete(g)&&(f=!0);return f?(ir(cn,y),y):p}),n(p=>{let f=!1;const y=new Set(p);for(const g of u)y.delete(g)&&(f=!0);return f?(ir(Ea,y),y):p})},[]),i=l.useCallback(m=>{Qt(m).some(f=>e.has(f))?o(m):a(m)},[e,a,o]),c=l.useCallback(m=>{if(!bu(m))return;const u=Ar(m);r.has(u)||(n(p=>{if(p.has(u))return p;const f=new Set(p);return f.add(u),ir(Ea,f),f}),t(p=>{if(p.has(u))return p;const f=new Set(p);return f.add(u),ir(cn,f),f}))},[r]),d=l.useCallback(m=>oy(e,m),[e]);return{mutedTargets:e,autoMutedTargets:r,muteTarget:a,unmuteTarget:o,toggleTarget:i,autoMuteIfCoordinator:c,isMuted:d}}function ly(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function cy(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 dy(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 uy({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(!ly(o))throw new Error(cy(o));return}await dy(e.sessionId,t,a)}function gu(e){const{ides:t,isP2PActive:r,p2pStates:n}=qt(),{sendCommand:a}=it(),[o,i]=l.useState(null),[c,d]=l.useState(!1),[m,u]=l.useState(null),p=l.useMemo(()=>rf(t,e),[t,e]),f=!!p,y=l.useMemo(()=>p?p.prompt.promptId===o?null:p:null,[o,p]),g=l.useCallback(async j=>{if(!y)return;const h=md(y.prompt,j);d(!0),u(null);try{const v=(n==null?void 0:n[y.daemonId])==="connected"||r===!0;await uy({promptSession:y,response:h,useP2PCommand:v,sendCommand:a}),i(y.prompt.promptId)}catch(v){throw u(v instanceof Error?v.message:String(v)),v}finally{d(!1)}},[r,n,y,a]),x=l.useCallback(()=>{y&&i(y.prompt.promptId)},[y]),k=l.useCallback(()=>{i(null),u(null)},[]);return{promptSession:y,hasActivePrompt:f,responseError:m,isSubmitting:c,submit:g,cancel:x,reopen:k}}function yu(e){return e instanceof Error?e.message:String(e||"")}function my(e){const t=yu(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 py(e){const t=yu(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function vu({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!Qe(e)||qe(e))return;const o=Vs(e);if(o===t)return;const i=e.sessionId;i&&a(c=>({...c,[i]:t}));try{await n(Cs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Gt(e),mode:t})}catch(c){const d=py(c);i&&!d&&a(m=>{const u={...m};return o===wu(r,i)?delete u[i]:u[i]=o,u}),my(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function Fl(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 hy(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=Fl(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(d=>Fl(d,t)):a.childSessions,c=i!==a.childSessions;return o!==a||c?(r=!0,{...o,...c?{childSessions:i}:{}}):a});return r?n:e}function wu(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 fy(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))wu(t,a)===o&&(delete n[a],r=!0);return r?n:e}function xy({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){l.useEffect(()=>{wd()},[]);const a=l.useMemo(()=>e.map(o=>({id:o.tabKey,name:Vd(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return Rf(a),l.useEffect(()=>{if(Object.keys(t).length===0)return;const i=setTimeout(()=>{r(c=>{const d=Date.now(),m={};for(const[u,p]of Object.entries(c))d-p<5e3&&(m[u]=p);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 d=c.filter(m=>m.timestamp>i).slice(-100);return d.length===c.length?c:d})},6e4);return()=>clearInterval(o)},[n]),null}function Hl(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 vs(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=Hl(t==null?void 0:t.receivedAt)||Hl(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function Ro(e,t=0){return vs(e)||e.lastUpdated||t||0}function ju(e){return vs(e)||e.lastUpdated||0}function ku(e,t,r=ju){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 Do(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 by(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Do(e)&&!e.title.trim()}function gy(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(Do(r))-Number(Do(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:ku(t,r)})[0]||null}function Ot(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=gy(a);return n?o&&by(n)?o:n:o||r[0]||null}function yy(e){const t=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return!t||r.startsWith(`${t}:`)?r:`${t}:${r}`}function vy(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=yy(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 Ba(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 wy(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 Wl(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?wy(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 jy(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||""),Wl(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||""),Wl(r.activeChat)].join(":"))].join("|")}function ky(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 Sy(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of Qt({routeId:n.routeId}))r.set(o,a);for(const o of Qt({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Qt({tabKey:n.tabKey}))r.set(o,n)}return r}function Ny(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Cy(e){const t=Ny(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 Iy({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=l.useMemo(()=>vy(e),[e]),o=l.useMemo(()=>su(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),m=l.useRef(new Map),u=l.useRef(new Map),p=l.useMemo(()=>{const I=new Map,w=[];for(const S of a){const{connectionState:T="new",machineName:_}=ru(S,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),L=jy(S),M=m.current.get(S.id);if(M&&M.ide===S&&M.sourceSignature===L&&M.connectionState===T&&M.machineName===_){I.set(S.id,M),w.push(...M.conversations);continue}const A=ci(S,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),H={ide:S,sourceSignature:L,connectionState:T,machineName:_,conversations:A};I.set(S.id,H),w.push(...A)}m.current=I;const b=new Map,C=S=>{const T=Cy(S),_=u.current.get(S.tabKey);if(_&&_.signature===T)return b.set(S.tabKey,_),_.timestamp;const L={signature:T,timestamp:ju(S)||(_==null?void 0:_.timestamp)||0};return b.set(S.tabKey,L),L.timestamp},N=[...w].sort((S,T)=>ku(S,T,C));return u.current=b,N},[a,t,o]),f=l.useMemo(()=>{const I=ky(p,r);return Ba(i.current,I)?i.current:(i.current=I,I)},[p,r]),y=l.useMemo(()=>{const I=new Map,w=Array.from(new Set(f.map(b=>b.routeId)));for(const b of w){const C=Ot(f,b);C&&I.set(b,C)}return I},[f]),g=l.useMemo(()=>{const I=new Map;for(const w of f){const b=y.get(w.routeId),C=w.streamSource==="native"&&b?b:w;for(const N of Qt({providerSessionId:w.providerSessionId,sessionId:w.sessionId,tabKey:w.tabKey}))I.set(N,C)}return I},[f,y]),x=l.useMemo(()=>Sy(f,y),[f,y]),k=l.useCallback(I=>{if(I)return g.get(I)},[g]),j=l.useCallback(I=>{if(I)return x.get(I)},[x]),h=l.useMemo(()=>{const I=f.filter(w=>!pa(n,w));return Ba(c.current,I)?c.current:(c.current=I,I)},[f,n]),v=l.useMemo(()=>{const I=h.map(w=>w.tabKey);return Ba(d.current,I)?d.current:(d.current=I,I)},[h]);return{chatIdes:a,conversations:f,visibleConversations:h,visibleTabKeys:v,resolveConversationBySessionId:k,resolveConversationByTarget:j}}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 d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function Ay({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){l.useEffect(()=>{tt.setIdes(e)},[e]),l.useEffect(()=>{tt.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=tt.onToast(o=>{r(c=>c.some(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(d=>d.id!==o.id)),i)});return()=>{a()}},[r]),l.useEffect(()=>{const a=Ud.on("status_event",o=>{tt.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 d=c.targetSessionId||c.targetKey||c.daemonId,m=n(d),u=(m==null?void 0:m.routeId)||c.daemonId;if(!u)return;const p=Number(c.buttonIndex),f=c.button||((x=m==null?void 0:m.modalButtons)==null?void 0:x[p])||"Approve",y=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),g=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(y);t(u,"resolve_action",{action:g?"approve":"reject",button:f,...Number.isFinite(p)&&{buttonIndex:p},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(k=>console.error("[SW Action] approval failed:",k))};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 Ty="adhdev_dashboardLayout_v1",_y="adhdev_dashboardDockview_v1",Ly="adhdev_dashboardDockviewHiddenRestore_v1",lr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function hi(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Py(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Su(e){return`${Ty}:${e}`}function Ry(e){const t=Su(e);return hi(t,null)}function Dy(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=Su(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Nu(e){return`${_y}:${e}`}function $y(e){const t=Nu(e);return hi(t,null)}function Ey(e,t){try{const r=Nu(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Cu(e){return`${Ly}:${e}`}function By(e){const t=Cu(e);return hi(t,{})}function Oy(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 Fy(){return{groupAssignments:[...lr.groupAssignments],focusedGroup:lr.focusedGroup,groupActiveTabIds:{...lr.groupActiveTabIds},groupTabOrders:{...lr.groupTabOrders},groupSizes:[...lr.groupSizes]}}function Hy(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Wy(){const[e]=l.useState(()=>Py(typeof window<"u"?window.innerWidth:1280)),[t,r]=l.useState(()=>new Map),[n,a]=l.useState(0),[o,i]=l.useState({}),[c,d]=l.useState({}),[m,u]=l.useState([]),[p,f]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[y,g]=l.useState(!1),x=l.useCallback(()=>{if(y)return;const S=Ry(e)??Fy();r(new Map(S.groupAssignments)),a(S.focusedGroup),i(S.groupActiveTabIds),d(S.groupTabOrders),u(S.groupSizes),g(!0)},[y,e]);l.useEffect(()=>{y&&Dy(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:c,groupSizes:m})},[y,e,t,n,o,c,m]),l.useEffect(()=>{const S=window.matchMedia("(max-width: 767px)"),T=_=>f(_.matches);return S.addEventListener("change",T),()=>S.removeEventListener("change",T)},[]);const k=l.useCallback(S=>{r(S)},[]),j=l.useCallback(S=>{a(S)},[]),h=l.useCallback(S=>{i(S)},[]),v=l.useCallback(S=>{d(S)},[]),I=l.useCallback(S=>{u(S)},[]),w=l.useCallback(S=>{j(S)},[j]),b=l.useCallback((S,T)=>{i(_=>(_[S]??null)===(T??null)?_:{..._,[S]:T})},[]),C=l.useCallback((S,T)=>{d(_=>{const L=_[S];return Hy(L,T)?_:{..._,[S]:T}})},[]),N=l.useCallback((S,T)=>{const _=T.get(S)??0;return b(_,S),w(_),_},[w,b]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:k,focusedGroup:n,updateFocusedGroup:j,focusGroup:w,groupActiveTabIds:o,updateGroupActiveTabIds:h,setGroupActiveTab:b,groupTabOrders:c,updateGroupTabOrders:v,setGroupTabOrder:C,groupSizes:m,updateGroupSizes:I,isMobile:p,hasHydratedStoredLayout:y,hydrateStoredLayout:x,focusConversationTab:N}}function Ky(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=ua(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Uy({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,ides:p,handleRefreshHistory:f}){const y=l.useRef(!1),g=l.useRef(!1),x=l.useRef(null),k=l.useRef(!1);l.useEffect(()=>{if(!e||y.current||t.length===0)return;if(!a){o();return}const j=r(e);j&&(i(j.tabKey,n),y.current=!0,g.current=!0,x.current!=null&&(window.clearTimeout(x.current),x.current=null),c(h=>{const v=new URLSearchParams(h);return v.delete("activeTab"),v},{replace:!0}))},[e,t,r,n,a,o,i,c]),l.useEffect(()=>{if(!(g.current||a)&&t.length!==0){if(!e){o(),g.current=!0;return}if(y.current){g.current=!0;return}if(x.current==null)return x.current=window.setTimeout(()=>{x.current=null,!(g.current||a)&&(o(),g.current=!0)},1500),()=>{x.current!=null&&(window.clearTimeout(x.current),x.current=null)}}},[e,t.length,a,o]),l.useEffect(()=>{if(!d){k.current=!1;return}if(!m||k.current||u)return;const j=p.find(h=>h.id===m.routeId);j&&(!j.chats||j.chats.length===0||Ky(j.chats,m))&&(k.current=!0,f())},[d,m,u,p,f])}function Oa(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=ua(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Iu({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[i,c]=l.useState(!1),[d,m]=l.useState(!1),u=l.useCallback(async g=>{try{await e("standalone","launch_ide",{ideType:g,enableCdp:!0})}catch(x){console.error("Launch failed",x)}},[e]),p=l.useCallback(async(g,x)=>{try{const k=g||(t==null?void 0:t.daemonId)||"",j=await e(k,"switch_chat",{id:x,sessionId:x,...fs(t)}),h=j==null?void 0:j.result;if((j==null?void 0:j.success)===!0||h==="switched"||h==="switched-by-title")return;h===!1||h==="not_found"?rr(a,"⚠️ Session tab not found — try refreshing history"):typeof h=="string"&&h.startsWith("error:")?rr(a,`⚠️ Switch error: ${h}`):rr(a,"⚠️ Session switch failed")}catch(k){console.error("Switch failed",k),rr(a,`❌ Switch failed: ${k.message||"connection error"}`)}},[t,e,a]),f=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const g=xs(t);await e(g,"new_chat",{...fs(t)}),Zx(g,t.sessionId,ua(t)[0]),o(x=>({...x,[t.tabKey]:Date.now()}))}catch(g){console.error("New chat failed",g)}finally{c(!1)}}},[t,i,e,o]),y=l.useCallback(async()=>{var g,x;if(!(!t||d)){m(!0);try{const k=xs(t),j=async()=>e(k,"list_chats",{forceExpand:!0,...fs(t)});let h=await j(),v=(h==null?void 0:h.chats)||((g=h==null?void 0:h.result)==null?void 0:g.chats);Oa(v,t)&&(await new Promise(I=>setTimeout(I,450)),h=await j(),v=(h==null?void 0:h.chats)||((x=h==null?void 0:h.result)==null?void 0:x.chats)),h!=null&&h.success&&Array.isArray(v)&&(n(t.routeId,v),Oa(v,t)&&!Oa(r,t)&&rr(a,"⚠️ History dialog did not fully open — try once more"))}catch(k){console.error("Refresh history failed",k)}finally{m(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:p,handleNewChat:f,handleRefreshHistory:y}}function zy(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 Gy(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Kl(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 dn(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[i,c]of e)!r.has(i)||c<=0||n.includes(c)||n.push(c);n.sort((i,c)=>i-c);const a={};n.forEach((i,c)=>{a[i]=c}),n.length===0&&(a[0]=0);const o=new Map;for(const[i,c]of e){if(!r.has(i)||c<=0)continue;const d=a[c];typeof d=="number"&&d>0&&o.set(i,d)}return{assignments:o,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function Ul(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 Vy(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 qy(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 zl(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 Gl(e){return Array(e).fill(100/e)}function Yy({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:m}){const u=l.useRef(null),p=l.useMemo(()=>dn(e,m),[e,m]),f=p.assignments,y=l.useMemo(()=>c?1:p.groupCount,[p.groupCount,c]),g=y>1,x=l.useCallback((w,b)=>{t(C=>{const N=new Map(dn(C,m).assignments);return b===0?N.delete(w):N.set(w,b),N}),n(C=>({...C,[b]:w})),r(b)},[t,m,n,r]),k=l.useCallback(w=>{t(b=>{const C=dn(b,m).assignments,N=new Map;for(const[S,T]of C)T!==w&&(T>w?N.set(S,T-1):N.set(S,T));return N}),i(b=>{if(b.length<=1)return[];const C=[...b];C.splice(w,1);const N=C.reduce((S,T)=>S+T,0);return N>0?C.map(S=>S/N*100):[]}),r(0)},[t,m,i,r]),j=l.useCallback((w,b)=>{b.preventDefault();const C=u.current;if(!C)return;const N=b.clientX,S=C.offsetWidth,T=o.length===y?[...o]:Gl(y),_=M=>{const H=(M.clientX-N)/S*100,P=[...T];P[w]=Math.max(15,T[w]+H),P[w+1]=Math.max(15,T[w+1]-H),i(P)},L=()=>{document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",L),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",_),document.addEventListener("mouseup",L)},[o,y,i]),h=l.useCallback((w,b,C)=>{if(y>=4)return;const N=C==="left"?b:b+1;t(S=>{const T=dn(S,m).assignments,_=new Map;for(const L of d){const M=T.get(L.tabKey)??0,A=M>=N?M+1:M;A>0&&_.set(L.tabKey,A)}return N>0&&_.set(w,N),_}),i(S=>{const T=S.length===y?[...S]:Gl(y),_=T[b]??100/y,L=Math.max(15,_/2),M=Math.max(15,_/2),A=[...T];A[b]=L,A.splice(N,0,M);const H=A.reduce((P,D)=>P+D,0);return A.map(P=>P/H*100)}),n(S=>{const T=zl(S,N);return T[N]=w,T}),a(S=>{const T=zl(S,N);return T[N]=[w],T}),r(N)},[y,t,m,d,i,n,a,r]);l.useEffect(()=>{zy(e,f)||t(f)},[e,f,t]),l.useEffect(()=>{const{mapping:w,usedGroups:b}=p;n(C=>{const N=Ul(C,w);return Kl(C,N)?C:N}),a(C=>{const N=Ul(C,w);return Kl(C,N)?C:N}),r(C=>{const N=c?0:Vy(C,b,w);return C===N?C:N}),i(C=>{const N=c?[]:qy(C,b,p.groupCount);return Gy(C,N)?C:N})},[p,c,n,a,r,i]);const v=l.useMemo(()=>{const w=Array.from({length:y},()=>[]);for(const b of d){const C=f.get(b.tabKey)??0,N=Math.min(C,y-1);w[N].push(b)}return w},[d,f,y]),I=l.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:f,numGroups:y,isSplitMode:g,groupedConvs:v,moveTabToGroup:x,closeGroup:k,handleResizeStart:j,splitTabRelative:h,clearAllSplits:I}}function Fa(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 Xy(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 un(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function fi(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=Fa(t.channel)||Fa(e.updateChannel)||Fa(e.releaseChannel)||void 0,n=Xy(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=un(t.targetVersion)||un(e.serverVersion)||void 0,o=un(t.minVersion)||void 0,i=un(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 Ps(e,t=null){return fi(e).targetVersion||t}function Mu(e){return fi(e).channel||null}function Au(e){const t=fi(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 Jy({ides:e,sendDaemonCommand:t}){const r="0.9.82",n=l.useMemo(()=>e.filter(p=>p.type!=="adhdev-daemon"?!1:di(p,Ps(p,r))).sort((p,f)=>Number(jr(f,Ps(f,r)))-Number(jr(p,Ps(p,r)))),[r,e]),a=l.useMemo(()=>n.some(p=>jr(p,Ps(p,r))),[r,n]),o=l.useMemo(()=>n.map(p=>Ps(p,r)).find(p=>typeof p=="string"&&p.trim().length>0)||r,[r,n]),[i,c]=l.useState(!1),[d,m]=l.useState({}),u=l.useCallback(async p=>{var y,g;const f=e.find(x=>x.id===p);if(f){m(x=>({...x,[p]:"upgrading"}));try{const x=await t(p,"daemon_upgrade",Au(f));(y=x==null?void 0:x.result)!=null&&y.upgraded||(g=x==null?void 0:x.result)!=null&&g.success?m(k=>({...k,[p]:"done"})):m(k=>({...k,[p]:"error"}))}catch{m(x=>({...x,[p]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const Tu=80;function An(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function Qy(e){return{...e,createdAt:An(e.createdAt),updatedAt:An(e.updatedAt,e.createdAt),lastEventAt:An(e.lastEventAt,e.updatedAt||e.createdAt)}}function Zy(e){const t=Ar(e);return t==="unknown:"?e.id:t}function e0(e){return[e.type,Ed(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function t0(e,t=Tu){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Zy(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 s0(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=la(a,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=An(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),m=e0({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(Qy({id:m,dedupKey:m,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Id(a),preview:dx(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return t0(n)}function r0(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function n0(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Tu}=e,a=l.useMemo(()=>s0(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=l.useMemo(()=>r0(a),[a]);return{notifications:a,unreadCount:o}}function a0({notifications:e,sendDaemonCommand:t}){const r=l.useCallback(o=>{const i=e.find(d=>d.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),n=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}const o0=l.createContext(null);function _u(){return l.useContext(o0)}function xi(...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 i0(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 bi(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=i0(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 l0(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 c0(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function gi(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=c0(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,u)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${u}`:m==="/"||m==="\\"?`${i}${u}`:`${m.replace(/[\\/]+$/,"")}${i}${u}`,d=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,u)=>m.name.localeCompare(u.name)):[];return{path:o,directories:d}}function d0(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 Lu(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:d0(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function u0(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 Lr(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Pu(e){return Fr(e)||e.tabKey||e.routeId||null}function Ru(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=Ot(e.conversations,n)||e.conversations.find(i=>i.routeId===n);if(o!=null&&o.tabKey)return o.tabKey}return t||r||n||null}function ss(e){return String(e||"").trim()}function Du(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Qn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function m0(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function p0(e,t){const r=ss(e.providerSessionId),n=ss(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(ss).filter(Boolean);return!!(r&&i.includes(r)||n&&i.includes(n))});return a?a.tabKey:n||r||null}function h0(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=Du(t.daemonId);if(n&&n!==e.machineId)return null;const a=ss(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=ss(e.resumeSessionId),i=ss(e.launchedSessionId),c=ss(t.providerSessionId),d=ss(t.targetSessionId);if(o&&o!==c&&o!==d||i&&i!==c&&i!==d)return null;const m=Qn(e.workspacePath);if(m){const u=Qn(t.workspaceName);if(u&&!m0(u,m))return null}return p0(t,r)}function Vl(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function f0({ides:e,conversations:t,onOpenSession:r}){const[n,a]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,a(null)},[]),c=l.useCallback(d=>{o.current=d,a(d)},[]);return l.useEffect(()=>{if(!n)return;const d=Qn(n.workspacePath),m=e.find(p=>{var k,j,h,v;if(!p||p.type==="adhdev-daemon"||Du(p.daemonId||p.id)!==n.machineId||(Mr(p)?"cli":Ds(p)?"acp":"ide")!==n.kind)return!1;const g=String(p.agentType||p.type||"");if(n.providerType&&g!==n.providerType)return!1;if(n.resumeSessionId)return String(p.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const I=String(n.launchedSessionId||"");return[p.providerSessionId,p.sessionId,p.instanceId,p.id].map(b=>String(b||"")).filter(Boolean).includes(I)}if(d){const I=Qn(p.workspace||p.runtimeWorkspaceLabel);return I?I===d:!1}return Number(p.lastUpdated||p._lastUpdate||p.timestamp||((v=(h=(j=(k=p.activeChat)==null?void 0:k.messages)==null?void 0:j.at)==null?void 0:h.call(j,-1))==null?void 0:v.timestamp)||0)>=n.startedAt-5e3});if(!m)return;const u=Ru({entrySessionId:m.sessionId,entryInstanceId:m.instanceId,entryRouteId:m.id,conversations:t});u&&(i(),r(u))},[i,t,e,r,n]),l.useEffect(()=>tt.onStatusEvent(d=>{const m=o.current;if(!m)return;const u=h0(m,d,t);u&&(i(),r(u))}),[i,t,r]),l.useEffect(()=>{if(!n)return;const d=window.setTimeout(()=>{a(m=>!m||m.startedAt!==n.startedAt?m:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[n]),{trackPendingLaunch:c}}function x0({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const i=_u(),{launchCli:c}=na(),d=l.useCallback(async(k,j)=>gi(e,k,j),[e]),m=l.useCallback(async(k,j)=>{if(!j.trim())return{ok:!1,error:"Choose a workspace path first."};try{const h=await e(k,"workspace_add",{path:j.trim()});return h!=null&&h.success?{ok:!0}:{ok:!1,error:(h==null?void 0:h.error)||"Could not save workspace"}}catch(h){return{ok:!1,error:h instanceof Error?h.message:"Could not save workspace"}}},[e]),u=l.useCallback(async(k,j,h)=>{var v;try{const I={ideType:j,enableCdp:!0};(v=h==null?void 0:h.workspacePath)!=null&&v.trim()&&(I.workspace=h.workspacePath.trim());const w=await e(k,"launch_ide",I);return!(w!=null&&w.success)&&(w==null?void 0:w.success)!==void 0?{ok:!1,error:(w==null?void 0:w.error)||"Could not launch IDE"}:(t({machineId:k,kind:"ide",providerType:j,workspacePath:(h==null?void 0:h.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(I){return{ok:!1,error:I instanceof Error?I.message:"Could not launch IDE"}}},[e,t]),p=l.useCallback(async(k,j,h,v)=>{var w,b,C;const I=Date.now();try{const N={cliType:h};(w=v==null?void 0:v.workspacePath)!=null&&w.trim()?N.dir=v.workspacePath.trim():v!=null&&v.workspaceId&&(N.workspaceId=v.workspaceId),(b=v==null?void 0:v.resumeSessionId)!=null&&b.trim()&&(N.resumeSessionId=v.resumeSessionId.trim()),Array.isArray(v==null?void 0:v.cliArgs)&&v.cliArgs.length>0&&(N.cliArgs=v.cliArgs),(C=v==null?void 0:v.initialModel)!=null&&C.trim()&&(N.initialModel=v.initialModel.trim());const S=await c(k,N),T=(S==null?void 0:S.result)||S,_=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);return S!=null&&S.success&&_?(t({machineId:k,kind:j,providerType:h,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,launchedSessionId:_,startedAt:I}),{ok:!0}):S!=null&&S.success?(t({machineId:k,kind:j,providerType:h,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:I}),{ok:!0}):{ok:!1,error:(S==null?void 0:S.error)||(T==null?void 0:T.error)||`Could not launch ${j.toUpperCase()} session`}}catch(N){return Vl(N)?(t({machineId:k,kind:j,providerType:h,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:I}),{ok:!0}):{ok:!1,error:N instanceof Error?N.message:`Could not launch ${j.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async k=>{var j;if(i!=null&&i.listMeshes)return i.listMeshes(k);if(!k)return[];try{const h=await e(k,"list_meshes",{}),v=(h==null?void 0:h.result)??h;if((v==null?void 0:v.success)===!1)throw new Error((v==null?void 0:v.error)||"Could not load meshes");return(Array.isArray(v==null?void 0:v.meshes)?v.meshes:Array.isArray((j=v==null?void 0:v.result)==null?void 0:j.meshes)?v.result.meshes:[]).map(w=>{var b;return{id:String((w==null?void 0:w.id)||""),name:String((w==null?void 0:w.name)||(w==null?void 0:w.id)||"Untitled mesh"),repoIdentity:(w==null?void 0:w.repoIdentity)||(w==null?void 0:w.repo_identity)||null,workspace:Array.isArray(w==null?void 0:w.nodes)&&w.nodes.length>0?String(((b=w.nodes[0])==null?void 0:b.workspace)||""):null,nodesCount:Array.isArray(w==null?void 0:w.nodes)?w.nodes.length:void 0,status:(w==null?void 0:w.status)||null}}).filter(w=>w.id)}catch(h){throw console.error("List meshes failed",h),h}},[i,e]),y=l.useCallback(async(k,j,h)=>{if(!j.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(k,j,h);const v=Date.now();try{const I={meshId:j.trim()};h.trim()&&(I.cliType=h.trim());const w=await e(k,"launch_mesh_coordinator",I),b=(w==null?void 0:w.result)??w;if((b==null?void 0:b.success)===!1||(w==null?void 0:w.success)===!1){const N=String((b==null?void 0:b.code)||(w==null?void 0:w.code)||""),S=u0((b==null?void 0:b.meshCoordinatorSetup)||(b==null?void 0:b.manualSetup)||(w==null?void 0:w.meshCoordinatorSetup)||(w==null?void 0:w.manualSetup));return{ok:!1,error:(b==null?void 0:b.error)||(w==null?void 0:w.error)||"Could not launch mesh coordinator",code:N||void 0,manualSetup:S}}const C=(b==null?void 0:b.sessionId)||(b==null?void 0:b.id);return C?r(C):t({machineId:k,kind:"cli",providerType:(b==null?void 0:b.cliType)||h.trim()||void 0,workspacePath:(b==null?void 0:b.workspace)||null,startedAt:v}),{ok:!0}}catch(I){return Vl(I)?(t({machineId:k,kind:"cli",providerType:h.trim()||void 0,startedAt:v}),{ok:!0}):{ok:!1,error:I instanceof Error?I.message:"Could not launch mesh coordinator"}}},[i,r,e,t]),g=l.useCallback(async(k,j)=>{if(!k||!j)return[];try{const h=await e(k,"list_saved_sessions",{providerType:j,kind:"cli",limit:30}),v=(h==null?void 0:h.result)??h;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(h){return console.error("List saved sessions failed",h),[]}},[e]),x=l.useCallback(async k=>{await vu({conversation:n,mode:k,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:m,handleLaunchMachineIde:u,handleLaunchMachineProvider:p,handleListMachineMeshes:f,handleLaunchMeshCoordinator:y,handleListMachineSavedSessions:g,setActiveCliViewMode:x}}function b0(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 g0(e,t,r=Date.now()){return!e||!b0(t)?null:{tabKey:e,nonce:r}}function y0({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:i}){const[c,d]=l.useState(null),[m,u]=l.useState(null),p=l.useMemo(()=>{var k,j;if(!e){if(c){const h=t.find(v=>v.tabKey===c);if(h)return h}return r[0]}const x=n[a];if(x){const h=t.find(v=>v.tabKey===x);if(h)return h}return((k=o[a])==null?void 0:k[0])||((j=o[0])==null?void 0:j[0])},[t,c,a,n,o,e,r]),f=l.useCallback(x=>{d(x)},[]),y=l.useCallback(x=>{d(x.tabKey),i(k=>{const j=new URLSearchParams(k),h=mx(x);return h?j.set("activeTab",h):j.delete("activeTab"),j},{replace:!0})},[i]),g=l.useCallback((x,k)=>{const j=g0(x,k);j&&u(j)},[]);return{activeConv:p,openDesktopConversation:y,requestScrollToBottom:g,scrollToBottomRequest:m,setDesktopActiveTab:f}}function v0(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 w0(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 j0({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),d=l.useRef(null);l.useEffect(()=>{const m=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const u=On(e,r),p=w0({tabKey:e.tabKey,historySessionId:Fr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:vs(e),liveState:u}),f=p.autoReadKey,y=v0({autoReadKey:f,shouldMarkSeen:p.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!p.shouldMarkSeen){y.shouldCancelPending&&m(),a.current=f;return}if(!y.shouldSchedule)return;y.shouldCancelPending&&m();const g=()=>{if(document.visibilityState!=="visible"||a.current===f)return;a.current=f,o.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const k=p.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:k,completionMarker:p.completionMarker}).catch(()=>{})};if(o.current=y.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(g,1500);const k=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=k,document.addEventListener("visibilitychange",k);return}const x=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(g,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=x,document.addEventListener("visibilitychange",x)},[e,t,r,n]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function Ha(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 k0({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var O;const{launchCli:m}=na(),[u,p]=l.useState(!1),[f,y]=l.useState([]),[g,x]=l.useState(()=>Nt()),[k,j]=l.useState(!1),[h,v]=l.useState(null),I=l.useRef(null),w=l.useMemo(()=>r||t||e,[e,r,t]),b=!!w&&Qe(w)&&!qe(w),C=l.useMemo(()=>{if(!w||!b)return null;const R=w.daemonId||w.routeId||"",B=Gt(w),E=Ha(w);return`${R}:${B}:${w.providerSessionId||""}:${E}`},[w,b]),N=l.useMemo(()=>!w||!b?"":Ha(w),[w,b]),{isCreatingChat:S,isRefreshingHistory:T,handleSwitchSession:_,handleNewChat:L,handleRefreshHistory:M}=Iu({sendDaemonCommand:a,activeConv:w,chats:(O=n.find(R=>R.id===(w==null?void 0:w.routeId)))==null?void 0:O.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),A=l.useCallback(()=>{p(!0)},[]),H=l.useCallback(()=>{p(!1)},[]),P=l.useCallback(async()=>{if(!(!w||!b||k)){j(!0);try{const R=w.daemonId||w.routeId,B=Gt(w),E=Ha(w),F=await a(R,"list_saved_sessions",{agentType:B,providerType:B,kind:"cli",limit:50,...w.providerSessionId?{providerSessionId:w.providerSessionId}:{},...E?{workspace:E}:{}}),Q=(F==null?void 0:F.result)??F;y(Array.isArray(Q==null?void 0:Q.sessions)?Q.sessions:[])}catch(R){console.error("Refresh saved sessions failed",R),y([])}finally{j(!1)}}},[w,k,b,a]);l.useEffect(()=>{if(!u){I.current=null;return}if(!b){I.current=null,y([]),j(!1);return}!C||k||I.current!==C&&(I.current=C,P())},[P,u,k,b,C]);const D=l.useCallback(async R=>{if(!w||!b||!R.providerSessionId||!R.workspace)return;const B=w.daemonId||w.routeId,E=Gt(w);try{v(R.providerSessionId);const F=await m(B,{cliType:E,dir:R.workspace,resumeSessionId:R.providerSessionId,initialModel:yd(R.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Q=(F==null?void 0:F.result)??F,Z=typeof(Q==null?void 0:Q.sessionId)=="string"?Q.sessionId:typeof(Q==null?void 0:Q.id)=="string"?Q.id:"";Z&&d(Y=>{const te=new URLSearchParams(Y);return te.set("activeTab",Z),te},{replace:!0}),H()}catch(F){console.error("Resume saved session failed",F)}finally{v(null)}},[H,w,b,a,d]);return{historyModalOpen:u,openHistoryModal:A,closeHistoryModal:H,historyTargetConv:w,isSavedSessionHistoryTarget:b,isHistoryCreatingChat:S,isHistoryRefreshingHistory:T,handleHistorySwitchSession:_,handleHistoryNewChat:L,handleHistoryRefresh:M,savedHistorySessions:f,savedHistoryFilters:g,setSavedHistoryFilters:x,missingWorkspaceResumePath:N,isSavedHistoryLoading:k,resumingSavedHistorySessionId:h,handleRefreshSavedHistory:P,handleResumeSavedHistorySession:D}}function S0({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}){const[d,m]=l.useState(null),[u,p]=l.useState(null),f=l.useMemo(()=>{if(e||!n)return null;const j=c(n);return j&&!Qe(j)&&!qe(j)?j:null},[e,n,c]),y=l.useMemo(()=>{const j=d==null?void 0:d.routeId;if(!j)return null;const h=d!=null&&d.tabKey?o.find(v=>v.tabKey===d.tabKey):a?o.find(v=>v.tabKey===a):null;return(h==null?void 0:h.routeId)===j?h:Ot(o,j)},[o,d,a]),g=l.useMemo(()=>{if(y)return i.find(j=>j.id===y.routeId)},[i,y]);l.useEffect(()=>{f&&(m({routeId:f.routeId,tabKey:hl(f)}),p(f),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,f]);const x=l.useCallback(j=>{j&&(m({routeId:j.routeId,tabKey:hl(j)}),p(j))},[]),k=l.useCallback(()=>{m(null),p(null)},[]);return{remoteDialogConv:y,remoteDialogIdeEntry:g,remoteDialogActiveConv:u,setRemoteDialogActiveConv:p,openRemoteDialog:x,closeRemoteDialog:k}}function N0({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:p,remoteDialogActiveConv:f,setRemoteDialogActiveConv:y,openRemoteDialog:g,closeRemoteDialog:x}=S0({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}),[k,j]=l.useState(!1),[h,v]=l.useState(null),I=l.useCallback(async C=>{const N=C||d;!N||!Qe(N)&&!qe(N)||(v(N),j(!0))},[d]),w=l.useCallback(()=>{j(!1),v(null)},[]),b=l.useCallback(async C=>{const N=h||d;if(!N||!Qe(N)&&!qe(N)){w();return}j(!1);try{const S=Gt(N),T=N.routeId||N.daemonId||"";await m(T,"stop_cli",{cliType:S,targetSessionId:N.sessionId,mode:C})}catch(S){console.error("Stop CLI failed:",S)}finally{v(null)}},[d,w,h,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:p,remoteDialogActiveConv:f,setRemoteDialogActiveConv:y,openRemoteDialog:g,closeRemoteDialog:x,cliStopDialogOpen:k,cliStopTargetConv:h,requestCliStop:I,cancelCliStop:w,confirmCliStop:b}}function Wa(e,t=!0){return(e??!0)&&t}const yi=l.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:d,handleForceSendChat:m,isSendingChat:u,sendFeedbackMessage:p=null,handleFocusAgent:f,isFocusingAgent:y,actionLogs:g,userName:x,scrollToBottomRequestNonce:k,isInputActive:j=!0,isVisible:h=!0}){const v=n,I=!n,w=Wa(h,v),b=Wa(h,I),C=Wa(h),N=hu(t),S=N.status||N.modalMessage||N.modalButtons?{...t,...N.status?{status:N.status}:{},...N.modalMessage!==void 0?{modalMessage:N.modalMessage}:{},...N.modalButtons!==void 0?{modalButtons:N.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(fd,{activeConv:S,onModalButton:i}),S.transport!=="pty"&&S.transport!=="acp"&&S.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(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,S.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:v?"visible":"hidden",pointerEvents:v?"auto":"none"},children:s.jsx(Ob,{activeConv:S,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:p,isVisible:w,isInputActive:j&&w})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:I?"visible":"hidden",pointerEvents:I?"auto":"none"},children:s.jsx(Ao,{activeConv:S,ideEntry:a,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:p,handleFocusAgent:f,isFocusingAgent:y,actionLogs:g,userName:x,scrollToBottomRequestNonce:k,isInputActive:j&&b,isVisible:b})})]}):s.jsx(Ao,{activeConv:S,ideEntry:a,handleSendChat:d,handleForceSendChat:m,isSendingChat:u,sendFeedbackMessage:p,handleFocusAgent:f,isFocusingAgent:y,actionLogs:g,userName:x,scrollToBottomRequestNonce:k,isInputActive:j&&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 C0({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var v,I,w;const i=Dr(),c=Cs(e),d=o?null:Cd(e),m=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!o&&e.streamSource==="agent-stream"&&!!e.agentName,p=!o&&!u&&(e.transport==="pty"||e.transport==="acp"),f=Ws(e),y=ux(e),g=(v=e.settings)==null?void 0:v.meshNodeFor,x=e.meshQueueStats,k=((I=e.coordinator)==null?void 0:I.meshId)||((w=e.settings)==null?void 0:w.meshCoordinatorFor),j=l.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),h=l.useCallback(()=>{if(r){r();return}const b=Pu(e);b&&i(Lr(b))},[e,i,r]);return!m&&!u&&!p&&!d&&!g&&!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:h,title:y,children:[s.jsx(Ft,{size:12}),s.jsx("span",{children:y})]}):s.jsxs("span",{className:"conversation-meta-chip",title:y,children:[s.jsx(Ft,{size:12}),s.jsx("span",{children:y})]})),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[s.jsx(Hs,{size:12}),s.jsx("span",{children:f})]}),p&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[s.jsx(Hs,{size:12}),s.jsx("span",{children:f})]}),d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:j,title:d,children:[s.jsx(as,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(as,{size:12}),s.jsx("span",{children:d})]})),g&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(as,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),k&&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(oh,{size:12}),s.jsxs("span",{children:[x.pending," Pending"]})]})]})}function I0({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:m,onOpenNativeConversation:u,onOpenMachine:p,onOpenHistory:f,onOpenRemote:y,onOpenMeshGraph:g,onStopCli:x,cliViewMode:k,onSetCliViewMode:j,handleSendChat:h,handleForceSendChat:v,handleFocusAgent:I,handleModalButton:w,handleRelaunch:b}){var L,M;const C=l.useRef(null),N=Qe(e)&&!t,S=N&&k==="terminal",T=!!e.daemonId&&!!((L=e.coordinator)!=null&&L.meshId||(M=e.settings)!=null&&M.meshCoordinatorFor),_=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 ${_} 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(zo,{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:ot(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(C0,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>p(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[N&&k&&s.jsx(Yd,{mode:k,onChange:j,compact:!0}),N&&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(yt,{size:14})}),T&&g&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(Jt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(Go,{size:14})}),!t&&!N&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(e),type:"button",children:s.jsx(Ft,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(yi,{activeConv:e,clearToken:0,isCliTerminal:S,ideEntry:n,terminalRef:C,handleModalButton:w,handleRelaunch:b,handleSendChat:h,handleForceSendChat:v,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:I,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const Ka={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 $u(){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(Ka[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:Ka[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Ka[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 Eu({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Ft},{key:"chats",label:"Chats",icon:Ns}];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 mn({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 As({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 cr({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 A0({conversation:e,onCancel:t,onConfirm:r}){const n=ot(e),a=ks(e);return s.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"fade-in relative w-full sm:w-[min(92vw,420px)] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] border border-border-subtle bg-bg-primary shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border-subtle bg-[var(--surface-primary)] px-4 py-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base font-extrabold text-text-primary",children:"Hide this chat from the inbox?"}),s.jsx("div",{className:"mt-1 text-[13px] leading-relaxed text-text-muted",children:"This only collapses the chat locally. You can restore it from Hidden tabs."})]}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary text-text-secondary transition-colors hover:bg-surface-primary hover:text-text-primary",onClick:t,"aria-label":"Cancel hide chat",children:s.jsx(yt,{size:16})})]}),s.jsx("div",{className:"px-4 py-4",children:s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary/60 px-3.5 py-3",children:[s.jsx("div",{className:"truncate text-sm font-bold text-text-primary",children:n}),s.jsx("div",{className:"mt-1 truncate text-xs text-text-muted",children:a})]})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-border-subtle bg-bg-secondary px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))]",children:[s.jsx("button",{type:"button",className:"btn btn-secondary min-h-[40px] px-4 text-sm",onClick:t,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary min-h-[40px] px-4 text-sm",onClick:r,children:"Hide tab"})]})]})]})}function pn({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onOpenMeshGraph:o,onCollectChatDebugBundle:i,isMuted:c,onToggleMute:d}){var L,M;const m=t==="needs_attention"||t==="task_complete",u=t==="working",p=t==="earlier",f=t==="task_complete",{isReconnecting:y,isConnecting:g}=Gs(e.conversation),x=ot(e.conversation),k=ks(e.conversation),j=Gd(e.conversation,{requiresAction:t==="needs_attention"}),h=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":u?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":p?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",v=m?"bg-accent-primary shadow-glow":u?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":p?"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",I=p?"text-text-secondary":"text-text-primary",w=p?"text-text-muted":"text-text-secondary",b=p?"text-text-secondary opacity-80":"text-text-muted",C=p?"text-text-muted opacity-80":"text-text-muted",N=!u&&!f,S=!!e.conversation.daemonId&&!!((L=e.conversation.coordinator)!=null&&L.meshId||(M=e.conversation.settings)!=null&&M.meshCoordinatorFor),T="text-[color:var(--status-warning)]",_=A=>{if(!i)return;A.preventDefault(),A.stopPropagation();const H=i==null?void 0:i(e.conversation);Promise.resolve(H).catch(P=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",P)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${h}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||u?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${v}`,style: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:A=>{A.preventDefault(),A.stopPropagation(),a()},"aria-label":`Hide ${x}`,title:"Hide conversation",children:[s.jsx(Vo,{size:11}),s.jsx("span",{children:"Hide"})]}),d&&s.jsxs("button",{type:"button",className:`mobile-inbox-mute-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border px-2 text-[10px] font-semibold transition-colors ${c?"border-amber-500/40 bg-amber-500/10 text-amber-300 hover:bg-amber-500/20":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:A=>{A.preventDefault(),A.stopPropagation(),d()},"aria-label":c?`Unmute ${x}`:`Mute ${x}`,title:c?"Unmute (resume notifications)":"Mute notifications",children:[s.jsx($r,{size:11}),s.jsx("span",{children:c?"Muted":"Mute"})]}),S&&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:A=>{A.preventDefault(),A.stopPropagation(),o(e.conversation)},"aria-label":`Open mesh graph for ${x}`,title:"Open live repo mesh graph",children:[s.jsx(Jt,{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:_,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 ${I}`,children:x}),N&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${C}`,children:hd(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${w}`,children:[s.jsx("span",{className:"truncate",children:k}),s.jsx(Un,{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:`${T} animate-pulse`,children:"Reconnecting…"})]}):g?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):j==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:T,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${b}`,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"}),u&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]})},e.conversation.tabKey)}function ql({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 T0({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:p,onHideConversation:f,onOpenMeshGraph:y,onOpenNewSession:g,onOpenMachine:x,onOpenSettings:k,onSectionChange:j,wsStatus:h="connected",isStandalone:v=!1,onCollectChatDebugBundle:I,isConversationMuted:w,onToggleMuteConversation:b}){const[C,N]=l.useState(null),S=h==="disconnected"||h==="reconnecting"||h==="offline"||h==="auth_failed",T=i.length>0,_=t.length>0||r.length>0||n.length>0||a.length>0,L=e==="machines"?"Machines":"Chats",M=v?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",A=v?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",H=l.useCallback(async O=>{const R=xs(O);if(!R)return;const B=Array.isArray(O.messages)?O.messages:[],E=Ld({activeConv:O,visibleMessages:B,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:B.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),F=await m(R,"get_chat_debug_bundle",{...fs(O),delivery:"daemon_file",frontendSnapshot:E}),Q=yr(F),Z=Dd(Q),Y=await Rd(Z);Y==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),tt.showToast(Pd(Q,{locatorCopyStatus:Y}),Y==="failed"?"warning":"success")},[d,m]),P=I||H,D=l.useCallback(()=>{C&&(f==null||f(C),N(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:L}),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($r,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:k,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(aa,{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] ${A}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:S?s.jsx(cr,{icon:s.jsx(ql,{}),title:h==="offline"?"Network offline":h==="auth_failed"?"Session expired":"Reconnecting",subtitle:h==="offline"?"Waiting for network…":h==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):i.length===0?s.jsx(cr,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:v?"Waiting for your daemon":"Connect your machines",subtitle:v?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can launch sessions with any installed provider.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!v&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx($u,{})})}):s.jsx(As,{children:i.map((O,R)=>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] ${R>0?"border-t border-border-subtle/70":""}`,onClick:()=>x(O.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(O.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:O.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:O.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[O.unread," new"]}):O.total>0?`${O.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:O.subtitle}),O.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[O.total," chat",O.total!==1?"s":"",O.unread>0?` · ${O.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},O.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(mn,{title:"Needs attention",className:"mb-0"}),s.jsx(As,{children:t.map((O,R)=>s.jsx("div",{className:R>0?"border-t border-border-subtle/70":"",children:s.jsx(pn,{item:O,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>N(O.conversation):void 0,onOpenMeshGraph:y,onCollectChatDebugBundle:P,isMuted:w==null?void 0:w(O.conversation),onToggleMute:b?()=>b(O.conversation):void 0})},O.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(mn,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(As,{children:r.map((O,R)=>s.jsx("div",{className:R>0?"border-t border-border-subtle/70":"",children:s.jsx(pn,{item:O,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>N(O.conversation):void 0,onOpenMeshGraph:y,onCollectChatDebugBundle:P,isMuted:w==null?void 0:w(O.conversation),onToggleMute:b?()=>b(O.conversation):void 0})},O.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(mn,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(As,{children:n.map((O,R)=>s.jsx("div",{className:R>0?"border-t border-border-subtle/70":"",children:s.jsx(pn,{item:O,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>N(O.conversation):void 0,onOpenMeshGraph:y,onCollectChatDebugBundle:P,isMuted:w==null?void 0:w(O.conversation),onToggleMute:b?()=>b(O.conversation):void 0})},O.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(mn,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(As,{children:a.map((O,R)=>s.jsx("div",{className:R>0?"border-t border-border-subtle/70":"",children:s.jsx(pn,{item:O,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>N(O.conversation):void 0,onOpenMeshGraph:y,onCollectChatDebugBundle:P,isMuted:w==null?void 0:w(O.conversation),onToggleMute:b?()=>b(O.conversation):void 0})},O.conversation.tabKey))}):_?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):S?s.jsx(cr,{icon:s.jsx(ql,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):T?s.jsx(cr,{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(Ns,{size:20})}),title:"No conversations yet",subtitle:Xd,children:g&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:g,"aria-label":Ut,title:Ut,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:Ut})]})}):s.jsx(cr,{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(As,{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:p,children:"Restore all"})]})})})]}),e==="chats"&&g&&_&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:g,"aria-label":Ut,title:Ut,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(A0,{conversation:C,onCancel:()=>N(null),onConfirm:D}),s.jsx(Eu,{section:e,onSectionChange:j})]})}function _0(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 Bu(e){const t=[e.workspace||"Workspace unknown"],r=js(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=_0(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function vi({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:d,onConfirm:m}){const[u,p]=l.useState(r);l.useEffect(()=>{p(r)},[r]);const f=l0(r),y=u.trim();return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:c,"aria-label":"Close folder browser",children:s.jsx(yt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!f||a||d(f)},disabled:!f||a,children:[s.jsx(zo,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:g=>p(g.target.value),onKeyDown:g=>{g.key!=="Enter"||!y||a||(g.preventDefault(),d(y))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!y||a||d(y)},disabled:!y||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):n.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:n.map(g=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(g.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(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:g.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:g.path})]})]},g.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(y||r),disabled:!y&&!r||a,children:i})]})]})})}function Ou({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:i="Launch",busyLabel:c="Launching…",busy:d=!1,showArgsInput:m,argsValue:u,onArgsChange:p,showModelInput:f,modelValue:y,onModelChange:g,historyProviderNode:x,onConfirm:k,onCancel:j}){const h=n==null?void 0:n.find(v=>v.key===a);return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:j,"aria-label":"Close launch confirmation",children:s.jsx(yt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:v=>o(v.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:n.map(v=>s.jsx("option",{value:v.key,children:v.label},v.key))}),(h==null?void 0:h.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h.description})]}),x,r.map(v=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:v.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:v.value})]},`${v.label}:${v.value}`)),f&&g&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:y||"",onChange:v=>g(v.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),m&&p&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:v=>p(v.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:j,disabled:d,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:k,disabled:d,children:[s.jsx(ed,{size:14}),d?c:i]})]})]})})}function Yl(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Fu(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,o=[];a&&o.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])o.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${Yl(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const i=(r==null?void 0:r.trim())||"",c=i?(t.workspaces||[]).find(d=>d.path===i):null;if(i&&!c&&o.push({key:`custom:${i}`,label:Yl(i),description:i,workspaceId:null,workspacePath:i}),n){const d=`saved:${n}`;if(o.some(m=>m.key===d))return{options:o,selectedKey:d}}return c?{options:o,selectedKey:`saved:${c.id}`}:i?{options:o,selectedKey:`custom:${i}`}:{options:o,selectedKey:"__home__"}}function L0(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function P0(e){return[L0(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function R0(e){return e.lastLaunchedAt?ia(e.lastLaunchedAt):""}function Hu(e){return{metaText:P0(e),updatedLabel:R0(e)}}function Ua(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function D0({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var Je,Ze,dt,ft;const i=Or(),[c,d]=l.useState(!1),m=(((Je=e.detectedIdes)==null?void 0:Je.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(he=>({id:he.id,path:he.path,label:he.label})),[e]),p=e.defaultWorkspaceId||null,[f,y]=l.useState(p||((Ze=u[0])==null?void 0:Ze.id)||""),[g,x]=l.useState(""),[k,j]=l.useState(""),[h,v]=l.useState([]),[I,w]=l.useState(!1),[b,C]=l.useState(""),[N,S]=l.useState(!1),[T,_]=l.useState(Ua(m,t.length,r.length)),L=l.useRef(null),[M,A]=l.useState(null),H=l.useRef("__home__"),[P,D]=l.useState("__home__"),[O,R]=l.useState(""),[B,E]=l.useState(""),[F,Q]=l.useState(""),[Z,Y]=l.useState([]),[te,fe]=l.useState(()=>Nt().textQuery),[Ne,X]=l.useState(()=>Nt().workspaceQuery),[we,ge]=l.useState(()=>Nt().modelQuery),[be,de]=l.useState(()=>Nt().resumableOnly),[Ie,ee]=l.useState(()=>Nt().sortMode),[ve,ce]=l.useState(!1),[W,ne]=l.useState(!1),ue=l.useRef(null),me=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const J=f==="__custom__"?g.trim():((dt=u.find(he=>he.id===f))==null?void 0:dt.path)||"",q=f==="__custom__"&&!!J&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),$=f!=="__custom__"&&((ft=u.find(he=>he.id===f))==null?void 0:ft.path)||"",re=l.useMemo(()=>(e.recentLaunches||[]).map(he=>he.workspace),[e]),xe=l.useCallback(async he=>{w(!0),C("");try{const Oe=await a(he);j(Oe.path),x(Oe.path),v(Oe.directories)}catch(Oe){C(Oe instanceof Error?Oe.message:"Could not load folder")}finally{w(!1)}},[a]),je=l.useCallback(()=>{var Oe;y("__custom__"),S(!0);const he=bi(e.platform,xi(g.trim(),$,re,e.defaultWorkspacePath,(Oe=u.find(et=>et.id===p))==null?void 0:Oe.path,u.map(et=>et.path)));xe(he)},[g,p,xe,re,$,e.platform,u]),ae=l.useCallback(he=>{if(he!=null&&he.workspaceId){y(he.workspaceId),x("");return}if(he!=null&&he.workspacePath){y("__custom__"),x(he.workspacePath);return}y(""),x("")},[]),Pe=l.useCallback(he=>{if(y(he),he==="__custom__"){je();return}x("")},[je]),$e=l.useCallback(he=>{y("__custom__"),x(he)},[]),Re=l.useCallback((he,Oe)=>{L.current=Oe,H.current=he.selectedWorkspaceKey||"__home__",D(he.selectedWorkspaceKey||"__home__"),R(he.initialArgs||""),E(he.initialModel||""),Q(""),Y([]);const et=he.providerType?`${e.id}:${he.providerType}`:null;if(Yb(me.current,et)){const ze=Nt();fe(ze.textQuery),X(ze.workspaceQuery),ge(ze.modelQuery),de(ze.resumableOnly),ee(ze.sortMode)}me.current=et,A(he),he.providerType&&o&&(ce(!0),o(he.providerType).then(ze=>Y(ze||[])).catch(ze=>console.warn("Failed to load saved sessions",ze)).finally(()=>ce(!1)))},[o,e.id]),Ge=l.useMemo(()=>Jd(Z,{textQuery:te,workspaceQuery:Ne,modelQuery:we,resumableOnly:be,sortMode:Ie}),[we,be,Z,Ie,te,Ne]);l.useEffect(()=>{F&&(Ge.some(he=>he.providerSessionId===F)||Q(""))},[Ge,F]);const Ye=l.useCallback(()=>{L.current&&(ne(!0),L.current().finally(()=>{L.current=null,ne(!1),A(null)}))},[]),Xe=l.useCallback(()=>{L.current=null,A(null)},[]),at=l.useCallback(he=>{H.current=he,D(he)},[]);return l.useEffect(()=>{var he;ue.current!==e.id&&(ue.current=e.id,y(p||((he=u[0])==null?void 0:he.id)||"__custom__"),x(""),j(""),v([]),C(""),S(!1),fe(Nt().textQuery),X(Nt().workspaceQuery),ge(Nt().modelQuery),de(Nt().resumableOnly),ee(Nt().sortMode),me.current=null,_(Ua(m,t.length,r.length)))},[r.length,t.length,p,m,e.id,u]),l.useEffect(()=>{var he;f!=="__custom__"&&(f&&u.some(Oe=>Oe.id===f)||y(p||((he=u[0])==null?void 0:he.id)||"__custom__"))},[p,f,u]),l.useEffect(()=>{T==="ide"&&m||T==="cli"&&t.length>0||T==="acp"&&r.length>0||_(Ua(m,t.length,r.length))},[T,r.length,t.length,m]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:m,workspaceRows:u,defaultWorkspaceId:p,workspaceChoice:f,customWorkspacePath:g,browseCurrentPath:k,browseDirectories:h,browseBusy:I,browseError:b,browseDialogOpen:N,activeLauncherKind:T,launchConfirm:M,launchConfirmWorkspaceKeyRef:H,launchConfirmWorkspaceKey:P,launchConfirmArgs:O,launchConfirmModel:B,launchConfirmResumeId:F,launchConfirmSavedSessions:Z,launchConfirmTextFilter:te,launchConfirmWorkspaceFilter:Ne,launchConfirmModelFilter:we,launchConfirmResumableOnly:be,launchConfirmSortMode:Ie,filteredLaunchConfirmSavedSessions:Ge,launchConfirmSessionsLoading:ve,launchConfirmBusy:W,resolvedWorkspacePath:J,canCreateMissingWorkspace:q,openBrowseDialog:je,loadBrowsePath:xe,handleWorkspaceChoiceChange:Pe,chooseCustomWorkspacePath:$e,setCustomWorkspacePath:x,setBrowseDialogOpen:S,setActiveLauncherKind:_,openLaunchConfirm:Re,handleConfirmLaunch:Ye,closeLaunchConfirm:Xe,setWorkspaceSelectionFromOption:ae,setLaunchConfirmWorkspaceKeyAndSync:at,setLaunchConfirmArgs:R,setLaunchConfirmModel:E,setLaunchConfirmResumeId:Q,setLaunchConfirmTextFilter:fe,setLaunchConfirmWorkspaceFilter:X,setLaunchConfirmModelFilter:ge,setLaunchConfirmResumableOnly:de,setLaunchConfirmSortMode:ee}}function $0({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:d,section:m,showBottomNav:u,onBack:p,onSectionChange:f,onOpenConversation:y,onOpenRecent:g,onOpenMachineDetails:x,onMachineUpgrade:k,onLaunchDetectedIde:j,onAddWorkspace:h,onBrowseDirectory:v,onLaunchWorkspaceProvider:I,onListSavedSessions:w}){const b=P=>P==="ide"?"Workspace":P==="cli"?"CLI":"ACP",C=r.slice(0,4),N=t.slice(0,3),S=D0({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:c,onBrowseDirectory:v,onListSavedSessions:w}),T=l.useMemo(()=>C.map(P=>{const{metaText:D,updatedLabel:O}=Hu(P);return{key:`recent-launch:${P.id}`,primary:P.label,secondary:D,updatedLabel:O,onClick:()=>{const{options:R,selectedKey:B}=Fu({machine:{workspaces:S.workspaceRows,defaultWorkspaceId:S.defaultWorkspaceId},currentWorkspacePath:P.workspace});S.openLaunchConfirm({title:P.kind==="ide"?Gn("restart-ide",P.label):P.providerSessionId?Qd(P.label):Gn("start-fresh",P.label),description:P.kind==="ide"?Vn("restart-ide"):P.providerSessionId?Zd():Vn("start-fresh"),confirmLabel:P.kind==="ide"?qn("restart-ide"):P.providerSessionId?zn(!0):qn("start-fresh"),busyLabel:P.kind==="ide"?Yn("restart-ide"):P.providerSessionId?ii(!0):Yn("start-fresh"),workspaceOptions:R,selectedWorkspaceKey:B,details:[{label:"Mode",value:b(P.kind)},...P.providerType?[{label:"Provider",value:P.providerType}]:[]]},async()=>{const E=R.find(F=>F.key===S.launchConfirmWorkspaceKeyRef.current);S.setWorkspaceSelectionFromOption(E),await g({...P,workspace:(E==null?void 0:E.workspacePath)??null})})}}}),[S,g,C]),_=l.useMemo(()=>N.map(P=>({key:`recent-chat:${P.conversation.tabKey}`,primary:ot(P.conversation),secondary:_b(P.conversation,{timestampLabel:P.timestamp?hd(P.timestamp):null}),unread:P.unread,onClick:()=>y(P.conversation)})),[y,N]),L=S.showAllRecent?T:T.slice(0,4),M=T.length>0,A=_.length>0,H=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${H} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(zo,{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:Pt(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:[A&&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:_.map(P=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${P.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:P.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:P.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:P.secondary})]},P.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:L.map(P=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:P.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:P.primary}),P.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:P.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:P.secondary})]},P.key))}),T.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:()=>S.setShowAllRecent(P=>!P),children:S.showAllRecent?"Show fewer":`Show ${T.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:k,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"})]})]})]})]}),S.browseDialogOpen&&s.jsx(vi,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:S.browseCurrentPath,directories:S.browseDirectories,busy:S.browseBusy,error:S.browseError,confirmLabel:"Use this folder",onClose:()=>S.setBrowseDialogOpen(!1),onNavigate:P=>{S.loadBrowsePath(P)},onConfirm:P=>{S.chooseCustomWorkspacePath(P),S.setBrowseDialogOpen(!1)}}),S.launchConfirm&&s.jsx(Ou,{title:S.launchConfirm.title,description:S.launchConfirm.description,details:S.launchConfirm.details,workspaceOptions:S.launchConfirm.workspaceOptions,selectedWorkspaceKey:S.launchConfirmWorkspaceKey,onWorkspaceChange:S.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:S.launchConfirm.providerType?zn(!!S.launchConfirmResumeId):S.launchConfirm.confirmLabel,busyLabel:S.launchConfirm.providerType?void 0:S.launchConfirm.busyLabel,busy:S.launchConfirmBusy,showArgsInput:S.launchConfirm.showArgsInput,argsValue:S.launchConfirmArgs,onArgsChange:S.setLaunchConfirmArgs,showModelInput:S.launchConfirm.showModelInput,modelValue:S.launchConfirmModel,onModelChange:S.setLaunchConfirmModel,historyProviderNode:S.launchConfirm.providerType&&(S.launchConfirmSessionsLoading||S.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"}),S.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:li()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:S.launchConfirmTextFilter,onChange:P=>S.setLaunchConfirmTextFilter(P.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:S.launchConfirmBusy||S.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:S.launchConfirmWorkspaceFilter,onChange:P=>S.setLaunchConfirmWorkspaceFilter(P.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:S.launchConfirmBusy||S.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:S.launchConfirmModelFilter,onChange:P=>S.setLaunchConfirmModelFilter(P.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:S.launchConfirmBusy||S.launchConfirmSessionsLoading}),s.jsxs("select",{value:S.launchConfirmSortMode,onChange:P=>S.setLaunchConfirmSortMode(P.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:S.launchConfirmBusy||S.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:S.launchConfirmResumableOnly,onChange:P=>S.setLaunchConfirmResumableOnly(P.target.checked),disabled:S.launchConfirmBusy||S.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:S.launchConfirmResumeId,onChange:P=>S.setLaunchConfirmResumeId(P.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:S.launchConfirmBusy||S.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Qb()}),S.filteredLaunchConfirmSavedSessions.map(P=>s.jsxs("option",{value:P.providerSessionId,disabled:!P.canResume,children:[P.title||P.providerSessionId," ",P.canResume?"":"(workspace missing)"]},P.providerSessionId))]}),!S.launchConfirmSessionsLoading&&S.launchConfirmSavedSessions.length>0&&S.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),S.launchConfirmResumeId&&(()=>{const P=S.filteredLaunchConfirmSavedSessions.find(O=>O.providerSessionId===S.launchConfirmResumeId);if(!P)return null;const D=Bu(P);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:D.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:D.providerSessionId}),s.jsx("div",{className:"mt-1",children:D.metaLine}),D.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:D.updatedLabel}),D.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:D.preview})]})})()]}),onConfirm:S.handleConfirmLaunch,onCancel:S.closeLaunchConfirm}),u&&s.jsx(Eu,{section:m,onSectionChange:f})]})}function Tn(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function E0(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:Tn(e)}function B0(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 O0(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:js(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=Mr(n)?"cli":Ds(n)?"acp":"ide",o=js(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||(Mr(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 F0(e,t){const r=new Map;for(const n of t){const a=Cs(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((p,f)=>f.timestamp-p.timestamp)[0]||null,i=(o==null?void 0:o.conversation)||null,c=jo(n),d=a.filter(p=>p.unread||p.requiresAction).length,m=B0(n),u=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:Pt(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:i,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:c,preview:i?Lb(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 H0(e){return e==="chat"}function hn(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 W0({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:f,onRequestedMobileSectionConsumed:y,setSelectedTabKey:g,setScreen:x,setSelectedMachineId:k,setSection:j,setMachineBackTarget:h,resetMachineAction:v}){const I=l.useRef(null),w=l.useCallback(b=>{if(!(b!=null&&b.sessionId))return;const C=On(b,i),N=Math.max(Date.now(),vs(b),C.lastUpdated||0);hn("mark_read:start",{tabKey:b.tabKey,sessionId:b.sessionId,displayPrimary:ot(b),inboxBucket:C.inboxBucket,unread:C.unread,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,activityAt:vs(b),readAt:N}),c(Cs(b)||b.routeId,"mark_session_seen",{sessionId:b.sessionId,providerSessionId:b.providerSessionId,seenAt:N,completionMarker:C.completionMarker}).then(S=>{hn("mark_read:result",{tabKey:b.tabKey,sessionId:b.sessionId,result:S})}).catch(S=>{hn("mark_read:error",{tabKey:b.tabKey,sessionId:b.sessionId,error:S instanceof Error?S.message:String(S)})})},[i,c]);return l.useEffect(()=>{var C;if(!n){H0(o)&&x("inbox"),g(((C=e[0])==null?void 0:C.tabKey)||null),I.current=null;return}if(o!=="chat"){I.current=null;return}const b=`${n.tabKey}:${n.sessionId||""}`;I.current!==b&&(I.current=b,w(n))},[e,w,o,n,x,g]),l.useEffect(()=>{if(!d)return;const b=e.find(C=>C.tabKey===d);b&&(g(b.tabKey),x("chat"),m==null||m())},[e,m,d,x,g]),l.useEffect(()=>{if(!u)return;const b=t.find(C=>C.id===u);b&&(k(b.id),v(),j("machines"),h("inbox"),x("machine"),p==null||p())},[t,p,u,v,h,x,j,k]),l.useEffect(()=>{f&&(j(f),x("inbox"),y==null||y())},[y,f,x,j]),l.useEffect(()=>{const b=r.filter(C=>C.inboxBucket==="task_complete"||C.unread);b.length!==0&&hn("inbox_state",{screen:o,selectedTabKey:a,items:b.map(C=>{const N=On(C.conversation,i);return{liveState:N,tabKey:C.conversation.tabKey,sessionId:C.conversation.sessionId,displayPrimary:ot(C.conversation),serverBucket:N.inboxBucket,computedBucket:C.inboxBucket,serverUnread:N.unread,computedUnread:C.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:vs(C.conversation)}})})},[r,i,o,a]),{markConversationRead:w}}function K0(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Xl(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function U0(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function z0({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const{launchCli:a}=na(),[o,i]=l.useState("idle"),[c,d]=l.useState(""),[m,u]=l.useState(null),p=l.useCallback(()=>{i("idle"),d(""),u(null)},[]),f=l.useCallback(async(v,I,w)=>{var b;try{i("loading"),d(`Launching ${I}…`);const C={ideType:I,enableCdp:!0};(b=w==null?void 0:w.workspacePath)!=null&&b.trim()&&(C.workspace=w.workspacePath.trim()),await e(v,"launch_ide",C),i("done"),d(`${I} launch requested`)}catch(C){i("error"),d(C instanceof Error?C.message:"Launch IDE failed"),console.error("Launch IDE failed",C)}},[e]),y=l.useCallback(async(v,I,w)=>{if(I.trim())try{i("loading"),d(w!=null&&w.createIfMissing?"Creating folder…":"Saving workspace…");const b=await e(v,"workspace_add",{path:I.trim(),createIfMissing:(w==null?void 0:w.createIfMissing)===!0});if(b!=null&&b.success){i("done"),d(w!=null&&w.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((b==null?void 0:b.error)||"Could not save workspace")}catch(b){i("error"),d(b instanceof Error?b.message:"Could not save workspace")}},[e]),g=l.useCallback(async v=>{var I,w,b,C,N,S;try{i("loading"),d("Starting daemon upgrade…");const T=await e(v,"daemon_upgrade",{});if((I=T==null?void 0:T.result)!=null&&I.alreadyLatest){i("done"),d(`Already on v${((w=T==null?void 0:T.result)==null?void 0:w.version)||"latest"}.`);return}if((b=T==null?void 0:T.result)!=null&&b.upgraded||(C=T==null?void 0:T.result)!=null&&C.success){i("done"),d(`Upgrade to v${((N=T==null?void 0:T.result)==null?void 0:N.version)||"latest"} started. Daemon is restarting…`);return}i("error"),d(((S=T==null?void 0:T.result)==null?void 0:S.error)||"Upgrade failed")}catch(T){i("error"),d(T instanceof Error?T.message:"Upgrade failed")}},[e]),x=l.useCallback(async(v,I,w,b)=>{var S,T,_;const C=Date.now(),N={machineId:v,kind:I,providerType:w,workspaceId:(b==null?void 0:b.workspaceId)||null,workspacePath:(b==null?void 0:b.workspacePath)||null,resumeSessionId:(b==null?void 0:b.resumeSessionId)||null,startedAt:C};try{i("loading"),d(`Launching ${w}…`),u(N);const L={cliType:w};(S=b==null?void 0:b.workspacePath)!=null&&S.trim()?L.dir=b.workspacePath.trim():b!=null&&b.workspaceId&&(L.workspaceId=b.workspaceId),b!=null&&b.resumeSessionId&&(L.resumeSessionId=b.resumeSessionId),(T=b==null?void 0:b.args)!=null&&T.trim()&&(L.cliArgs=b.args.trim().split(/\s+/).filter(Boolean)),(_=b==null?void 0:b.model)!=null&&_.trim()&&(L.initialModel=b.model.trim());const M=await a(v,L),A=(M==null?void 0:M.result)||M,H=(A==null?void 0:A.sessionId)||(A==null?void 0:A.id);if(M!=null&&M.success&&H){u(null),i("done"),d(`${w} launched`),t(Lr(H));return}if(M!=null&&M.success){i("loading"),d(`${w} launch requested — waiting for session…`);return}u(null),i("error"),d((M==null?void 0:M.error)||(A==null?void 0:A.error)||`Could not launch ${I.toUpperCase()} workspace`)}catch(L){if(U0(L)){i("loading"),d(`${w} launch requested — waiting for session…`);return}u(null),i("error"),d(L instanceof Error?L.message:`Could not launch ${I.toUpperCase()} workspace`)}},[t,e]),k=l.useCallback(async(v,I)=>{try{const w=await e(v,"list_saved_sessions",{providerType:I,kind:"cli",limit:30}),b=(w==null?void 0:w.result)??w;return Array.isArray(b==null?void 0:b.sessions)?b.sessions:[]}catch(w){return console.error("Failed to list saved sessions on mobile:",w),[]}},[e]),j=l.useCallback(async(v,I)=>gi(e,v,I),[e]);l.useEffect(()=>{if(!m)return;const v=Xl(m.workspacePath),I=r.find(b=>{var L,M,A,H;if(!b||b.type==="adhdev-daemon"||K0(b.daemonId||b.id)!==m.machineId||(b.transport==="acp"?"acp":b.transport==="pty"?"cli":null)!==m.kind||String(b.agentType||b.type||"")!==m.providerType)return!1;const T=String(b.providerSessionId||"");if(m.resumeSessionId&&T)return T===m.resumeSessionId;if(v){const P=Xl(b.workspace||b.runtimeWorkspaceLabel);return P?P===v:!1}return Number(b.lastUpdated||b._lastUpdate||b.timestamp||((H=(A=(M=(L=b.activeChat)==null?void 0:L.messages)==null?void 0:M.at)==null?void 0:A.call(M,-1))==null?void 0:H.timestamp)||0)>=m.startedAt-5e3});if(!I)return;const w=Ru({entrySessionId:I.sessionId,entryInstanceId:I.instanceId,entryRouteId:I.id,conversations:n});w&&(u(null),i("done"),d(`${m.providerType} launched`),t(Lr(w)))},[n,r,t,m]),l.useEffect(()=>{if(!m)return;const v=window.setTimeout(()=>{u(I=>!I||I.startedAt!==m.startedAt?I:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(v)},[m]);const h=l.useCallback(async(v,I)=>{if(I.kind==="ide"&&I.providerType){await f(v,I.providerType,{workspacePath:I.workspace||null});return}(I.kind==="cli"||I.kind==="acp")&&I.providerType&&await x(v,I.kind,I.providerType,{workspacePath:I.workspace||null,resumeSessionId:I.providerSessionId||null})},[f,x]);return{machineAction:{state:o,message:c},resetMachineAction:p,handleLaunchDetectedIde:f,handleAddWorkspace:y,handleMachineUpgrade:g,handleLaunchWorkspaceProvider:x,handleListSavedSessions:k,handleBrowseDirectory:j,handleOpenRecent:h}}function G0({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:m}){const u=l.useCallback(j=>{o(j.tabKey),i("chat"),n(j)},[n,i,o]),p=l.useCallback(j=>{const h=e.find(v=>v.routeId===j.routeId&&v.streamSource==="native");h&&(o(h.tabKey),i("chat"),n(h))},[e,n,i,o]),f=l.useCallback(()=>{n(t),i("inbox")},[n,t,i]),y=l.useCallback((j,h="inbox")=>{c(j),a(),d("machines"),m(h),i("machine")},[a,m,i,d,c]),g=l.useCallback(j=>{const h=Cs(j);h&&y(h,"chat")},[y]),x=l.useCallback(()=>{a(),i(r)},[r,a,i]),k=l.useCallback(j=>{d(j),i("inbox")},[i,d]);return{openConversation:u,openNativeConversation:p,backFromConversation:f,openMachine:y,openConversationMachine:g,backFromMachine:x,changeMachineSection:k}}function Ks(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function V0(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function q0({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:f,onRequestedMobileSectionConsumed:y,onOpenHistory:g,onOpenRemote:x,onStopCli:k,wsStatus:j,isConnected:h,onShowAllHiddenConversations:v,onHideConversation:I,onOpenMeshGraph:w,onOpenNewSession:b,liveSessionInboxState:C,setCliViewModeOverrides:N}){const[S,T]=l.useState(()=>{var ae;return((ae=e[0])==null?void 0:ae.tabKey)||null}),[_,L]=l.useState(()=>e[0]?"chat":"inbox"),[M,A]=l.useState("chats"),[H,P]=l.useState(null),[D,O]=l.useState("inbox"),R=l.useRef([]),B=Dr(),E="0.9.82",F=l.useMemo(()=>e.find(ae=>ae.tabKey===S)||e[0]||null,[e,S]),Q=l.useMemo(()=>F?r.find(ae=>ae.id===F.routeId):void 0,[r,F]),Z=l.useMemo(()=>!F||qe(F)||!Qe(F)?null:Vs(F),[F]),Y=l.useMemo(()=>r.filter(ae=>ae.type==="adhdev-daemon").sort(Zo),[r]),te=l.useMemo(()=>Y.find(ae=>ae.id===H)||null,[Y,H]),fe=da({sendDaemonCommand:a,activeConv:F||void 0,setActionLogs:o,isStandalone:i}),Ne=z0({sendDaemonCommand:a,navigate:B,ides:r,conversations:e}),X=l.useMemo(()=>e.map(ae=>{const Pe=_==="chat"&&(F==null?void 0:F.tabKey)===ae.tabKey,$e=la(ae,C,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Pe}),Re=vs(ae),Ge=zd(ae);return{conversation:ae,timestamp:Re,preview:Ge,unread:$e.unread,requiresAction:$e.requiresAction,isWorking:$e.isWorking,inboxBucket:$e.inboxBucket}}),[e,C,_,F]),{markConversationRead:we}=W0({conversations:e,machineEntries:Y,items:X,selectedConversation:F,selectedTabKey:S,screen:_,liveSessionInboxState:C,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:f,onRequestedMobileSectionConsumed:y,setSelectedTabKey:T,setScreen:L,setSelectedMachineId:P,setSection:A,setMachineBackTarget:O,resetMachineAction:Ne.resetMachineAction}),ge=G0({conversations:e,selectedConversation:F,machineBackTarget:D,markConversationRead:we,resetMachineAction:Ne.resetMachineAction,setSelectedTabKey:T,setScreen:L,setSelectedMachineId:P,setSection:A,setMachineBackTarget:O}),{isMuted:be,autoMuteIfCoordinator:de,toggleTarget:Ie}=iy();l.useEffect(()=>{if(i)for(const ae of X)de(ae.conversation)},[X,i,de]);const ee=l.useMemo(()=>Tn(X.filter(ae=>ae.requiresAction&&!be(ae.conversation))),[X,be]),ve=l.useMemo(()=>Tn(X.filter(ae=>ae.unread&&!ae.requiresAction&&!be(ae.conversation))),[X,be]),ce=l.useMemo(()=>E0(X.filter(ae=>!ae.unread&&!ae.requiresAction&&ae.isWorking),R.current),[X]);l.useEffect(()=>{R.current=ce.map(ae=>ae.conversation.tabKey)},[ce]);const W=l.useMemo(()=>Tn(X.filter(ae=>!ae.unread&&!ae.requiresAction&&!ae.isWorking)),[X]),ne=l.useMemo(()=>te?X.filter(ae=>Cs(ae.conversation)===te.id):[],[X,te]),ue=l.useMemo(()=>O0(te,r),[r,te]),me=(te==null?void 0:te.version)||null,J=!!te&&!!me&&!0&&me!==E,q=l.useMemo(()=>(te==null?void 0:te.availableProviders)||[],[te]),$=l.useMemo(()=>q.filter(ae=>Ks(ae,"cli")).map(ae=>({type:ae.type,displayName:ae.displayName||ae.type,icon:ae.icon})),[q]),re=l.useMemo(()=>q.filter(ae=>Ks(ae,"acp")).map(ae=>({type:ae.type,displayName:ae.displayName||ae.type,icon:ae.icon})),[q]),xe=l.useMemo(()=>F0(Y,X),[X,Y]),je=l.useCallback(async ae=>{te&&await Ne.handleOpenRecent(te.id,ae)},[Ne,te]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:_==="chat"&&F?s.jsx(I0,{selectedConversation:F,isAcp:qe(F),isStandalone:i,selectedIdeEntry:Q,actionLogs:n,userName:c,isSendingChat:fe.isSendingChat,sendFeedbackMessage:fe.sendFeedbackMessage,isFocusingAgent:fe.isFocusingAgent,handleModalButton:fe.handleModalButton,handleRelaunch:fe.handleRelaunch,onBack:ge.backFromConversation,onOpenNativeConversation:ge.openNativeConversation,onOpenMachine:ge.openConversationMachine,onOpenHistory:g,onOpenRemote:x,onOpenMeshGraph:w,onStopCli:k,cliViewMode:Z,onSetCliViewMode:async ae=>{await vu({conversation:F,mode:ae,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:N})},handleSendChat:fe.handleSendChat,handleForceSendChat:fe.handleForceSendChat,handleFocusAgent:fe.handleFocusAgent}):_==="machine"&&te?s.jsx($0,{selectedMachineEntry:te,selectedMachineConversations:ne,selectedMachineRecentLaunches:ue,cliProviders:$,acpProviders:re,selectedMachineNeedsUpgrade:J,appVersion:E,machineAction:Ne.machineAction,isStandalone:i,section:M,showBottomNav:D==="inbox",onBack:ge.backFromMachine,onSectionChange:ge.changeMachineSection,onOpenConversation:ge.openConversation,onOpenRecent:je,onOpenMachineDetails:()=>B(`/machines/${te.id}`),onMachineUpgrade:()=>Ne.handleMachineUpgrade(te.id),onLaunchDetectedIde:(ae,Pe)=>Ne.handleLaunchDetectedIde(te.id,ae,Pe),onAddWorkspace:(ae,Pe)=>Ne.handleAddWorkspace(te.id,ae,Pe),onBrowseDirectory:ae=>Ne.handleBrowseDirectory(te.id,ae),onLaunchWorkspaceProvider:(ae,Pe,$e)=>Ne.handleLaunchWorkspaceProvider(te.id,ae,Pe,$e),onListSavedSessions:ae=>Ne.handleListSavedSessions(te.id,ae)}):s.jsx(T0,{section:M,attentionItems:ee,unreadItems:ve,workingItems:ce,completedItems:W,hiddenConversations:t,machineCards:xe,getAvatarText:V0,actionLogs:n,sendDaemonCommand:a,onOpenConversation:ge.openConversation,onShowAllHidden:v,onHideConversation:I,onOpenMeshGraph:w,onOpenNewSession:b,onOpenMachine:ge.openMachine,onOpenSettings:()=>B("/settings"),onSectionChange:A,wsStatus:j,isConnected:h,isStandalone:i,isConversationMuted:i?be:void 0,onToggleMuteConversation:i?Ie:void 0})})}function za(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Y0({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const i=l.useRef(0),[c,d]=l.useState(!1),[m,u]=l.useState(null),p=l.useCallback(()=>{i.current=0,d(!1),u(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",p),window.addEventListener("drop",p),()=>{window.removeEventListener("dragend",p),window.removeEventListener("drop",p)}),[p]);const f=l.useCallback(k=>{k.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),y=l.useCallback(k=>{if(!k.dataTransfer.types.includes("text/tab-key"))return;if(k.preventDefault(),!za(t,r)){u("merge");return}const j=k.currentTarget.getBoundingClientRect(),h=k.clientX-j.left,v=j.width/3;h<v?u("split-left"):h>v*2?u("split-right"):u("merge")},[t,r]),g=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),u(null))},[]),x=l.useCallback(k=>{i.current=0,d(!1);const j=k.dataTransfer.getData("text/tab-key"),h=j?e.some(I=>I.tabKey===j):!1,v=m;if(u(null),o(),!!j){if(k.preventDefault(),v==="split-left"&&za(t,r)){r==null||r(j,"split-left");return}if(v==="split-right"&&za(t,r)){r==null||r(j,"split-right");return}if(h){a(j);return}n==null||n(j)}},[e,m,t,r,n,a,o]);return{dragOver:c,dropAction:m,resetDragState:p,handleDragEnter:f,handleDragOver:y,handleDragLeave:g,handleDrop:x}}function X0(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 J0({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,i]=l.useState(t??null),[c,d]=l.useState(r??[]),[m,u]=l.useState(null),p=l.useRef(null),f=l.useRef(null),y=l.useRef(n),g=l.useRef(a);l.useEffect(()=>{y.current=n},[n]),l.useEffect(()=>{g.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(C=>{const N=X0(C,e);return N.length===C.length&&N.every((S,T)=>S===C[T])?C:N})},[e]);const x=l.useMemo(()=>{const C=m??c;if(C.length===0)return e;const N=new Map(C.map((S,T)=>[S,T]));return[...e].sort((S,T)=>{const _=N.get(S.tabKey)??999,L=N.get(T.tabKey)??999;return _-L})},[e,m,c]);l.useEffect(()=>{var N,S;if(x.length===0){o!==null&&(i(null),(N=y.current)==null||N.call(y,null));return}if(o&&x.some(T=>T.tabKey===o))return;const C=x[0].tabKey;C!==o&&(i(C),(S=y.current)==null||S.call(y,C))},[x,o]);const k=l.useMemo(()=>x.find(C=>C.tabKey===o),[x,o]),j=l.useCallback(C=>{var N;i(C),(N=y.current)==null||N.call(y,C)},[]),h=l.useCallback((C,N,S)=>{d(T=>{var A;const _=T.filter(H=>H!==C),L=_.indexOf(N);if(L<0)return T;const M=S==="left"?L:L+1;return _.splice(M,0,C),(A=g.current)==null||A.call(g,_),_}),u(null)},[]),v=l.useCallback((C,N,S)=>{const _=(c.length>0?c:e.map(A=>A.tabKey)).filter(A=>A!==C),L=_.indexOf(N);if(L<0)return;const M=S==="left"?L:L+1;_.splice(M,0,C),p.current=_,u(_)},[c,e]),I=l.useCallback(()=>{var N;const C=p.current;C&&(d(C),(N=g.current)==null||N.call(g,C))},[]),w=l.useCallback(()=>{p.current=null,u(null)},[]),b=l.useCallback(C=>{d(N=>{var T;const S=N.filter(_=>_!==C);return S.push(C),(T=g.current)==null||T.call(g,S),S})},[]);return{activeTabId:o,activeConv:k,sortedConversations:x,previewOrderRef:p,draggingTabRef:f,selectTab:j,handleTabReorder:h,updatePreviewOrder:v,commitPreviewOrder:I,clearPreviewOrder:w,moveTabToEnd:b,setDraggingTabKey:C=>{f.current=C}}}function Q0({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 wi({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:o}){if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const i=!r&&!n,c=n&&!!o,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?Xd:r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can launch sessions with any installed provider.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children: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:Ut,"aria-label":Ut,children:[s.jsx(td,{size:14}),s.jsx("span",{children:Ut})]})}),i&&s.jsx($u,{}),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 Wu="adhdev-tab-shortcuts";function Ku(){try{return JSON.parse(localStorage.getItem(Wu)||"{}")}catch{return{}}}function Uu({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>Ku()),[c,d]=l.useState(null),m=l.useCallback(p=>{const f=[];return p.metaKey&&f.push(a?"⌘":"Meta"),p.ctrlKey&&f.push("Ctrl"),p.altKey&&f.push(a?"⌥":"Alt"),p.shiftKey&&f.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(f.push(p.key.length===1?p.key.toUpperCase():p.key),f.join("+"))},[a]),u=l.useCallback(p=>{i(p);try{localStorage.setItem(Wu,JSON.stringify(p))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const p=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){d(null);return}const y=m(f);if(!y)return;const g={...o};for(const[x,k]of Object.entries(g))k===y&&delete g[x];g[c]=y,u(g),d(null)};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[e,c,o,u,m]),l.useEffect(()=>{if(!e)return;const p=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[y,g]of Object.entries(o))if(t.includes(y)&&m(f)===g){f.preventDefault(),r(),n(y);return}}};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[e,o,t,r,n,m]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const Ga=e=>{e.preventDefault()},Z0=l.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:p,onReorderTab:f,onCommitPreviewOrder:y,onClearPreviewOrder:g,onDragStateReset:x,onDragTabKeyChange:k,onReceiveTab:j,onOpenContextMenu:h,longPressTimer:v,isGroupActive:I}){const w=Gs(t),b=w.isGenerating?"agent-tab-generating":w.isWaiting?"agent-tab-waiting":"",C=w.isReconnecting,N=Ab(t),S=Tb(t),T=l.useCallback(R=>{c.current=t.tabKey,k(t.tabKey),R.dataTransfer.setData("text/tab-key",t.tabKey),R.dataTransfer.effectAllowed="move"},[t.tabKey,c,k]),_=l.useCallback(()=>{c.current=null,k(null),y(),g(),x()},[c,k,y,g,x]),L=l.useCallback(R=>{const B=c.current;if(!(!B||B===t.tabKey)&&R.dataTransfer.types.includes("text/tab-key")){R.preventDefault(),R.stopPropagation();const E=R.currentTarget.getBoundingClientRect(),F=R.clientX<E.left+E.width/2?"left":"right";p(B,t.tabKey,F)}},[t.tabKey,c,p]),M=l.useCallback(R=>{R.preventDefault(),R.stopPropagation();const B=R.dataTransfer.getData("text/tab-key");if(B&&B!==t.tabKey){const E=R.currentTarget.getBoundingClientRect(),F=R.clientX<E.left+E.width/2?"left":"right";i.includes(B)?f(B,t.tabKey,F):j&&j(B)}g()},[t.tabKey,i,f,j,g]),A=l.useCallback(R=>{R.stopPropagation(),d(),m(t.tabKey),u(t)},[t,u,d,m]),H=l.useCallback(R=>{R.preventDefault(),h(R.clientX,R.clientY,t.tabKey)},[t.tabKey,h]),P=l.useCallback(R=>{const B=R.touches[0];v.current=setTimeout(()=>{h(B.clientX,B.clientY,t.tabKey)},600)},[t.tabKey,v,h]),D=l.useCallback(()=>{v.current&&clearTimeout(v.current)},[v]),O=["adhdev-dockview-tab",b,r&&"is-active",I&&"is-group-active",C&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:O,draggable:!0,onDragStart:T,onDragEnd:_,onDragOver:L,onDrop:M,onClick:A,onContextMenu:H,onTouchStart:P,onTouchEnd:D,onTouchMove:D,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:w.isGenerating?s.jsx("div",{className:"tab-spinner"}):w.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):C?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):w.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),N.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:S,"aria-label":S||N.join(" · "),children:N.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:ot(t),children:ot(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:bs(t)}):w.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[bs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:bs(t)}),s.jsx(Un,{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 ev({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:p,onDragStateReset:f,onDragTabKeyChange:y,onReceiveTab:g,onHideTab:x,isGroupActive:k,allowTabShortcuts:j=!0}){const[h,v]=l.useState(null),I=l.useRef(null),w=l.useRef(null),b=l.useMemo(()=>e.map(M=>M.tabKey),[e]);Er("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:C,tabShortcuts:N,shortcutListening:S,setShortcutListening:T,saveShortcuts:_}=Uu({enabled:j,sortedTabKeys:e.map(M=>M.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!h)return;const M=A=>{const H=document.querySelector("[data-pane-context-menu]");H&&H.contains(A.target)||v(null)};return window.addEventListener("mousedown",M,!0),()=>window.removeEventListener("mousedown",M,!0)},[h]),l.useEffect(()=>{const M=w.current;if(!M)return;const A=H=>{Math.abs(H.deltaY)<=Math.abs(H.deltaX)||(H.preventDefault(),M.scrollLeft+=H.deltaY)};return M.addEventListener("wheel",A,{passive:!1}),()=>M.removeEventListener("wheel",A)},[]);const L=l.useCallback((M,A,H)=>{v({x:M,y:A,tabKey:H})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:w,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(M=>s.jsx(Z0,{conv:M,isActive:t===M.tabKey,isDraggedTab:a.current===M.tabKey,isTaskCompleteUnread:n.has(M.tabKey),shortcut:j?N[M.tabKey]:void 0,conversationKeys:b,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:p,onDragStateReset:f,onDragTabKeyChange:y,onReceiveTab:g,onOpenContextMenu:L,longPressTimer:I,isGroupActive:k},M.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),h&&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:h.x,top:h.y},children:[j&&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:Ga,onClick:M=>{M.stopPropagation(),T(h.tabKey),v(null)},children:["⌨ ",N[h.tabKey]?`Change shortcut (${N[h.tabKey]})`:"Set shortcut"]}),N[h.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:Ga,onClick:()=>{const M={...N};delete M[h.tabKey],_(M),v(null)},children:"✕ Remove shortcut"})]}),x&&s.jsxs(s.Fragment,{children:[j&&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:Ga,onClick:()=>{x(h.tabKey),v(null)},children:"🚫 Hide from Dashboard"})]})]}),j&&S&&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:()=>T(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 tv({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,userName:d,groupIndex:m,onFocus:u,isSplitMode:p,numGroups:f,onMoveTab:y,onReceiveTab:g,style:x,onActiveTabChange:k,initialActiveTabId:j,initialTabOrder:h,onTabOrderChange:v,onHideTab:I,isFocused:w,allowTabShortcuts:b=!0,onOpenNewSession:C,liveSessionInboxState:N}){const{sendCommand:S}=it(),T=l.useRef(null),{activeTabId:_,activeConv:L,sortedConversations:M,draggingTabRef:A,selectTab:H,handleTabReorder:P,updatePreviewOrder:D,commitPreviewOrder:O,clearPreviewOrder:R,moveTabToEnd:B,setDraggingTabKey:E}=J0({conversations:e,initialActiveTabId:j,initialTabOrder:h,onActiveTabChange:k,onTabOrderChange:v}),F=da({sendDaemonCommand:a,activeConv:L,setActionLogs:o,isStandalone:i}),{dragOver:Q,dropAction:Z,resetDragState:Y,handleDragEnter:te,handleDragOver:fe,handleDragLeave:Ne,handleDrop:X}=Y0({conversations:e,numGroups:f,onMoveTab:y,onReceiveTab:g,onOwnTabDrop:B,onClearPreviewOrder:R}),we=L&&!qe(L)&&Vs(L)==="terminal",ge=l.useMemo(()=>L?t.find(ee=>ee.id===L.routeId):void 0,[t,L]),be=l.useMemo(()=>L?n.filter(ee=>ee.routeId===L.tabKey):[],[n,L]),de=l.useMemo(()=>new Set(M.filter(ee=>lf(ee,N,{isOpenConversation:ee.tabKey===_})).map(ee=>ee.tabKey)),[_,N,M]);Er("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:_,dragOver:Q});const Ie=l.useCallback(ee=>{ee.streamSource==="agent-stream"&&ee.agentType&&S(ee.routeId,_d(),{agentType:ee.agentType,...ee.sessionId&&{targetSessionId:ee.sessionId}}).catch(()=>{})},[S]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...x,outline:Q?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(ev,{conversations:M,activeTabId:_,groupIndex:m,numGroups:f,unreadTabKeys:de,draggingTabRef:A,onFocus:u,onSelectTab:H,onConversationActivated:Ie,onPreviewReorder:D,onReorderTab:P,onCommitPreviewOrder:O,onClearPreviewOrder:R,onDragStateReset:Y,onDragTabKeyChange:E,onMoveTab:y,onReceiveTab:g,onHideTab:I,isGroupActive:w??!1,allowTabShortcuts:b}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:te,onDragOver:fe,onDragLeave:Ne,onDrop:X,children:[Q&&s.jsx(Q0,{dropAction:Z,canSplit:!!(f<4&&y)}),L?s.jsx(yi,{activeConv:L,clearToken:r[L.tabKey]||0,isCliTerminal:!!we,ideEntry:ge,terminalRef:T,handleModalButton:F.handleModalButton,handleRelaunch:F.handleRelaunch,handleSendChat:F.handleSendChat,handleForceSendChat:F.handleForceSendChat,isSendingChat:F.isSendingChat,sendFeedbackMessage:F.sendFeedbackMessage,handleFocusAgent:F.handleFocusAgent,isFocusingAgent:F.isFocusingAgent,actionLogs:be,userName:d,isInputActive:!p||!!w}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(wi,{conversationsCount:e.length,isSplitMode:p,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:C})})]})]})}function sv({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:p,userName:f,focusedGroup:y,focusGroup:g,moveTabToGroup:x,splitTabRelative:k,closeGroup:j,handleResizeStart:h,groupActiveTabIds:v,setGroupActiveTab:I,groupTabOrders:w,setGroupTabOrder:b,toggleHiddenTab:C,onOpenNewSession:N,allowTabShortcuts:S=!0,liveSessionInboxState:T}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((_,L)=>{const M=t&&n.length===r?`${n[L]}%`:void 0;return s.jsxs(gt.Fragment,{children:[t&&L>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:A=>h(L-1,A),onDoubleClick:()=>j(L),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(tv,{style:t?{flexBasis:M??`${100/r}%`,flexGrow:M?0:1,flexShrink:M?0:1}:void 0,conversations:_,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:p,userName:f,groupIndex:L,isFocused:t&&y===L,onFocus:()=>g(L),isSplitMode:t,numGroups:r,onMoveTab:(A,H)=>{H==="left"&&L>0?x(A,L-1):H==="right"&&L<r-1?x(A,L+1):H==="split-left"&&r<4?k(A,L,"left"):H==="split-right"&&r<4&&k(A,L,"right")},onReceiveTab:A=>x(A,L),onActiveTabChange:A=>I(L,A),initialActiveTabId:v[L],initialTabOrder:w[L],onTabOrderChange:A=>b(L,A),onHideTab:C,onOpenNewSession:N,allowTabShortcuts:S,liveSessionInboxState:T})]},L)})})}function zu({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?pt.onScreenshot("ide-page",(u,p)=>{if(u!==e)return;const f=new FileReader;f.onload=()=>o(f.result),f.readAsDataURL(p)}):void 0,[e]),l.useEffect(()=>{r!=="connected"&&o(null)},[r]),l.useEffect(()=>{var u;return e?((u=pt.onStatus)==null?void 0:u.call(pt,(p,f)=>{p===e&&f!=null&&f.screenshotUsage&&c(f.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const m=e?pt.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 d=l.useCallback(async(m,u)=>{const p=e?pt.get(e):null;return!p||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):p.sendInput(m,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:i,handleRemoteAction:d}}const Gu="adhdev-dashboard-action-shortcuts",rv=1200,nv=[["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 av(){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 Vu(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 Zn(e){const t=Object.fromEntries(Vu(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Gu)||"{}"),n={...t,...r};for(const[a,o]of nv)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function qu(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function ov({enabled:e=!0,onTrigger:t}){const r=av(),[n,a]=l.useState(()=>Zn(r)),[o,i]=l.useState(null),[c,d]=l.useState([]),m=l.useRef({parts:[],timer:null}),u=l.useCallback(x=>{const k=[];return x.metaKey&&k.push(r?"⌘":"Meta"),x.ctrlKey&&k.push("Ctrl"),x.altKey&&k.push(r?"⌥":"Alt"),x.shiftKey&&x.key.length!==1&&k.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(x.key)?null:(k.push(qu(x.key)),k.join("+"))},[r]),p=l.useCallback(x=>{a(x);try{localStorage.setItem(Gu,JSON.stringify(x))}catch{}},[]);l.useEffect(()=>{const x=Zn(r),k=Object.entries(n),j=Object.entries(x);k.length===j.length&&k.every(([h,v])=>x[h]===v)||p(x)},[n,r,p]);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}},rv))},[]);l.useEffect(()=>{if(!o)return;const x=k=>{if(k.preventDefault(),k.stopPropagation(),k.key==="Escape"){i(null),d([]);return}const j=u(k);if(!j)return;const v=!(k.metaKey||k.ctrlKey||k.altKey)&&/^[A-Z0-9]$/.test(j);if(c.length===0&&v){d([j]);return}const w=[...c,j].slice(0,2).join(" "),b={...n};for(const[C,N]of Object.entries(b))N===w&&delete b[C];b[o]=w,p(b),i(null),d([])};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[n,u,p,o,c]),l.useEffect(()=>{if(!e||o)return;const x=k=>{if(k.defaultPrevented)return;const j=u(k);if(!j)return;const h=k.metaKey||k.ctrlKey||k.altKey;if($o(k.target))return;const v=m.current.parts,I=h?[j]:[...v.slice(-1),j].slice(-2),w=I.join(" "),b=I[I.length-1],C=Object.entries(n).filter(([,L])=>!!L),N=C.find(([,L])=>L===w);if(N){k.preventDefault(),f(),t(N[0]);return}if(C.some(([,L])=>L.startsWith(`${w} `))){k.preventDefault(),m.current.parts=I,y();return}const T=C.find(([,L])=>L===b);if(T){k.preventDefault(),f(),t(T[0]);return}if(C.some(([,L])=>L.startsWith(`${b} `))){k.preventDefault(),m.current.parts=[b],y();return}f()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[n,y,e,u,t,f,o]),l.useEffect(()=>()=>f(),[f]);const g=l.useMemo(()=>Vu(r),[r]);return{isMac:r,actionDefinitions:g,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:p}}function iv({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 Yu(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Jl({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!Yu(n):!0}function lv({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:Yu(r)}const Xu=1e3,cv=4;function Ql(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Zl(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function dv({detachDelayMs:e=Xu,stillnessThresholdPx:t=cv,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,d=null,m=null,u=!1;const p=()=>{m!=null&&(a(m),m=null)},f=()=>{p(),c=null},y=()=>{p(),o=null,i=null,c=null,d=null,u=!1},g=()=>{!o||!c||!d||u||m!=null||(m=n(()=>{m=null,!(!o||!c||!d||u)&&Ql(d,i)&&(Zl(c,d,t)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},x=j=>{if(!(!o||u)){if(!Ql(j,i)){d={clientX:j.clientX,clientY:j.clientY},f();return}(!c||Zl(c,j,t))&&(p(),c={clientX:j.clientX,clientY:j.clientY}),d={clientX:j.clientX,clientY:j.clientY},g()}},k=j=>{!o||u||(j&&(d={clientX:j.clientX,clientY:j.clientY}),f())};return{startDrag:j=>{p(),o=j.panelId,i=j.selfPanelBounds??null,c=null,d={clientX:j.clientX,clientY:j.clientY},u=!1},markSelfPanel:x,markNonSelfPanel:k,markNoDropTarget:k,markDockTarget:k,endDrag:y,isDragging:()=>o!=null,hasDetached:()=>u,dispose:y}}function uv(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function fn(e){return e.isActive}function ec(e){return e.isVisible}const Ju=l.createContext(null);function ha(){const e=l.useContext(Ju);if(!e)throw new Error("DashboardDockviewContext missing");return e}function _n(e){return ot(e)||e.tabKey}function mv(e){return`remote:${e}`}function $t(e){return e.startsWith("remote:")}function tc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function pv(e){e.preventDefault()}function Va(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 qa(e,t){e.classList.remove(ho.className,fo.className),e.classList.add(t==="light"?ho.className:fo.className)}function sc(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 hv(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 fv(e,t,r){var i;const n=[t];let a;for(const c of n){let d;for(const m of c){const u=e.addPanel({id:m.tabKey,component:"conversation",title:_n(m),params:{kind:"conversation",tabKey:m.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=u.id)}a=d??a}return r??((i=t[0])==null?void 0:i.tabKey)??null}function rc(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])$t(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!==_n(a)&&o.api.setTitle(_n(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:_n(a),params:{kind:"conversation",tabKey:a.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function nc(e,t,r){var d,m;const n=r?mv(r):null;for(const u of[...e.panels])$t(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Ot(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),i=qd(a);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((m=e.panels.find(u=>!$t(u.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 xv({params:e,api:t}){var y;const r=ha(),n=l.useRef(null),[a,o]=l.useState(()=>fn(t)),[i,c]=l.useState(()=>ec(t)),d=r.conversationsByTabKey.get(e.tabKey),m=da({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});l.useEffect(()=>{o(fn(t)),c(ec(t));const g=[t.onDidActiveChange(x=>o(x.isActive)),t.onDidActiveGroupChange(x=>{if(!fn(t)&&!x.isActive){o(!1);return}o(fn(t))}),t.onDidVisibilityChange(x=>c(x.isVisible))];return()=>{for(const x of g)x.dispose()}},[t]);const u=l.useMemo(()=>d?r.ides.find(g=>g.id===d.routeId):void 0,[r.ides,d]),p=l.useMemo(()=>d?r.actionLogs.filter(g=>g.routeId===d.tabKey):[],[r.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(wi,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const f=!qe(d)&&Vs(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(yi,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:f,ideEntry:u,terminalRef:n,handleModalButton:m.handleModalButton,handleRelaunch:m.handleRelaunch,handleSendChat:m.handleSendChat,handleForceSendChat:m.handleForceSendChat,isSendingChat:m.isSendingChat,handleFocusAgent:m.handleFocusAgent,isFocusingAgent:m.isFocusingAgent,actionLogs:p,userName:r.userName,scrollToBottomRequestNonce:((y=r.scrollToBottomRequest)==null?void 0:y.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:i})})}function bv({params:e}){var d;const t=ha(),r=l.useMemo(()=>Ot([...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)||((d=r==null?void 0:r.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=zu({doId:a,targetSessionId:r?Td(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(ud,{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 gv(){const e=ha();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(wi,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function yv(e){var h,v;hv(e);const t=ha(),r=l.useCallback(I=>{"button"in I&&I.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(I=>pb(I),[]),i=l.useCallback(()=>mb(a),[a]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const I=Ot([...t.conversationsByTabKey.values()],e.params.routeId),w=((h=e.api.group.activePanel)==null?void 0:h.id)===e.api.id,b=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${w?" is-active":""}${b?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(I==null?void 0:I.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:I!=null&&I.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:I.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const d=t.conversationsByTabKey.get(e.params.tabKey);if(!d)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const m=((v=e.api.group.activePanel)==null?void 0:v.id)===e.api.id,u=e.api.isGroupActive,p=la(d,t.liveSessionInboxState,{isOpenConversation:m}),f=p.isReconnecting,y=p.isConnecting,g=p.isGenerating||c,x=p.isWaiting,k=p.unread,j=t.tabShortcuts[d.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${m?" is-active":""}${u?" is-group-active":""}${f?" is-reconnecting":""}`,title:ot(d),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:I=>{var w;I.preventDefault(),r(I),t.openTabContextMenu({x:I.clientX,y:I.clientY,tabKey:d.tabKey,sourceDocument:((w=I.target)==null?void 0:w.ownerDocument)??document})},children:[k&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:g?s.jsx("div",{className:"tab-spinner"}):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"}):d.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:ot(d)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:bs(d)}):y?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:bs(d)}):s.jsx("span",{children:bs(d)})})]}),j&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:j,children:j})]})}function vv({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:m,toggleHiddenTab:u,actionShortcuts:p,registerActionHandlers:f,onActiveTabChange:y,onOpenNewSession:g,onRequestScrollToBottom:x,requestedActiveTabKey:k,requestedRemoteIdeId:j,onRequestedActiveTabConsumed:h,scrollToBottomRequest:v,liveSessionInboxState:I,layoutProfile:w}){var et,ze,ht;const{theme:b}=qs(),{sendCommand:C}=it(),N=l.useRef(null),S=l.useRef(null),T=l.useRef(null),_=l.useRef(!1),L=l.useRef(!1),M=l.useRef(!1),A=l.useRef(null),H=l.useRef([]),[P,D]=l.useState(null),[O,R]=l.useState(0),B=l.useRef(typeof window>"u"?{}:By(w)),E=l.useMemo(()=>new Map(e.map(K=>[K.tabKey,K])),[e]),F=l.useMemo(()=>{const K=N.current;return K?K.groups.some(U=>{try{const V=U.model.location.type;return V!=="floating"&&V!=="popout"?!1:U.panels.some(ie=>E.has(ie.id))}catch{return!1}}):!1},[E,O,e]),Q=l.useCallback(()=>{var K;(K=N.current)==null||K.focus()},[]),Z=l.useCallback((K,U)=>{x==null||x(K,U)},[x]),Y=l.useCallback(K=>{const U=document,V=K.document;for(const G of U.querySelectorAll('link[rel="stylesheet"]')){const le=V.createElement("link");le.rel="stylesheet",le.href=G.href,G.crossOrigin&&(le.crossOrigin=G.crossOrigin),V.head.appendChild(le)}for(const G of U.querySelectorAll("style")){const le=V.createElement("style");le.textContent=G.textContent,V.head.appendChild(le)}const ie=[];for(const G of U.styleSheets)try{for(const le of G.cssRules)le instanceof CSSStyleRule&&(le.selectorText===":root"||le.selectorText==="html")&&ie.push(le.cssText)}catch{}if(ie.length>0){const G=V.createElement("style");G.textContent=ie.join(`
62
+ `),V.head.appendChild(G)}const pe=U.documentElement.getAttribute("data-theme");pe&&V.documentElement.setAttribute("data-theme",pe),V.documentElement.style.colorScheme=pe==="light"?"light":"dark",V.body.className=U.body.className;const ke=U.documentElement.getAttribute("style");ke&&V.documentElement.setAttribute("style",ke);const z=V.getElementById("dv-popout-window");z instanceof HTMLElement&&(z.classList.add("adhdev-dockview"),qa(z,b))},[b]),te=l.useCallback(()=>{var U;const K=N.current;if(K)for(const V of K.groups)try{const ie=(U=V.element)==null?void 0:U.ownerDocument;if(!ie||ie===document)continue;const pe=ie.getElementById("dv-popout-window");pe instanceof HTMLElement&&(pe.classList.add("adhdev-dockview"),qa(pe,b));const ke=document.documentElement.getAttribute("data-theme");ke&&ie.documentElement.setAttribute("data-theme",ke),ie.documentElement.style.colorScheme=ke==="light"?"light":"dark",ie.body.className=document.body.className;const z=document.documentElement.getAttribute("style");z?ie.documentElement.setAttribute("style",z):ie.documentElement.removeAttribute("style")}catch{}},[b]),fe=l.useCallback(K=>{const U=N.current;if(!U)return;const V=U.getPanel(K);V&&U.addPopoutGroup(V,{popoutUrl:"/popout.html",onDidOpen:({window:ie})=>{Y(ie),ve();const pe=E.get(K);ie.document.title=pe?`${ot(pe)} — ADHDev`:"ADHDev — Popout"}})},[E,Y]),Ne=l.useCallback(K=>{const U=N.current,V=U==null?void 0:U.getPanel(K);if(!U||!V)return;const ie=U.groups.filter(pe=>{var ke;try{return((ke=pe.element)==null?void 0:ke.ownerDocument)===document}catch{return!0}});ie.length>0?V.api.moveTo({group:ie[0],position:"center"}):V.api.moveTo({position:"center"}),V.api.setActive()},[]),X=l.useCallback(K=>{var ie;const U=N.current;if(!U)return!1;const V=U.getPanel(K);if(!V)return!1;try{return((ie=V.group.element)==null?void 0:ie.ownerDocument)!==document}catch{return!1}},[]),we=l.useCallback(K=>{X(K)&&Ne(K),u(K)},[X,Ne,u]),ge=l.useCallback(K=>{const U=N.current,V=U==null?void 0:U.getPanel(K);!U||!V||U.addFloatingGroup(V,{width:600,height:500})},[]),be=l.useCallback(K=>{var V;const U=(V=N.current)==null?void 0:V.getPanel(K);if(!U)return!1;try{return U.group.model.location.type==="floating"}catch{return!1}},[]),de=l.useCallback(()=>{var U,V;const K=(V=(U=N.current)==null?void 0:U.activePanel)==null?void 0:V.id;return!K||$t(K)?null:E.has(K)?K:null},[E]),Ie=l.useCallback(K=>{const U=N.current,V=U==null?void 0:U.getPanel(K);if(!U||!V)return;const ie=U.groups.filter(pe=>{try{return pe.model.location.type==="grid"}catch{return!0}});ie.length>0?V.api.moveTo({group:ie[0],position:"center"}):V.api.moveTo({position:"center"}),V.api.setActive()},[]),ee=l.useCallback(()=>{var ke;const K=N.current;if(!K)return;const V=K.groups.filter(z=>{var G;try{return((G=z.element)==null?void 0:G.ownerDocument)===document&&z.model.location.type==="grid"}catch{return!1}})[0]||null,ie=[...K.panels];for(const z of ie){const G=(ke=z.group.element)==null?void 0:ke.ownerDocument,le=z.group.model.location.type;G===document&&le==="grid"||(V&&V.id!==z.group.id?z.api.moveTo({group:V,position:"center"}):z.api.moveTo({position:"center"}))}const pe=K.activePanel;pe&&(pe.group.model.openPanel(pe),pe.api.setActive()),Va(document)},[]),ve=l.useCallback(()=>{var U,V;const K=N.current;if(K)for(const ie of K.groups){const pe=(U=ie.element)==null?void 0:U.ownerDocument;if(!pe||pe===document)continue;const ke=pe.getElementById("dv-popout-window");if(!(ke instanceof HTMLElement))continue;let z=null,G=pe.title||"ADHDev",le="Popout workspace";const Ce=ie.activePanel;if(Ce)if(z=Ce.id,$t(Ce.id)){const Ae=((V=Ce.params)==null?void 0:V.routeId)||Ce.id.slice(7),He=Ot([...E.values()],Ae);G=qd(He),le=He!=null&&He.machineName?`Remote view · ${He.machineName}`:"Remote view"}else{const Ae=E.get(Ce.id);G=Ae?ot(Ae):Ce.title||Ce.id,le=Ae?bs(Ae):"Dockview panel"}pe.title=`${G} — ADHDev`;const Te=Array.from(pe.querySelectorAll("#adhdev-popout-header"));for(const Ae of Te)Ae.remove();const Me=pe.createElement("div");Me.id="adhdev-popout-header",pe.body.appendChild(Me),Me.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(";")),Me.innerHTML=`
63
+ <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
64
+ <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
65
+ <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${tc(G)}</div>
66
+ <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${tc(le)}</div>
67
+ </div>
68
+ <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
69
+ <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>
70
+ <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>
71
+ </div>
72
+ `,ke.style.top="52px",ke.style.height="calc(100% - 52px)";const _e=Me.querySelector("[data-adhdev-popout-focus]");_e&&(_e.onclick=()=>{window.focus()});const De=Me.querySelector("[data-adhdev-popout-dock]");De&&(De.disabled=!z,De.style.opacity=z?"1":"0.5",De.style.cursor=z?"pointer":"default",De.onclick=()=>{var Ae;z&&Ne(z),(Ae=pe.defaultView)==null||Ae.focus()})}},[E,Ne]),ce=l.useCallback(K=>{var ie;const U=N.current,V=U==null?void 0:U.getPanel(K);if(!(!U||!V)){V.group.model.openPanel(V),V.api.setActive(),Z(K,"dockview-shortcut");try{const pe=V.group.model.location;pe.type==="popout"?pe.getWindow().focus():Va((ie=V.group.element)==null?void 0:ie.ownerDocument)}catch{}}},[Z]),W=l.useCallback(K=>{const U=N.current,V=U==null?void 0:U.activePanel,ie=(U==null?void 0:U.activeGroup)||(V==null?void 0:V.group);if(!U||!V||!ie)return;const pe=ie.panels||[];if(pe.length<=1)return;const ke=pe.findIndex(le=>le.id===V.id);if(ke<0)return;const z=(ke+K+pe.length)%pe.length,G=pe[z];G&&(G.group.model.openPanel(G),G.api.setActive(),$t(G.id)||Z(G.id,"dockview-shortcut"))},[Z]),ne=l.useCallback(K=>{var _e;const U=N.current,V=(U==null?void 0:U.activeGroup)||((_e=U==null?void 0:U.activePanel)==null?void 0:_e.group);if(!U||!V)return;const ie=U.groups||[],pe=ie.find(De=>De.id===V.id);if(!pe)return;const ke=pe.element.getBoundingClientRect(),z=ke.left+ke.width/2,G=ke.top+ke.height/2,le=(De,Ae,He,Ve)=>Math.max(0,Math.min(Ae,Ve)-Math.max(De,He)),Ce=De=>{const Ae=De.element.getBoundingClientRect(),He=Ae.left+Ae.width/2,Ve=Ae.top+Ae.height/2;let ut=0,bt=0,lt=0,mt=!1;if(K==="left"?(mt=He<z,ut=Math.max(0,ke.left-Ae.right),bt=Math.abs(Ve-G),lt=le(ke.top,ke.bottom,Ae.top,Ae.bottom)):K==="right"?(mt=He>z,ut=Math.max(0,Ae.left-ke.right),bt=Math.abs(Ve-G),lt=le(ke.top,ke.bottom,Ae.top,Ae.bottom)):K==="above"?(mt=Ve<G,ut=Math.max(0,ke.top-Ae.bottom),bt=Math.abs(He-z),lt=le(ke.left,ke.right,Ae.left,Ae.right)):(mt=Ve>G,ut=Math.max(0,Ae.top-ke.bottom),bt=Math.abs(He-z),lt=le(ke.left,ke.right,Ae.left,Ae.right)),!mt)return Number.POSITIVE_INFINITY;const Be=lt>0?0:120;return ut*3+bt+Be};let Te=null,Me=Number.POSITIVE_INFINITY;for(const De of ie){if(De.id===pe.id)continue;const Ae=Ce(De);Number.isFinite(Ae)&&(Ae>=Me||(Me=Ae,Te=De))}return Te||void 0},[]),ue=l.useCallback(K=>{var ie;const U=ne(K);if(!U)return;const V=U.activePanel||U.panels[0];V&&(U.model.openPanel(V),V.api.setActive(),$t(V.id)||Z(V.id,"dockview-focus"),Va((ie=U.element)==null?void 0:ie.ownerDocument))},[ne,Z]),me=l.useCallback((K,U)=>{const V=N.current,ie=V==null?void 0:V.activePanel,pe=(V==null?void 0:V.activeGroup)||(ie==null?void 0:ie.group);if(!V||!ie||!pe)return;let ke=ne(K);!ke&&(U!=null&&U.createGroupIfMissing)&&(ke=V.addGroup({referenceGroup:pe,direction:K})),ke&&(ie.api.moveTo({group:ke,position:"center"}),ie.group.model.openPanel(ie),ie.api.setActive(),$t(ie.id)||Z(ie.id,U!=null&&U.createGroupIfMissing?"dockview-split":"dockview-move"))},[ne,Z]),{isMac:J,tabShortcuts:q,shortcutListening:$,setShortcutListening:re,saveShortcuts:xe}=Uu({sortedTabKeys:e.map(K=>K.tabKey),onFocus:Q,onSelectTab:ce}),je=l.useCallback(()=>{var V;const K=N.current;if(!K)return;const U=K.activePanel;if(U){if($t(U.id)){const ie=((V=U.params)==null?void 0:V.routeId)||U.id.slice(7),pe=Ot(e,ie);pe!=null&&pe.tabKey&&re(pe.tabKey);return}E.has(U.id)&&re(U.id)}},[E,ce,re,e]),ae=l.useCallback(K=>{const U=[];return K.metaKey&&U.push(J?"⌘":"Meta"),K.ctrlKey&&U.push("Ctrl"),K.altKey&&U.push(J?"⌥":"Alt"),K.shiftKey&&K.key.length!==1&&U.push(J?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(K.key)?null:(U.push(qu(K.key)),U.join("+"))},[J]),Pe=l.useCallback(K=>{var U,V;switch(K){case"splitActiveTabRight":me("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":me("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const ie=de();ie&&ge(ie);return}case"popoutActiveTab":{const ie=de();ie&&fe(ie);return}case"dockActiveTab":{const ie=de();if(!ie)return;X(ie)?Ne(ie):be(ie)&&Ie(ie);return}case"focusLeftPane":ue("left");return;case"focusRightPane":ue("right");return;case"focusUpPane":ue("above");return;case"focusDownPane":ue("below");return;case"moveActiveTabToLeftPane":me("left");return;case"moveActiveTabToRightPane":me("right");return;case"moveActiveTabToUpPane":me("above");return;case"moveActiveTabToDownPane":me("below");return;case"selectPreviousGroupTab":W(-1);return;case"selectNextGroupTab":W(1);return;case"setActiveTabShortcut":je();return;case"hideCurrentTab":{const ie=(V=(U=N.current)==null?void 0:U.activePanel)==null?void 0:V.id;ie&&!$t(ie)&&we(ie);return}default:return}},[W,Ie,ue,ge,de,we,be,X,Ne,me,fe,je]);l.useEffect(()=>{if(!P)return;const K=P.sourceDocument,U=K.defaultView??window,V=ie=>{const pe=K.querySelector("[data-dockview-tab-context-menu]");pe&&pe.contains(ie.target)||D(null)};return U.addEventListener("mousedown",V,!0),U!==window&&window.addEventListener("mousedown",()=>D(null),!0),()=>{U.removeEventListener("mousedown",V,!0),U!==window&&window.removeEventListener("mousedown",()=>D(null),!0)}},[P]);const $e=l.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:E,hasDetachedConversationPanels:F,ides:r,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:g,liveSessionInboxState:I,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:we,userName:m,scrollToBottomRequest:v,tabShortcuts:q,openTabContextMenu:({x:K,y:U,tabKey:V,sourceDocument:ie})=>D({x:K,y:U,tabKey:V,sourceDocument:ie??document}),popoutTab:fe,moveTabBackToMain:Ne,isTabInPopout:X,floatTab:ge,isTabFloating:be}),[n,t,E,F,r,i,c,g,I,a,o,we,m,v,q,fe,Ne,X,ge,be]),Re=P?iv({isTabInPopout:X(P.tabKey),isTabFloating:be(P.tabKey),tabShortcut:q[P.tabKey],actionShortcuts:p}):[],Ge=l.useCallback(K=>{var ie;const U=N.current;if((((ie=U==null?void 0:U.activePanel)==null?void 0:ie.id)??null)===K.id){K.group.model.openPanel(K);return}K.group.model.openPanel(K),K.api.setActive()},[]),Ye=l.useCallback((K,U="requested-tab")=>{if(!K)return!1;const V=N.current;if(!V)return!1;const ie=V.getPanel(K);return ie?(Ge(ie),Z(K,U),h==null||h(),!0):!1},[Ge,h,Z]),Xe=l.useCallback(()=>{if(M.current)return!1;const K=Ye(A.current,"stored-layout-restore");return K&&(M.current=!0),K},[Ye]),at=l.useCallback(()=>{var U;const K=N.current;K&&Ey(w,{activeTabId:((U=K.activePanel)==null?void 0:U.id)??null,layout:K.toJSON()})},[w]),Je=l.useCallback(()=>{Oy(w,B.current)},[w]),Ze=l.useCallback(K=>{var ie,pe,ke,z;const U=N.current;if(!U)return{kind:"grid"};const V=U.toJSON();for(const G of V.floatingGroups||[])if((pe=(ie=G.data)==null?void 0:ie.views)!=null&&pe.includes(K)&&G.position)return{kind:"floating",position:G.position};for(const G of V.popoutGroups||[])if((z=(ke=G.data)==null?void 0:ke.views)!=null&&z.includes(K))return{kind:"popout",position:G.position,popoutUrl:G.url};return{kind:"grid"}},[]),dt=l.useCallback(K=>{const U=N.current;if(!U)return;const V=U.getPanel(K),ie=B.current[K];if(!V||!ie||ie.kind==="grid")return;if(V.group.model.location.type===ie.kind){delete B.current[K],Je();return}if(ie.kind==="floating"){U.addFloatingGroup(V,{x:ie.position.left??24,y:ie.position.top??24,width:ie.position.width,height:ie.position.height}),delete B.current[K],Je();return}delete B.current[K],Je()},[Je]);l.useEffect(()=>(f==null||f({setShortcutForActiveTab:je,restoreHiddenTabToSavedLocation:dt,activateConversationTab:ce,resetAllPanelsToMain:ee,activatePreviousTabInGroup:()=>W(-1),activateNextTabInGroup:()=>W(1),floatActiveTab:()=>{const K=de();K&&ge(K)},popoutActiveTab:()=>{const K=de();K&&fe(K)},dockActiveTab:()=>{const K=de();K&&(X(K)?Ne(K):be(K)&&Ie(K))},splitActiveTabRight:()=>me("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>me("below",{createGroupIfMissing:!0}),focusLeftPane:()=>ue("left"),focusRightPane:()=>ue("right"),focusUpPane:()=>ue("above"),focusDownPane:()=>ue("below"),moveActiveTabToLeftPane:()=>me("left"),moveActiveTabToRightPane:()=>me("right"),moveActiveTabToUpPane:()=>me("above"),moveActiveTabToDownPane:()=>me("below")}),()=>f==null?void 0:f(null)),[W,Ie,ge,ue,de,be,X,me,Ne,fe,f,ee,dt,ce,je]),l.useEffect(()=>()=>{var K;(K=T.current)==null||K.call(T),T.current=null},[]);const ft=l.useCallback(K=>{var V,ie;N.current=K.api,(V=T.current)==null||V.call(T),T.current=null;const U=$y(w);if(A.current=(U==null?void 0:U.activeTabId)??null,U!=null&&U.layout&&K.api.fromJSON(U.layout,{reuseExistingPanels:!1}),L.current=Jl({hasStoredLayout:!!(U!=null&&U.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),L.current||(rc(K.api,e),nc(K.api,e,j)),K.api.totalPanels===0&&e.length>0){const pe=fv(K.api,e,k);if(pe){const ke=K.api.getPanel(pe);ke&&Ge(ke)}}else!L.current&&!Ye(k)&&Xe();if(_.current=!0,K.api.onDidActivePanelChange(pe=>{var z;if(A.current=(pe==null?void 0:pe.id)??null,M.current=!0,ve(),pe&&$t(pe.id)){const G=((z=pe.params)==null?void 0:z.routeId)||pe.id.slice(7),le=Ot(e,G);y((le==null?void 0:le.tabKey)??null),at();return}if(y((pe==null?void 0:pe.id)??null),at(),!pe)return;const ke=E.get(pe.id);(ke==null?void 0:ke.streamSource)==="agent-stream"&&ke.agentType&&C(ke.routeId,_d(),{agentType:ke.agentType,...ke.sessionId&&{targetSessionId:ke.sessionId}}).catch(()=>{})}),K.api.onDidLayoutChange(()=>{at(),ve(),R(pe=>pe+1)}),uv()){const pe=Me=>({clientX:Me.clientX,clientY:Me.clientY}),ke=Me=>{const _e=Me==null?void 0:Me.getBoundingClientRect();return _e?{left:_e.left,right:_e.right,top:_e.top,bottom:_e.bottom}:null},z=Me=>{var De;const _e=(De=S.current)==null?void 0:De.getBoundingClientRect();return _e?Me.clientX<_e.left||Me.clientX>_e.right||Me.clientY<_e.top||Me.clientY>_e.bottom:!1},G=dv({detachDelayMs:Xu,onDetach:({panelId:Me,clientX:_e,clientY:De})=>{var lt,mt;const Ae=K.api.getPanel(Me);if(!Ae)return;try{if(Ae.group.model.location.type!=="grid")return}catch{return}const He=(lt=S.current)==null?void 0:lt.getBoundingClientRect(),Ve=(mt=Ae.group.element)==null?void 0:mt.getBoundingClientRect(),ut=Math.round(Math.min(Math.max((Ve==null?void 0:Ve.width)??600,360),720)),bt=Math.round(Math.min(Math.max((Ve==null?void 0:Ve.height)??500,260),640));K.api.addFloatingGroup(Ae,{x:He?Math.max(0,_e-He.left-32):void 0,y:He?Math.max(0,De-He.top-18):void 0,width:ut,height:bt}),Ae.api.setActive(),at(),ve(),R(Be=>Be+1)}}),le=[K.api.onWillDragPanel(Me=>{if(!(Me.nativeEvent.defaultPrevented||Me.nativeEvent.shiftKey)){try{if(Me.panel.group.model.location.type!=="grid")return}catch{return}G.startDrag({panelId:Me.panel.id,selfPanelBounds:ke(Me.panel.group.element),...pe(Me.nativeEvent)})}}),K.api.onWillShowOverlay(Me=>{if(G.hasDetached()){Me.preventDefault();return}G.markDockTarget(pe(Me.nativeEvent))}),K.api.onWillDrop(Me=>{if(G.hasDetached()){Me.preventDefault(),G.endDrag();return}G.markDockTarget(pe(Me.nativeEvent))}),K.api.onDidDrop(()=>G.endDrag()),K.api.onUnhandledDragOverEvent(Me=>{G.isDragging()&&G.markSelfPanel(pe(Me.nativeEvent))})],Ce=Me=>{if(!G.isDragging())return;const _e=pe(Me);z(_e)&&G.markNonSelfPanel(_e)},Te=()=>G.endDrag();window.addEventListener("dragover",Ce,!0),window.addEventListener("drop",Te,!0),window.addEventListener("dragend",Te,!0),T.current=()=>{G.dispose();for(const Me of le)Me.dispose();window.removeEventListener("dragover",Ce,!0),window.removeEventListener("drop",Te,!0),window.removeEventListener("dragend",Te,!0)}}K.api.onDidAddGroup(pe=>{requestAnimationFrame(()=>{var ke,z;try{const G=(ke=pe.element)==null?void 0:ke.ownerDocument;if(!G||G===document)return;(z=G.getElementById("dv-popout-window"))==null||z.classList.add("adhdev-dockview");const le=document.documentElement.getAttribute("data-theme");le&&G.documentElement.setAttribute("data-theme",le),G.body.className=document.body.className;const Ce=document.documentElement.getAttribute("style");Ce&&G.documentElement.setAttribute("style",Ce)}catch{}ve(),R(G=>G+1)})}),y(((ie=K.api.activePanel)==null?void 0:ie.id)??null)},[Ge,Ye,E,r,d,w,y,at,k,j,C,ve,e]);l.useLayoutEffect(()=>{const K=N.current;if(!K||!_.current||L.current&&Jl({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;L.current&&(L.current=!1);const U=H.current,V=new Set(U),ie=e.map(Te=>Te.tabKey),pe=new Set(ie),ke=lv({previousVisibleConversationCount:U.length,visibleConversationCount:e.length,ides:r});let z=!1;for(const Te of U)pe.has(Te)||ke||(B.current[Te]=Ze(Te),z=!0);z&&Je(),ke||(rc(K,e),nc(K,e,j));const G=ie.filter(Te=>!V.has(Te));let le=!1;for(const Te of G){const Me=K.getPanel(Te),_e=B.current[Te];if(!Me||!_e||_e.kind==="grid")continue;if(Me.group.model.location.type===_e.kind){delete B.current[Te],le=!0;continue}if(_e.kind==="floating"){K.addFloatingGroup(Me,{x:_e.position.left??24,y:_e.position.top??24,width:_e.position.width,height:_e.position.height}),delete B.current[Te],le=!0;continue}}if(le&&Je(),H.current=ie,k&&Ye(k))return;!K.activePanel&&K.panels[0]&&Ge(K.panels[0]),!!(K.activePanel&&K.getPanel(K.activePanel.id))||Xe()},[Ge,Ye,Xe,r,d,Je,Ze,k,j,e]),l.useEffect(()=>{_.current&&Ye(k)},[Ye,k]),l.useEffect(()=>{const K=V=>{const ie=V.target;if(!ie)return;const pe=ie.querySelector("[data-tab-key]")||ie.closest("[data-tab-key]");if(pe){const ke=pe.getAttribute("data-tab-key");if(ke&&V.dataTransfer){const z=ie.closest(".dv-tab")||pe.closest(".dv-tab")||pe;V.dataTransfer.effectAllowed="move",V.dataTransfer.setData("text/tab-key",ke),z instanceof HTMLElement&&V.dataTransfer.setDragImage(z,Math.max(12,Math.round(z.clientWidth/2)),Math.max(10,Math.round(z.clientHeight/2)))}}};window.addEventListener("dragstart",K);const U=sc(N.current);for(const V of U)V.addEventListener("dragstart",K);return()=>{window.removeEventListener("dragstart",K);for(const V of U)V.removeEventListener("dragstart",K)}},[O]),l.useEffect(()=>{var U;const K=(U=S.current)==null?void 0:U.querySelector(".adhdev-dockview");K instanceof HTMLElement&&qa(K,b),te(),ve()},[ve,te,b]),l.useEffect(()=>{ve()},[ve]),l.useEffect(()=>{const K=U=>{if(U.defaultPrevented||$)return;const V=ae(U);if(!V)return;const ie=U.metaKey||U.ctrlKey||U.altKey;$o(U.target)&&!ie||Zn(J).setActiveTabShortcut!==V||(U.preventDefault(),U.stopPropagation(),je())};return window.addEventListener("keydown",K,!0),()=>window.removeEventListener("keydown",K,!0)},[ae,J,$,je]),l.useEffect(()=>{const K=S.current;if(!K)return;const U=V=>{var G,le;if(!V.isTrusted)return;const ie=(le=(G=V.target)==null?void 0:G.closest)==null?void 0:le.call(G,".dv-scrollable");if(!ie)return;V.preventDefault(),V.stopPropagation();const pe=Math.abs(V.deltaX),ke=Math.abs(V.deltaY),z=pe>ke?V.deltaX:V.deltaY;ie.dispatchEvent(new WheelEvent("wheel",{deltaY:z,deltaMode:V.deltaMode,bubbles:!1,cancelable:!0}))};return K.addEventListener("wheel",U,{passive:!1,capture:!0}),()=>K.removeEventListener("wheel",U,{capture:!0})},[]),l.useEffect(()=>{const K=sc(N.current);if(K.length===0)return;const U=K.map(V=>{let ie=[],pe=null;const ke=()=>{pe!=null&&V.clearTimeout(pe),pe=null,ie=[]},z=()=>{pe!=null&&V.clearTimeout(pe),pe=V.setTimeout(()=>{pe=null,ie=[]},1200)},G=Ce=>{if(!Ce.ctrlKey&&!Ce.metaKey&&!Ce.altKey)return;const Te=ae(Ce);if(!Te)return;const Me=Ku();for(const[_e,De]of Object.entries(Me))if(e.some(Ae=>Ae.tabKey===_e)&&De===Te){Ce.preventDefault(),ce(_e);return}},le=Ce=>{if(Ce.defaultPrevented||$)return;const Te=ae(Ce);if(!Te)return;const Me=Ce.metaKey||Ce.ctrlKey||Ce.altKey;if($o(Ce.target))return;const _e=Zn(J),De=Object.entries(_e).filter(([Be,Mt])=>!!Mt&&(Be==="splitActiveTabRight"||Be==="splitActiveTabDown"||Be==="floatActiveTab"||Be==="popoutActiveTab"||Be==="dockActiveTab"||Be==="focusLeftPane"||Be==="focusRightPane"||Be==="focusUpPane"||Be==="focusDownPane"||Be==="moveActiveTabToLeftPane"||Be==="moveActiveTabToRightPane"||Be==="moveActiveTabToUpPane"||Be==="moveActiveTabToDownPane"||Be==="selectPreviousGroupTab"||Be==="selectNextGroupTab"||Be==="setActiveTabShortcut"||Be==="hideCurrentTab")),Ae=Me?[Te]:[...ie.slice(-1),Te].slice(-2),He=Ae.join(" "),Ve=Ae[Ae.length-1],ut=De.find(([,Be])=>Be===He);if(ut){Ce.preventDefault(),ke(),Pe(ut[0]);return}if(De.some(([,Be])=>Be.startsWith(`${He} `))){Ce.preventDefault(),ie=Ae,z();return}const lt=De.find(([,Be])=>Be===Ve);if(lt){Ce.preventDefault(),ke(),Pe(lt[0]);return}if(De.some(([,Be])=>Be.startsWith(`${Ve} `))){Ce.preventDefault(),ie=[Ve],z();return}ke()};return V.addEventListener("keydown",G),V.addEventListener("keydown",le),()=>{ke(),V.removeEventListener("keydown",G),V.removeEventListener("keydown",le)}});return()=>{for(const V of U)V()}},[ae,J,O,ce,$,Pe,e]);const he=b==="light"?ho:fo,Oe=((ht=(ze=(et=N.current)==null?void 0:et.activePanel)==null?void 0:ze.group.element)==null?void 0:ht.ownerDocument)??document;return s.jsxs(Ju.Provider,{value:$e,children:[s.jsx("div",{ref:S,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(dp,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:xv,remote:bv},defaultTabComponent:yv,watermarkComponent:gv,onReady:ft,singleTabMode:"default",tabAnimation:"smooth",theme:he,popoutUrl:"/popout.html"})}),P&&Cr.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:P.x,top:P.y},children:Re.map(K=>{if(K.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},K.id);let U=s.jsx(wh,{size:13,className:"shrink-0 opacity-70"}),V=()=>{};switch(K.id){case"dockInWindow":case"dockBackToGrid":U=s.jsx(kh,{size:13,className:"shrink-0 opacity-70"}),V=()=>{Ie(P.tabKey),D(null)};break;case"moveBackToMain":U=s.jsx(vh,{size:13,className:"shrink-0 opacity-70"}),V=()=>{Ne(P.tabKey),D(null)};break;case"floatAsPanel":U=s.jsx(jh,{size:13,className:"shrink-0 opacity-70"}),V=()=>{ge(P.tabKey),D(null)};break;case"openInNewWindow":U=s.jsx(yh,{size:13,className:"shrink-0 opacity-70"}),V=()=>{fe(P.tabKey),D(null)};break;case"setShortcut":V=ie=>{ie.stopPropagation(),re(P.tabKey),D(null)};break;case"removeShortcut":U=s.jsx(yt,{size:13,className:"shrink-0 opacity-70"}),V=()=>{const ie={...q};delete ie[P.tabKey],xe(ie),D(null)};break;case"hideTab":U=s.jsx(Vo,{size:13,className:"shrink-0 opacity-70"}),V=()=>{we(P.tabKey),D(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:pv,onClick:V,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)})}),P.sourceDocument.body),$&&Cr.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:()=>re(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. ",J?"⌘+1":"Ctrl+1",", ",J?"⌥+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"})]})}),Oe.body)]})}const Qu="adhdev-recent-launch-args-v1",wv=8;function jv(e){return String(e||"").trim().replace(/\s+/g," ")}function Zu(e,t){return`${e.trim()}::${t.trim()}`}function em(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Qu)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function kv(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Qu,JSON.stringify(e))}catch{}}function Sv(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=em().byKey[Zu(r,n)])==null?void 0:o.items)||[]}function Nv(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=jv(r);if(!n||!a||!o)return;const i=em(),c=Zu(n,a),d=((u=i.byKey[c])==null?void 0:u.items)||[],m=[o,...d.filter(p=>p!==o)].slice(0,wv);i.byKey[c]={items:m},kv(i)}function Cv(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Ln({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 Iv({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:d}){const m=o?Bu(o):null,u=Iv({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Ln,{title:"Saved history",description:li(),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:sg()})]}),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:d,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:u}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function tm({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 Av({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 Ya(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 xn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Tv({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Be,Mt;const u=Or(),p=l.useMemo(()=>[...e].sort(Zo),[e]),[f,y]=l.useState(((Be=p[0])==null?void 0:Be.id)||""),g=l.useMemo(()=>p.find(se=>se.id===f)||p[0],[f,p]),x=l.useMemo(()=>((g==null?void 0:g.workspaces)||[]).map(se=>({id:se.id,path:se.path,label:se.label})),[g]),k=(g==null?void 0:g.defaultWorkspaceId)||null,[j,h]=l.useState("workspace"),[v,I]=l.useState(""),[w,b]=l.useState(""),[C,N]=l.useState([]),[S,T]=l.useState(""),[_,L]=l.useState(!1),[M,A]=l.useState(null),[H,P]=l.useState(""),[D,O]=l.useState(Ya(p[0])),[R,B]=l.useState(""),[E,F]=l.useState(""),[Q,Z]=l.useState([]),[Y,te]=l.useState(""),[fe,Ne]=l.useState([]),[X,we]=l.useState(!1),[ge,be]=l.useState(!1),[de,Ie]=l.useState(""),[ee,ve]=l.useState(!1),[ce,W]=l.useState(()=>Nt()),[ne,ue]=l.useState(null),[me,J]=l.useState(!1),[q,$]=l.useState(""),[re,xe]=l.useState(null),[je,ae]=l.useState(!1),[Pe,$e]=l.useState(""),[Re,Ge]=l.useState([]),[Ye,Xe]=l.useState(!1),[at,Je]=l.useState(""),[Ze,dt]=l.useState(!1),ft=l.useRef(null),he=l.useRef(0);l.useEffect(()=>{var se;!f&&((se=p[0])!=null&&se.id)&&y(p[0].id)},[f,p]),l.useEffect(()=>{!g||!(!g.workspaces||!g.availableProviders||!g.detectedIdes||!g.recentLaunches)||u(g.id,{minFreshMs:3e4}).catch(()=>{})},[u,g]);const Oe=l.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(se=>Ks(se,"cli")),[g]),et=l.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(se=>Ks(se,"acp")),[g]),ze=l.useMemo(()=>((g==null?void 0:g.detectedIdes)||[]).map(se=>({id:se.type,label:se.name||se.type,meta:se.running?"Detected locally":"Available to open"})),[g]),ht=l.useMemo(()=>D==="cli"?Oe.map(se=>({id:se.type,label:se.displayName||se.type,meta:"CLI provider"})):D==="acp"?et.map(se=>({id:se.type,label:se.displayName||se.type,meta:"ACP provider"})):ze,[et,D,Oe,ze]),K=l.useMemo(()=>C.find(se=>se.id===S)||null,[C,S]),U=l.useMemo(()=>Oe.find(se=>se.type===R)||null,[Oe,R]),V=l.useMemo(()=>Lu(U==null?void 0:U.meshCoordinator,{meshId:(K==null?void 0:K.id)||"",workspace:(K==null?void 0:K.workspace)||""}),[U,K]),ie=re||V,pe=l.useCallback(async se=>{L(!0),P("");try{const Le=await c(se);N(Le),T(oe=>{var ye;return Le.some(We=>We.id===oe)?oe:((ye=Le[0])==null?void 0:ye.id)||""}),A(se)}catch(Le){N([]),T(""),A(se),P(Le instanceof Error?Le.message:"Could not load meshes")}finally{L(!1)}},[c]);l.useEffect(()=>{var Le;if(!g)return;if(ft.current!==g.id){ft.current=g.id,h("workspace"),I(k||((Le=x[0])==null?void 0:Le.id)||"__home__"),b(""),N([]),T(""),A(null),P(""),O(Ya(g)),B(""),F(""),te(""),Ne([]),be(!1),Ie(""),W(Nt()),$(""),xe(null);return}I(oe=>{var ye;return oe==="__custom__"||oe==="__home__"||x.some(We=>We.id===oe)?oe:k||((ye=x[0])==null?void 0:ye.id)||"__home__"}),O(oe=>oe==="ide"&&ze.length>0||oe==="cli"&&Oe.length>0||oe==="acp"&&et.length>0?oe:Ya(g))},[et.length,Oe.length,k,ze.length,g,x]),l.useEffect(()=>{!g||j!=="mesh"||M===g.id||_||pe(g.id)},[pe,M,_,g,j]),l.useEffect(()=>{j==="mesh"&&D!=="cli"&&Oe.length>0&&O("cli")},[D,Oe.length,j]),l.useEffect(()=>{var se;D&&(ht.some(Le=>Le.id===R)||B(((se=ht[0])==null?void 0:se.id)||""))},[D,ht,R]),l.useEffect(()=>{xe(null)},[g==null?void 0:g.id,S,R,j]);const ke=l.useCallback(async(se,Le)=>{const oe=he.current+1;return he.current=oe,we(!0),Ie(""),m(se,Le).then(ye=>{he.current===oe&&Ne(ye)}).catch(ye=>{he.current===oe&&(Ne([]),Ie(ye instanceof Error?ye.message:"Could not load saved sessions"))}).finally(()=>{he.current===oe&&(we(!1),be(!0))})},[m]),z=l.useCallback((se,Le)=>{Z(Sv(se,Le))},[]);l.useEffect(()=>{he.current+=1,te(""),W(Nt()),!g||!R||D==="ide"?Z([]):z(g.id,R),be(!1),Ne([]),Ie(""),we(!1)},[D,z,ke,g,R]),l.useEffect(()=>{if(!Y)return;const se=fe.find(Le=>Le.providerSessionId===Y);se!=null&&se.canResume||te("")},[fe,Y]);const G=v==="__custom__"?w.trim():v==="__home__"?"":((Mt=x.find(se=>se.id===v))==null?void 0:Mt.path)||"",le=l.useMemo(()=>g?t.filter(se=>se.id!==g.id&&se.daemonId===g.id).map(se=>se.workspace):[],[t,g]),Ce=l.useMemo(()=>((g==null?void 0:g.recentLaunches)||[]).map(se=>se.workspace),[g]),Te=l.useCallback(se=>{const Le=String(se.workspace||"").trim();if(!Le)return;const oe=x.find(ye=>xn(ye.path)===xn(Le));if(oe){I(oe.id),b("");return}I("__custom__"),b(Le)},[x]),Me=l.useCallback(se=>{const Le=String(se.workspace||"").trim();if(!Le)return{workspaceId:null,workspacePath:null};const oe=x.find(ye=>xn(ye.path)===xn(Le));return oe?{workspaceId:oe.id,workspacePath:null}:{workspaceId:null,workspacePath:Le}},[x]),_e=l.useMemo(()=>fe.find(se=>se.providerSessionId===Y)||null,[fe,Y]),De=l.useMemo(()=>{var Le;if(D!=="cli"||!g||!R)return null;const se=((Le=Oe.find(oe=>oe.type===R))==null?void 0:Le.displayName)||R;return{routeId:g.id,daemonId:g.id,providerSessionId:Y||void 0,transport:"pty",mode:"chat",agentName:se,agentType:R,status:"idle",title:se,messages:[],ideType:R,workspaceName:G,workspacePath:G,displayPrimary:se,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${g.id}:${R}`,machineName:Pt(g,{fallbackId:g.id})}},[D,Oe,G,g,Y,R]),Ae=l.useCallback(()=>{var Le;if(!g)return;I("__custom__"),ae(!0),Je("");const se=bi(g.platform,xi(w.trim(),G,le,Ce,g.defaultWorkspacePath,(Le=x.find(oe=>oe.id===k))==null?void 0:Le.path,x.map(oe=>oe.path)));Xe(!0),n(g.id,se).then(oe=>{$e(oe.path),b(oe.path),Ge(oe.directories)}).catch(oe=>{Je(oe instanceof Error?oe.message:"Could not load folder")}).finally(()=>Xe(!1))},[w,k,Ce,le,n,G,g,x]),He=l.useCallback(se=>{g&&(Xe(!0),Je(""),n(g.id,se).then(Le=>{$e(Le.path),b(Le.path),Ge(Le.directories)}).catch(Le=>{Je(Le instanceof Error?Le.message:"Could not load folder")}).finally(()=>Xe(!1)))},[n,g]),Ve=l.useCallback(async()=>{if(!g||!G)return;dt(!0),$("");const se=await a(g.id,G);if(dt(!1),!se.ok){$(se.error||"Could not save workspace");return}$("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,G,g]),ut=l.useCallback(async()=>{if(!g)return;if(j==="mesh"){if(!S||!R)return;J(!0),$(""),xe(null);const oe=await d(g.id,S,R);if(J(!1),!oe.ok){if(oe.code==="mesh_coordinator_manual_mcp_setup_required"&&oe.manualSetup){xe(oe.manualSetup),$("Manual MCP setup required before this provider can act as mesh coordinator.");return}$(oe.error||"Could not start mesh coordinator");return}r();return}if(!D||!R)return;J(!0),$("");const se=E.trim()?E.trim().split(/\s+/).filter(Boolean):[],Le=D==="ide"?await o(g.id,R,{workspacePath:G||null}):await i(g.id,D,R,{workspaceId:v!=="__home__"&&v!=="__custom__"?v:null,workspacePath:v==="__custom__"&&G||null,resumeSessionId:D==="cli"&&Y?Y:null,cliArgs:se});if(J(!1),!Le.ok){$(Le.error||"Could not start session");return}D!=="ide"&&E.trim()&&(Nv(g.id,R,E),z(g.id,R)),r()},[D,E,z,r,o,d,i,G,g,S,Y,R,v,j]),bt=j==="mesh"?"Start mesh coordinator":D?Zb(D,D==="cli"&&!!Y):"Start",lt=j==="mesh"?"Starting coordinator…":D?eg(D,D==="cli"&&!!Y):"Starting…",mt=p.length>5;return g?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(yt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[p.length>1&&s.jsx(Ln,{title:"Machine",children:mt?s.jsx("select",{"aria-label":"Machine",value:g.id,onChange:se=>y(se.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:me,children:p.map(se=>s.jsx("option",{value:se.id,children:Pt(se,{fallbackId:se.id})},se.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:p.map(se=>{const Le=Pt(se,{fallbackId:se.id}),oe=g.id===se.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${Le}`,"aria-pressed":oe,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${oe?"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(se.id),disabled:me,title:Le,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${se.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:Le})]},se.id)})})}),s.jsxs(Ln,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:j==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ae,disabled:me,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(se=>s.jsxs("button",{type:"button",role:"radio","aria-checked":j===se.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${j===se.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:()=>{h(se.id),$(""),se.id==="mesh"&&g&&M!==g.id&&!_&&pe(g.id)},disabled:me,children:[s.jsx("div",{className:"text-sm font-semibold",children:se.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:se.desc})]},se.id))}),j==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:v,onChange:se=>{const Le=se.target.value;I(Le),Le==="__custom__"?Ae():$("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:me,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),x.map(se=>s.jsxs("option",{value:se.id,children:[se.id===k?"⭐ ":"",xd(se.path,se.label)||se.path]},se.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v==="__home__"?"Launch without a workspace.":G||"Select a workspace folder."}),v==="__custom__"&&G&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ae,disabled:me,children:[s.jsx(Os,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ve,disabled:me||Ze,children:Ze?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[_&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!_&&H&&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:H}),!_&&!H&&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(se=>s.jsxs("button",{type:"button",role:"radio","aria-checked":S===se.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${S===se.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>T(se.id),disabled:me,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:se.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[se.repoIdentity||"Repo mesh",typeof se.nodesCount=="number"?` · ${se.nodesCount} node${se.nodesCount===1?"":"s"}`:""]}),se.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",se.workspace]})]},se.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(Av,{workspaceMode:j,activeKind:D,cliEnabled:Oe.length>0,ideEnabled:ze.length>0,acpEnabled:et.length>0,busy:me,onSelect:O}),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:D==="ide"?"Choose IDE":D==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[ht.map(se=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${R===se.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>B(se.id),disabled:me,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:se.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:se.meta})]},se.id)),ht.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."})]})]}),j==="mesh"&&ie&&s.jsx(tm,{setup:ie,providerName:(U==null?void 0:U.displayName)||(U==null?void 0:U.name)||R}),j!=="mesh"&&D!=="ide"&&s.jsxs(Ln,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:E,onChange:se=>F(se.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:me}),Q.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:Q.map(se=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>F(se),disabled:me,title:se,children:se},se))})]}),j!=="mesh"&&D==="cli"&&s.jsx(Mv,{busy:me,savedSessionsLoading:X,savedSessionsError:de,selectedSession:_e,onRefresh:()=>{!g||!R||ke(g.id,R)},onOpenHistory:()=>{!g||!R||(ve(!0),Cv({hasLoadedInitialResults:ge,isLoading:X})&&ke(g.id,R))},onClearSelection:()=>te("")}),q&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${q.includes("saved")||q.includes("requested")||q.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:q})]}),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:me,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:ut,disabled:me||(j==="mesh"?!S||!R||D!=="cli"||_:!D||!R||v==="__custom__"&&!G),children:[s.jsx(ed,{size:14}),me?lt:bt]})]})]})}),je&&s.jsx(vi,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:Pe,directories:Re,busy:Ye,error:at,onClose:()=>ae(!1),onNavigate:He,onConfirm:se=>{b(se),$e(se),I("__custom__"),ae(!1)}}),ee&&De&&s.jsx(eu,{activeConv:De,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:fe,isSavedSessionsLoading:X,isResumingSavedSessionId:ne,savedHistoryFilters:ce,missingWorkspaceResumePath:G||null,onSavedHistoryFiltersChange:W,onClose:()=>ve(!1),onNewChat:()=>{te(""),ve(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!g||!R||ke(g.id,R)},onResumeSavedSession:se=>{if(!g||!R||ne||!se.canResume)return;const Le=Me(se);te(se.providerSessionId),Te(se),ue(se.providerSessionId),ve(!1),J(!0),$(""),i(g.id,"cli",R,{workspaceId:Le.workspaceId,workspacePath:Le.workspacePath,resumeSessionId:se.providerSessionId}).then(oe=>{if(!oe.ok){$(oe.error||"Could not resume session");return}r()}).finally(()=>{J(!1),ue(oe=>oe===se.providerSessionId?null:oe)})}})]}):null}function sm(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 ji(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=sm(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 ki(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function rm(e){var t;return!ki(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 bn(e){return[...new Set(e.filter(t=>!!t))]}function _v(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?bn([t==null?void 0:t.id,...n.map(i=>i.id)]):a.length>0?bn(a.map(i=>i.id)):o.length>0?bn(o.map(i=>i.id)):bn(e.nodes.map(i=>i.id))}function nm(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 Lv(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${nm(e)}::${n}x${a}`}const Pv={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"},Rv={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"},Dv={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"},$v={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 flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-slate-200 bg-[radial-gradient(circle_at_top,_rgba(14,165,233,0.16),_rgba(248,250,252,0.98)_42%,_rgba(255,255,255,1))]",graphStatChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-slate-700 shadow-sm",graphHintChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-[10px] text-slate-500 shadow-sm",graphControlsClass:"!bottom-4 !left-4 !shadow-md",graphBackgroundDotColor:"rgba(148, 163, 184, 0.34)",edgeLabelTextColor:"#334155",edgeLabelBackgroundColor:"rgba(255, 255, 255, 0.96)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.45)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-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 flex flex-col 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=>Rv[t],actionButton:t=>$v[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",graphStatChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-slate-200",graphHintChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-[10px] text-slate-300",graphControlsClass:"!bottom-4 !left-4 !shadow-lg",graphBackgroundDotColor:"rgba(148, 163, 184, 0.22)",edgeLabelTextColor:"#cbd5e1",edgeLabelBackgroundColor:"rgba(2, 6, 23, 0.86)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.2)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-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 flex flex-col 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=>Pv[t],actionButton:t=>Dv[t]}}const Us={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,layerGap:220,nodeGap:82,edgeLabelBuffer:180,placeholderTopOffset:0},Ur={worktreeCardWidth:188,submoduleCardWidth:188,minWorktreeCardHeight:88,minSubmoduleCardHeight:88,maxEstimatedCardHeight:178,layerGap:160,nodeGap:52,edgeLabelBuffer:120},Ev={maxWidth:180};function Bv(e){return e==="TB"?"DOWN":"RIGHT"}function Si(e,t){return{"elk.algorithm":"layered","elk.direction":Bv(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 Ov=Si(Us,"LR");Si(Ur,"LR");function Fv(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 Hv=new up;function Pr(e,t=!1){const r=t?Ur:Us;return e.type==="submoduleNode"?r.submoduleCardWidth:r.worktreeCardWidth}function Pn(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=sm(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 am(e,t=!1){const r=t?Ur:Us,n=Pr(e,t),a=t?e.type==="submoduleNode"?20:22:e.type==="submoduleNode"?24:30,o=t?(e.type==="submoduleNode",2):e.type==="submoduleNode"?2:3,i=Math.ceil(Wv(e)/o),c=gn(e.label,a,2),d=gn(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,a,2),m=gn(Pn(e),a+(t?1:4),t?2:3),u=ji(e),p=rm(e)?ki(e):null,f=t?0:gn(p,Math.max(24,Math.floor(n/8)),4),y=t?40+c*16+d*12+(u?22:0)+Math.max(0,i-1)*18+Math.max(18,m*16):52+c*18+d*14+(u?30:0)+i*24+Math.max(22,m*18)+(f>0?22+f*16:0),g=e.type==="submoduleNode"?r.minSubmoduleCardHeight:r.minWorktreeCardHeight;return Math.min(r.maxEstimatedCardHeight,Math.max(g,Math.ceil(y)))}function gn(e,t,r){const n=(e||"").trim();return n?Math.max(1,Math.min(r,Math.ceil(n.length/t))):0}function Wv(e){let t=1;return e.type==="submoduleNode"&&(t+=1),e.branch&&e.type!=="submoduleNode"&&(t+=1),e.submoduleCommit&&e.type==="submoduleNode"&&(t+=1),e.dirty&&(t+=1),e.outOfSync&&(t+=1),e.hasConflicts&&(t+=1),e.type!=="submoduleNode"&&e.upstream&&e.upstreamStatus!=="fresh"&&(t+=1),e.isOrphan&&(t+=1),t}function Kv(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 Uv(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function zv(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 Gv(e,t,r){return{id:e.id,x:t,y:r,width:Pr(e),height:am(e)}}function Vv(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 om(e){const t=[...e.nodes].sort(Kv),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,Vv(r,e)]}function qv(e,t=Ov,r=!1,n="LR"){const a=om(e),o=new Set(a.map(d=>d.id)),i=a.map(d=>({id:d.id,width:Pr(d,r),height:am(d,r)})),c=e.edges.filter(d=>o.has(d.source)&&o.has(d.target)).sort(Uv).map(d=>({id:d.id,sources:[d.source],targets:[d.target]}));return{id:`${e.meshId||"mesh"}__elk_root`,layoutOptions:{...t},children:i,edges:c}}function Yv(e,t=!1){const r=[...new Set(e.map(a=>Math.round(a.x)))].sort((a,o)=>a-o),n=t?Ur.layerGap:Us.layerGap;return r.length<2?n:Math.min(...r.slice(1).map((a,o)=>a-r[o]))}async function Xv(e,t=!1,r="LR"){var f,y;const a=Si(t?Ur:Us,r),o=om(e),i=new Map(o.map(g=>[g.id,g])),c=await Hv.layout(qv(e,a,t,r)),d=(c.children??[]).map(g=>{const x=i.get(g.id);return x?zv(x,Math.round(g.x??0),Math.round(g.y??Us.placeholderTopOffset),!g.id.endsWith("__placeholder")):null}).filter(Boolean),m=new Map(o.map((g,x)=>[g.id,x]));d.sort((g,x)=>(m.get(g.id)??0)-(m.get(x.id)??0));const u=d.map(g=>Gv(g.graphNode,g.position.x,g.position.y)),p=new Map;for(const g of c.edges??[]){const x=g.sections;if(!x||x.length===0)continue;const k=x[0],j=(f=g.sources)==null?void 0:f[0],h=(y=g.targets)==null?void 0:y[0];if(!j||!h)continue;const v=[];v.push({x:Math.round(k.startPoint.x),y:Math.round(k.startPoint.y)});for(const I of k.bendPoints??[])v.push({x:Math.round(I.x),y:Math.round(I.y)});v.push({x:Math.round(k.endPoint.x),y:Math.round(k.endPoint.y)}),p.set(g.id,{id:g.id,source:j,target:h,points:v})}return{nodes:d,bounds:u,edgeRoutes:p,columnGap:Yv(u,t),layoutOptions:{...a}}}function Jv(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 im(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function Qv(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(Jv),...e.edges.map(im)].join("::")}function Zv(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(im)].join("::")}const ew=7,Ni=l.createContext(Ys("dark")),lm=l.createContext(!1),cm=l.createContext("LR"),dm={overflowWrap:"anywhere",wordBreak:"break-word"},tw={...dm,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},sw={...dm,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function um(e){return e.activeSessionCount>0}function rw(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function ac(e,t,r){const n=um(e),a=rw(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=ji(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 oc(e,t){switch(e){case"danger":return t?"border-rose-400/35 bg-rose-500/14 text-rose-50":"border-rose-300 bg-rose-50 text-rose-700";case"warn":return t?"border-amber-400/35 bg-amber-500/14 text-amber-50":"border-amber-300 bg-amber-50 text-amber-700";case"info":return t?"border-violet-400/35 bg-violet-500/14 text-violet-50":"border-violet-300 bg-violet-50 text-violet-700";case"good":default:return t?"border-emerald-400/35 bg-emerald-500/12 text-emerald-50":"border-emerald-300 bg-emerald-50 text-emerald-700"}}function ic(e){switch(e){case"online":return"#34d399";case"dirty":return"#fbbf24";case"degraded":return"#fb7185";case"wrong_branch":return"#a78bfa";case"offline":return"#94a3b8";default:return"#64748b"}}function nw(e){return e.replace(/_/g," ")}function Ht(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 aw(e){var t;return((t=e.sessionDetails)==null?void 0:t.some(r=>Ht(r)==="generating"))??!1}function Xa(e,t){const r=Ht(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 ow(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function lc(e){const t=ow(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 Ja(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function dr(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function iw(e){if(e.sessionDetails.length===0)return null;const t=e.sessionDetails.filter(o=>Ht(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 cc(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function lw(e){return e.locality==="remote"?"meta":"health"}function cw({data:e,selected:t}){const r=l.useContext(Ni),n=l.useContext(lm),a=l.useContext(cm),o=e.graphNode,i=o.type==="defaultBranchNode",c=o.type==="submoduleNode",d=rm(o),m=i?"default branch anchor":c?o.submodulePath||"submodule checkout":[o.machineLabel,cc(o.locality)].filter(Boolean).join(" · ")||o.workspace,u=o.submoduleCommit?o.submoduleCommit.slice(0,7):null,p=ji(o),f=ki(o),y=um(o),g=o.sessionDetails,x=o.sessionDetails,k=iw(o),j=o.sessionDetails.map(v=>{const I=Ht(v),w=v.providerType||"provider unknown",b=dr(v),C=v.startedAt||v.createdAt||null,N=v.statusNote?` · ${v.statusNote}`:"";return`Session: ${v.sessionId} · ${w} · ${I} · ${b} · ${lc(C)}${N}`});if(n)return s.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${ac(o,t,r.isDark)}`,style:{width:Pr(o,!0)},title:[o.label,o.branch?`Branch: ${o.branch}`:null,o.machineLabel?`Machine: ${o.machineLabel}`:null,o.workspace?`Workspace: ${o.workspace}`:null,p?`Status: ${p.label}`:null,Pn(o),...j].filter(Boolean).join(`
73
+ `),children:[s.jsx(en,{type:"target",position:a==="TB"?es.Top:es.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:ic(o.health)},"aria-hidden":!0})]})]}),p&&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] ${oc(p.tone,r.isDark)}`,title:p.label,children:s.jsx("span",{className:"truncate",children:p.label})}),!p&&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}),k&&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:j.join(`
74
+ `),children:k}),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(v=>s.jsxs("div",{className:`min-w-0 rounded-md border px-1.5 py-1 ${r.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/80"}`,title:[`Session ID: ${v.sessionId}`,v.providerType?`Provider: ${v.providerType}`:null,`Status: ${Ht(v)}`,`Role: ${dr(v)}`].filter(Boolean).join(`
75
+ `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-1.5",children:[s.jsx("span",{className:`min-w-0 truncate text-[9px] ${r.textMuted}`,children:v.providerType||"provider unknown"}),s.jsx("span",{className:`shrink-0 rounded-full border px-1 py-0 text-[8px] font-semibold uppercase tracking-[0.1em] ${Xa(v,r.isDark)}`,children:Ht(v)})]}),s.jsxs("div",{className:`mt-0.5 flex min-w-0 items-center gap-1.5 text-[8px] ${r.textMuted}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",children:Ja(v.sessionId)}),s.jsx("span",{className:"shrink-0",children:dr(v)})]})]},v.sessionId))}),s.jsx(en,{type:"source",position:a==="TB"?es.Bottom:es.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]});const h=[o.label,m,p?`Status: ${p.label}`:null,Pn(o),o.branch?`Branch: ${o.branch}`:null,o.dirty?c?"Local changes":`${o.dirtyFiles} dirty`:null,o.hasConflicts?"Has conflicts":null,o.outOfSync?"Out of sync":null,!c&&o.upstream&&o.upstreamStatus!=="fresh"?"Upstream unverified":null,o.isOrphan?"Needs follow-up":null,d&&f?`Note: ${f}`:null,...j].filter(Boolean).join(`
76
+ `);return s.jsxs("div",{className:`rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all ${ac(o,t,r.isDark)}${aw(o)?" mesh-node-generating":""}`,style:{width:Pr(o)},title:h,children:[s.jsx(en,{type:"target",position:a==="TB"?es.Top:es.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:ic(o.health)},"aria-hidden":!0})]})]}),p?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] ${oc(p.tone,r.isDark)}`,title:p.label,children:s.jsx("span",{className:"truncate",children:p.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,k&&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:j.join(`
77
+ `),children:s.jsx("span",{className:"truncate",children:k})}),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(v=>{const I=dr(v);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/85"}`,title:[`Session ID: ${v.sessionId}`,v.providerType?`Provider: ${v.providerType}`:null,`Status: ${Ht(v)}`,`Role: ${I}`].filter(Boolean).join(`
78
+ `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate text-[10px] ${r.textMuted}`,children:v.providerType||"provider unknown"}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${Xa(v,r.isDark)}`,children:Ht(v)})]}),s.jsxs("div",{className:`mt-0.5 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",children:Ja(v.sessionId)}),s.jsx("span",{children:I})]})]},v.sessionId)})}),s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"flex min-w-0 flex-wrap gap-1.5 text-[10px]",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${At("health",r.isDark)}`,children:nw(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(lw(o),r.isDark)}`,children:cc(o.locality)}),u&&c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${At("meta",r.isDark)}`,children:u}),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:tw,children:Pn(o)}),g.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[9px] font-semibold uppercase tracking-[0.16em] ${r.textMuted}`,children:"Attached Chats"}),s.jsx("div",{className:"flex max-h-56 flex-col gap-1.5 overflow-y-auto pr-1",children:g.map(v=>{const I=v.startedAt||v.createdAt||null,w=dr(v);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-white/8 bg-white/[0.035]":"border-slate-200 bg-white/80"}`,title:[`Session ID: ${v.sessionId}`,v.providerType?`Provider: ${v.providerType}`:null,`Status: ${Ht(v)}`,`Role: ${w}`,I?`Started: ${I}`:"Started: not reported",v.statusNote?`Note: ${v.statusNote}`:null].filter(Boolean).join(`
79
+ `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono text-[10px] select-text ${r.textPrimary}`,children:Ja(v.sessionId)}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${Xa(v,r.isDark)}`,children:Ht(v)})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"truncate",children:v.providerType||"provider unknown"}),s.jsx("span",{children:w}),s.jsx("span",{children:lc(I)})]}),v.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${r.textMuted}`,children:v.statusNote})]},v.sessionId)})})]}),d&&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:sw,children:f})]}),s.jsx(en,{type:"source",position:a==="TB"?es.Bottom:es.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const dw={meshNode:cw},uw=8;function mw(e){if(e.length<2)return null;if(e.length===2){const[m,u]=e;return{d:`M ${m.x},${m.y} L ${u.x},${u.y}`,labelX:(m.x+u.x)/2,labelY:(m.y+u.y)/2}}const t=uw,r=[`M ${e[0].x},${e[0].y}`];for(let m=1;m<e.length-1;m+=1){const u=e[m-1],p=e[m],f=e[m+1],y=Math.sign(p.x-u.x),g=Math.sign(p.y-u.y),x=Math.sign(f.x-p.x),k=Math.sign(f.y-p.y),j=Math.hypot(p.x-u.x,p.y-u.y),h=Math.hypot(f.x-p.x,f.y-p.y),v=Math.min(t,j/2,h/2);if(v<1||y===x&&g===k){r.push(`L ${p.x},${p.y}`);continue}const I=p.x-y*v,w=p.y-g*v,b=p.x+x*v,C=p.y+k*v;r.push(`L ${I},${w}`),r.push(`Q ${p.x},${p.y} ${b},${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,d=e[0].y;for(let m=1;m<e.length;m+=1)if(o[m]>=i){const u=o[m]-o[m-1],p=u===0?0:(i-o[m-1])/u;c=e[m-1].x+(e[m].x-e[m-1].x)*p,d=e[m-1].y+(e[m].y-e[m-1].y)*p;break}return{d:r.join(" "),labelX:c,labelY:d}}function pw(e){const t=e.data.routePoints;if(t&&t.length>=2){const o=mw(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=Sp(r):n.type==="worktreeLink"||n.type==="submoduleLink"||n.type==="cloneLink"?a=jp(r):a=kp(r),[a[0],a[1],a[2]]}function hw(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 fw(e){const t=l.useContext(Ni),r=e.data.graphEdge,[n,a,o]=pw(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(gp,{id:e.id,path:n,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(yp,{children:s.jsx("div",{className:hw(r,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${a}px, ${o}px)`,pointerEvents:"none",maxWidth:Ev.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const xw={meshEdge:fw};async function bw(e,t=Ys("dark"),r=!1,n="LR"){const a=await Xv(e,r,n),o=new Set(a.nodes.map(u=>u.id)),i=a.nodes.map(u=>({id:u.id,type:u.type,position:u.position,data:{graphNode:u.graphNode,compact:r},selected:u.selected,draggable:u.draggable,selectable:u.selectable})),c=e.edges.filter(u=>o.has(u.source)&&o.has(u.target)),d=vw(c),m=c.map(u=>{var p;return{id:u.id,source:u.source,target:u.target,label:d.has(u.id)?u.label:void 0,type:"meshEdge",data:{graphEdge:u,routePoints:(p=a.edgeRoutes.get(u.id))==null?void 0:p.points},animated:u.type==="orphanLink",markerEnd:u.direction==="directed"?{type:bp.ArrowClosed,width:u.type==="submoduleLink"?16:18,height:u.type==="submoduleLink"?16:18,color:uc(u)}:void 0,style:{stroke:uc(u),strokeWidth:u.type==="orphanLink"?2.25:u.type==="submoduleLink"?1.7:u.type==="worktreeLink"?1.8:u.type==="cloneLink"?1.6:2,strokeDasharray:u.type==="orphanLink"?"5 4":u.type==="submoduleLink"?"4 3":u.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 gw=3,yw=2;function dc(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 vw(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<gw){for(const o of n)t.add(o.id);continue}const a=[...n].sort((o,i)=>{const c=dc(i)-dc(o);return c!==0?c:o.id.localeCompare(i.id)});for(const o of a.slice(0,yw))t.add(o.id)}return t}function uc(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 ww(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 jw(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 kw({data:e,viewportKey:t}){const r=vp(),n=wp(),a=l.useRef(null),o=l.useMemo(()=>nm(e),[e]),i=l.useMemo(()=>_v(e),[e]);return l.useEffect(()=>{if(!r||e.nodes.length===0||a.current===t)return;let c=!1;const d=requestAnimationFrame(()=>{if(c)return;const m=i.length>0&&i.length<e.nodes.length;n.fitView({nodes:m?i.map(u=>({id:u})):void 0,padding:m?.24:.2,maxZoom:m?.98:.9,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(d)}},[e.nodes.length,i,o,r,n,t]),null}function Sw(e){return e>=16?"min-h-[720px]":e>=10?"min-h-[580px]":"min-h-[460px]"}const Nw=12;function Cw({data:e,selectedNodeId:t=null,onNodeClick:r,onNodeHoverChange:n,onEdgeHoverChange:a}){const{theme:o}=qs(),i=l.useMemo(()=>Ys(o),[o]),c=l.useMemo(()=>Qv(e),[e]),d=l.useMemo(()=>Zv(e),[e]),m=e.nodes.length>=ew,[u,p]=l.useState("LR"),f=l.useMemo(()=>u==="auto"?Fv(e):u,[u,c,e]),y=e.nodes.length>=Nw,[g,x]=l.useState({nodes:[],edges:[]}),k=l.useRef(null),[j,h]=l.useState({width:0,height:0}),v=l.useMemo(()=>`${Lv(e,j.width,j.height)}::${f}`,[c,e,j.height,j.width,f]);l.useEffect(()=>{let C=!1;return bw(e,i,m,f).then(N=>{C||x(N)}),()=>{C=!0}},[e,d,i,m,f]);const I=l.useMemo(()=>g.nodes.map(C=>({...C,selected:C.id===t})),[g.nodes,t]);l.useEffect(()=>{const C=k.current;if(!C)return;const N=()=>{const T=Math.max(0,Math.round(C.clientWidth)),_=Math.max(0,Math.round(C.clientHeight));h(L=>L.width===T&&L.height===_?L:{width:T,height:_})};N();const S=typeof ResizeObserver=="function"?new ResizeObserver(()=>N()):null;return S==null||S.observe(C),window.addEventListener("resize",N),()=>{S==null||S.disconnect(),window.removeEventListener("resize",N)}},[]);const w=Sw(e.nodes.length),b=C=>C?i.isDark?"rounded-md border border-cyan-400/40 bg-cyan-500/15 px-2 py-0.5 text-cyan-100":"rounded-md border border-sky-400 bg-sky-100 px-2 py-0.5 text-sky-800":i.isDark?"rounded-md border border-white/10 bg-white/[0.03] px-2 py-0.5 text-slate-400 hover:text-slate-200":"rounded-md border border-slate-300 bg-white/80 px-2 py-0.5 text-slate-500 hover:text-slate-800";return s.jsx(Ni.Provider,{value:i,children:s.jsx(lm.Provider,{value:m,children:s.jsx(cm.Provider,{value:f,children:s.jsxs("div",{ref:k,className:i.graphShellClass,children:[s.jsxs("div",{className:`shrink-0 flex flex-wrap items-center justify-between gap-2 px-3 pt-3 pb-2 text-[11px] ${i.textSecondary}`,children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs("span",{className:i.graphStatChipClass,children:[e.stats.totalNodes," node",e.stats.totalNodes===1?"":"s"]}),e.stats.totalActiveSessions>0&&s.jsxs("span",{className:i.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:i.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"]}),m&&s.jsx("span",{className:i.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:i.isDark?"flex items-center gap-0.5 rounded-md border border-white/10 bg-slate-950/40 p-0.5 text-[10px]":"flex items-center gap-0.5 rounded-md border border-slate-300 bg-white/70 p-0.5 text-[10px]",role:"group","aria-label":"Graph layout direction",children:[s.jsx("button",{type:"button",onClick:()=>p("auto"),className:b(u==="auto"),title:`Auto (currently ${f==="TB"?"top-bottom":"left-right"})`,children:"Auto"}),s.jsx("button",{type:"button",onClick:()=>p("LR"),className:b(u==="LR"),title:"Left to right",children:"LR"}),s.jsx("button",{type:"button",onClick:()=>p("TB"),className:b(u==="TB"),title:"Top to bottom",children:"TB"})]}),s.jsx("div",{className:i.graphHintChipClass,children:"drag or scroll to pan"})]})]}),s.jsx("div",{className:`w-full min-w-0 flex-1 min-h-0 ${w}`,children:s.jsxs(mp,{nodes:I,edges:g.edges,nodeTypes:dw,edgeTypes:xw,minZoom:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(C,N)=>r==null?void 0:r(N.data.graphNode),onNodeMouseEnter:(C,N)=>n==null?void 0:n(N.data.graphNode),onNodeMouseLeave:()=>n==null?void 0:n(null),onEdgeMouseEnter:(C,N)=>{var S;return a==null?void 0:a(((S=N.data)==null?void 0:S.graphEdge)??null)},onEdgeMouseLeave:()=>a==null?void 0:a(null),className:"h-full w-full",colorMode:i.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(kw,{data:e,viewportKey:v}),s.jsx(pp,{className:i.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),y&&s.jsx(hp,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:ww,nodeClassName:jw,nodeStrokeWidth:3,className:i.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(fp,{variant:xp.Dots,gap:18,size:1.2,color:i.graphBackgroundDotColor})]})})]})})})})}function nt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Se(...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 Ct(...e){for(const t of e)if(typeof t=="boolean")return t}function Qa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function Ci(e){switch(e){case"fresh":return 30;case"no_upstream":return 4;case"unchecked":case void 0:return 0;case"stale":return-10;case"unavailable":return-15;default:return 0}}function Iw(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 Mw(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=nt(n),o=Se(a.path),i=Se(a.commit),c=Se(a.repoPath,a.repo_root)??Iw(t,o);return!o||!i||!c?null:{path:o,commit:i,repoPath:c,dirty:Ct(a.dirty)??!1,outOfSync:Ct(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:It(a.lastCheckedAt,a.last_checked_at)??Date.now(),...Se(a.error)?{error:Se(a.error)}:{}}}).filter(n=>n!==null);return r.length>0?r:void 0}function Aw(e){return Ct(e.isGitRepo)!==void 0||!!Se(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 Rn(e,t,r){const n=Ct(e.isGitRepo);if(!Object.keys(e).length||!Aw(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(v=>typeof v=="string"):[],i=It(e.conflicts)??o.length,c=Ct(e.hasConflicts)??i>0,d=Se(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,m=Mw(e.submodules,d),u=Se(e.upstreamStatus,e.upstream_status),p=It(e.upstreamFetchedAt,e.upstream_fetched_at),f=Se(e.upstreamFetchError,e.upstream_fetch_error),y=Se(e.error),g=It(e.staged)??0,x=It(e.modified)??0,k=It(e.untracked)??0,j=It(e.deleted)??0,h=It(e.renamed)??0;return{workspace:Se(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:a,branch:Se(e.branch)??null,headCommit:Se(e.headCommit)??null,headMessage:Se(e.headMessage)??null,upstream:Se(e.upstream)??null,upstreamStatus:u??"unchecked",...p!==void 0?{upstreamFetchedAt:p}:{},...f?{upstreamFetchError:f}:{},ahead:It(e.ahead)??0,behind:It(e.behind)??0,staged:g,modified:x,untracked:k,deleted:j,renamed:h,dirty:Ct(e.dirty,e.isDirty,e.is_dirty)??(g+x+k+j+h>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 Tw(e){if(!e)return Number.NEGATIVE_INFINITY;let t=0;return e.isGitRepo===!0&&(t+=50),e.isGitRepo===!1&&(t-=10),e.branch&&(t+=20),e.headCommit&&(t+=20),e.upstream&&(t+=10),t+=Ci(e.upstreamStatus),typeof e.ahead=="number"&&(t+=2),typeof e.behind=="number"&&(t+=2),Array.isArray(e.submodules)&&e.submodules.length>0&&(t+=4+e.submodules.length),e.error&&(t-=20),t}function _w(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),d=nt(i.status),m=nt(c.status);let u=null;for(const p of[n,a,d,m]){const f=Rn(p,e,{lastCheckedAt:Date.now()});if(!f)continue;const y=Tw(f);(!u||y>u.score)&&(u={git:f,score:y})}return u==null?void 0:u.git}function Lw(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 Pw(e){return e?(e.staged??0)>0||(e.modified??0)>0||(e.untracked??0)>0||(e.deleted??0)>0||(e.renamed??0)>0||e.hasConflicts===!0:!1}function ea(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=Lw(e);return t.outOfSync?"degraded":t.dirty||Pw(e)?"dirty":"online"}function Rw(e,t){const r=t?ea(t):void 0;return!e||e==="unknown"?r:e}function mm(e){const t=nt(e),r=Se(t.sessionId,t.session_id,t.id);return r?{sessionId:r,...Se(t.providerType,t.provider)?{providerType:Se(t.providerType,t.provider)}:{},...Se(t.state,t.status)?{state:Se(t.state,t.status)}:{},...Se(t.chatStatus,t.chat_status)?{chatStatus:Se(t.chatStatus,t.chat_status)}:{},...Se(t.lifecycle)?{lifecycle:Se(t.lifecycle)}:{},...Se(t.surfaceKind,t.surface_kind)?{surfaceKind:Se(t.surfaceKind,t.surface_kind)}:{},...Se(t.recoveryState,t.recovery_state)?{recoveryState:Se(t.recoveryState,t.recovery_state)}:{},...Se(t.workspace)?{workspace:Se(t.workspace)}:{},...Se(t.title)?{title:Se(t.title)}:{},...Se(t.role)?{role:Se(t.role)}:{},...Ct(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:Ct(t.isSelfCoordinator,t.is_self_coordinator)}:{},...Se(t.statusNote,t.status_note)?{statusNote:Se(t.statusNote,t.status_note)}:{},...Se(t.createdAt,t.created_at)?{createdAt:Se(t.createdAt,t.created_at)}:{},...Se(t.startedAt,t.started_at)?{startedAt:Se(t.startedAt,t.started_at)}:{},...Se(t.lastActivityAt,t.last_activity_at)?{lastActivityAt:Se(t.lastActivityAt,t.last_activity_at)}:{},...Ct(t.isCached,t.is_cached)!==void 0?{isCached:Ct(t.isCached,t.is_cached)}:{}}:null}function Dw(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(mm).filter(o=>o!==null);if(a.length>0)return a}const r=nt(e.activeSession??e.active_session),n=Se(r.id,r.sessionId,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id);if(n)return[{sessionId:n,...Se(r.providerType,r.provider)?{providerType:Se(r.providerType,r.provider)}:{},...Se(r.state,r.status)?{state:Se(r.state,r.status)}:{},...Se(r.chatStatus,r.chat_status)?{chatStatus:Se(r.chatStatus,r.chat_status)}:{},...Se(r.statusNote,r.status_note)?{statusNote:Se(r.statusNote,r.status_note)}:{},...Se(r.createdAt,r.created_at)?{createdAt:Se(r.createdAt,r.created_at)}:{},...Se(r.startedAt,r.started_at)?{startedAt:Se(r.startedAt,r.started_at)}:{}}]}function $w(e){const t=nt(e.connection);return Object.keys(t).length>0?t:void 0}function Ew(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 Ii(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 mc(e){var n,a,o,i,c,d;let t=0;const r=e.git;return Ii(e)&&(t+=80,(r==null?void 0:r.isGitRepo)===!0&&(t+=20),(r==null?void 0:r.isGitRepo)===!1&&(t+=5),r!=null&&r.branch&&(t+=20),r!=null&&r.upstream&&(t+=12),r!=null&&r.headCommit&&(t+=12),t+=Ci(r==null?void 0:r.upstreamStatus),typeof(r==null?void 0:r.lastCheckedAt)=="number"&&(t+=6),t+=(((n=r==null?void 0:r.submodules)==null?void 0:n.length)??0)*6),(a=e.branchConvergence)!=null&&a.status&&(t+=12),(((o=e.connection)==null?void 0:o.state)==="connected"||((i=e.connection)==null?void 0:i.state)==="self")&&(t+=8),((c=e.connection)==null?void 0:c.transport)==="direct"&&(t+=4),((d=e.connection)==null?void 0:d.source)==="mesh_peer_status"&&(t+=4),e.health==="online"&&(t+=4),e.health==="dirty"&&(t+=3),e.health==="degraded"&&(t+=2),e.launchReady&&(t+=2),e.gitProbePending&&(t-=40),e.error&&(t-=10),t}function Bw(e,t){var g,x,k,j;const r=mc(e),a=mc(t)>r?t:e,o=a===t?e:t,i=a.git??o.git,c=(((g=a.providers)==null?void 0:g.length)??0)>0?a.providers:o.providers,d=(((x=a.activeSessions)==null?void 0:x.length)??0)>0?a.activeSessions:o.activeSessions,m=(((k=a.activeSessionDetails)==null?void 0:k.length)??0)>0?a.activeSessionDetails:o.activeSessionDetails,u=(((j=a.providerPriority)==null?void 0:j.length)??0)>0?a.providerPriority:o.providerPriority,p=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")?ea(i):a.health,providers:c??[],activeSessions:d??[],...m&&m.length>0?{activeSessionDetails:m}:{},...u&&u.length>0?{providerPriority:u}:{},...p?{connection:p}:{},...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 pm(e){const t=nt(e),r=Se(t.nodeId,t.id);if(!r)return null;const n=nt(t.cachedStatus),a=_w(t),o=a?void 0:Rn(nt(t.git),t)??Rn(t,t),i=a??o,c=i?void 0:Rn(nt(n.git),t),d=i??c,m=Se(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),u=Se(t.health),p=a?ea(d):Rw(u,i)||(d?ea(d):void 0)||Se(n.health)||m||Se(t.status)||"unknown",y=(a?void 0:Se(t.error))??(i?void 0:Se(n.error)),g=Dw(t),x=Qa(t.activeSessions),k=(g==null?void 0:g.map(N=>N.sessionId))??[],j=Qa(t.providerPriority),h=Ct(t.gitProbePending,t.git_probe_pending),v=i?void 0:h,I=$w(t),w=nt(t.branchConvergence??t.branch_convergence),b=I==null?void 0:I.state,C=a&&(!(I!=null&&I.reported)||b==="unknown")?Ew(I):I;return{nodeId:r,machineLabel:Se(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:Se(t.workspace,d==null?void 0:d.workspace)||"",...Se(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:Se(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},...Se(t.daemonId,t.daemon_id)?{daemonId:Se(t.daemonId,t.daemon_id)}:{},...Se(t.machineId,t.machine_id)?{machineId:Se(t.machineId,t.machine_id)}:{},...m?{machineStatus:m}:{},...Ct(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Ct(t.isLocalWorktree,t.is_local_worktree)}:{},...Se(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:Se(t.worktreeBranch,t.worktree_branch)}:{},...Se(t.clonedFromNodeId,t.cloned_from_node_id)?{clonedFromNodeId:Se(t.clonedFromNodeId,t.cloned_from_node_id)}:{},health:p,...d?{git:d}:{},...v!==void 0?{gitProbePending:v}:{},providers:Qa(t.providers),activeSessions:x.length>0?x:k,...g&&g.length>0?{activeSessionDetails:g}:{},...j.length>0?{providerPriority:j}:{},...Ct(t.launchReady)!==void 0?{launchReady:Ct(t.launchReady)}:a?{launchReady:!0}:{},...Se(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:Se(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},...Se(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:Se(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...C?{connection:C}:{},...Object.keys(w).length>0?{branchConvergence:w}:{},...y?{error:y}:{}}}function pc(e){const t=new Map;for(const r of e){const n=t.get(r.sessionId);t.set(r.sessionId,n?{...n,...r}:r)}return[...t.values()]}function hm(e,t){const r=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],n=r.map(mm).filter(a=>a!==null);return n.length===0?t:t.map(a=>{const o=n.filter(c=>{const d=nt(r.find(f=>{const y=nt(f);return Se(y.sessionId,y.session_id,y.id)===c.sessionId})),m=Se(d.nodeId,d.node_id),u=Se(d.daemonId,d.daemon_id),p=Se(d.workspace);return m&&m===a.nodeId?!0:u&&a.daemonId&&u===a.daemonId?!p||!a.workspace||p===a.workspace:!!(p&&a.workspace&&p===a.workspace)});if(o.length===0)return a;const i=pc([...a.activeSessionDetails??[],...o]);return{...a,activeSessionDetails:i,activeSessions:pc([...a.activeSessionDetails??[],...o,...(a.activeSessions??[]).map(c=>({sessionId:c}))]).map(c=>c.sessionId)}})}function Ow(e){const t=nt(e);return Array.isArray(t.sessions)||Array.isArray(t.active_session_details)||Se(t.daemon_id,t.machine_id,t.repo_root,t.worktree_branch,t.cloned_from_node_id)!==void 0||Ct(t.is_local_worktree)!==void 0}function fm(e){const t=new Map,r=[];for(const n of e){const a=Ow(n)?pm(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=Bw(o,a);t.set(a.nodeId,i);const c=r.findIndex(d=>d.nodeId===a.nodeId);c>=0&&(r[c]=i)}return r}function xm(e){const t=fm(e.nodes??[]);return{...e,nodes:hm(e,t)}}function Fw(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:Ii(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 Hw(e){const t=Se(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(d=>pm(d)).filter(d=>d!==null):null;if(!t||!n)return null;const a=hm(e,fm(n)),o=Se(e.meshName,e.mesh_name,e.name),i=Se(e.repoIdentity,e.repo_identity),c=Se(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 Ww(e){var o;let t=0;const r=nt(e.sourceOfTruth),n=nt(r.directPeerTruth);Se(r.currentStatus)==="live_git_and_session_probes"&&(t+=100),r.coordinatorOwnsLiveTruth===!0&&(t+=25),n.satisfied===!0&&(t+=15);for(const i of e.nodes){const c=i.git;if(!c){i.gitProbePending&&(t-=8);continue}t+=10,c.isGitRepo===!0&&(t+=5),c.isGitRepo===!1&&(t+=1),c.branch&&(t+=4),c.upstream&&(t+=3),c.headCommit&&(t+=3),t+=Ci(c.upstreamStatus),typeof c.ahead=="number"&&(t+=1),typeof c.behind=="number"&&(t+=1),typeof c.lastCheckedAt=="number"&&(t+=2),t+=(((o=c.submodules)==null?void 0:o.length)??0)*2}return t}function hc(e){let t=null;for(const r of e){const n=Hw(nt(r));if(!n)continue;const a=Ww(n);(!t||a>t.score)&&(t={status:n,score:a})}return(t==null?void 0:t.status)??null}function bm(e){const r=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,n=hc([r==null?void 0:r.status,r]);return n||hc([e==null?void 0:e.status,e])}const Kw=5*60*1e3;function gm(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function ym(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function Uw(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"||gm(e)||ym(e)?"remote":"unknown"}function zw(e){return Ii(e)}function vm(e){var t;return zw(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function Gw(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function Vw(e){return e.activeSessionDetails&&e.activeSessionDetails.length>0?e.activeSessionDetails:(e.activeSessions??[]).map(t=>({sessionId:t,workspace:e.workspace,isCached:!0}))}function wm(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function jm(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function Mi(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function qw(e){return Mi(e)?"degraded":jm(e)?"dirty":"online"}function Yw(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function fc(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 Za(e){return e.length===0?"unknown":e.reduce((t,r)=>fc(r)>fc(t)?r:t)}function Xw(e){var o,i,c,d,m;const t=new Map,r=new Map;for(const u of e){const p=(i=(o=u.git)==null?void 0:o.branch)==null?void 0:i.trim();p&&(r.set(p,(r.get(p)??0)+1),(c=u.git)!=null&&c.upstream&&t.set(p,(t.get(p)??0)+1))}const n=[...t.entries()].sort((u,p)=>{if(p[1]!==u[1])return p[1]-u[1];const f=["main","master","develop","dev"],y=f.indexOf(u[0]),g=f.indexOf(p[0]);return y!==-1||g!==-1?y===-1?1:g===-1?-1:y-g:u[0].localeCompare(p[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((m=[...r.entries()].sort((u,p)=>p[1]-u[1])[0])==null?void 0:m[0])??null}function Jw(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 xc(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 Qw(e){return e.reduce((t,r)=>xc(r.status)>xc(t.status)?r:t)}function Zw(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 ej(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 tj(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 sj(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 rj(e,t){if(vm(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=wm(a)||jm(a),i=!!(a!=null&&a.hasConflicts)||Mi(a),c=(a==null?void 0:a.ahead)??0,d=(a==null?void 0:a.behind)??0,m=(a==null?void 0:a.branch)??null,u=(a==null?void 0:a.upstream)??null,p=(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??u,upstreamStatus:r.upstreamStatus??p,ahead:r.ahead??c,behind:r.behind??d,dirty:r.dirty??o,hasConflicts:r.hasConflicts??i}}function nj(e,t){const r=rj(e,t);return r?{...r,defaultBranch:r.defaultBranch??t}:null}function aj(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function oj(e){var d,m,u;const{nodeStatus:t,expectedSubmodulePaths:r,refreshedAtMs:n}=e,a=[],o=t.machineLabel||t.nodeId,i=t.git;if(!i){if(vm(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const p=t.health==="online"||t.machineStatus==="online"||((d=t.connection)==null?void 0:d.state)==="connected"||((m=t.connection)==null?void 0:m.state)==="self";return a.push(p?`${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(p=>p.path));if(r.size>0){const p=[...r].filter(f=>!c.has(f));p.length>0&&a.push(`${o} is missing submodule visibility for ${p.join(", ")} even though another peer reported it.`)}return((u=t.connection)==null?void 0:u.state)!=="self"&&n!==null&&typeof i.lastCheckedAt=="number"&&n-i.lastCheckedAt>Kw&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(p=>p.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(p=>p.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function ij(e){const t=xm(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??Xw(t.nodes),a=Gw(t.refreshedAt),o=new Set(t.nodes.flatMap(M=>{var A;return(((A=M.git)==null?void 0:A.submodules)??[]).map(H=>H.path)})),i=[],c=[],d=ej(t),m=new Map;for(const M of t.nodes){const A=M.git,H=(A==null?void 0:A.branch)??null,P=qw(A),D=wm(A)||P==="dirty",O=Jw(M,n),R=nj(M,n),B=oj({nodeStatus:M,expectedSubmodulePaths:o,refreshedAtMs:a}),E=typeof M.clonedFromNodeId=="string"?M.clonedFromNodeId:null,F=Vw(M),Q={id:M.nodeId,type:O.length>0?"orphanNode":"worktreeNode",label:M.machineLabel||M.nodeId.slice(0,8),workspace:M.workspace,branch:H,upstream:(A==null?void 0:A.upstream)??null,upstreamStatus:(A==null?void 0:A.upstreamStatus)??null,daemonId:gm(M),machineId:ym(M),machineLabel:M.machineLabel||null,locality:Uw(M),health:Za([M.health,P]),ahead:(A==null?void 0:A.ahead)??0,behind:(A==null?void 0:A.behind)??0,dirty:D,dirtyFiles:Yw(A),hasConflicts:(A==null?void 0:A.hasConflicts)??!1,activeSessionCount:F.length,activeSessions:F.map(Z=>Z.sessionId),sessionDetails:F,providers:M.providers??[],isOrphan:O.length>0,orphanReasons:O,error:M.error,nextStepHint:B.snapshotWarnings[0]??O[0]??(R==null?void 0:R.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:E,worktreeBranch:M.worktreeBranch??null,submodulePath:null,submoduleCommit:(A==null?void 0:A.headCommit)??null,outOfSync:Mi(A),snapshotCompleteness:B.snapshotCompleteness,snapshotWarnings:B.snapshotWarnings,branchConvergence:R,source:M};if(i.push(Q),H){const Z=m.get(H)??[];Z.push(Q.id),m.set(H,Z)}for(const Z of(A==null?void 0:A.submodules)??[]){const Y=`${Q.id}::submodule::${Z.path}`,te=Z.path.split("/").filter(Boolean).pop()||Z.path;i.push({id:Y,type:"submoduleNode",label:te,workspace:Z.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:Q.daemonId,machineId:Q.machineId,machineLabel:Q.machineLabel,locality:Q.locality,health:aj(Z),ahead:0,behind:0,dirty:Z.dirty,dirtyFiles:Z.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],error:Z.error,nextStepHint:Z.error||(Z.outOfSync?`${Z.path} is out of sync with the parent checkout`:Z.dirty?`${Z.path} has local changes`:`${Z.path} is in sync with the parent checkout`),parentNodeId:Q.id,submodulePath:Z.path,submoduleCommit:Z.commit,outOfSync:Z.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:Q.id,parentWorkspace:M.workspace,submodule:Z}}),c.push({id:`${Q.id}--${Y}`,source:Q.id,target:Y,type:"submoduleLink",label:Z.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const u=n?`__branch_${n}`:null;if(u&&n){const A=(m.get(n)??[]).map(E=>i.find(F=>F.id===E)).filter(Boolean),H=A.map(E=>E.branchConvergence).filter(Boolean),P=Zw(t),D=A.length>0&&A.every(E=>tj(E,n)),O=(P==null?void 0:P.length)===0&&D?sj(n,A):H.length>0?Qw(H):null,R=(P==null?void 0:P.length)===0&&D?0:H.filter(E=>E.needsConvergence).length,B={id:u,type:"defaultBranchNode",label:n,workspace:t.repoIdentity,branch:n,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:"default branch",locality:"unknown",health:Za(A.map(E=>E.health)),ahead:0,behind:0,dirty:A.some(E=>E.dirty),dirtyFiles:A.reduce((E,F)=>E+F.dirtyFiles,0),hasConflicts:A.some(E=>E.hasConflicts),activeSessionCount:A.reduce((E,F)=>E+F.activeSessionCount,0),activeSessions:A.flatMap(E=>E.activeSessions),sessionDetails:A.flatMap(E=>E.sessionDetails),providers:[...new Set(A.flatMap(E=>E.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:R>0?`${R} workspace(s) on ${n} still need follow-up`:A.length>0?`${A.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:O,source:{nodeId:u,machineLabel:n,workspace:t.repoIdentity,health:Za(A.map(E=>E.health)),providers:[],activeSessions:[],activeSessionDetails:[]}};i.push(B);for(const E of i)if(!(E.id===u||E.type==="submoduleNode")){if(E.branch===n){c.push({id:`${u}--${E.id}`,source:u,target:E.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(E.branch){c.push({id:`${u}--${E.id}`,source:u,target:E.id,type:E.isOrphan?"orphanLink":"parentBranch",label:E.branch,direction:"undirected"});continue}E.isOrphan&&c.push({id:`${u}--${E.id}`,source:u,target:E.id,type:"orphanLink",label:"detached",direction:"undirected"})}}const p=new Set(i.map(M=>M.id)),f=new Set;for(const M of i){if(!M.clonedFromNodeId||M.type==="submoduleNode"||!p.has(M.clonedFromNodeId))continue;const A=`clone_${M.clonedFromNodeId}--${M.id}`;if(f.has(A))continue;f.add(A);const H=M.worktreeBranch??M.branch??void 0;c.push({id:A,source:M.clonedFromNodeId,target:M.id,type:"cloneLink",label:H?`cloned · ${H}`:"cloned",direction:"directed"})}const y=i.filter(M=>M.type!=="defaultBranchNode"),g=y.filter(M=>M.isOrphan).length,x=y.filter(M=>M.hasConflicts).length,k=y.filter(M=>M.health==="offline").length,j=y.filter(M=>M.type==="submoduleNode"&&M.outOfSync).length,h=y.filter(M=>{var A;return M.type!=="submoduleNode"&&((A=M.branchConvergence)==null?void 0:A.needsConvergence)}).length,v=y.filter(M=>{var A;return((A=M.branchConvergence)==null?void 0:A.status)==="blocked_review"}).length,I=y.filter(M=>{var A;return((A=M.branchConvergence)==null?void 0:A.status)==="pushed_feature_branch_needs_merge"}).length,w=y.filter(M=>{var A;return((A=M.branchConvergence)==null?void 0:A.status)==="cleanup_candidate"}).length,b=y.filter(M=>{var A;return((A=M.branchConvergence)==null?void 0:A.status)==="not_mergeable"}).length,C=y.filter(M=>M.snapshotWarnings.length>0).length,N=y.filter(M=>M.snapshotCompleteness==="pending_git").length,S=y.filter(M=>M.snapshotCompleteness==="missing_git").length,T=y.filter(M=>M.snapshotCompleteness==="missing_submodule_report").length,_=y.filter(M=>M.snapshotCompleteness==="stale").length,L=[N>0?`${N} node(s) are still waiting for a live peer git snapshot`:null,S>0?`${S} node(s) have no visible peer git snapshot`:null,T>0?`${T} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,_>0?`${_} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return h>0&&d.push(`${h} workspace(s) still need follow-up before the mesh is converged`),g>0&&d.push(`${g} workspace(s) need attention before safe coordination`),v>0&&d.push(`${v} workspace(s) are blocked on branch convergence or upstream sync`),I>0&&d.push(`${I} clean feature branch workspace(s) still need merge follow-up`),w>0&&d.push(`${w} worktree workspace(s) are ready for refine / cleanup`),b>0&&d.push(`${b} workspace(s) have local changes or conflicts blocking convergence`),x>0&&d.push(`${x} workspace(s) report merge conflicts`),k>0&&d.push(`${k} node(s) are currently offline`),j>0&&d.push(`${j} submodule(s) are out of sync with their parent checkout`),d.push(...L),n||d.push("Could not infer a default branch from live mesh status"),{meshId:t.meshId,meshName:t.meshName,repoIdentity:t.repoIdentity,refreshedAt:t.refreshedAt,nodes:i,edges:c,stats:{totalNodes:y.length,onlineNodes:y.filter(M=>M.health==="online").length,dirtyNodes:y.filter(M=>M.dirty).length,orphanNodes:g,errorNodes:y.filter(M=>!!M.error||M.outOfSync).length,offlineNodes:k,followUpNodes:h,blockedReviewNodes:v,mergeReadyNodes:I,cleanupCandidateNodes:w,notMergeableNodes:b,incompleteSnapshotNodes:C,missingGitSnapshotNodes:S,missingSubmoduleSnapshotNodes:T,staleGitSnapshotNodes:_,totalActiveSessions:y.reduce((M,A)=>M+A.activeSessionCount,0)},warnings:d,snapshotWarnings:L}}const lj={recentFailures:0,taskCompleted:0,taskFailed:0,sessionLaunched:0},Ai=l.createContext(Ys("dark"));function Fe({label:e,tone:t="default"}){const r=l.useContext(Ai);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 rt({label:e,value:t}){const r=l.useContext(Ai);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 bc(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 eo(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 yn(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 cj(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function dj(e){return e.startedAt||e.createdAt||null}function uj(e){const t=dj(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 mj(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function pj(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 hj(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 fj(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 xj(e){return e.assignedNodeId||e.targetNodeId||null}function gc(e){return e?e.slice(0,7):null}function bj(e,t){var o,i,c;const r=gc((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?[gc(a.commit),a.message].filter(Boolean).join(" · "):null}function gj(e,t){const r=bj(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function yj(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 vj(e){var r,n,a,o,i,c;const t=((r=e.selectedSessionEntry)==null?void 0:r.session.workspace)||((n=e.selectedSessionEntry)==null?void 0:n.workspace)||((o=(a=e.selectedNodeStatus)==null?void 0:a.git)==null?void 0:o.workspace)||((i=e.selectedNodeStatus)==null?void 0:i.workspace)||null;if(t&&e.selectedSessionEntry){const d=((c=e.selectedNodeStatus)==null?void 0:c.daemonId)||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}if(t&&e.selectedNodeStatus){const d=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}return null}function wj(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":hj(e.connection)}function yc(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 vc(e){switch(e.type){case"parentBranch":return"default branch link";case"worktreeLink":return"worktree relationship";case"sessionLink":return"session relationship";case"orphanLink":return"orphan relationship";case"submoduleLink":return"submodule relationship";case"cloneLink":return"clone relationship";default:return e.type}}function jj(e){return e.direction==="directed"?"directed":"undirected"}function wc(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function kj(e){var t,r,n,a;return[e.meshId,e.refreshedAt,e.nodes.length,((r=(t=e.queue)==null?void 0:t.summary)==null?void 0:r.active)??"",((a=(n=e.ledger)==null?void 0:n.summary)==null?void 0:a.recentFailures)??"",...e.nodes.map(o=>{var i,c,d,m,u,p,f,y,g,x,k,j,h,v,I,w,b,C,N,S,T,_;return[o.nodeId,o.daemonId??"",o.machineId??"",o.machineLabel,o.machineStatus??"",((i=o.connection)==null?void 0:i.state)??"",((c=o.connection)==null?void 0:c.transport)??"",((d=o.connection)==null?void 0:d.source)??"",o.health,o.gitProbePending?1:0,((m=o.git)==null?void 0:m.branch)??"",((u=o.git)==null?void 0:u.upstream)??"",((p=o.git)==null?void 0:p.upstreamStatus)??"",((f=o.git)==null?void 0:f.ahead)??"",((y=o.git)==null?void 0:y.behind)??"",((g=o.git)==null?void 0:g.headCommit)??"",((x=o.git)==null?void 0:x.staged)??"",((k=o.git)==null?void 0:k.modified)??"",((j=o.git)==null?void 0:j.untracked)??"",((h=o.git)==null?void 0:h.deleted)??"",((v=o.git)==null?void 0:v.renamed)??"",(I=o.git)!=null&&I.hasConflicts?1:0,((w=o.git)==null?void 0:w.lastCheckedAt)??"",((b=o.activeSessions)==null?void 0:b.join(","))??"",((C=o.activeSessionDetails)==null?void 0:C.length)??"",((N=o.activeSessionDetails)==null?void 0:N.map(L=>[L.sessionId,L.providerType??"",L.state??"",L.chatStatus??"",L.lifecycle??"",L.role??"",L.isSelfCoordinator?1:0,L.statusNote??"",L.startedAt??"",L.createdAt??""].join("/")).join(","))??"",((S=o.providers)==null?void 0:S.join(","))??"",((T=o.providerPriority)==null?void 0:T.join(","))??"",o.error??"",(((_=o.git)==null?void 0:_.submodules)??[]).map(L=>[L.path,L.commit,L.dirty?1:0,L.outOfSync?1:0,L.error??""].join("/")).join(",")].join("|")})].join("::")}function km({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null}){var de,Ie,ee,ve,ce;const{theme:a}=qs(),o=l.useMemo(()=>Ys(a),[a]),i=l.useMemo(()=>xm(e),[e]),c=l.useMemo(()=>kj(i),[i]),d=l.useMemo(()=>ij(i),[c]),[m,u]=l.useState(null),[p,f]=l.useState(null),[y,g]=l.useState(null),[x,k]=l.useState(null),[j,h]=l.useState({}),[v,I]=l.useState(null),[w,b]=l.useState(null),C=l.useMemo(()=>new Map(i.nodes.map(W=>[W.nodeId,W])),[i.nodes]),N=l.useMemo(()=>new Map(d.nodes.map(W=>[W.id,W])),[d.nodes]),S=((de=i.queue)==null?void 0:de.summary)??null,T=((Ie=i.ledger)==null?void 0:Ie.summary)??lj,_=l.useMemo(()=>fj(i),[i]),L=l.useMemo(()=>{const W=new Map;for(const ne of _){const ue=yn(ne.session);W.set(ue,(W.get(ue)??0)+1)}return[...W.entries()].sort((ne,ue)=>ue[1]-ne[1])},[_]);l.useEffect(()=>{m&&(N.has(m)||(u(null),k(W=>!W||"nodeId"in W&&W.nodeId===m?null:W)))},[N,m]);const M=m?C.get(m)??null:null,A=wc(d,m),H=wc(d,p),P=y?d.edges.find(W=>W.id===y)??null:null,D=P?d.nodes.find(W=>W.id===P.source)??null:null,O=P?d.nodes.find(W=>W.id===P.target)??null:null;l.useEffect(()=>{var W,ne,ue;if(m)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:i.meshId,selectedNodeId:m,canonicalNode:Fw(M),graphNode:A?{id:A.id,branch:A.branch,upstream:A.upstream,headCommit:A.submoduleCommit,submoduleCount:((ne=(W=M==null?void 0:M.git)==null?void 0:W.submodules)==null?void 0:ne.length)??0,snapshotCompleteness:A.snapshotCompleteness,snapshotWarnings:A.snapshotWarnings,branchConvergence:((ue=A.branchConvergence)==null?void 0:ue.status)??null}:null})}catch{}},[i.meshId,A,m,M]);const R=(x==null?void 0:x.kind)==="session"?_.find(W=>W.nodeId===x.nodeId&&W.session.sessionId===x.sessionId)??null:null,B=l.useMemo(()=>_.filter(W=>W.nodeId===m),[m,_]),E=vj({coordinatorDaemonId:r,selectedNodeStatus:M,selectedSessionEntry:R}),F=(E==null?void 0:E.workspace)??null,Q=F?j[F]??null:null,Z=gj(M,(Q==null?void 0:Q.entries)??[]),Y=(A==null?void 0:A.daemonId)??(M==null?void 0:M.daemonId)??r??null,te=!!(A&&n&&Y&&A.type!=="submoduleNode"&&A.behind>0&&A.ahead===0&&A.dirtyFiles===0&&!A.dirty&&!A.hasConflicts&&A.upstreamStatus==="fresh"),fe=l.useCallback(()=>{u(null),k(null),I(null)},[]);l.useEffect(()=>{I(null)},[m]);const Ne=l.useCallback(async()=>{if(!(!A||!Y||!n||!te)){b(A.id),I(null);try{const W=await n(Y,"fast_forward_mesh_node",{meshId:i.meshId,nodeId:A.id,dryRun:!0,execute:!1});if(I({phase:"dry_run",code:typeof(W==null?void 0:W.code)=="string"?W.code:void 0,error:typeof(W==null?void 0:W.operationError)=="string"?W.operationError:null,executed:(W==null?void 0:W.executed)===!0}),!(W!=null&&W.success)||W.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${A.label}?`))return;const ue=await n(Y,"fast_forward_mesh_node",{meshId:i.meshId,nodeId:A.id,dryRun:!1,execute:!0});I({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(W){I({phase:"dry_run",error:W instanceof Error?W.message:"fast-forward failed"})}finally{b(null)}}},[te,i.meshId,A,Y,n]);l.useEffect(()=>{if(!A)return;const W=ne=>{ne.key==="Escape"&&fe()};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[fe,A]),l.useEffect(()=>{if(!E||!n)return;const{daemonId:W,workspace:ne}=E,ue=j[ne];if(ue!=null&&ue.loading||ue&&(ue.entries.length>0||ue.error))return;let me=!1;return h(J=>{var q;return{...J,[ne]:{loading:!0,error:null,entries:((q=J[ne])==null?void 0:q.entries)??[]}}}),n(W,"git_log",{workspace:ne,limit:5}).then(J=>{me||h(q=>({...q,[ne]:{loading:!1,error:null,entries:yj(J)}}))}).catch(J=>{me||h(q=>({...q,[ne]:{loading:!1,error:J instanceof Error?J.message:"git_log failed",entries:[]}}))}),()=>{me=!0}},[j,E,n]);const X=[...d.warnings??[],...i.nodes.filter(W=>W.machineStatus&&W.machineStatus!=="online").map(W=>`${W.machineLabel}: ${W.machineStatus}`)],we=d.stats.incompleteSnapshotNodes>0,ge=d.stats.followUpNodes>0?`${d.stats.followUpNodes} need follow-up`:we?"mesh visibility incomplete":"mesh converged",be=d.stats.followUpNodes>0?"danger":we?"warn":"good";return s.jsx(Ai.Provider,{value:o,children:s.jsx("div",{className:"flex min-h-0 flex-1 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 flex min-h-0 flex-1 flex-col 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(Fe,{label:ge,tone:be}),d.stats.blockedReviewNodes>0&&s.jsx(Fe,{label:`${d.stats.blockedReviewNodes} blocked review`,tone:"danger"}),d.stats.notMergeableNodes>0&&s.jsx(Fe,{label:`${d.stats.notMergeableNodes} not mergeable`,tone:"danger"}),d.stats.mergeReadyNodes>0&&s.jsx(Fe,{label:`${d.stats.mergeReadyNodes} need merge`,tone:"warn"}),d.stats.cleanupCandidateNodes>0&&s.jsx(Fe,{label:`${d.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),d.stats.offlineNodes>0&&s.jsx(Fe,{label:`${d.stats.offlineNodes} offline`,tone:"danger"}),d.stats.incompleteSnapshotNodes>0&&s.jsx(Fe,{label:`${d.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),d.stats.missingGitSnapshotNodes>0&&s.jsx(Fe,{label:`${d.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),d.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Fe,{label:`${d.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),d.stats.staleGitSnapshotNodes>0&&s.jsx(Fe,{label:`${d.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((S==null?void 0:S.active)??0)>0&&s.jsx(Fe,{label:`${(S==null?void 0:S.active)??0} active queue`,tone:"info"}),s.jsx(Fe,{label:`${d.stats.totalNodes} nodes`,tone:"default"}),d.stats.totalActiveSessions>0&&s.jsx(Fe,{label:`${d.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(Fe,{label:`${d.stats.dirtyNodes} dirty`,tone:d.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Fe,{label:`${d.stats.orphanNodes} orphan`,tone:d.stats.orphanNodes>0?"warn":"good"}),s.jsx(Fe,{label:`${T.recentFailures} recent failures`,tone:T.recentFailures>0?"danger":"good"}),L.length===0?s.jsx(Fe,{label:"no session metadata"}):L.slice(0,2).map(([W,ne])=>s.jsx(Fe,{label:`${ne} ${W}`,tone:eo(W)},W))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Fe,{label:"Anchor = default branch",tone:"info"}),s.jsx(Fe,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Fe,{label:"Submodule link = child checkout",tone:"warn"})]}),X.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:X.map(W=>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:W},W))}),s.jsx("div",{className:`text-xs ${o.textMuted}`,children:"Hover nodes or edges for a quick preview. Click a node when you want pinned drill-down details."})]})]})]}),d.nodes.length>0?s.jsx(Cw,{data:d,selectedNodeId:m,onNodeHoverChange:W=>{f((W==null?void 0:W.id)??null),W&&g(null)},onEdgeHoverChange:W=>{g((W==null?void 0:W.id)??null),W&&f(null)},onNodeClick:W=>{if((x==null?void 0:x.kind)==="node"&&m===W.id){u(null),k(null);return}u(W.id),k({kind:"node",nodeId:W.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}),!A&&H&&s.jsx("div",{className:"pointer-events-none absolute inset-x-3 bottom-3 z-20 flex justify-center p-2 sm:inset-x-auto sm:right-5 sm:top-24 sm:bottom-auto sm:justify-end",children:s.jsxs("section",{"aria-label":"Hovered node preview",className:o.isDark?"w-full max-w-[min(24rem,calc(100vw-2.5rem))] rounded-2xl border border-white/12 bg-slate-950/94 p-4 shadow-2xl shadow-black/35 backdrop-blur-xl":"w-full max-w-[min(24rem,calc(100vw-2.5rem))] rounded-2xl border border-slate-200 bg-white/96 p-4 shadow-2xl shadow-slate-900/12 backdrop-blur-xl",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:H.label}),s.jsx("div",{className:`mt-1 font-mono text-[11px] ${o.textMuted}`,children:H.id.slice(0,16)})]}),s.jsx(Fe,{label:"hover preview",tone:"info"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[s.jsx(Fe,{label:H.health,tone:bc(H.health)}),H.branch&&s.jsx(Fe,{label:H.branch,tone:"default"}),H.ahead>0&&s.jsx(Fe,{label:`ahead ${H.ahead}`,tone:"warn"}),H.behind>0&&s.jsx(Fe,{label:`behind ${H.behind}`,tone:"warn"}),H.dirtyFiles>0&&s.jsx(Fe,{label:`${H.dirtyFiles} dirty`,tone:"warn"}),H.activeSessionCount>0&&s.jsx(Fe,{label:`${H.activeSessionCount} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[s.jsx(rt,{label:"Machine",value:H.machineLabel??"not reported"}),s.jsx(rt,{label:"Locality",value:H.locality}),s.jsx(rt,{label:"Workspace",value:H.workspace}),s.jsx(rt,{label:"Upstream",value:H.upstream??"none"}),s.jsx(rt,{label:"Dirty/ahead/behind",value:`${H.dirtyFiles} dirty · ↑${H.ahead}/↓${H.behind}`}),s.jsx(rt,{label:"Source",value:yc(H)})]})]})}),!A&&!H&&P&&s.jsx("div",{className:"pointer-events-none absolute inset-x-3 bottom-3 z-20 flex justify-center p-2 sm:inset-x-auto sm:right-5 sm:top-24 sm:bottom-auto sm:justify-end",children:s.jsxs("section",{"aria-label":"Hovered edge preview",className:o.isDark?"w-full max-w-[min(22rem,calc(100vw-2.5rem))] rounded-2xl border border-white/12 bg-slate-950/94 p-4 shadow-2xl shadow-black/35 backdrop-blur-xl":"w-full max-w-[min(22rem,calc(100vw-2.5rem))] rounded-2xl border border-slate-200 bg-white/96 p-4 shadow-2xl shadow-slate-900/12 backdrop-blur-xl",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:P.label||vc(P)}),s.jsx("div",{className:`mt-1 text-[11px] ${o.textMuted}`,children:P.id})]}),s.jsx(Fe,{label:"hover preview",tone:"info"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[s.jsx(Fe,{label:vc(P),tone:"default"}),s.jsx(Fe,{label:jj(P),tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs",children:[s.jsx(rt,{label:"From",value:(D==null?void 0:D.label)??P.source}),s.jsx(rt,{label:"To",value:(O==null?void 0:O.label)??P.target}),s.jsx(rt,{label:"Label",value:P.label??"none"})]})]})}),A&&(x==null?void 0:x.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:fe,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:W=>W.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:A.label}),s.jsx("div",{className:`mt-1 font-mono text-[11px] ${o.textMuted}`,children:A.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[A.behind>0&&s.jsx("button",{type:"button",onClick:()=>{Ne()},disabled:!te||w===A.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:w===A.id?"Checking":"Heal"}),s.jsx("button",{type:"button",onClick:fe,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(Fe,{label:(M==null?void 0:M.health)??A.health,tone:bc((M==null?void 0:M.health)??A.health)}),A.branch&&s.jsx(Fe,{label:A.branch,tone:"default"}),A.ahead>0&&s.jsx(Fe,{label:`ahead ${A.ahead}`,tone:"warn"}),A.behind>0&&s.jsx(Fe,{label:`behind ${A.behind}`,tone:"warn"}),A.dirtyFiles>0&&s.jsx(Fe,{label:`${A.dirtyFiles} dirty`,tone:"warn"}),(M==null?void 0:M.connection)&&s.jsx(Fe,{label:wj(M),tone:pj(M.connection)}),B.length>0&&s.jsx(Fe,{label:`${B.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[s.jsx(rt,{label:"Machine",value:A.machineLabel??"not reported"}),s.jsx(rt,{label:"Locality",value:A.locality}),s.jsx(rt,{label:"Machine id",value:A.machineId??(M==null?void 0:M.machineId)??"not reported"}),s.jsx(rt,{label:"Daemon id",value:A.daemonId??(M==null?void 0:M.daemonId)??"not reported"}),s.jsx(rt,{label:"Workspace",value:(M==null?void 0:M.workspace)??A.workspace}),s.jsx(rt,{label:"Branch",value:A.branch??"unknown"}),s.jsx(rt,{label:"HEAD",value:Z??(M!=null&&M.gitProbePending?"Pending live git probe":"not reported")}),s.jsx(rt,{label:"Upstream",value:A.upstream??"none"}),s.jsx(rt,{label:"Dirty/ahead/behind",value:`${A.dirtyFiles} dirty · ↑${A.ahead}/↓${A.behind}`}),s.jsx(rt,{label:"Source",value:String(((ee=M==null?void 0:M.connection)==null?void 0:ee.source)??yc(A))}),s.jsx(rt,{label:"Transport",value:((ve=M==null?void 0:M.connection)==null?void 0:ve.transport)??"unknown"}),s.jsx(rt,{label:"Sessions",value:B.length>0?B.map(W=>yn(W.session)).join(", "):"none active"})]}),B.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:B.map(W=>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:W.session.sessionId,children:mj(W.session.sessionId)}),s.jsx(Fe,{label:yn(W.session),tone:eo(yn(W.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:W.session.providerType||"provider unknown"}),s.jsx("span",{children:cj(W.session)}),s.jsx("span",{children:uj(W.session)})]}),W.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${o.textMuted}`,children:W.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${o.textMuted}`,title:W.session.workspace||W.workspace,children:[(W.session.workspace||W.workspace).slice(0,42),W.branch?` · ${W.branch}`:""]})]},W.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(rt,{label:"Completed",value:String(T.taskCompleted)}),s.jsx(rt,{label:"Failed",value:s.jsx("span",{className:T.taskFailed>0?o.isDark?"text-rose-300":"text-rose-600":"",children:T.taskFailed})}),s.jsx(rt,{label:"Launched",value:String(T.sessionLaunched)}),s.jsx(rt,{label:"Recent failures",value:s.jsx("span",{className:T.recentFailures>0?o.isDark?"text-amber-300":"text-amber-600":"",children:T.recentFailures})})]})]}),(()=>{var ue,me;const W=((ue=i.queue)==null?void 0:ue.tasks)??((me=i.queue)==null?void 0:me.items)??null;if(!Array.isArray(W)||W.length===0)return null;const ne=W.filter(J=>xj(J)===m).slice(0,3);return ne.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:ne.map(J=>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:J.id.slice(0,12)}),s.jsx(Fe,{label:J.status??"unknown",tone:eo(J.status)})]}),J.message&&s.jsx("div",{className:`mt-0.5 truncate ${o.textMuted}`,children:J.message.slice(0,48)})]},J.id))})]})})(),A.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:A.snapshotWarnings[0]})]}),((ce=A.branchConvergence)==null?void 0:ce.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:A.branchConvergence.nextStep})]}),v&&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:v.phase==="execute"?"Heal result":"Heal preview"}),s.jsx("div",{className:"mt-1",children:v.code??v.error??"No result code returned."})]})]})})]})})})})}function xt(e){return typeof e=="string"?e.trim():""}function Eo(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ti(...e){const t=new Set;for(const r of e){const n=xt(r);n&&t.add(n)}return[...t]}function Sj(e,t){var p,f;const r=Eo(e==null?void 0:e.settings),n=xt((p=e==null?void 0:e.coordinator)==null?void 0:p.meshId)||xt(r.meshCoordinatorFor),a=xt(r.meshNodeFor),o=!!n||!!a,i=n===t||a===t;if(o&&!i)return null;const c=Eo(e==null?void 0:e.activeChat),d=Ti(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=d[0]||"";if(!m)return null;const u=n===t?xt((f=e==null?void 0:e.coordinator)==null?void 0:f.role)||"coordinator":a===t?xt(r.meshNodeRole)||"worker":xt(e==null?void 0:e.role)||xt(r.meshNodeRole)||void 0;return{sessionId:m,aliases:d,meshId:t,nodeId:i&&xt(r.meshNodeId)||null,providerType:xt(e==null?void 0:e.providerType)||void 0,state:xt(e==null?void 0:e.status)||void 0,chatStatus:xt(c.status)||void 0,lifecycle:xt(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:xt(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:xt(e==null?void 0:e.runtimeRecoveryState)||void 0,...u?{role:u}:{},...i?{isSelfCoordinator:n===t}:{},workspace:xt(e==null?void 0:e.workspace)||null}}function Sm(e,t){var n;return t?(Array.isArray((n=e.status)==null?void 0:n.sessions)?e.status.sessions:[]).map(a=>Sj(a,t)).filter(a=>a!==null):[]}function ta(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function Nj(e,t){const r=new Set(ta(t));return ta(e).some(n=>r.has(n))}function Cj(e,t){const r=t.filter(a=>!!a);return r.length===0?e:[...e.filter(a=>!r.some(o=>Nj(a,o))),...r]}function Ij(e,t){if(t.length===0)return e;const r=new Map;for(const o of t)for(const i of ta(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 u=Ti(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),p=u[0]||"";if(!p)continue;const f=u.map(y=>r.get(y)).find(Boolean);f&&(n=!0),c.set(p,f?{...m,sessionId:p,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:p})}for(const m of o.activeSessions??[])c.has(m)||c.set(m,{sessionId:m,workspace:o.workspace,isCached:!0});for(const m of t)ta(m).some(p=>c.has(p))||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 d=[...c.values()];return d.length===0?o:{...o,activeSessionDetails:d,activeSessions:d.map(m=>m.sessionId)}});return n?{...e,nodes:a}:e}function Mj(e,t){const n=Sm(e,t).map(a=>{var d;const o=(Array.isArray((d=e.status)==null?void 0:d.sessions)?e.status.sessions:[]).find(m=>xt(m==null?void 0:m.id)===a.sessionId),i=Eo(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??"",xt(i.status)||xt(i.kind)||xt(i.type),a.nodeId??"",a.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(a=>!!a).sort();return n.length>0?n.join(`
80
+ `):null}function Nm({status:e,daemonId:t,extraDaemonIds:r,meshId:n,sendData:a,extraLiveSessions:o=[]}){const[i,c]=l.useState(new Map),d=l.useRef(new Map),m=l.useMemo(()=>{const y=new Set;if(t&&y.add(t),r)for(const g of r)g&&y.add(g);return[...y].sort()},[t,r]),u=m.join(",");l.useEffect(()=>{d.current=new Map,c(new Map)},[t,n]),l.useEffect(()=>{if(!n||!a||m.length===0)return;const y=m.map(g=>Vt.subscribe({sendData:a},g,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${g}`,params:{includeSessions:!0}},x=>{if(x.topic!=="daemon.metadata")return;const k=Mj(x,n);if(k===(d.current.get(g)??null))return;d.current.set(g,k);const j=Sm(x,n);c(h=>{const v=new Map(h);return v.set(g,j),v})}));return()=>{for(const g of y)g()}},[u,n,a]);const p=l.useMemo(()=>{const y=[];for(const g of i.values())y.push(...g);return y},[i]),f=l.useMemo(()=>Cj(p,o),[o,p]);return l.useMemo(()=>e?Ij(e,f):null,[f,e])}const vn=new Map;function Aj(e,t){return!e||!t?null:`${e}::${t}`}function Tj(e,t){var o,i,c,d;if(!t||!e.sessionId)return null;const r=((o=e.coordinator)==null?void 0:o.meshId)??(typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),n=typeof((c=e.settings)==null?void 0:c.meshNodeFor)=="string"?e.settings.meshNodeFor:null;if(r!==t&&n!==t)return null;const a=typeof((d=e.settings)==null?void 0:d.meshNodeId)=="string"?e.settings.meshNodeId:null;return{sessionId:e.sessionId,aliases:Ti(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 _j({activeConv:e,sendDaemonCommand:t,onClose:r}){var P,D,O,R,B,E;const n=((P=e.coordinator)==null?void 0:P.meshId)??(typeof((D=e.settings)==null?void 0:D.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),a=e.daemonId??null,o=Aj(a,n),i=o?vn.get(o)??null:null,c=_u(),{sendData:d}=it(),{theme:m}=qs(),u=l.useMemo(()=>Ys(m),[m]),p=l.useMemo(()=>Tj(e,n),[e.agentType,(O=e.coordinator)==null?void 0:O.meshId,e.sessionId,(R=e.settings)==null?void 0:R.meshCoordinatorFor,(B=e.settings)==null?void 0:B.meshNodeFor,(E=e.settings)==null?void 0:E.meshNodeId,e.status,e.workspacePath,n]),[f,y]=l.useState(i),[g,x]=l.useState(!1),[k,j]=l.useState(!1),[h,v]=l.useState(null),[I,w]=l.useState((i==null?void 0:i.refreshedAt)??null),b=l.useRef(i!==null),C=l.useRef(!1),N=l.useRef(!1),S=l.useRef(!0);l.useEffect(()=>{b.current=f!==null},[f]),l.useEffect(()=>{const F=o?vn.get(o)??null:null;y(F),w((F==null?void 0:F.refreshedAt)??null),b.current=F!==null,N.current=!1,j(!1),v(null)},[o]);const T=l.useCallback(async(F=!1)=>{if(!a||!n){v("This coordinator does not expose a live mesh id."),y(null);return}if(C.current){F&&(N.current=!0);return}if(!F&&o){const Z=vn.get(o);if(Z){y(Z),w(Z.refreshedAt||null),b.current=!0,x(!1),v(null);return}}C.current=!0;const Q=!b.current;x(Q),j(F&&b.current),v(null);try{const Z=c!=null&&c.loadMeshStatus?await c.loadMeshStatus(a,n,{refresh:F,retryProfile:F?"settled":"interactive"}):await t(a,"mesh_status",{meshId:n,refresh:F}),Y=bm(Z);if(!Y){v("mesh_status returned an unexpected payload.");return}o&&vn.set(o,Y),y(Y),b.current=!0,w(Y.refreshedAt||new Date().toISOString())}catch(Z){v(Z instanceof Error?Z.message:"Failed to load live mesh status")}finally{C.current=!1,x(!1),j(!1),N.current&&S.current&&(N.current=!1,window.setTimeout(()=>{S.current&&T(!0)},0))}},[o,a,n,c,t]);l.useEffect(()=>(S.current=!0,T(!1),()=>{S.current=!1}),[T]),l.useEffect(()=>{const F=Q=>{Q.key==="Escape"&&r()};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[r]);const _=(f==null?void 0:f.meshName)||n||"Repo Mesh",L=l.useMemo(()=>p?[p]:[],[p]),M=Nm({status:f,daemonId:a,meshId:n,sendData:d,extraLiveSessions:L}),A=I?new Date(I).toLocaleTimeString():null,H=l.useMemo(()=>g?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[g]);return s.jsx("div",{className:u.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:u.dialogShellClass,onClick:F=>F.stopPropagation(),children:[s.jsxs("div",{className:u.dialogHeaderClass,children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-400/20 bg-sky-500/12 text-sky-200 shadow-[0_12px_30px_rgba(14,165,233,0.18)]",children:s.jsx(Jt,{size:18})}),s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("h2",{className:u.dialogTitleClass,children:_}),s.jsx("span",{className:u.dialogKickerClass,children:"Mesh observability"})]}),s.jsxs("p",{className:u.dialogSubtitleClass,children:[ot(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:[A&&s.jsx("span",{className:u.dialogRefreshedChipClass,children:k?"Refreshing mesh...":`Refreshed ${A}`}),!k&&f&&s.jsx("span",{className:u.dialogRefreshedChipClass,children:d&&!h?"Live daemon metadata":"Metadata subscription unavailable"}),s.jsx("button",{type:"button",onClick:()=>{T(!0)},disabled:g||k,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:g||k?"Refreshing...":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:u.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:s.jsx(yt,{size:16})})]})]}),h&&s.jsx("div",{className:u.isDark?"shrink-0 border-b border-rose-400/20 bg-rose-500/12 px-4 py-2 text-sm text-rose-200 md:px-5":"shrink-0 border-b border-rose-300 bg-rose-50 px-4 py-2 text-sm text-rose-700 md:px-5",children:h}),s.jsx("div",{className:u.dialogBodyClass,children:M?s.jsx(km,{status:M,emptyMessage:H,daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:u.dialogEmptyClass,children:H})})]})})}function Lj(e,t){const{sendCommand:r}=it(),[n,a]=l.useState(null),[o,i]=l.useState(!1);l.useEffect(()=>{if(!e||!t){a(null);return}i(!0),r(e,"git_remote_url",{workspace:t}).then(d=>{const m=(d==null?void 0:d.result)??d;a(typeof(m==null?void 0:m.remoteUrl)=="string"?m.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>i(!1))},[e,t,r]);const c=Pj(n);return{remoteUrl:n,githubUrl:c,loading:o}}function Pj(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 Cm=5e3;function Rj(e){return`git:${e}`}function Dj({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Cm}){return{type:"subscribe",topic:"workspace.git",key:Rj(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function _i(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Ss(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 $j(e){const t=_i(e);return(t==null?void 0:t.success)===!1?{status:null,error:Ss(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Ss(t,"Git status response did not include status")}}function Ej(e){const t=_i(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Ss(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Ss(t,"Git diff summary response did not include diffSummary")}}function to(e){return e===void 0||typeof e=="boolean"}function Bj(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&to(t.binary)&&to(t.truncated)&&to(t.staged)}function Oj(e){const t=_i(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Ss(t,"Git file diff request failed")}:Bj(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Ss(t,"Git file diff response did not include a valid diff object")}}function Fj({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Cm}){const{sendCommand:o,sendData:i}=it(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[m,u]=l.useState(null),[p,f]=l.useState(null),[y,g]=l.useState(!1),[x,k]=l.useState(null),j=l.useCallback(async()=>{if(!(!d||!e||!c)){g(!0),k(null);try{const v=$j(await o(e,"git_status",{workspace:c}));if(v.error){u(null),f(null),k(v.error);return}if(u(v.status),!n){f(null);return}const I=Ej(await o(e,"git_diff_summary",{workspace:c}));if(I.error){f(null),k(I.error);return}f(I.diffSummary)}catch(v){k(Ss(v,"Git status request failed"))}finally{g(!1)}}},[d,e,n,o,c]),h=l.useMemo(()=>c?Dj({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return l.useEffect(()=>{if(!d||!e||!c||!h){u(null),f(null),g(!1),k(null);return}const v=i?Vt.subscribe({sendData:i},e,h,I=>{var w,b;I.workspace===c&&(u(I.status),f(I.diffSummary??null),k(((w=I.status)==null?void 0:w.error)||((b=I.diffSummary)==null?void 0:b.error)||null),g(!1))},{retryIntervalMs:1e3}):null;return j(),()=>{v==null||v()}},[d,e,j,h,i,c]),{status:m,diffSummary:p,loading:y,error:x,refresh:j}}const Hj={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},Wj={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 jc(e){return e.split("/").pop()??e}function Kj(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function Uj({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=Hj[o.status]??"?",d=Wj[o.status]??"text-zinc-400",m=Kj(o.path),u=jc(o.path),p=o.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${i?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(o),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:o.status,children:c}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&s.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),s.jsx("span",{className:"text-text-primary",children:u}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",jc(o.oldPath)]}),p]}),!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 zj(e,t){let r="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?r="bg-emerald-500/10 text-emerald-300":e.startsWith("-")&&!e.startsWith("---")?r="bg-red-500/10 text-red-300":e.startsWith("@@")?r="text-sky-400":(e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ "))&&(r="text-text-secondary"),s.jsx("div",{className:`px-3 ${r}`,children:s.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},t)}function Im({diff:e,binary:t,truncated:r,loading:n,error:a,className:o=""}){const i=l.useRef(null);if(l.useEffect(()=>{i.current&&(i.current.scrollTop=0)},[e]),n)return s.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${o}`,children:"Loading diff…"});if(a)return s.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${o}`,children:a});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"No diff available."});const c=e.split(`
81
+ `);return s.jsxs("div",{ref:i,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((d,m)=>zj(d,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 Gj(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(`
82
+ `)}function Mm({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=it(),{status:a,diffSummary:o,loading:i,error:c,refresh:d}=Fj({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=l.useState(null),[p,f]=l.useState(null),[y,g]=l.useState(""),[x,k]=l.useState(!1),[j,h]=l.useState(!1),[v,I]=l.useState(null),[w,b]=l.useState(null),{githubUrl:C}=Lj(e,t),N=l.useCallback(async A=>{if(!((m==null?void 0:m.path)===A.path&&!m.loading)){u({path:A.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const H=await n(e,"git_diff_file",{workspace:t,path:A.path,staged:A.staged}),P=Oj(H);if(P.error||!P.diff){u({path:A.path,diff:"",binary:!1,truncated:!1,loading:!1,error:P.error??"Failed to load diff"});return}u({path:A.path,diff:P.diff.diff,binary:P.diff.binary??!1,truncated:P.diff.truncated??!1,loading:!1,error:null})}catch(H){const P=H instanceof Error?H.message:"Failed to load diff";u({path:A.path,diff:"",binary:!1,truncated:!1,loading:!1,error:P})}}},[e,n,m,t]),S=l.useCallback(A=>{g(""),k(!1),I(null),b(null),f(A)},[]),T=l.useCallback(()=>{f(null),I(null),h(!1)},[]),_=l.useCallback(async()=>{var A,H,P;if(p){h(!0),I(null);try{let D;p==="checkpoint"?D=await n(e,"git_checkpoint",{workspace:t,message:y,includeUntracked:x}):p==="stash"?D=await n(e,"git_stash_push",{workspace:t,message:y,includeUntracked:x}):p==="stash_pop"?D=await n(e,"git_stash_pop",{workspace:t}):p==="checkout_files"&&m&&(D=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const O=(D==null?void 0:D.result)??D;if((O==null?void 0:O.success)===!1||O!=null&&O.error){I((O==null?void 0:O.error)??"Action failed"),h(!1);return}p==="checkpoint"?b(`Checkpoint created: ${((H=(A=O==null?void 0:O.checkpoint)==null?void 0:A.commit)==null?void 0:H.slice(0,7))??"done"}`):p==="stash"?b(`Stashed as ${((P=O==null?void 0:O.stash)==null?void 0:P.stashRef)??"stash@{0}"}`):p==="stash_pop"?b("Stash restored"):(b("File reverted"),u(null)),f(null),await d()}catch(D){I(D instanceof Error?D.message:"Action failed")}finally{h(!1)}}},[p,n,e,t,y,x,m,d]),L=!!(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:A=>{A.target===A.currentTarget&&r()},children:s.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),C&&s.jsx("a",{href:`${C}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-sky-400 underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:d,disabled:i,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),s.jsx("button",{onClick:r,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(yt,{className:"h-4 w-4"})})]}),a&&s.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[a.headCommit&&s.jsxs("span",{title:a.headMessage??void 0,children:[s.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&s.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&s.jsxs("span",{className:"text-orange-400",children:["↑",a.ahead," ahead"]}),a.behind>0&&s.jsxs("span",{className:"text-orange-400",children:["↓",a.behind," behind"]}),a.staged>0&&s.jsxs("span",{className:"text-emerald-400",children:[a.staged," staged"]}),a.modified>0&&s.jsxs("span",{children:[a.modified," modified"]}),a.untracked>0&&s.jsxs("span",{children:[a.untracked," untracked"]}),a.deleted>0&&s.jsxs("span",{className:"text-red-400",children:[a.deleted," deleted"]}),a.stashCount>0&&s.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&s.jsx("span",{className:"font-bold text-red-400",children:"conflicts"}),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(Uj,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:N}),!i&&!o&&!c&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:m?s.jsx(Im,{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"})})]}),w&&s.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-emerald-500/10 px-4 py-2 text-xs text-emerald-400 flex items-center justify-between",children:[s.jsx("span",{children:w}),s.jsx("button",{onClick:()=>b(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:()=>S("checkpoint"),disabled:L,title:L?"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:()=>S("stash"),disabled:L,title:L?"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:()=>S("stash_pop"),disabled:L||!(a!=null&&a.stashCount),title:L?"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:()=>S("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 A=Gj((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(A),b("Copied to clipboard"),setTimeout(()=>b(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),p&&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:[p==="checkpoint"&&"Create checkpoint commit",p==="stash"&&"Stash changes",p==="stash_pop"&&"Restore latest stash?",p==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(p==="checkpoint"||p==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:y,onChange:A=>g(A.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:A=>k(A.target.checked)}),"Include untracked files"]})]}),v&&s.jsx("p",{className:"text-xs text-red-400",children:v}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:T,disabled:j,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:_,disabled:j||(p==="checkpoint"||p==="stash")&&!y.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:j?"Working…":"Confirm"})]})]})})]})})}function Vj({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=l.useState(!1),[o,i]=l.useState(!1),[c,d]=l.useState(!1),[m,u]=l.useState(!1),[p,f]=l.useState(!1),[y,g]=l.useState("quickstart"),[x,k]=l.useState("workspace"),j=l.useMemo(()=>!t&&!e,[t,e]),h=l.useCallback(N=>{a(N),N&&i(!1)},[]),v=l.useCallback(N=>{i(N),N&&a(!1)},[]),I=l.useCallback(()=>{g(r===0?"quickstart":"shortcuts"),k("workspace"),d(!0),a(!1),i(!1)},[r]),w=l.useCallback(()=>{d(!1)},[]),b=l.useCallback(()=>{u(!0)},[]),C=l.useCallback(()=>{u(!1)},[]);return l.useEffect(()=>{if(!j){f(!1);return}f(!0);const N=window.setTimeout(()=>{f(!1)},1e4);return()=>window.clearTimeout(N)},[j]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:m,guideNudgeVisible:p,guideTab:y,shortcutSection:x,isDesktopDashboard:j,setGuideTab:g,setShortcutSection:k,handleInboxOpenChange:h,handleHiddenOpenChange:v,handleOpenShortcutHelp:I,closeShortcutHelp:w,openNewSession:b,closeNewSession:C}}function qj(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 Yj(e){return e instanceof Error?e.message:String(e||"")}function Xj(e){const t=Yj(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Jj({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:i,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:p,ides:f,actionLogs:y,sendDaemonCommand:g,setActionLogs:x,setCliViewModeOverrides:k,isStandalone:j,initialDataLoaded:h,userName:v,requestedMobileTabKey:I,onRequestedMobileTabConsumed:w,requestedMachineId:b,onRequestedMachineConsumed:C,requestedMobileSection:N,onRequestedMobileSectionConsumed:S,containerRef:T,isSplitMode:_,numGroups:L,groupSizes:M,groupedConvs:A,clearedTabs:H,focusedGroup:P,focusGroup:D,moveTabToGroup:O,splitTabRelative:R,closeGroup:B,handleResizeStart:E,groupActiveTabIds:F,setGroupActiveTab:Q,groupTabOrders:Z,setGroupTabOrder:Y,toggleHiddenTab:te,visibleConversations:fe,requestedDesktopTabKey:Ne,onRequestedDesktopTabConsumed:X,onDesktopActiveTabChange:we,onRequestScrollToBottom:ge,onHideConversation:be,onShowHiddenConversation:de,onShowAllHiddenConversations:Ie,scrollToBottomRequest:ee,machineEntries:ve,layoutProfile:ce,onBrowseMachineDirectory:W,onSaveMachineWorkspace:ne,onLaunchMachineIde:ue,onLaunchMachineProvider:me,onListMachineMeshes:J,onLaunchMeshCoordinator:q,onListMachineSavedSessions:$,notifications:re,notificationUnreadCount:xe,liveSessionInboxState:je,onMarkNotificationRead:ae,onMarkNotificationUnread:Pe,onDeleteNotification:$e}){const Re=gt.useRef(null),{inboxOpen:Ge,hiddenOpen:Ye,shortcutHelpOpen:Xe,newSessionOpen:at,guideNudgeVisible:Je,guideTab:Ze,shortcutSection:dt,isDesktopDashboard:ft,setGuideTab:he,setShortcutSection:Oe,handleInboxOpenChange:et,handleHiddenOpenChange:ze,handleOpenShortcutHelp:ht,closeShortcutHelp:K,openNewSession:U,closeNewSession:V}=Vj({isMobile:t,showMobileChatMode:e,visibleConversationCount:fe.length}),[ie,pe]=gt.useState(null),[ke,z]=gt.useState(null),G=gt.useCallback((oe,ye)=>{pe({daemonId:oe,workspace:ye})},[]),le=gt.useCallback(oe=>{z(oe)},[]),Ce=gt.useCallback(oe=>{var ye;Cr.flushSync(()=>{de(oe)}),(ye=Re.current)==null||ye.restoreHiddenTabToSavedLocation(oe.tabKey)},[de]),Te=gt.useCallback(oe=>{var We;const ye=u.find(vt=>No(vt,oe))||p.find(vt=>No(vt,oe));ye&&(p.some(vt=>vt.tabKey===ye.tabKey)&&Ce(ye),we(ye.tabKey),(We=Re.current)==null||We.activateConversationTab(ye.tabKey),ge(ye.tabKey,"notification-open")),ae(oe.id),et(!1)},[Ce,p,u,we,ae,ge]),Me=gt.useCallback(()=>{var ye;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((ye=Re.current)==null||ye.resetAllPanelsToMain(),ze(!1))},[ze]),_e=gt.useCallback(async oe=>{var is;if(!r)return;const ye=(is=r.modalButtons)==null?void 0:is[oe];if(!ye)return;const We=xs(r);if(!We)return;const vt=ye.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Is=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(vt);try{await g(We,"resolve_action",{button:ye,action:Is?"approve":"reject",buttonIndex:oe,...fs(r)})}catch(ls){Xj(ls)||console.error("[Shortcut approval] Failed:",ls)}},[r,g]),{isMac:De,actionDefinitions:Ae,actionShortcuts:He,shortcutListening:Ve,shortcutListeningDraft:ut,setShortcutListening:bt,setShortcutListeningDraft:lt,saveShortcuts:mt}=ov({enabled:ft&&!Xe,onTrigger:oe=>{var ye,We,vt,Is,is,ls,zr,Gr,Vr,qr,Yr,Xr,Jr,Qr,cs,Zr;if(oe==="openShortcutHelp"){ht();return}if(oe==="openNewSession"){U();return}if(oe==="hideCurrentTab"){r&&be(r);return}if(oe==="toggleHiddenTabs"){ze(!Ye);return}if(oe==="openHistoryForActiveTab"){r&&!qe(r)&&o(r);return}if(oe==="openRemoteForActiveTab"){r&&!Qe(r)&&!qe(r)&&i(r);return}if(oe==="splitActiveTabRight"){(ye=Re.current)==null||ye.splitActiveTabRight();return}if(oe==="splitActiveTabDown"){(We=Re.current)==null||We.splitActiveTabDown();return}if(oe==="floatActiveTab"){(vt=Re.current)==null||vt.floatActiveTab();return}if(oe==="popoutActiveTab"){(Is=Re.current)==null||Is.popoutActiveTab();return}if(oe==="dockActiveTab"){(is=Re.current)==null||is.dockActiveTab();return}if(oe==="focusLeftPane"){(ls=Re.current)==null||ls.focusLeftPane();return}if(oe==="focusRightPane"){(zr=Re.current)==null||zr.focusRightPane();return}if(oe==="focusUpPane"){(Gr=Re.current)==null||Gr.focusUpPane();return}if(oe==="focusDownPane"){(Vr=Re.current)==null||Vr.focusDownPane();return}if(oe==="moveActiveTabToLeftPane"){(qr=Re.current)==null||qr.moveActiveTabToLeftPane();return}if(oe==="moveActiveTabToRightPane"){(Yr=Re.current)==null||Yr.moveActiveTabToRightPane();return}if(oe==="moveActiveTabToUpPane"){(Xr=Re.current)==null||Xr.moveActiveTabToUpPane();return}if(oe==="moveActiveTabToDownPane"){(Jr=Re.current)==null||Jr.moveActiveTabToDownPane();return}if(oe==="triggerPrimaryApprovalAction"){_e(0);return}if(oe==="triggerSecondaryApprovalAction"){_e(1);return}if(oe==="triggerTertiaryApprovalAction"){_e(2);return}if(oe==="setActiveTabShortcut"){(Qr=Re.current)==null||Qr.setShortcutForActiveTab();return}if(oe==="selectPreviousGroupTab"){(cs=Re.current)==null||cs.activatePreviousTabInGroup();return}if(oe==="selectNextGroupTab"){(Zr=Re.current)==null||Zr.activateNextTabInGroup();return}!r||!Qe(r)||qe(r)||oe==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),Be=gt.useCallback(()=>{K(),bt(null),lt([])},[K,bt,lt]),Mt=gt.useMemo(()=>dt==="all"?Ae:Ae.filter(oe=>qj(oe)===dt),[Ae,dt]),se=gt.useCallback(()=>{const oe=Object.fromEntries(Ae.map(ye=>[ye.id,""]));mt(oe)},[Ae,mt]),Le=gt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const oe=Object.fromEntries(Ae.map(ye=>[ye.id,ye.defaultShortcut]));mt(oe)},[Ae,mt]);return gt.useEffect(()=>{const oe=ye=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?ye.metaKey&&ye.key.toLowerCase()==="w":ye.ctrlKey&&ye.key.toLowerCase()==="w")&&(ye.preventDefault(),r&&be&&be(r))};return window.addEventListener("keydown",oe),()=>window.removeEventListener("keydown",oe)},[r,be]),gt.useEffect(()=>{if(!Xe||Ve)return;const oe=ye=>{ye.key==="Escape"&&(ye.preventDefault(),Be())};return window.addEventListener("keydown",oe,!0),()=>window.removeEventListener("keydown",oe,!0)},[Be,Xe,Ve]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(qb,{activeConv:r,wsStatus:n,isConnected:a,conversations:fe,hiddenConversations:p,onOpenHistory:o,onHideConversation:be,onShowConversation:Ce,onShowAllHidden:Ie,onResetPanelsToMain:Me,notifications:re,notificationUnreadCount:xe,onOpenNotification:Te,onMarkNotificationRead:ae,onMarkNotificationUnread:Pe,onDeleteNotification:$e,inboxOpen:Ge,onInboxOpenChange:et,hiddenOpen:Ye,onHiddenOpenChange:ze,onOpenNewSession:t?void 0:U,onOpenDashboardGuide:ht,guideNudgeVisible:Je,actionShortcuts:He,onOpenRemote:()=>{!r||Qe(r)||qe(r)||i(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:G,onOpenMeshGraph:le}),e?s.jsx(q0,{conversations:u,hiddenConversations:p,ides:f,actionLogs:y,sendDaemonCommand:g,setActionLogs:x,setCliViewModeOverrides:k,isStandalone:j,userName:v,requestedActiveTabKey:I,onRequestedActiveTabConsumed:w,requestedMachineId:b,onRequestedMachineConsumed:C,requestedMobileSection:N,onRequestedMobileSectionConsumed:S,onOpenHistory:o,onOpenRemote:i,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Ie,onHideConversation:be,onOpenMeshGraph:le,onOpenNewSession:U,liveSessionInboxState:je}):t?s.jsx(sv,{containerRef:T,isSplitMode:_,numGroups:L,groupSizes:M,groupedConvs:A,clearedTabs:H,ides:f,actionLogs:y,sendDaemonCommand:g,setActionLogs:x,isStandalone:j,hasRegisteredMachines:ve.length>0,userName:v,focusedGroup:P,focusGroup:D,moveTabToGroup:O,splitTabRelative:R,closeGroup:B,handleResizeStart:E,groupActiveTabIds:F,setGroupActiveTab:Q,groupTabOrders:Z,setGroupTabOrder:Y,toggleHiddenTab:te,onOpenNewSession:U,allowTabShortcuts:!1,liveSessionInboxState:je}):s.jsx(vv,{visibleConversations:fe,clearedTabs:H,ides:f,actionLogs:y,sendDaemonCommand:g,setActionLogs:x,isStandalone:j,hasRegisteredMachines:ve.length>0,initialDataLoaded:h,userName:v,toggleHiddenTab:te,actionShortcuts:He,registerActionHandlers:oe=>{Re.current=oe},onActiveTabChange:we,requestedActiveTabKey:Ne,onRequestedActiveTabConsumed:X,onRequestScrollToBottom:ge,scrollToBottomRequest:ee,onOpenNewSession:U,liveSessionInboxState:je,layoutProfile:ce}),at&&s.jsx(Tv,{machines:ve,ides:f,onClose:V,onBrowseDirectory:W,onSaveWorkspace:ne,onLaunchIde:ue,onLaunchProvider:me,onListMeshes:J,onLaunchMeshCoordinator:q,onListSavedSessions:$}),ke&&s.jsx(_j,{activeConv:ke,sendDaemonCommand:g,onClose:()=>z(null)}),ie&&s.jsx(Mm,{daemonId:ie.daemonId,workspace:ie.workspace,onClose:()=>pe(null)}),Xe&&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:Be,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:oe=>oe.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:Be,"aria-label":"Close dashboard guide",children:s.jsx(yt,{size:14})})]}),s.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(oe=>s.jsx("button",{type:"button",className:`btn btn-sm ${Ze===oe.id?"btn-primary":"btn-secondary"}`,onClick:()=>he(oe.id),children:oe.label},oe.id))}),Ze==="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 ",De?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Ze==="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."]})]})]})]}),Ze==="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(oe=>s.jsx("button",{type:"button",className:`btn btn-sm ${dt===oe.id?"btn-primary":"btn-secondary"}`,onClick:()=>Oe(oe.id),children:oe.label},oe.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:se,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:Le,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Mt.map(oe=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Ve===oe.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:oe.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:oe.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:oe.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:Ve===oe.id?ut.length>0?`${ut.join(" ")} ...`:"Listening...":He[oe.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{bt(oe.id),lt([])},children:Ve===oe.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const ye={...He};ye[oe.id]="",mt(ye)},children:"Disable"})]})]})},oe.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",De?"⌘⇧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 so=[{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 Qj({onClose:e}){const[t,r]=l.useState(0),n=so[t],a=t===so.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:o=>{o.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(yt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:so.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:`
83
+ @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
84
+ @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
85
+ `})]})}function Zj({hasExtensions:e,ideName:t,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?s.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[s.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${r==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a("native"),children:t}),n.map(o=>{const i=r===o.tabKey,c=o.status==="waiting_approval",d=o.status==="generating";return s.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${i?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(o.tabKey),children:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:c?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),o.title,c&&s.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},o.tabKey)})]}):null}function e1({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,i]=l.useState(()=>a||"native"),c=l.useMemo(()=>su(t),[t]),d=l.useMemo(()=>e?ci(e,{machineNames:c,connectionStates:r,defaultConnectionState:"new"}):[],[e,c,r]),m=l.useMemo(()=>d.find(x=>x.streamSource==="native"),[d]),u=l.useMemo(()=>d.filter(x=>x.streamSource==="agent-stream"),[d]),p=l.useMemo(()=>e?Ot(d,e.id):null,[d,e]);l.useEffect(()=>{a&&i(a)},[a]),l.useEffect(()=>{if(a||!p)return;const x=p.streamSource==="native"?"native":p.tabKey;!x||o===x||o==="native"&&i(x)},[o,p,a]),l.useEffect(()=>{var x;o!=="native"&&(u.some(k=>k.tabKey===o)||i(((x=u[0])==null?void 0:x.tabKey)||"native"))},[o,u]),l.useEffect(()=>{o==="native"&&(m||u[0]&&i(u[0].tabKey))},[o,m,u]);const f=l.useMemo(()=>o==="native"&&m?m:u.find(x=>x.tabKey===o)||p||m||u[0],[o,m,p,u]),y=l.useMemo(()=>u.map(x=>({tabKey:x.tabKey,title:Vd(x)||n,status:x.status})),[u,n]),g=l.useCallback(x=>{if(x)return d.find(k=>No(k,{sessionId:x,routeId:x,tabKey:x,providerSessionId:x}))},[d]);return{activeChatTab:o,setActiveChatTab:i,activeConv:f,conversations:d,extensionTabs:y,hasExtensions:y.length>0,resolveConversationByTarget:g}}function t1({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:i,isStandalone:c,userName:d,onOpenHistory:m,onConversationChange:u,onClose:p}){const[f,y]=l.useState("split"),[g,x]=l.useState(()=>os(e)?"native":e.tabKey),k=l.useRef(null),j=l.useMemo(()=>t||r.find(D=>D.id===e.routeId),[e.routeId,t,r]),h=l.useMemo(()=>wt((j==null?void 0:j.type)||""),[j==null?void 0:j.type]),{conversations:v,extensionTabs:I,hasExtensions:w}=e1({ideData:j,allIdes:r,connectionStates:n,ideName:h||"IDE",preferredTabKey:os(e)?void 0:e.tabKey}),b=l.useMemo(()=>j?Ot(v,j.id):null,[j,v]);l.useEffect(()=>{const D=k.current,O={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(k.current=O,!(D&&D.routeId===O.routeId&&D.tabKey===O.tabKey&&D.streamSource===O.streamSource)){if(os(e)){x("native");return}x(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),l.useEffect(()=>{if(g==="native"){if(v.some(D=>D.streamSource==="native"))return;(b==null?void 0:b.streamSource)==="agent-stream"&&x(b.tabKey);return}if(!v.some(D=>D.tabKey===g)){if((b==null?void 0:b.streamSource)==="agent-stream"){x(b.tabKey);return}x("native")}},[v,g,b]);const C=l.useMemo(()=>g==="native"?v.find(D=>D.streamSource==="native")||e:v.find(D=>D.tabKey===g)||e,[e,v,g]),N=hu(C),S=l.useMemo(()=>N.status||N.modalMessage||N.modalButtons?{...C,...N.status?{status:N.status}:{},...N.modalMessage!==void 0?{modalMessage:N.modalMessage}:{},...N.modalButtons!==void 0?{modalButtons:N.modalButtons}:{}}:C,[C,N]),T=Br(S),_=da({sendDaemonCommand:o,activeConv:S,setActionLogs:i,isStandalone:c}),{connScreenshot:L,screenshotUsage:M,handleRemoteAction:A}=zu({doId:T,targetSessionId:Td(S),connState:S.connectionState||"new",viewMode:f}),H=l.useMemo(()=>a.filter(D=>D.routeId===S.tabKey),[a,S.tabKey]);l.useEffect(()=>{u==null||u(S)},[S,u]),l.useEffect(()=>{const D=O=>{O.key==="Escape"&&p()};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[p]);const P=l.useCallback(D=>{D.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:p,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:P,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(Ft,{size:16})}),s.jsx("span",{className:"truncate",children:si(C)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:p,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(D=>{const O=f===D;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${O?"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(D),title:D==="split"?"Split view":"Remote only",children:D==="split"?s.jsx(lh,{size:15}):s.jsx(Ft,{size:15})},D)})}),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(Go,{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:p,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(Zj,{hasExtensions:w,ideName:h||"IDE",activeChatTab:g,extensionTabs:I,onSelectTab:x}),s.jsx(fd,{activeConv:S,onModalButton:_.handleModalButton}),s.jsx(Ao,{activeConv:S,ideEntry:j,showMetaChips:!1,handleSendChat:_.handleSendChat,handleForceSendChat:_.handleForceSendChat,isSendingChat:_.isSendingChat,sendFeedbackMessage:_.sendFeedbackMessage,handleFocusAgent:_.handleFocusAgent,isFocusingAgent:_.isFocusingAgent,actionLogs:H,userName:d})]}),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(ud,{addLog:()=>{},connState:S.connectionState||"new",connScreenshot:L,screenshotUsage:M,transportType:S.transport,onAction:A})})]})]})})}function s1({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=Rb(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 r1({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(eu,{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(t1,{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&&(Qe(r.targetConv)||qe(r.targetConv))&&s.jsx(s1,{activeConv:r.targetConv,canSaveAndStop:Qe(r.targetConv)&&!qe(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(tu,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),s.jsx(pd,{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(Qj,{onClose:o.onClose})]})}function n1({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(oa,{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=Pt(i,{fallbackId:i.id}),d=n[i.id],m=i.version||i.daemonVersion||"unknown",u=i.versionUpdateRequired===!0,f=Mu(i)==="preview"?"Update to preview":u?"Update now":"Upgrade";return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:c}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),u&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),d==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:u?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):d==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(i.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:u?"var(--status-danger)":"var(--status-warning)",background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(i.id),children: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(yt,{size:16})})]})}function a1(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function o1(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 i1(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>o1(t)).map(t=>t.id)}}function l1(){var Bi,Oi,Fi,Hi;const{sendCommand:e}=it(),t=Or(),r=pu(),n=Ko(),a=Dr(),[o,i]=Np(),c=o.get("activeTab"),d=((Bi=n.state)==null?void 0:Bi.openRemoteForTabKey)||null,m=((Oi=n.state)==null?void 0:Oi.openMachineId)||null,u=((Fi=n.state)==null?void 0:Fi.mobileSection)||null,p=Kd(),f=p.ides||[],y=p.initialLoaded??!0,{updateRouteChats:g,setToasts:x}=p,[k,j]=l.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),h=p.toasts||[],v=p.wsStatus||"connected",I=p.isConnected??!0,w=p.connectionStates||{},b=p.showReconnected||!1,{layoutProfile:C,groupAssignments:N,updateGroupAssignments:S,focusedGroup:T,updateFocusedGroup:_,focusGroup:L,groupActiveTabIds:M,updateGroupActiveTabIds:A,setGroupActiveTab:H,groupTabOrders:P,updateGroupTabOrders:D,setGroupTabOrder:O,groupSizes:R,updateGroupSizes:B,isMobile:E,hasHydratedStoredLayout:F,hydrateStoredLayout:Q,focusConversationTab:Z}=Wy(),[Y,te]=l.useState(()=>pi());l.useEffect(()=>Vg(te),[]);const fe=l.useMemo(()=>a1({isMobile:E,mobileViewMode:Y}),[E,Y]),[Ne,X]=l.useState([]),[we,ge]=l.useState({}),[be,de]=l.useState({});Er("Dashboard",{ideCount:f.length,toastCount:h.length,focusedGroup:T,groupCount:Object.keys(N).length,actionLogCount:Ne.length});const Ie=l.useMemo(()=>f.filter(Ke=>Ke.type==="adhdev-daemon").sort(Zo),[f]),ve=!!Ie[0];l.useEffect(()=>{const{metadataDaemonIds:Ke,runtimeDaemonIds:Rt}=i1(Ie);for(const Xs of Ke)t(Xs,{minFreshMs:3e4}).catch(()=>{});for(const Xs of Rt)r(Xs,{minFreshMs:3e4}).catch(()=>{})},[t,r,Ie]);const ce=l.useMemo(()=>hy(f,we),[f,we]),{hiddenTabs:W,autoHiddenTabs:ne,autoHideTarget:ue,hideTarget:me,toggleTarget:J,showTarget:q,showAllTabs:$}=ay(),{conversations:re,visibleConversations:xe,visibleTabKeys:je,resolveConversationBySessionId:ae,resolveConversationByTarget:Pe}=Iy({ides:ce,connectionStates:w,clearedTabs:be,hiddenTabs:W}),$e=l.useMemo(()=>new Map(re.map(Ke=>[Ke.tabKey,Ke])),[re]),Re=l.useMemo(()=>ny(re,W,ne),[re,W,ne]);l.useEffect(()=>{for(const Ke of Re)ue(Ke)},[Re,ue]),ob(xe,fe),l.useEffect(()=>{Object.keys(we).length!==0&&ge(Ke=>fy(Ke,f))},[f,we]);const Ge=l.useMemo(()=>of(f),[f]),{notifications:Ye,unreadCount:Xe}=n0({conversations:re,liveSessionInboxState:Ge}),{handleMarkDashboardNotificationRead:at,handleMarkDashboardNotificationUnread:Je,handleDeleteDashboardNotification:Ze}=a0({notifications:Ye,sendDaemonCommand:e}),{containerRef:dt,normalizedGroupAssignments:ft,numGroups:he,isSplitMode:Oe,groupedConvs:et,moveTabToGroup:ze,closeGroup:ht,handleResizeStart:K,splitTabRelative:U}=Yy({groupAssignments:N,updateGroupAssignments:S,updateFocusedGroup:_,updateGroupActiveTabIds:A,updateGroupTabOrders:D,groupSizes:R,updateGroupSizes:B,isMobile:E,visibleConversations:xe,visibleTabKeys:je}),{activeConv:V,openDesktopConversation:ie,requestScrollToBottom:pe,scrollToBottomRequest:ke,setDesktopActiveTab:z}=y0({isMobile:E,conversations:re,visibleConversations:xe,groupActiveTabIds:M,focusedGroup:T,groupedConvs:et,setSearchParams:i});j0({activeConv:V,isMobile:E,liveSessionInboxState:Ge,sendDaemonCommand:e});const{requestedDesktopTabKey:G,requestedMobileTabKey:le,consumeRequestedActiveTab:Ce}=My({isMobile:E,urlActiveTab:c,resolveConversationBySessionId:ae,setSearchParams:i}),{remoteDialogConv:Te,remoteDialogIdeEntry:Me,remoteDialogActiveConv:_e,setRemoteDialogActiveConv:De,openRemoteDialog:Ae,closeRemoteDialog:He,cliStopDialogOpen:Ve,cliStopTargetConv:ut,requestCliStop:bt,cancelCliStop:lt,confirmCliStop:mt}=N0({isMobile:E,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:G,conversations:re,ides:f,resolveConversationByTarget:Pe,activeConv:V,sendDaemonCommand:e}),{historyModalOpen:Be,openHistoryModal:Mt,closeHistoryModal:se,historyTargetConv:Le,isSavedSessionHistoryTarget:oe,isHistoryCreatingChat:ye,isHistoryRefreshingHistory:We,handleHistorySwitchSession:vt,handleHistoryNewChat:Is,handleHistoryRefresh:is,savedHistorySessions:ls,savedHistoryFilters:zr,setSavedHistoryFilters:Gr,missingWorkspaceResumePath:Vr,isSavedHistoryLoading:qr,resumingSavedHistorySessionId:Yr,handleRefreshSavedHistory:Xr,handleResumeSavedHistorySession:Jr}=k0({activeConv:V,remoteDialogConv:Te,remoteDialogActiveConv:_e,ides:f,sendDaemonCommand:e,updateRouteChats:g,setToasts:x,setClearedTabs:de,setSearchParams:i}),Qr=l.useMemo(()=>xe,[xe]),cs=E&&Y==="chat",Zr=l.useMemo(()=>re.filter(Ke=>pa(W,Ke)),[re,W]),Di=l.useCallback(Ke=>{const Rt=new URLSearchParams(o);Rt.set("activeTab",Ke),i(Rt,{replace:!0})},[o,i]),{trackPendingLaunch:Em}=f0({ides:f,conversations:re,onOpenSession:Di}),{handleBrowseMachineDirectory:Bm,handleSaveMachineWorkspace:Om,handleLaunchMachineIde:Fm,handleLaunchMachineProvider:Hm,handleListMachineMeshes:Wm,handleLaunchMeshCoordinator:Km,handleListMachineSavedSessions:Um,setActiveCliViewMode:zm}=x0({sendDaemonCommand:e,trackPendingLaunch:Em,onOpenSession:Di,activeConv:V,ides:f,setCliViewModeOverrides:ge});xy({visibleConversations:xe,clearedTabs:be,setClearedTabs:de,setActionLogs:X}),Ay({ides:f,sendDaemonCommand:e,setToasts:x,resolveConversationByTarget:Pe});const Gm=gu(),{isRefreshingHistory:Vm,handleRefreshHistory:qm}=Iu({sendDaemonCommand:e,activeConv:V,chats:(Hi=f.find(Ke=>Ke.id===(V==null?void 0:V.routeId)))==null?void 0:Hi.chats,updateRouteChats:g,setToasts:x,setClearedTabs:de});Uy({urlActiveTab:E&&!cs?c:null,conversations:re,resolveConversationBySessionId:ae,normalizedGroupAssignments:ft,hasHydratedStoredLayout:E&&!cs?F:!0,hydrateStoredLayout:E&&!cs?Q:()=>{},focusConversationTab:Z,setSearchParams:i,historyModalOpen:Be,activeConv:V,isRefreshingHistory:Vm,ides:f,handleRefreshHistory:qm});const Ym=l.useMemo(()=>!V||!Qe(V)||qe(V)?null:Vs(V),[V]),{versionMismatchDaemons:Xm,hasRequiredVersionDaemons:$i,targetVersion:Jm,versionBannerDismissed:Qm,setVersionBannerDismissed:Zm,upgradingDaemons:ep,handleBannerUpgrade:tp}=Jy({ides:f,sendDaemonCommand:e}),Ei=l.useCallback(Ke=>{q(Ke),ie(Ke)},[ie,q]),sp=l.useCallback(Ke=>{me(Ke)},[me]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[(!Qm||$i)&&s.jsx(n1,{daemons:Xm,targetVersion:Jm,required:$i,upgradingDaemons:ep,onUpgrade:tp,onDismiss:()=>Zm(!0)}),s.jsx(Jj,{showMobileChatMode:cs,isMobile:E,activeConv:V,wsStatus:v,isConnected:I,onOpenHistory:Ke=>{Ke&&De(Ke),Mt()},onOpenRemote:Ae,onStopCli:bt,activeCliViewMode:Ym,onSetActiveCliViewMode:zm,mobileChatConversations:Qr,ides:f,actionLogs:Ne,sendDaemonCommand:e,setActionLogs:X,setCliViewModeOverrides:ge,isStandalone:ve,initialDataLoaded:y,userName:p.userName,requestedMobileTabKey:le,onRequestedMobileTabConsumed:Ce,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:u,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:dt,isSplitMode:Oe,numGroups:he,groupSizes:R,groupedConvs:et,clearedTabs:be,focusedGroup:T,focusGroup:L,moveTabToGroup:ze,splitTabRelative:U,closeGroup:ht,handleResizeStart:K,groupActiveTabIds:M,setGroupActiveTab:H,groupTabOrders:P,setGroupTabOrder:O,toggleHiddenTab:Ke=>J($e.get(Ke)||{tabKey:Ke}),visibleConversations:xe,hiddenConversations:Zr,requestedDesktopTabKey:G,onRequestedDesktopTabConsumed:Ce,onDesktopActiveTabChange:z,onRequestScrollToBottom:pe,onHideConversation:sp,onShowHiddenConversation:Ei,onShowAllHiddenConversations:$,scrollToBottomRequest:ke,machineEntries:Ie,layoutProfile:C,onBrowseMachineDirectory:Bm,onSaveMachineWorkspace:Om,onLaunchMachineIde:Fm,onLaunchMachineProvider:Hm,onListMachineMeshes:Wm,onLaunchMeshCoordinator:Km,onListMachineSavedSessions:Um,notifications:Ye,notificationUnreadCount:Xe,liveSessionInboxState:Ge,onMarkNotificationRead:at,onMarkNotificationUnread:Je,onDeleteNotification:Ze}),s.jsx("style",{children:`
86
+ body { overflow: hidden; overscroll-behavior: none; }
87
+ `}),s.jsx(r1,{historyModal:{open:Be,targetConv:Le,ides:f,isCreatingChat:ye,isRefreshingHistory:oe?!1:We,savedSessions:ls,savedHistoryFilters:zr,missingWorkspaceResumePath:Vr||null,onSavedHistoryFiltersChange:Gr,isSavedSessionsLoading:qr,isResumingSavedSessionId:Yr,onClose:se,onNewChat:Is,onSwitchSession:vt,onRefreshHistory:oe?Xr:is,onResumeSavedSession:Jr},remoteDialog:{conversation:Te,ideEntry:Me,ides:f,connectionStates:w,actionLogs:Ne,sendDaemonCommand:e,setActionLogs:X,isStandalone:ve,userName:p.userName,onOpenHistory:Ke=>{Ke&&De(Ke),Mt()},onConversationChange:De,onClose:He},cliStopDialog:{open:Ve,targetConv:ut,onCancel:lt,onStopNow:async()=>{await mt("hard")},onSaveAndStop:async()=>{await mt("save")}},connectionBanner:{wsStatus:v,showReconnected:b,loginUrl:p.connectionLoginUrl,onReconnect:p.retryServerConnection},toastOverlay:{toasts:h,onDismiss:Ke=>x(Rt=>Rt.filter(Xs=>Xs.id!==Ke)),onClick:Ke=>{if(Ke.targetKey){const Rt=Pe(Ke.targetKey);Rt&&(Z(Rt.tabKey,ft),Ei(Rt),pe(Rt.tabKey,"toast-open"))}}},onboarding:{open:k,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}j(!1)}},interactivePrompt:Gm})]})}function c1({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const{launchCli:o}=na(),[i,c]=l.useState([]),[d,m]=l.useState(null),[u,p]=l.useState(null),[f,y]=l.useState(!1),[g,x]=l.useState(null),[k,j]=l.useState(!1),[h,v]=l.useState(""),I=l.useRef(null),w=l.useCallback(B=>{I.current=B},[]),b=l.useCallback((B,E,F=!1)=>{c(Q=>[...Q.slice(-100),{timestamp:Date.now(),level:B,message:E}]),setTimeout(()=>{var Q;return(Q=a.current)==null?void 0:Q.scrollIntoView({behavior:"smooth"})},100),F&&tt.showToast(E,B==="error"||B==="warn"?"warning":"success")},[a]),C=l.useCallback(B=>{const E=B instanceof Error?B.message:String(B||"");return E.includes("P2P command timeout")||E.includes("P2P not connected")||E.includes("P2P not available")},[]),N=l.useCallback(async(B,E)=>{var F;if(!e||d)return!1;m(B),b("info",`Launching ${wt(B)}${E!=null&&E.workspace?` in ${E.workspace}`:""}...`);try{const Q={ideType:B,enableCdp:!0};(F=E==null?void 0:E.workspace)!=null&&F.trim()?Q.workspace=E.workspace.trim():E!=null&&E.useDefaultWorkspace&&(Q.useDefaultWorkspace=!0);const Z=await r(e,"launch_ide",Q);return b(Z!=null&&Z.success?"info":"error",Z!=null&&Z.success?`${wt(B)} launched`:`Failed: ${Z==null?void 0:Z.error}`,!0),!!(Z!=null&&Z.success)}catch(Q){return b("error",`Launch error: ${Q.message}`,!0),!1}finally{m(null)}},[e,d,b,r]),S=l.useCallback(async B=>{if(!e)return{success:!1};const{cliType:E,dir:F,workspaceId:Q,useDefaultWorkspace:Z,useHome:Y,argsStr:te,model:fe,resumeSessionId:Ne}=B;if(!E)return b("warn","Select a CLI or ACP provider first",!0),{success:!1};const X=te?te.split(/\s+/).filter(Boolean):void 0,we=(F==null?void 0:F.trim())||(Q?"(saved id)":Z?"(default workspace)":Y?"(home)":"");b("info",`Launching ${E}${we?` in ${we}`:""}${fe?` (model: ${fe})`:""}...`),p(E);try{const ge={cliType:E,cliArgs:X,initialModel:fe||void 0};F!=null&&F.trim()?ge.dir=F.trim():Q?ge.workspaceId=Q:Z?ge.useDefaultWorkspace=!0:Y&&(ge.useHome=!0),Ne&&(ge.resumeSessionId=Ne);const be=await o(e,ge),de=(be==null?void 0:be.result)||be;return be!=null&&be.success?(b("info",`${E} launched`,!0),(de==null?void 0:de.launchSource)==="home"?b("info","📂 Running in home directory (explicit choice)"):(de==null?void 0:de.launchSource)==="defaultWorkspace"&&b("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:de==null?void 0:de.sessionId}):(b("error",`Failed: ${(be==null?void 0:be.error)||(de==null?void 0:de.error)}`,!0),(be==null?void 0:be.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&x({cliType:E,argsStr:te,model:fe}),{success:!1,sessionId:de==null?void 0:de.sessionId})}catch(ge){return C(ge)?(b("warn",`${E} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(b("error",`Launch error: ${ge.message}`,!0),{success:!1})}finally{p(null)}},[e,b,C,r]),T=l.useCallback(async(B,E,F,Q)=>e?B?E.trim()?S({cliType:B,dir:E,argsStr:F,model:Q}):(x({cliType:B,argsStr:F,model:Q}),{success:!1}):(b("warn","Select a provider",!0),{success:!1}):{success:!1},[e,b,S]),_=l.useCallback(async(B,E,F)=>{if(e&&window.confirm(`Stop ${B}?
88
+ This will terminate the process.`))try{const Q=await r(e,"stop_cli",{cliType:B,dir:E,targetSessionId:F});Q!=null&&Q.success?b("info",`${B} stopped`,!0):b("error",`Stop failed: ${(Q==null?void 0:Q.error)||"Unknown error"}`,!0)}catch(Q){b("error",`Stop failed: ${Q.message}`,!0)}},[e,b,r]),L=l.useCallback(async B=>{try{await r(B.daemonId,"restart_ide",{ideType:B.type}),b("info",`${wt(B.type)} restart initiated`,!0)}catch(E){b("error",`Restart failed: ${E.message}`,!0)}},[b,r]),M=l.useCallback(async B=>{if(window.confirm(`Stop ${wt(B.type)}?
89
+ This will disconnect CDP and optionally kill the process.`))try{const E=await r(B.daemonId,"stop_ide",{ideType:B.type,killProcess:!0});E!=null&&E.success?b("info",`${wt(B.type)} stopped`,!0):b("error",`Stop failed: ${(E==null?void 0:E.error)||"Unknown error"}`,!0)}catch(E){b("error",`Stop failed: ${E.message}`,!0)}},[b,r]),A=l.useCallback(async()=>{if(e)try{const B=await r(e,"detect_ides",{});b("info",`Found ${((B==null?void 0:B.result)||[]).length} IDE(s)`,!0)}catch(B){b("error",`Detection failed: ${B.message}`,!0)}},[e,b,r]),H=l.useCallback(async B=>{if(!e||!B.trim())return!1;y(!0);try{const E=await r(e,"workspace_add",{path:B.trim()});return E!=null&&E.success?(b("info",`Workspace added: ${B.trim()}`),!0):(b("error",(E==null?void 0:E.error)||"workspace_add failed"),!1)}catch(E){return b("error",E.message),!1}finally{y(!1)}},[e,b,r]),P=l.useCallback(async B=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){y(!0);try{const E=await r(e,"workspace_remove",{id:B});E!=null&&E.success?b("info","Workspace removed",!0):b("error",(E==null?void 0:E.error)||"workspace_remove failed",!0)}catch(E){b("error",E.message,!0)}finally{y(!1)}}},[e,b,r]),D=l.useCallback(async B=>{var E;if(e){y(!0);try{const F=await r(e,"workspace_set_default",B===null?{clear:!0}:{id:B});if(F!=null&&F.success){b("info",B?"Default workspace updated":"Default workspace cleared",!0);const Q=typeof F.defaultWorkspacePath=="string"?F.defaultWorkspacePath:"";Q&&((E=I.current)==null||E.call(I,Q))}else b("error",(F==null?void 0:F.error)||"workspace_set_default failed",!0)}catch(F){b("error",F.message,!0)}finally{y(!1)}}},[e,b,r]),O=l.useCallback(async B=>{var F;if(!e||!B.trim())return;const E=B.trim();y(!0);try{const Q=await r(e,"workspace_set_default",{path:E});Q!=null&&Q.success?(b("info","Default workspace set from history"),(F=I.current)==null||F.call(I,E)):b("error",(Q==null?void 0:Q.error)||"Could not set default (path missing on disk?)")}catch(Q){b("error",Q.message)}finally{y(!1)}},[e,b,r]),R=l.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:h}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:h})}catch(B){b("warn",`Live nickname updated, but account sync failed: ${B.message}`)}b("info",`Nickname set to "${h||"(cleared)"}"`),j(!1)}catch(B){b("error",`Failed: ${B.message}`)}},[e,h,t,b,n,r]);return{logs:i,launchingIde:d,launchingAgentType:u,workspaceBusy:f,launchPick:g,setLaunchPick:x,editingNickname:k,setEditingNickname:j,nicknameInput:h,setNicknameInput:v,addLog:b,handleLaunchIde:N,runLaunchCliCore:S,handleLaunchCli:T,handleStopCli:_,handleRestartIde:L,handleStopIde:M,handleDetectIdes:A,handleWorkspaceAdd:H,handleWorkspaceRemove:P,handleWorkspaceSetDefault:D,handleWorkspaceResumePath:O,handleSaveNickname:R,setOnDefaultWorkspaceChanged:w}}function d1({machine:e,ideSessions:t,cliSessions:r,acpSessions:n}){var d;const a=typeof e.uptime=="number"||typeof e.freeMem=="number"||typeof e.availableMem=="number"||Array.isArray(e.loadavg)&&e.loadavg.length>0,o=e.availableMem??e.freeMem??e.totalMem,i=a&&e.totalMem>0?Math.min(100,Math.max(0,Math.round((e.totalMem-o)/e.totalMem*100))):0,c=((d=e.loadavg)==null?void 0:d[0])||0;return s.jsxs("div",{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[s.jsx(sn,{icon:s.jsx(Zc,{size:16}),label:"Uptime",value:typeof e.uptime=="number"?pf(e.uptime):"Waiting…"}),s.jsx(sn,{icon:s.jsx(Ft,{size:16}),label:"IDEs",value:`${t.length}`}),s.jsx(sn,{icon:s.jsx(qo,{size:16}),label:"CLIs",value:`${r.length}`}),s.jsx(sn,{icon:s.jsx(dh,{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(tl,{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(tl,{value:i,max:100,label:"Memory",color:"#3b82f6",detail:a?`${ka(e.totalMem-o)} / ${ka(e.totalMem)}${e.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${ka(e.totalMem)} total`})]})]})]})}function u1(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 m1(e,t,r){const n=[];for(const[a,o]of Object.entries(e.settings)){const i=r!=null&&r.filterSchema?r.filterSchema(o):o;if(i.length===0)continue;const c=t.find(d=>d.type===a);n.push({type:a,displayName:(c==null?void 0:c.displayName)||a,icon:(c==null?void 0:c.icon)||"",category:(c==null?void 0:c.category)||"unknown",schema:i,values:e.values[a]||{}})}return n}function ro(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 kc(e){if(!e||typeof e!="object")return null;if(ro(e))return e;const t=e,r=t.result;return ro(r)?r:ro(t.sourceConfig)?t.sourceConfig:null}function p1(e){const t=e.trim();return t||null}function h1({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var w;const o=t.filter(b=>b.category==="ide"),[i,c]=l.useState(((w=o[0])==null?void 0:w.type)||""),[d,m]=l.useState(""),[u,p]=l.useState(""),[f,y]=l.useState(!1),[g,x]=l.useState(""),[k,j]=l.useState(!1),h=b=>{const C=b.toLowerCase().replace(/[^a-z0-9-]/g,"");m(C),(!u||u===v(d))&&p(v(C))},v=b=>b.split("-").map(C=>C.charAt(0).toUpperCase()+C.slice(1)).join(" "),I=async()=>{if(!(!d||!u||!i)){y(!0),x("");try{const b=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:i});b!=null&&b.success||b!=null&&b.created?(j(!0),a==null||a(d)):x((b==null?void 0:b.error)||"Failed to create provider")}catch(b){x((b==null?void 0:b.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:b=>b.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:k?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:d})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:o.map(b=>s.jsxs("button",{onClick:()=>c(b.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:i===b.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:i===b.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:b.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:i===b.type?"#a78bfa":"var(--text-secondary)"},children:b.displayName})]},b.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:d,onChange:b=>h(b.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",d||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:u,onChange:b=>p(b.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),g&&s.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:g})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:k?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:I,disabled:!d||!u||f,className:"machine-btn",style:{background:d&&u?"rgba(34,197,94,0.12)":void 0,borderColor:d&&u?"rgba(34,197,94,0.3)":void 0,color:d&&u?"#86efac":void 0,opacity:!d||!u||f?.4:1},children:f?"⏳ Creating...":"✨ Create Provider"})]})})]})})}const Sc={"user-custom":"Custom",trusted:"Official","trusted-with-scripts":"Official · runs JS","external-safe":"External · spec-only","external-untrusted":"⚠ External · untrusted JS"},f1={"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 x1({trust:e,sourceName:t,description:r}){const n=t&&(e==="external-safe"||e==="external-untrusted")?`${Sc[e]} · ${t}`:Sc[e];return s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded border whitespace-nowrap ${f1[e]}`,title:r,children:n})}function b1(e){if(typeof e!="string")return null;try{const t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"?t.toString():null}catch{return null}}const g1={detected:"Detected",not_detected:"Not detected",enabled_unchecked:"Enabled (unchecked)",disabled:"Disabled"},Nc={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"},y1={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 Cc(e){if(!e)return"—";const t=e.ok?"OK":"Failed",r=e.message||e.path||e.command||"";return r?`${t} — ${r}`:t}function v1(e){return e==="cli"||e==="acp"}function w1({prov:e,providerInfo:t,savingKey:r,onSetSetting:n,onEnableToggle:a,onDetect:o,onResetCommand:i}){const[c,d]=l.useState(!1),m=(t==null?void 0:t.enabled)===!0||e.values.enabled===!0,u=t==null?void 0:t.machineStatus,p=m&&u==="disabled"?"enabled_unchecked":u||(m?"enabled_unchecked":"disabled"),f=v1(e.category);return s.jsxs("div",{className:"rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("button",{onClick:()=>d(y=>!y),className:"w-full px-4 py-2.5 flex items-center gap-3 text-left",children:[s.jsx("span",{className:"text-base shrink-0",children:e.icon}),s.jsx("span",{className:"text-[13px] font-semibold text-text-primary truncate",children:e.displayName}),s.jsx("span",{className:`text-[9px] font-semibold px-1.5 py-px rounded border ${y1[e.category]??"border-border-subtle text-text-muted"}`,children:e.category.toUpperCase()}),(t==null?void 0:t.trust)&&s.jsx(x1,{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 ${Nc[p]??Nc.disabled}`,children:g1[p]??p}),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 g=Object.entries(y).map(([x,k])=>({k:x,href:b1(k)})).filter(x=>x.href!==null);return g.length===0?null:s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Links:"})," ",g.map(({k:x,href:k})=>s.jsx("a",{href:k,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:"})," ",Cc(t==null?void 0:t.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Verification:"})," ",Cc(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:g=>{const x=parseInt(g.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:g=>void n(e.type,y.key,g.target.value),className:"machine-input text-[11px]",children:y.options.map(g=>s.jsx("option",{value:g,children:g},g))}):s.jsx("input",{type:"text",defaultValue:String(e.values[y.key]??y.default??""),onBlur:g=>void n(e.type,y.key,g.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 wn(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function j1({machineId:e,sendDaemonCommand:t,onChange:r}){const[n,a]=l.useState([]),[o,i]=l.useState([]),[c,d]=l.useState(!1),[m,u]=l.useState(null),[p,f]=l.useState(!1),[y,g]=l.useState(""),[x,k]=l.useState("main"),[j,h]=l.useState(""),[v,I]=l.useState(!1),[w,b]=l.useState(null),[C,N]=l.useState(null),S=l.useCallback(async()=>{if(e){d(!0),u(null);try{const M=wn(await t(e,"list_provider_sources",{}));if(!(M!=null&&M.success)){u((M==null?void 0:M.error)||"Failed to load sources");return}a(M.sources||[]),i(M.conflicts||[])}catch(M){u((M==null?void 0:M.message)||String(M))}finally{d(!1)}}},[e,t]);l.useEffect(()=>{S()},[S]);const T=async()=>{if(y.trim()){I(!0),u(null);try{const M=wn(await t(e,"add_provider_source",{url:y.trim(),ref:x.trim()||"main",...j.trim()?{name:j.trim()}:{}}));M!=null&&M.success?(f(!1),g(""),k("main"),h(""),await S(),r==null||r()):u((M==null?void 0:M.error)||"Failed to add source")}catch(M){u((M==null?void 0:M.message)||String(M))}finally{I(!1)}}},_=async M=>{if(confirm(`Remove provider source ${M}? This deletes the cloned manifests and clears any active-source entries that pointed here.`)){b(M),u(null);try{const A=wn(await t(e,"remove_provider_source",{name:M}));A!=null&&A.success?(await S(),r==null||r()):u((A==null?void 0:A.error)||"Failed to remove source")}catch(A){u((A==null?void 0:A.message)||String(A))}finally{b(null)}}},L=async(M,A)=>{N(`${M}:${A}`),u(null);try{const H=wn(await t(e,"set_active_provider_source",{type:M,sourceName:A}));H!=null&&H.success?(await S(),r==null||r()):u((H==null?void 0:H.error)||"Failed to set active source")}catch(H){u((H==null?void 0:H.message)||String(H))}finally{N(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 S(),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 _(M.name),disabled:w===M.name,className:"machine-btn text-[10px] text-red-400 hover:bg-red-500/[0.10]",children:w===M.name?"…":"Remove"})]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:Object.entries(M.providers).map(([A,H])=>s.jsxs("span",{className:"mr-3",children:[s.jsxs("span",{className:"text-text-secondary",children:[A,":"]})," ",H.length]},A))})]},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(A=>s.jsxs("button",{type:"button",onClick:()=>void L(M.type,A),disabled:C===`${M.type}:${A}`,className:`text-[10px] px-2 py-0.5 rounded border ${M.active===A?"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===A?"Active":`Switch active to ${A}`,children:[M.active===A?"● ":"",A]},A))})]},M.type))})]}),p&&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=>g(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=>k(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:j,onChange:M=>h(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 T(),disabled:v||!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:v?"Cloning…":"Clone + register"})]})]})]})}function k1({machineId:e,providers:t,sendDaemonCommand:r}){var D;const[n,a]=l.useState([]),[o,i]=l.useState(!1),[c,d]=l.useState(null),[m,u]=l.useState("all"),[p,f]=l.useState(!1),[y,g]=l.useState(!1),[x,k]=l.useState(!1),[j,h]=l.useState(null),[v,I]=l.useState("normal"),[w,b]=l.useState(""),[C,N]=l.useState(!1),S=l.useCallback(async()=>{if(e)try{const O=await r(e,"get_provider_source_config",{}),R=kc(O);R&&(h(R),I(R.sourceMode),b(R.explicitProviderDir||""))}catch{}},[e,r]),T=l.useCallback(async()=>{if(e){i(!0);try{const O=await r(e,"get_provider_settings",{}),R=u1(O);if(R){const B=m1(R,t,{filterSchema:E=>E.filter(F=>F.key!=="enabled")});B.sort((E,F)=>E.category.localeCompare(F.category)||E.displayName.localeCompare(F.displayName)),a(B)}}catch{}i(!1)}},[e,t,r]);l.useEffect(()=>{n.length===0&&T(),j||S()},[]);const _=async(O,R,B)=>{d(`${O}.${R}`),a(E=>E.map(F=>F.type===O?{...F,values:{...F.values,[R]:B}}:F));try{const E=await r(e,"set_provider_setting",{providerType:O,key:R,value:B});E!=null&&E.success||T()}catch{T()}d(null)},L=async(O,R)=>{await _(O,"enabled",R),await T()},M=async O=>{d(`${O}.detect`);try{await r(e,"detect_provider",{providerType:O})}finally{await T(),d(null)}},A=async O=>{await _(O,"executablePath",""),await _(O,"executableArgs",""),await T()},H=async()=>{N(!0);try{const O=await r(e,"set_provider_source_config",{providerSourceMode:v,providerDir:p1(w)}),R=kc(O);R?(h(R),I(R.sourceMode),b(R.explicitProviderDir||"")):await S(),await T()}catch{await S()}N(!1)},P=n.filter(O=>m==="all"||O.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(O=>s.jsx("button",{onClick:()=>u(O),className:`machine-btn text-[10px] px-2 py-0.5 ${m===O?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:O.toUpperCase()},O))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>g(O=>!O),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:T,disabled:o,className:"machine-btn text-[10px]",children:[o?"⏳":"↻"," Refresh"]}),s.jsx("button",{onClick:()=>k(O=>!O),className:"machine-btn text-[10px]",title:"Show source configuration (advanced)",children:"⚙ Advanced"})]})]}),y&&s.jsx(j1,{machineId:e,sendDaemonCommand:r,onChange:()=>{T()}}),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:S,className:"machine-btn text-[10px]",children:"↻ Refresh"})]}),s.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),s.jsxs("select",{value:v,onChange:O=>I(O.target.value),className:"machine-input text-[11px]",children:[s.jsx("option",{value:"normal",children:"normal"}),s.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),s.jsx("input",{type:"text",value:w,onChange:O=>b(O.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void H(),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:"})," ",(j==null?void 0:j.userDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Upstream root:"})," ",(j==null?void 0:j.upstreamDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Provider roots:"})," ",((D=j==null?void 0:j.providerRoots)==null?void 0:D.join(" → "))||"—"]})]})]}),o&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings…"}):P.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:P.map(O=>s.jsx(w1,{prov:O,providerInfo:t.find(R=>R.type===O.type),savingKey:c,onSetSetting:_,onEnableToggle:L,onDetect:M,onResetCommand:A},O.type))}),p&&s.jsx(h1,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>f(!1),onCreated:()=>{f(!1),T()}})]})}const S1=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function N1({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function C1(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function I1(e){return e.trim().toLowerCase()}function fa(e,t){const r=I1(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function Li(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=Li(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function M1(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 A1(e,t){return e.filter(r=>fa([r.level,r.message],t))}function Ic(e){return`${e.timestamp}:${e.level}:${e.message}`}function T1(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const i of e.entries)n.set(Ic(i),i);for(const i of t.entries)n.set(Ic(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 _1(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 L1(e,t){return e.split(`
90
+ `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>fa([r],t))}function P1(e,t){return e.filter(r=>fa([r.level,r.category,r.stage,r.interactionId,Li(r.payload)],t))}function R1(e,t){return e.filter(r=>fa([r.kind,r.topic,r.interactionId,Li(r.payload)],t))}function Mc(e){return e==="warn"||e==="error"}function D1({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=>Mc(a.level)).length+r.filter(a=>Mc(a.level)).length}}function $1({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(`
91
+ `)):t.length>0&&a.push(["[daemon logs]",...t].join(`
92
+ `)),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(`
93
+ `)),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(`
94
+ `)),a.join(`
95
+
96
+ `)}function E1({machineId:e,sendDaemonCommand:t}){const[r,n]=l.useState([]),[a,o]=l.useState("empty"),[i,c]=l.useState(""),[d,m]=l.useState([]),[u,p]=l.useState([]),[f,y]=l.useState(null),[g,x]=l.useState(!0),[k,j]=l.useState("info"),[h,v]=l.useState("all"),[I,w]=l.useState(!0),[b,C]=l.useState(!0),[N,S]=l.useState(""),[T,_]=l.useState(""),[L,M]=l.useState(0),A=l.useRef(0),H=l.useRef(0),P=l.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),D=l.useRef([]),O=l.useCallback(()=>{const Y={entries:[],kind:"empty",rawText:"",lastTs:0};P.current=Y,A.current=0,n([]),c(""),o("empty"),w(!0)},[]),R=l.useCallback(()=>{D.current=[],H.current=0,m([]),C(!0)},[]),B=l.useCallback(Y=>{Y!==k&&(O(),j(Y))},[k,O]),E=l.useCallback(Y=>{v(te=>te===Y?te:Y)},[]),F=l.useCallback(()=>{O(),R(),p([]),y(null),S(""),_(""),Es.clear()},[O,R]),Q=l.useCallback(()=>{M(Y=>Y+1)},[]),Z=l.useCallback(async()=>{if(!e)return;const Y=A.current,te=H.current,[fe,Ne]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:k,since:Y}),t(e,"get_debug_trace",N1({count:120,since:te,category:h}))]);if(fe.status==="fulfilled"){const X=fe.value,we=(X==null?void 0:X.result)||X,ge=M1(we),be=T1(P.current,ge,300);P.current=be,A.current=be.lastTs,w(!1),S((X==null?void 0:X.success)===!1?String((X==null?void 0:X.error)||"Could not load daemon logs"):""),o(be.kind),c(be.rawText),n(be.entries)}else w(!1),S(fe.reason instanceof Error?fe.reason.message:"Could not load daemon logs");if(Ne.status==="fulfilled"){const X=Ne.value,we=(X==null?void 0:X.result)||X;if((X==null?void 0:X.success)===!1)_(String((X==null?void 0:X.error)||"Could not load daemon trace"));else if(Array.isArray(we==null?void 0:we.trace)){const ge=we.trace,be=_1(D.current,ge,120),de=ge.reduce((Ie,ee)=>Math.max(Ie,Number(ee.ts||0)),te);D.current=be,de>te&&(H.current=de),_(""),m(be)}else _("");C(!1)}else C(!1),_(Ne.reason instanceof Error?Ne.reason.message:"Could not load daemon trace");p(Es.list({limit:120})),y(Date.now())},[k,e,t,h]);return l.useEffect(()=>{R()},[R,h]),l.useEffect(()=>{if(!e||(Z(),!g))return;const Y=setInterval(()=>{Z()},3e3);return()=>clearInterval(Y)},[g,Z,e,L]),{daemonLogs:r,daemonLogKind:a,daemonRawText:i,debugTrace:d,webEvents:u,lastUpdatedAt:f,autoRefresh:g,logLevel:k,traceCategory:h,daemonLoading:I,traceLoading:b,daemonFetchError:N,traceFetchError:T,setAutoRefresh:x,setLogLevel:B,setTraceCategory:E,refresh:Q,clear:F}}function B1({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:i,traceCount:c,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":o>0||i>0?"ok":"empty",detail:r||(a==="text"?`${i} raw file-fallback line(s)`:`${o} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:n?"error":t?"loading":c>0?"ok":"empty",detail:n||`${c} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:d>0?"ok":"empty",detail:d>0?`${d} local browser event(s)`:"No browser events captured"}]}function Ac(e){return e==="warn"||e==="error"}function O1(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 F1(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 Tc(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function H1(e){const t=zs(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function W1(e){const t=zs(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function K1({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:W1(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:H1(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:F1(o,i),severity:O1(o),message:o,raw:o})}),a.sort((o,i)=>o.ts!==i.ts?o.ts-i.ts:Tc(o.source)-Tc(i.source))}function U1(e){return`${e.source}:${e.severity}:${e.message}`}function z1(e){const t=e.filter(n=>Ac(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!Ac(n.severity))continue;const a=U1(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 G1(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function _c(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${G1(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function V1({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
97
+ `)),a.push(["[source status]",...r.map(i=>`${i.label}: ${i.status} - ${i.detail}`)].join(`
98
+ `)),t.latestIssue&&a.push(["[latest issue]",_c(t.latestIssue)].join(`
99
+ `)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(i=>`${i.count}x ${i.severity.toUpperCase()} ${i.source} ${i.message}`)].join(`
100
+ `));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(_c):["No diagnostic events captured."]].join(`
101
+ `)),a.join(`
102
+
103
+ `)}function q1(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Y1(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function X1({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:i,searchQuery:c,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:p}){const f=C1(n,o),y=A1(e,c),g=L1(t,c),x=P1(f,c),k=R1(a,c),j=q1(y,i),h=i==="all"?g:[],v=Y1(x,i),I=i==="issues"?[]:k,w=D1({daemonLogs:y,daemonRawLines:g,trace:x,webEvents:k}),b=K1({daemonLogs:j,daemonRawLines:h,trace:v,webEvents:I}),C=z1(b),N=B1({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:p,daemonLogKind:r,daemonLogsCount:y.length,daemonRawLineCount:g.length,traceCount:x.length,webEventCount:k.length});return{filteredDaemonLogs:y,filteredDaemonRawLines:g,filteredTraceEntries:x,filteredWebEvents:k,visibleDaemonLogs:j,visibleDaemonRawLines:h,visibleTraceEntries:v,visibleWebEvents:I,quickFilterCounts:w,diagnosticEvents:b,diagnosticsSummary:C,sourceStates:N}}function J1(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Am(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Bo(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 no(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 Pi(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function Q1({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Bo(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Am(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:Pi(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 Z1({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:i,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:m,onClear:u}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(p=>s.jsx("button",{type:"button",onClick:()=>a(p.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===p.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:p.label},p.id))}),s.jsx("input",{value:r,onChange:p=>o(p.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:i,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:d,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function ek({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:S1.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 tk({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:i,traceFetchError:c}){var u,p;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((p=e.latestIssue)==null?void 0:p.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 ${no(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 ${no(d)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[Pi(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:Am(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 ${no(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: ",J1(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 sk({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()," · ",Pi(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function rk({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:i,visibleWebEvents:c,quickFilter:d,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(u=>({...u,timeline:!u.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(u=>s.jsx(Q1,{event:u},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,daemon:!u.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&o.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:d==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((u,p)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${p}`)),e.daemonLogKind!=="text"&&a.map((u,p)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Bo(u.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:u.level==="error"?"ERR":u.level==="warn"?"WRN":u.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:u.message})]},`log-${p}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,trace:!u.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[i.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&i.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children: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(u=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Bo(u.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.level.toUpperCase()}),s.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:zs(u.payload,360)||"No payload"})]},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(u=>({...u,web:!u.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[c.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),c.map(u=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.kind}),u.topic&&s.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:zs(u.payload,360)||"No payload"})]},u.id))]})]})]})}function nk({machineId:e,sendDaemonCommand:t}){const r=E1({machineId:e,sendDaemonCommand:t}),[n,a]=l.useState("info"),[o,i]=l.useState(""),[c,d]=l.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=l.useRef(null),u=l.useRef(!1),p=l.useMemo(()=>X1({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&&p.diagnosticEvents.length>0){const g=u.current?"smooth":"instant";setTimeout(()=>{var x;(x=m.current)==null||x.scrollIntoView({behavior:g}),u.current=!0},50)}},[p.diagnosticEvents.length,r.autoRefresh]);const f=l.useCallback(async()=>{var x;const g=$1({daemonLogs:p.visibleDaemonLogs,daemonRawLines:p.visibleDaemonRawLines,trace:p.visibleTraceEntries,webEvents:p.visibleWebEvents});if(!g.trim()){tt.showToast("No visible logs to copy.","info");return}try{await((x=navigator.clipboard)==null?void 0:x.writeText(g)),tt.showToast("Copied visible logs to clipboard.","success")}catch(k){tt.showToast(k instanceof Error?k.message:"Could not copy visible logs","warning")}},[p.visibleDaemonLogs,p.visibleDaemonRawLines,p.visibleTraceEntries,p.visibleWebEvents]),y=l.useCallback(async()=>{var x;const g=V1({events:p.diagnosticEvents,summary:p.diagnosticsSummary,sources:p.sourceStates});try{await((x=navigator.clipboard)==null?void 0:x.writeText(g)),tt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(k){tt.showToast(k instanceof Error?k.message:"Could not copy diagnostic bundle","warning")}},[p.diagnosticEvents,p.diagnosticsSummary,p.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(Z1,{quickFilter:n,quickFilterCounts:p.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:()=>{y()},onCopyVisible:()=>{f()},onToggleAutoRefresh:()=>r.setAutoRefresh(g=>!g),onRefresh:r.refresh,onClear:r.clear}),s.jsx(ek,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(tk,{diagnosticsSummary:p.diagnosticsSummary,diagnosticEventsCount:p.diagnosticEvents.length,sourceStates:p.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(sk,{patterns:p.diagnosticsSummary.repeatedPatterns}),s.jsx(rk,{streams:r,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:p.diagnosticEvents,visibleDaemonLogs:p.visibleDaemonLogs,visibleDaemonRawLines:p.visibleDaemonRawLines,visibleTraceEntries:p.visibleTraceEntries,visibleWebEvents:p.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:m})]})}function ak(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 Tm(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 ok(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=Tm((o==null?void 0:o.meta)||void 0),d=((a=o==null?void 0:o.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(i)?t.push(o):(i==="stopped"||i==="failed")&&(d||c)?r.push(o):n.push(o)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function ik(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function ao(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 oo(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function io(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Lc(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 lk(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function ck(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 dk(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 uk({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=l.useState(""),[o,i]=l.useState(null),[c,d]=l.useState(!1),m=ey(e,{enabled:!!e,includeSessions:!0,limit:vl,intervalMs:Px}),u=m.diagnostics,p=m.loading,f=m.applyDiagnostics,y=l.useMemo(()=>ak({diagnostics:u,loading:p,refreshing:c,error:n}),[u,p,c,n]),g=l.useMemo(()=>new Map(t.map(_=>[_.sessionId||_.id,_])),[t]),x=l.useCallback(async()=>{if(e){d(!0);try{const _=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:vl}),L=oo(_);if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Could not load hosted runtime diagnostics");f(L.diagnostics||L.result||null),a("")}catch(_){const L=_ instanceof Error?_.message:"Could not load hosted runtime diagnostics";a(L)}finally{d(!1)}}},[f,e,r]);l.useEffect(()=>{!e||u||p||c||x()},[u,p,e,x,c]);const k=l.useCallback(async(_,L)=>{const M=`${_}:${L.sessionId}`;if(!(_==="session_host_stop_session"&&!window.confirm(`Stop ${L.displayName}?
104
+ This will terminate the hosted runtime.`))){i(M);try{const A=await r(e,_,{sessionId:L.sessionId}),H=oo(A);if(!(H!=null&&H.success))throw new Error((H==null?void 0:H.error)||"Session host action failed");const P=_==="session_host_resume_session"?"resumed":_==="session_host_restart_session"?"restarted":"stopped";tt.showToast(`Session host ${P}: ${L.displayName}`,"success"),await x()}catch(A){const H=A instanceof Error?A.message:"Session host action failed";tt.showToast(H,"warning"),a(H)}finally{i(A=>A===M?null:A)}}},[e,x,r]),j=l.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
105
+ 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 L=await r(e,"session_host_prune_duplicate_sessions",{}),M=oo(L);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Duplicate prune failed");const A=M.result||{},H=Array.isArray(A.prunedSessionIds)?A.prunedSessionIds.length:0,P=typeof A.duplicateGroupCount=="number"?A.duplicateGroupCount:0;tt.showToast(`Pruned ${H} duplicate runtime(s) across ${P} group(s)`,"success"),await x()}catch(L){const M=L instanceof Error?L.message:"Duplicate prune failed";tt.showToast(M,"warning"),a(M)}finally{i(L=>L==="session_host_prune_duplicate_sessions"?null:L)}}},[e,x,r]),h=l.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((_,L)=>(L.lastActivityAt||0)-(_.lastActivityAt||0)),[u==null?void 0:u.sessions]),v=l.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:ok(h),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,h]),I=v.liveRuntimes,w=v.recoverySnapshots,b=v.inactiveRecords,C=l.useMemo(()=>dk(I),[I]),N=l.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),S=l.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(_=>_.level==="warn"||_.level==="error")||null,[u==null?void 0:u.recentLogs]),T=(_,L)=>{var E;const M=o===`session_host_resume_session:${_.sessionId}`,A=o===`session_host_restart_session:${_.sessionId}`,H=o===`session_host_stop_session:${_.sessionId}`,P=Tm(_.meta),D=g.get(_.sessionId),O=_.attachedClients.length===1?"1 client":`${_.attachedClients.length} clients`,R=L==="recovery"?"Recover":"Resume",B=ik(L);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:_.displayName||(D==null?void 0:D.cliName)||_.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${ck(_.lifecycle)}`,children:_.lifecycle}),P&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:P})]}),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:_.workspaceLabel||(D==null?void 0:D.runtimeWorkspaceLabel)||_.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:_.runtimeKey}),_.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",_.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((E=_.writeOwner)==null?void 0:E.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:lk(_.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(Yc,{size:11})," ",O]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Lc(_.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",B]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[L==="recovery"&&(_.lifecycle==="interrupted"||_.lifecycle==="failed"||_.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{k("session_host_resume_session",_)},children:M?`${R}ing…`:R}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{k("session_host_restart_session",_)},children:A?"Restarting…":"Restart"}),L==="live"&&(_.lifecycle==="running"||_.lifecycle==="starting"||_.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:()=>{k("session_host_stop_session",_)},children:H?"Stopping…":"Stop"})]})]})},_.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(as,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:tg()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[C>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{j()},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:p||c,children:[s.jsx(oa,{size:13}),p||c?"Refreshing…":"Refresh"]})]})]}),n&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(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})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:w.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Lc(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:io(u.hostStartedAt)})]})]}),S&&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:S.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[io(S.timestamp),S.sessionId?` · ${S.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(qo,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ao("live")}),I.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:I.map(_=>T(_,"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(as,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ao("recovery")}),w.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:w.map(_=>T(_,"recovery"))})]}),b.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:ao("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:b.map(_=>T(_,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),N.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:N.map(_=>{var M;const L=h.find(A=>A.sessionId===_.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:(L==null?void 0:L.displayName)||((M=g.get(_.sessionId))==null?void 0:M.cliName)||_.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[_.action,_.lifecycle?` · ${_.lifecycle}`:"",_.detail?` · ${_.detail}`:"",_.error?` · ${_.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${_.success===!1?"text-red-300":"text-text-secondary"}`,children:io(_.timestamp)})]},`${_.sessionId}:${_.timestamp}:${_.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function mk({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 pk(e,t){const r=Mu(e),n=Ps(e,t),a=di(e,n),o=jr(e,n),i=r==="preview"?"Update to preview":"Update daemon";return a?{visible:!0,showButton:!0,title:o?"Daemon update required":"Version mismatch detected",description:o?"This machine is on an incompatible daemon version. Update it before starting more sessions.":r==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",buttonLabel:i,targetVersion:n,channel:r,required:o,tone:"warn"}:r==="preview"?{visible:!0,showButton:!1,title:n?"Preview daemon is up to date":"Preview update status unknown",description:n?"This machine is already on the current preview daemon target.":"The app is connected to preview, but the server did not report a preview target version yet.",buttonLabel:i,targetVersion:n,channel:r,required:!1,tone:n?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:i,targetVersion:n,channel:r,required:!1,tone:"info"}}function lo({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 co({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 hk({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:i}){const c=n.slice(0,6),d=r.slice(0,4),u=pk(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(lo,{icon:s.jsx(Ns,{size:13}),children:"Current Chats"}),s.jsx(co,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(p=>{const f=Ro(p);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(p),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:ot(p)}),f>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:ia(f)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ks(p)})]},p.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(lo,{icon:s.jsx(Zc,{size:13}),children:"Recent Launches"}),s.jsx(co,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(p=>{const{metaText:f,updatedLabel:y}=Hu(p);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(p),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:p.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})]},p.id)})})})]}),u.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(lo,{icon:s.jsx(Fs,{size:13}),children:"Daemon Update"}),s.jsx(co,{className:u.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":u.tone==="info"?"border-sky-500/20 bg-sky-500/5":"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[u.description,u.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",u.targetVersion,u.channel?` (${u.channel})`:""]})]}),u.showButton?s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[s.jsx(oa,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:u.buttonLabel})]}):s.jsx("div",{className:u.tone==="good"?"text-xs font-medium text-emerald-300":"text-xs font-medium text-sky-300",children:"No preview update action is needed."})]})})]})]})}function fk({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:m,handleWorkspaceSetDefault:u}=o,[p,f]=l.useState(!1),[y,g]=l.useState(""),[x,k]=l.useState([]),[j,h]=l.useState(!1),[v,I]=l.useState(""),w=l.useCallback(async C=>{h(!0),I("");try{const N=await gi(i,e,C);g(N.path),k(N.directories)}catch(N){I(N instanceof Error?N.message:"Could not load folder")}finally{h(!1)}},[e,i]),b=l.useCallback(()=>{f(!0);const C=[...r.map(S=>S.workspace),...n.map(S=>S.workspace),...a.map(S=>S.workspace)],N=bi(t.platform,xi(C,t.defaultWorkspacePath,(t.workspaces||[]).map(S=>S.path)));w(N)},[a,n,r,w,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-4 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(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:b,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 N=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 ${N?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:N?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void u(N?null:C.id),className:`text-base leading-none shrink-0 transition-colors ${N?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary truncate",children:xd(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)})})]}),p&&s.jsx(vi,{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:j,error:v,confirmLabel:"Add workspace",onClose:()=>f(!1),onNavigate:C=>{w(C)},onConfirm:C=>{(async()=>{if(!C)return;await d(C)&&f(!1)})()}})]})}function xk({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(fk,{machineId:t,machine:e,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function bk({onNicknameSynced:e}={}){var Ie,ee,ve,ce,W,ne,ue,me,J,q;const{id:t}=Cp(),r=Dr(),n=Ko(),{sendCommand:a}=it(),o=Or(),i=pu(),c=Kd(),d=c.ides||[],m=c.initialLoaded??!0,u=d.find($=>$.id===t&&$.type==="adhdev-daemon"),p=d.some($=>$.type==="adhdev-daemon"),f=t?(Ie=c.connectionRetryStatuses)==null?void 0:Ie[t]:void 0,y=!!(f!=null&&f.blocked),[g,x]=l.useState("workspace"),[k,j]=l.useState(null);l.useCallback(($,re)=>{j({daemonId:$,workspace:re})},[]);const[,h]=l.useState("ide"),v=l.useRef(null),[I,w]=l.useState(null),b=l.useRef("__home__"),[C,N]=l.useState("__home__"),[S,T]=l.useState(!1),_=l.useRef(null);l.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||o(t,{minFreshMs:3e4}).catch(()=>{})},[o,u,t]),l.useEffect(()=>{if(!t||!u||g!=="overview")return;const $=u.machine;(typeof($==null?void 0:$.cpus)!="number"||typeof($==null?void 0:$.totalMem)!="number"||typeof($==null?void 0:$.arch)!="string"||typeof($==null?void 0:$.release)!="string")&&i(t,{minFreshMs:3e4}).catch(()=>{})},[g,i,u,t]),Zg(t&&g==="overview"?[t]:[],{enabled:g==="overview",intervalMs:Ax});const L=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},M=c1({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:_});l.useEffect(()=>tt.onToast(re=>{c.setToasts(je=>{if(je.some($e=>$e.message===re.message&&re.timestamp-$e.timestamp<3e3))return je;const Pe={id:re.id,message:re.message,type:re.type,timestamp:re.timestamp,targetKey:re.targetKey,actions:re.actions};return[...je.slice(-4),Pe]});const xe=re.duration||5e3;setTimeout(()=>c.setToasts(je=>je.filter(ae=>ae.id!==re.id)),xe)}),[c]);const A=(u==null?void 0:u.availableProviders)||[],H={};for(const $ of A)H[$.type]=$.icon;const P=u?{id:u.id,hostname:bd(u,{fallbackId:u.id}),platform:((ee=u.machine)==null?void 0:ee.platform)||"unknown",arch:((ve=u.machine)==null?void 0:ve.arch)||"",cpus:((ce=u.machine)==null?void 0:ce.cpus)||0,totalMem:((W=u.machine)==null?void 0:W.totalMem)||0,freeMem:(ne=u.machine)==null?void 0:ne.freeMem,availableMem:(ue=u.machine)==null?void 0:ue.availableMem,loadavg:(me=u.machine)==null?void 0:me.loadavg,uptime:(J=u.machine)==null?void 0:J.uptime,release:((q=u.machine)==null?void 0:q.release)||"",cdpConnected:!!u.cdpConnected,machineNickname:u.machineNickname||null,p2p:u.p2p?{screenshotActive:!1,...u.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:u.detectedIdes||[],workspaces:u.workspaces||[],defaultWorkspaceId:u.defaultWorkspaceId??u.activeWorkspaceId??null,defaultWorkspacePath:u.defaultWorkspacePath??u.activeWorkspacePath??null}:null,D=d.filter($=>$.daemonId===t&&$.type!=="adhdev-daemon").filter($=>!Mr($)&&!Ds($)).map($=>({id:$.id,sessionId:$.sessionId,type:$.type,version:$.version||"",instanceId:$.instanceId||"",status:$.status,workspace:$.workspace||null,terminals:$.terminals||0,aiAgents:wf($.aiAgents||($.agents||[]).map(re=>({id:re.name,name:re.name,status:re.status,version:re.version}))),activeChat:$.activeChat||null,chats:$.chats||[],childSessions:$.childSessions||[],cdpConnected:$.cdpConnected||!1,daemonId:t,lastMessageAt:$.lastMessageAt})),O=d.filter($=>$.daemonId===t&&Mr($)).map($=>({id:$.id,sessionId:$.sessionId,type:$.type,cliName:$.cliName||$.type,status:$.status,workspace:$.workspace||"",activeChat:$.activeChat||null,providerSessionId:$.providerSessionId,mode:$.mode,runtimeKey:$.runtimeKey,runtimeDisplayName:$.runtimeDisplayName,runtimeWorkspaceLabel:$.runtimeWorkspaceLabel,runtimeWriteOwner:$.runtimeWriteOwner||null,runtimeAttachedClients:$.runtimeAttachedClients||[],daemonId:t,lastMessageAt:$.lastMessageAt})),R=d.filter($=>$.daemonId===t&&Ds($)).map($=>({id:$.id,sessionId:$.sessionId,type:$.type,acpName:$.cliName||$.type,status:$.status,workspace:$.workspace||"",activeChat:$.activeChat||null,providerSessionId:$.providerSessionId,daemonId:t,lastMessageAt:$.lastMessageAt})),B=u?Pt(u,{fallbackId:t}):"",E="workspace",F=n.state,Q=F==null?void 0:F.initialMachineTab,Z=F==null?void 0:F.initialWorkspaceCategory;F==null||F.initialWorkspaceId,F==null||F.initialWorkspacePath;const Y=Q==="ides"||Q==="clis"||Q==="acps"?"workspace":Q||E,te=Q==="ides"?"ide":Q==="clis"?"cli":Q==="acps"?"acp":Z,fe=[...D.map($=>{var re;return{id:`ide:${$.type}:${$.workspace||""}`,label:((re=$.activeChat)==null?void 0:re.title)||$.type,kind:"ide",providerType:$.type,subtitle:$.workspace||void 0,workspace:$.workspace||void 0,lastLaunchedAt:$.lastMessageAt||0}}),...O.map($=>{var re;return{id:`cli:${$.type}:${$.workspace||""}`,label:((re=$.activeChat)==null?void 0:re.title)||$.cliName,kind:"cli",providerType:$.type,providerSessionId:$.providerSessionId,subtitle:$.workspace||void 0,workspace:$.workspace||void 0,lastLaunchedAt:$.lastMessageAt||0}}),...R.map($=>{var re;return{id:`acp:${$.type}:${$.workspace||""}`,label:((re=$.activeChat)==null?void 0:re.title)||$.acpName,kind:"acp",providerType:$.type,providerSessionId:$.providerSessionId,subtitle:js($.summaryMetadata)||$.workspace||void 0,workspace:$.workspace||void 0,lastLaunchedAt:$.lastMessageAt||0}})].sort(($,re)=>(re.lastLaunchedAt||0)-($.lastLaunchedAt||0)),Ne=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map($=>({id:$.id,label:$.title||$.providerName||$.providerType,kind:$.kind,providerType:$.providerType,providerSessionId:$.providerSessionId,subtitle:js($.summaryMetadata)||$.workspace||void 0,workspace:$.workspace,summaryMetadata:$.summaryMetadata,lastLaunchedAt:$.lastLaunchedAt})):fe,X=l.useMemo(()=>{var re;const $=((re=c.connectionStates)==null?void 0:re[t||""])||void 0;return d.filter(xe=>xe.daemonId===t&&xe.type!=="adhdev-daemon").flatMap(xe=>ci(xe,{connectionStates:t&&$?{[t]:$}:void 0,defaultConnectionState:$})).filter(xe=>!(xe.transport==="pty"&&xe.mode==="terminal")).sort((xe,je)=>Ro(je)-Ro(xe))},[d,c.connectionStates,t]),we=l.useCallback($=>{const re=Pu($);re&&r(Lr(re))},[r]),ge=l.useCallback(()=>{v.current&&(T(!0),v.current().finally(()=>{v.current=null,T(!1),w(null)}))},[]),be=l.useCallback($=>{if(!P)return;const{options:re,selectedKey:xe}=Fu({machine:P,currentWorkspacePath:$.workspace}),je=async()=>{h($.kind),x("workspace")};v.current=async()=>{const ae=re.find(Re=>Re.key===b.current),Pe=(ae==null?void 0:ae.workspacePath)??null,$e=(ae==null?void 0:ae.workspaceId)??null;if($.kind==="ide"&&$.providerType){await M.handleLaunchIde($.providerType,Pe?{workspace:Pe}:void 0);return}if(($.kind==="cli"||$.kind==="acp")&&$.providerType){await M.runLaunchCliCore({cliType:$.providerType,dir:$e?void 0:Pe||"",workspaceId:$e||void 0,model:$.kind==="acp"&&yd($.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:$.providerSessionId});return}await je()},b.current=xe,N(xe),w({title:$.kind==="ide"?Gn("restart-ide",$.label):$.providerSessionId?Qd($.label):Gn("start-fresh",$.label),description:$.kind==="ide"?Vn("restart-ide"):$.providerSessionId?Zd():Vn("start-fresh"),confirmLabel:$.kind==="ide"?qn("restart-ide"):$.providerSessionId?zn(!0):qn("start-fresh"),busyLabel:$.kind==="ide"?Yn("restart-ide"):$.providerSessionId?ii(!0):Yn("start-fresh"),workspaceOptions:re,details:[{label:"Mode",value:$.kind.toUpperCase()},...$.providerType?[{label:"Provider",value:$.providerType}]:[]]})},[M,P]);if(l.useEffect(()=>{x(Y)},[E,Y,t]),l.useEffect(()=>{te&&h(te)},[te,t]),!P)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:L,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const de=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ft,{size:14})," Workspace"]}),count:D.length+O.length+R.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(as,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(aa,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ih,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(nh,{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:L,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:$=>M.setNicknameInput($.target.value),onKeyDown:$=>{$.key==="Enter"&&M.handleSaveNickname(),$.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(P.machineNickname||"")},title:"Click to set nickname",children:B}),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:[P.platform," · ",P.arch]}),s.jsxs("span",{children:[P.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),P.p2p.available&&s.jsxs("span",{children:["P2P ",P.p2p.state==="connected"?"connected":P.p2p.state]}),P.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:P.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:de.map($=>s.jsxs("button",{onClick:()=>x($.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${g===$.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[$.label,$.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${g===$.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:$.count})]},$.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[g==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(hk,{machineEntry:u,providers:A,recentLaunches:Ne,currentConversations:X,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",Au(u))}catch{}},onOpenRecent:be,onOpenConversation:we}),s.jsx(xk,{machine:P,machineId:t,ideSessions:D,cliSessions:O,acpSessions:R,actions:M,sendDaemonCommand:a})]}),g==="providers"&&s.jsx(k1,{machineId:t,providers:A,sendDaemonCommand:a}),g==="overview"&&s.jsx(d1,{machine:P,ideSessions:D,cliSessions:O,acpSessions:R}),g==="session-host"&&s.jsx(uk,{machineId:t,cliSessions:O,sendDaemonCommand:a}),g==="logs"&&s.jsx(nk,{machineId:t,sendDaemonCommand:a})]})})}),M.launchPick&&P&&s.jsx(mk,{machine:P,launchPick:M.launchPick,actions:M}),I&&s.jsx(Ou,{title:I.title,description:I.description,details:I.details,workspaceOptions:I.workspaceOptions,selectedWorkspaceKey:C,onWorkspaceChange:$=>{b.current=$,N($)},confirmLabel:I.confirmLabel,busyLabel:I.busyLabel,busy:S,onConfirm:ge,onCancel:()=>{v.current=null,w(null)}}),k&&s.jsx(Mm,{daemonId:k.daemonId,workspace:k.workspace,onClose:()=>j(null)}),s.jsx(tu,{toasts:c.toasts||[],onDismiss:$=>c.setToasts(re=>re.filter(xe=>xe.id!==$)),onClickToast:$=>{$.targetKey&&r(Lr($.targetKey))}}),s.jsx("style",{children:`
106
+ @keyframes toast-in {
107
+ from { opacity: 0; transform: translateX(40px); }
108
+ to { opacity: 1; transform: translateX(0); }
109
+ }
110
+ `})]})}const gk={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},_m=l.createContext(null);function yk(){const e=l.useContext(_m);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function sa({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("polyline",{points:"1 20 1 14 7 14"}),s.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function vk({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"6",cy:"18",r:"3"}),s.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function wk({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"3 6 5 6 21 6"}),s.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})}function jk({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function Lm({status:e}){const r={online:{color:"#22c55e",label:"Online"},dirty:{color:"#f59e0b",label:"Dirty"},offline:{color:"#6b7280",label:"Offline"},degraded:{color:"#ef4444",label:"Degraded"},enabled:{color:"#22c55e",label:"Enabled"},pending:{color:"#a855f7",label:"Pending"},assigned:{color:"#3b82f6",label:"Assigned"},completed:{color:"#22c55e",label:"Completed"},failed:{color:"#ef4444",label:"Failed"},unknown:{color:"#6b7280",label:"Unknown"}}[e]||{color:"#6b7280",label:e};return s.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-md",style:{background:r.color+"15",color:r.color,border:`1px solid ${r.color}25`},children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:r.color}}),r.label]})}function kk(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function Sk({meshes:e,loading:t,error:r,onDismissError:n,daemons:a,features:o,showCreate:i,onToggleCreate:c,createName:d,onCreateNameChange:m,createRepoIdentity:u,onCreateRepoIdentityChange:p,createRepoRemoteUrl:f,onCreateRepoRemoteUrlChange:y,newMeshDaemonId:g,onNewMeshDaemonIdChange:x,newMeshWorkspace:k,onNewMeshWorkspaceChange:j,createPickerWorkspaces:h,onSelectMesh:v,onCreate:I,onCancelCreate:w}){return s.jsxs(Kr,{icon:s.jsx(Jt,{}),title:"Repo Meshes",subtitle:`${e.length} mesh${e.length!==1?"es":""}`,widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,children:"+ Create Mesh"}),children:[r&&s.jsx(ns,{variant:"error",onDismiss:n,className:"mb-4",children:r}),i&&s.jsxs(ct,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:"Create Repo Mesh"}),o.createDaemonPicker&&s.jsx(jt,{label:"Create on machine",hint:"Mesh setup is stored by the selected daemon.",children:s.jsx("select",{className:"input w-full",value:g,onChange:b=>x(b.target.value),disabled:!a.length,children:a.length===0?s.jsx("option",{value:"",children:"No connected daemon"}):a.map(b=>s.jsx("option",{value:b.id,children:kk(b)},b.id))})}),o.createDaemonPicker&&s.jsx(jt,{label:"Workspace",hint:"Choose from workspaces registered by the selected daemon.",children:s.jsx("select",{className:"input w-full",value:k,onChange:b=>j(b.target.value),disabled:!g||!h.length,children:g?h.length===0?s.jsx("option",{value:"",children:"No registered workspaces"}):h.map(b=>s.jsx("option",{value:b.path,children:b.label?`${b.label} · ${b.path}`:b.path},b.id||b.path)):s.jsx("option",{value:"",children:"Select a machine first"})})}),s.jsx(jt,{label:"Name",children:s.jsx(wr,{value:d,onChange:b=>m(b.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(jt,{label:"Repo remote URL (optional)",hint:"Provide a remote URL OR a stable identity.",children:s.jsx(wr,{value:f,onChange:b=>y(b.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(jt,{label:"Repo identity (optional)",hint:"Provide a remote URL OR a stable identity.",children:s.jsx(wr,{value:u,onChange:b=>p(b.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:I,disabled:!d.trim()||!f.trim()&&!u.trim()||o.createDaemonPicker&&(!g||!k),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:w,children:"Cancel"})]})]}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):e.length===0?s.jsx(ma,{icon:s.jsx(Jt,{}),title:"No Repo Meshes",description:a.length>0?"Create a mesh to get started.":"Connect an ADHDev daemon first.",action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!a.length,onClick:c,children:"Create First Mesh"})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(b=>{var C;return s.jsx("button",{type:"button",onClick:()=>v(b.id),className:"w-full text-left bg-bg-glass border border-border-subtle rounded-xl px-5 py-4 transition-colors hover:border-border-default hover:bg-bg-secondary/70",children:s.jsxs("div",{className:"flex justify-between items-start",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(Jt,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:b.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:b.repoIdentity||b.repo_identity||"No repo identity"}),(b.defaultBranch||b.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(vk,{size:11}),b.defaultBranch||b.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(b.createdAt||b.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((C=b.nodes)==null?void 0:C.length)??b.nodeCount??0," node(s)"]})]})]})},b.id)})})]})}function Pc(e){if(e.status!=="completed"&&e.status!=="failed")return null;const t=e.dispatchTimestamp?new Date(e.dispatchTimestamp).getTime():NaN,r=e.updatedAt?new Date(e.updatedAt).getTime():NaN;if(!Number.isFinite(t)||!Number.isFinite(r)||r<t)return null;const n=Math.round((r-t)/1e3);if(n<60)return`${n}s`;const a=Math.floor(n/60);return a<60?`${a}m ${n%60}s`:`${Math.floor(a/60)}h ${a%60}m`}function Nk({queueSummary:e,queueLoading:t,queueError:r,activeDaemonId:n,onRefresh:a}){return s.jsxs(ct,{title:"Queue",description:"Inspect active queue work separately from historical completed, failed, and cancelled task records.",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-7 gap-2 flex-1 min-w-[260px]",children:[["Active",(e==null?void 0:e.active)??0,"text-accent-primary"],["Pending",(e==null?void 0:e.activeCounts.pending)??(e==null?void 0:e.counts.pending)??0,"text-text-primary"],["Assigned",(e==null?void 0:e.activeCounts.assigned)??(e==null?void 0:e.counts.assigned)??0,"text-blue-400"],["Stale",(e==null?void 0:e.staleAssignedCount)??0,"text-amber-400"],["Historical",(e==null?void 0:e.historical)??0,"text-text-muted"],["Completed",(e==null?void 0:e.historicalCounts.completed)??(e==null?void 0:e.counts.completed)??0,"text-green-400"],["Failed",(e==null?void 0:e.historicalCounts.failed)??(e==null?void 0:e.counts.failed)??0,"text-red-400"]].map(([o,i,c])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-text-muted",children:o}),s.jsx("div",{className:`text-lg font-bold ${c}`,children:i})]},String(o)))}),s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:a,disabled:t||!n,children:[s.jsx(sa,{size:13}),t?"Loading...":"Refresh Queue"]})]}),r&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:r}),e?e.recent.length===0?s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:"Queue is empty."}):s.jsx("div",{className:"flex flex-col gap-2",children:e.recent.map(o=>{var i;return s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"font-mono text-[11px] text-text-muted",children:o.id.slice(0,12)}),s.jsx(Lm,{status:o.status}),o.staleAssigned&&s.jsx("span",{className:"text-[10px] text-amber-300 bg-amber-500/10 border border-amber-500/20 rounded-full px-2 py-0.5",title:o.staleReason||"Stale assignment",children:"stale"}),(((i=o.waitingOn)==null?void 0:i.length)??0)>0&&s.jsxs("span",{className:"text-[10px] text-sky-300 bg-sky-500/10 border border-sky-500/20 rounded-full px-2 py-0.5",title:`Waiting on: ${o.waitingOn.join(", ")}`,children:["waits on ",o.waitingOn.length," task",o.waitingOn.length>1?"s":""]}),o.blockedReason&&s.jsx("span",{className:"text-[10px] text-red-300 bg-red-500/10 border border-red-500/20 rounded-full px-2 py-0.5",title:o.blockedReason,children:"blocked"}),Pc(o)&&s.jsxs("span",{className:"text-[10px] text-text-muted bg-bg-tertiary border border-border-subtle rounded-full px-2 py-0.5",title:"Dispatched → terminal wall clock",children:[Pc(o),(o.requeueCount??0)>0?` · ${o.requeueCount} retr${o.requeueCount===1?"y":"ies"}`:""]})]}),o.message&&s.jsx("div",{className:"text-[12px] text-text-primary truncate",children:o.message})]}),s.jsxs("div",{className:"text-right text-[10px] text-text-muted shrink-0",children:[o.nodeId&&s.jsxs("div",{children:["node ",o.nodeId.slice(0,10)]}),o.sessionId&&s.jsxs("div",{children:["session ",o.sessionId.slice(0,10)]}),o.updatedAt&&s.jsx("div",{children:new Date(o.updatedAt).toLocaleTimeString()})]})]})},o.id)})}):s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:"Refresh the queue to view host-owned task counts and recent assignments."})]})}function Ck(e){return e==="refine_blocked_review"?{label:"Blocked review",color:"text-amber-400 bg-amber-500/10 border-amber-500/20"}:{label:"Merge candidate",color:"text-blue-400 bg-blue-500/10 border-blue-500/20"}}function Ik(e){if(!e)return null;const t=typeof e.stage=="string"?e.stage:null,r=e.passed===!0;if(!t)return null;const n={ran:r?"text-green-400 bg-green-500/10 border-green-500/20":"text-red-400 bg-red-500/10 border-red-500/20",cached:"text-blue-400 bg-blue-500/10 border-blue-500/20",failed:"text-red-400 bg-red-500/10 border-red-500/20",skipped:"text-text-muted bg-bg-secondary border-border-subtle",legacy:"text-text-muted bg-bg-secondary border-border-subtle",not_configured:"text-text-muted bg-bg-secondary border-border-subtle"};return{label:`bootstrap: ${t}`,color:n[t]??"text-text-muted bg-bg-secondary border-border-subtle"}}function Mk({file:e}){const r={added:"text-green-400",deleted:"text-red-400",modified:"text-amber-400",renamed:"text-blue-400"}[e.status??""]??"text-text-muted";return s.jsxs("div",{className:"flex items-center justify-between gap-2 py-0.5",children:[s.jsx("span",{className:`text-[11px] font-mono truncate flex-1 ${r}`,children:e.path}),(e.insertions!=null||e.deletions!=null)&&s.jsxs("span",{className:"text-[10px] text-text-muted shrink-0",children:[e.insertions!=null&&s.jsxs("span",{className:"text-green-400",children:["+",e.insertions]}),e.deletions!=null&&s.jsxs("span",{className:"text-red-400 ml-1",children:["-",e.deletions]})]})]})}function Ak({item:e,activeDaemonId:t,sendCommand:r,onDismiss:n,onRefineNode:a,onRequeueLast:o}){var I,w,b;const[i,c]=l.useState(null),[d,m]=l.useState(null),[u,p]=l.useState(!1),[f,y]=l.useState(null),{label:g,color:x}=Ck(e.reviewReason),k=Ik(e.evidence.bootstrap),j=((I=e.diffSummary)==null?void 0:I.files)??[],h=((w=e.diffSummary)==null?void 0:w.baseRef)??null,v=l.useCallback(async C=>{if(!(!e.workspace||!t)){if(i===C){c(null),m(null);return}c(C),m(null),p(!0),y(null);try{const N=await r(t,"git_diff_file",{workspace:e.workspace,path:C,...h?{base:h}:{}});(N==null?void 0:N.success)!==!1&&typeof(N==null?void 0:N.diff)=="string"?m(N.diff):(N==null?void 0:N.diff)!=null?m(String(N.diff)):y((N==null?void 0:N.error)||"No diff available")}catch(N){y((N==null?void 0:N.message)||"Failed to load diff")}finally{p(!1)}}},[e.workspace,t,r,i,h]);return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary p-4 space-y-3",children:[s.jsxs("div",{className:"flex flex-wrap items-start gap-2 justify-between",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2 min-w-0",children:[s.jsx("span",{className:"text-[12px] font-semibold text-text-primary font-mono truncate max-w-[240px]",children:e.branch??e.nodeId}),s.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${x}`,children:g}),k&&s.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${k.color}`,children:k.label}),e.activeRefineJob&&s.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded border text-blue-400 bg-blue-500/10 border-blue-500/20",children:"refine running"})]}),s.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[s.jsx("button",{className:"btn btn-primary btn-sm text-[11px]",onClick:()=>a(e.nodeId),disabled:!!e.activeRefineJob,children:"Refine"}),s.jsx("button",{className:"btn btn-secondary btn-sm text-[11px]",onClick:()=>o(e.nodeId),children:"Requeue"}),s.jsx("button",{className:"btn btn-secondary btn-sm text-[11px]",onClick:()=>n(e.nodeId),children:"Dismiss"})]})]}),e.workspace&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate",children:e.workspace}),e.evidence.available&&s.jsxs("div",{className:"text-[11px] text-text-secondary space-y-0.5",children:[e.evidence.source==="task_completion"&&e.evidence.worker&&s.jsxs("span",{children:["Last task: ",s.jsx("span",{className:e.evidence.worker.status==="success"?"text-green-400":"text-red-400",children:e.evidence.worker.status}),e.evidence.worker.classification&&s.jsxs("span",{className:"text-text-muted ml-1",children:["(",e.evidence.worker.classification,")"]}),e.evidence.worker.errors.length>0&&s.jsxs("span",{className:"text-red-400 ml-1",children:["· ",e.evidence.worker.errors[0]]})]}),e.evidence.source==="refine_job"&&s.jsxs("span",{children:["Refinery: ",s.jsx("span",{className:"text-amber-400",children:e.convergence.status}),e.convergence.nextStep&&s.jsxs("span",{className:"text-text-muted ml-1",children:["→ ",e.convergence.nextStep]})]})]}),e.diffSummary&&e.diffSummary.files.length>0&&s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-3",children:[s.jsxs("span",{children:[e.diffSummary.totalFiles," file",e.diffSummary.totalFiles!==1?"s":""]}),s.jsxs("span",{className:"text-green-400",children:["+",e.diffSummary.totalInsertions]}),s.jsxs("span",{className:"text-red-400",children:["-",e.diffSummary.totalDeletions]}),e.diffSummary.truncated&&s.jsx("span",{className:"text-amber-400",children:"truncated"}),h&&s.jsxs("span",{className:"font-mono",children:["vs ",h]})]}),s.jsxs("div",{className:"border border-border-subtle rounded px-2 py-1 bg-bg-primary space-y-0.5",children:[j.slice(0,20).map(C=>s.jsxs("div",{children:[s.jsx("button",{className:"w-full text-left hover:bg-bg-secondary rounded px-1 transition-colors",onClick:()=>v(C.path),children:s.jsx(Mk,{file:C})}),i===C.path&&s.jsx("div",{className:"mt-1 mb-1",children:s.jsx(Im,{diff:d??"",loading:u,error:f??void 0,truncated:!1,className:"text-[10px]"})})]},C.path)),j.length>20&&s.jsxs("div",{className:"text-[10px] text-text-muted px-1 pt-0.5",children:["+",j.length-20," more files"]})]})]}),((b=e.diffSummary)==null?void 0:b.error)&&s.jsxs("div",{className:"text-[11px] text-amber-400",children:["Diff probe: ",e.diffSummary.error]})]})}function Tk({items:e,loading:t,error:r,remoteNodesExcluded:n,meshId:a,activeDaemonId:o,onRefresh:i,onDismiss:c,onRefineNode:d,onRequeueLast:m,sendCommand:u}){return s.jsxs(ct,{title:"Review Inbox",description:"Local worktree nodes that need review: merge candidates and Refinery-blocked results. Click a file to preview its diff.",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[e.length>0&&s.jsxs("span",{className:"text-[12px] font-semibold text-accent-primary",children:[e.length," item",e.length!==1?"s":""]}),n&&s.jsx("span",{className:"text-[10px] text-text-muted px-1.5 py-0.5 rounded border border-border-subtle bg-bg-secondary",children:"remote nodes excluded"})]}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:i,disabled:t,children:[s.jsx(sa,{size:12}),t?"Loading...":"Refresh"]})]}),r&&s.jsx("div",{className:"mb-3 text-[12px] text-red-400 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2",children:r}),!t&&!r&&e.length===0&&s.jsxs("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:["No local nodes require review.",n&&" Remote nodes are excluded in this view."]}),s.jsx("div",{className:"space-y-3",children:e.map(p=>s.jsx(Ak,{item:p,activeDaemonId:o,sendCommand:u,onDismiss:c,onRefineNode:d,onRequeueLast:m},p.nodeId))})]})}function _k(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function Lk(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 Pm(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 Pk(e){const t=Pm(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 Rk(e){return e.isLocalWorktree===!0}function Dk(e,t){const r=t;return[...Array.isArray(r==null?void 0:r.cliSessions)?r.cliSessions:[],...Array.isArray(r==null?void 0:r.acpSessions)?r.acpSessions:[],...Array.isArray(r==null?void 0:r.sessions)?r.sessions:[]].filter(a=>{var o;return((o=a==null?void 0:a.settings)==null?void 0:o.meshNodeId)===e.id||(a==null?void 0:a.workspace)===e.workspace}).map(a=>{var o;return{id:a.sessionId||a.id||a.instanceId||"unknown",provider:a.providerType||a.cliType||a.acpType||a.type||"unknown",status:a.status||((o=a.activeChat)==null?void 0:o.status)||"unknown"}})}function Rc(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function $k(e,t){var r;return(e==null?void 0:e.ownerName)||(e==null?void 0:e.userName)||((r=e==null?void 0:e.user)==null?void 0:r.name)||t||"You"}function Ek({nodes:e,meshQueue:t,activeDaemon:r,daemons:n,selectedMeshId:a,userName:o,features:i,coordinatorDaemonId:c,nodeProviderPriorityDrafts:d,onNodeProviderPriorityDraftChange:m,availableCliProviders:u,savingNodePolicyId:p,onUpdateNodeProviderPriority:f,nodeSystemPromptDrafts:y,onNodeSystemPromptDraftChange:g,savingNodeSystemPromptId:x,onSaveNodeSystemPrompt:k,selectedNodeId:j,onSelectNode:h,showAddNode:v,onShowAddNode:I,onCancelAddNode:w,nodeWorkspace:b,onNodeWorkspaceChange:C,nodeProviderPriority:N,onNodeProviderPriorityChange:S,nodeDaemonId:T,onNodeDaemonIdChange:_,nodeCustomPath:L,onNodeCustomPathChange:M,nodePickerWorkspaces:A,nodePickerProviders:H,attachableDaemons:P,onAddNode:D,onRemoveNode:O}){return s.jsxs(ct,{title:i.addNodeDaemonPicker?`Attached machine daemons (${e.length})`:"Nodes",description:i.addNodeDaemonPicker?"Setup inventory only. Live graph, git, session, queue, and node detail truth is owned by the Mesh Host status above.":"Workspaces participating in this mesh.",children:[i.addNodeDaemonPicker&&s.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Machine daemon candidates"}),s.jsx("div",{className:"text-[12px] text-text-muted",children:"Choose connected daemons to attach to the selected Mesh Host setup."})]}),s.jsxs("span",{className:"text-[11px] text-text-muted",children:[P.length," available"]})]}),n.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:"No connected machine daemons are currently available."}):P.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:"All connected machine daemons are already attached."}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:P.map(R=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${R.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{_(R.id),C(""),M(!1),S(_r(Tr(R.availableProviders||[]))),I()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate",children:Rc(R)}),R.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary",children:"selected host"})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:R.id}),s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted",children:[(R.workspaces||[]).length," workspace(s) detected"]})]},R.id))})]}),!v&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:I,children:[s.jsx(jk,{size:13})," ",i.addNodeDaemonPicker?"Attach Machine Daemon":"+ Add Node"]}),v&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:i.addNodeDaemonPicker?"Attach Machine Daemon":"Add Node"}),s.jsx("button",{onClick:()=>{w(),_(""),M(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(yt,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(jt,{label:"Machine",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:T,onChange:R=>{var B;_(R.target.value),C(""),M(!1),S(_r(Tr(((B=n.find(E=>E.id===R.target.value))==null?void 0:B.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:"Select a machine..."}),n.map(R=>s.jsx("option",{value:R.id,children:Rc(R)},R.id))]})}),(i.addNodeDaemonPicker?T:!0)&&s.jsx(jt,{label:"Workspace Path",children:i.addNodeDaemonPicker&&!L&&A.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:A.map(R=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${b===R.path?"border-accent-primary bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-primary hover:bg-violet-500/10 text-text-primary"}`,onClick:()=>C(R.path),children:[s.jsx("span",{className:"font-medium block truncate",children:R.label||R.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:R.path})]},R.id||R.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{M(!0),C("")},children:"Or enter a custom path →"})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(wr,{value:b,onChange:R=>C(R.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:R=>{R.key==="Enter"&&D()}}),A.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{M(!1),C("")},children:"← Pick from saved workspaces"})]}):(()=>{var E;const R=Array.isArray(r==null?void 0:r.workspaces)?r.workspaces:[],B=`mesh-add-node-workspaces-${a||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(wr,{value:b,onChange:F=>C(F.target.value),placeholder:((E=R[0])==null?void 0:E.path)||"/Users/dev/projects/myapp",list:R.length>0?B:void 0,autoFocus:!0}),R.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:B,children:R.map(F=>s.jsx("option",{value:F.path,children:F.label||F.path},F.id||F.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:R.slice(0,6).map(F=>s.jsx("button",{type:"button",onClick:()=>C(F.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:F.path,children:F.label||F.path.split("/").filter(Boolean).pop()||F.path},F.id||F.path))})]})]})})()})}),s.jsx(jt,{label:i.addNodeDaemonPicker?"Default CLI providers":"Provider Priority",hint:"Order used when launching without an explicit provider.",children:s.jsx(Ll,{value:N,availableProviders:i.addNodeDaemonPicker?H:u,onChange:S})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:D,disabled:!b.trim()||i.addNodeDaemonPicker&&!T,className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>{w(),_(""),M(!1)},className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-300 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:"Setup inventory only — live git/session/branch detail is shown in the graph popup after direct aggregate mesh_status truth is available from the Mesh Host."}),e.length===0?s.jsx(ma,{icon:s.jsx(Os,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:e.map(R=>{const B=Pk(R),E=_k(R,t),F=Dk(R,r),Q=j===R.id,Z=Rk(R),Y=R.status||R.machine_status||(E.length>0||F.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${i.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${Q?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:i.addNodeDaemonPicker?void 0:"button",tabIndex:i.addNodeDaemonPicker?void 0:0,onClick:i.addNodeDaemonPicker?void 0:()=>h(Q?null:R.id),onKeyDown:i.addNodeDaemonPicker?void 0:te=>{(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),h(Q?null:R.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.addNodeDaemonPicker?s.jsx("span",{className:"font-semibold text-sm text-text-primary truncate",children:R.machine_label||R.machine_nickname||R.hostname||R.workspace}):s.jsx("span",{className:"text-sm font-medium",children:R.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx(Lm,{status:Y}),E.length>0&&!i.addNodeDaemonPicker&&s.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-orange-500/15 text-orange-300 border border-orange-500/25",children:[E.length," active task",E.length===1?"":"s"]}),Z&&s.jsx("span",{className:`text-[10px] px-2 py-0.5 rounded-full ${i.addNodeDaemonPicker?"bg-cyan-400/10 text-cyan-300 border border-cyan-400/30":"bg-cyan-500/15 text-cyan-300 border border-cyan-500/25"}`,children:"worktree"}),i.addNodeDaemonPicker&&s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:"setup inventory"})]}),i.addNodeDaemonPicker&&s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Owner: ",$k(n.find(te=>te.id===String(R.daemon_id||"")),o)," · Machine: ",R.machine_label||R.daemon_id||R.workspace]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:R.workspace}),Z&&s.jsxs("div",{className:`mt-2 rounded-lg px-3 py-2 text-[11px] ${i.addNodeDaemonPicker?"border border-cyan-400/20 bg-cyan-400/10 text-cyan-200":"border border-cyan-500/20 bg-cyan-500/10 text-cyan-200"}`,children:["Worktree node",R.worktreeBranch?` · ${R.worktreeBranch}`:"",". Provider priority saved here is node-local and disappears when removed."]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:"Live branch/git/session detail is graph-owned; use the node popup in the live graph above."}),s.jsxs("div",{className:`mt-3 max-w-2xl ${i.addNodeDaemonPicker,""}`,onClick:te=>te.stopPropagation(),children:[s.jsxs(jt,{label:i.addNodeDaemonPicker?"Default CLI providers":"Provider priority",hint:Z?"Worktree-local launch defaults. Configure the source node for durable defaults.":i.addNodeDaemonPicker?"Used for coordinator/session launches when no provider is selected explicitly.":"Used when launches omit an explicit provider.",children:[s.jsx(Ll,{value:d[R.id]??Pm(R),availableProviders:u,onChange:te=>m(R.id,te),disabled:p===R.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:te=>{te.stopPropagation(),f(R)},disabled:p===R.id,children:p===R.id?"Saving...":i.addNodeDaemonPicker?"Save defaults":"Save policy"})}),s.jsxs("div",{className:"mt-2 text-[12px]",children:[s.jsx("span",{className:"text-text-muted",children:i.addNodeDaemonPicker?"Saved default order: ":"Effective provider priority: "}),s.jsx("span",{className:B.configured?"text-text-primary font-mono":"text-amber-400",children:B.label}),!B.configured&&B.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",B.launchBlockedMessage,")"]})]})]}),i.nodeInstruction&&s.jsxs(jt,{label:"Node instruction (optional)",hint:"Surfaced in the coordinator system prompt as 📌 Node instruction.",children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:y[R.id]??"",onChange:te=>{const fe=te.target.value;g(R.id,fe)},onClick:te=>te.stopPropagation(),disabled:x===R.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:te=>{te.stopPropagation(),k(R)},disabled:x===R.id,children:x===R.id?"Saving…":"Save instruction"})})]})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${i.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:te=>{te.stopPropagation(),O(R.id)},title:"Remove node",children:i.addNodeDaemonPicker?s.jsx(wk,{size:14}):s.jsx(yt,{size:14})})]}),!i.addNodeDaemonPicker&&Q&&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:R.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:B.configured?"text-green-400":"text-amber-400",children:B.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:R.repoRoot||R.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",F.length]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),E.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:E.map(te=>s.jsx("li",{className:"font-mono",children:Lk(te)},te.id))})]}),F.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:F.map(te=>s.jsxs("li",{className:"font-mono",children:[te.provider," / ",te.status," / ",te.id]},te.id))})]})]}),i.addNodeDaemonPicker&&s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:[s.jsxs("span",{className:"mr-3",children:["Node ID: ",R.id.slice(0,16),"..."]}),s.jsxs("span",{children:["Added: ",new Date(R.created_at||R.createdAt||Date.now()).toLocaleDateString()]})]})]},R.id)})})]})}function Bk(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function Ok({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:r,coordinatorCliType:n,onCoordinatorCliTypeChange:a,launchingCoordinator:o,launchResult:i,attachedDaemonIds:c,isHostNodeAttached:d,selectedHostNode:m,onLaunchCoordinator:u,onAttachSelectedHost:p}){return s.jsxs(ct,{title:"Mesh Host daemon",description:"Choose the daemon that will own the coordinator. Host-owned live truth is required before cloud renders status, queue, graph, or node detail.",children:[s.jsxs(ns,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:"Start with one host workspace."})," ","Create a mesh on a connected daemon, then attach additional machine workspaces below. Live status, queue, and graph data come from the selected host daemon."]}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-[1fr_180px_auto] items-end",children:[s.jsx(jt,{label:"Mesh Host daemon",hint:"Cloud selects the connected daemon to command over P2P; the host must be attached before it can own a coordinator.",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:t,onChange:f=>r(f.target.value),children:[s.jsx("option",{value:"",children:"Select a Mesh Host..."}),e.map(f=>s.jsxs("option",{value:f.id,children:[Bk(f)," · ",c.has(f.id)?"attached":"not attached"]},f.id))]})}),s.jsx(jt,{label:"CLI provider",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:n,onChange:f=>a(f.target.value),children:[s.jsx("option",{value:"",children:"Use node provider priority"}),s.jsx("option",{value:"claude-cli",children:"Claude Code"}),s.jsx("option",{value:"codex-cli",children:"Codex"}),s.jsx("option",{value:"gemini-cli",children:"Gemini"}),s.jsx("option",{value:"hermes-cli",children:"Hermes"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm",onClick:u,disabled:!t||!d||o,title:!d&&t?"Attach this Mesh Host daemon first.":void 0,children:o?"Launching...":"Launch Host Coordinator"})]}),s.jsx("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:t?d?s.jsxs(s.Fragment,{children:["Host setup node: ",s.jsx("span",{className:"font-mono text-text-primary",children:m==null?void 0:m.workspace}),". Live graph/status/detail renders only from this daemon."]}):s.jsx(s.Fragment,{children:"Selected host is not attached yet. Attach one of its workspaces below before launching."}):"Select a connected daemon to become the Mesh Host."}),!d&&t&&s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm mt-3",onClick:p,children:"Attach selected host daemon"}),i&&s.jsx("div",{className:"mt-3 text-[12px] text-green-400 bg-green-500/10 border border-green-500/20 rounded-lg px-3 py-2",children:i})]})}function Fk({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const o=a.id.toLowerCase();return o==="hermes-cli"||o.includes("hermes")||a.name.toLowerCase().includes("hermes")}),n=Lu(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(tm,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}const uo=[{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."}],Hk={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function Oo(e){return{...Hk,...(e==null?void 0:e.policy)||{}}}function Wk({selectedMesh:e,error:t,onDismissError:r,onBack:n,onDelete:a,displayedMeshStatus:o,graphLoading:i,graphError:c,graphProvenance:d,onRefreshGraph:m,queueSummary:u,queueLoading:p,queueError:f,onLoadQueue:y,savingPolicy:g,onUpdatePolicy:x,coordinatorPromptDraft:k,onCoordinatorPromptDraftChange:j,savingCoordinatorPrompt:h,onSaveCoordinatorPrompt:v,daemons:I,coordinatorDaemonId:w,onCoordinatorDaemonIdChange:b,coordinatorCliType:C,onCoordinatorCliTypeChange:N,launchingCoordinator:S,launchResult:T,attachedDaemonIds:_,isHostNodeAttached:L,selectedHostNode:M,onLaunchCoordinator:A,activeDaemon:H,activeDaemonId:P,meshQueue:D,userName:O,nodeProviderPriorityDrafts:R,onNodeProviderPriorityDraftChange:B,availableCliProviders:E,savingNodePolicyId:F,onUpdateNodeProviderPriority:Q,nodeSystemPromptDrafts:Z,onNodeSystemPromptDraftChange:Y,savingNodeSystemPromptId:te,onSaveNodeSystemPrompt:fe,selectedNodeId:Ne,onSelectNode:X,showAddNode:we,onShowAddNode:ge,onCancelAddNode:be,nodeWorkspace:de,onNodeWorkspaceChange:Ie,nodeProviderPriority:ee,onNodeProviderPriorityChange:ve,nodeDaemonId:ce,onNodeDaemonIdChange:W,nodeCustomPath:ne,onNodeCustomPathChange:ue,nodePickerWorkspaces:me,nodePickerProviders:J,attachableDaemons:q,onAddNode:$,onRemoveNode:re,availableCliAgents:xe,features:je,reviewInboxItems:ae,reviewInboxLoading:Pe,reviewInboxError:$e,reviewInboxRemoteNodesExcluded:Re,onLoadReviewInbox:Ge,onDismissReviewInboxItem:Ye,onRefineNode:Xe,onRequeueLast:at,sendCommand:Je}){var ft;const Ze=Oo(e),dt=e.nodes||[];return s.jsxs(Kr,{icon:s.jsx(Jt,{}),title:e.name,subtitle:e.repoIdentity||e.repo_identity||"Repo Mesh",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:n,children:"← Back"}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>m(!0),disabled:i,children:[s.jsx(sa,{size:13}),i?"Probing...":"Refresh"]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>a(e.id),children:"Delete"})]}),children:[t&&s.jsx(ns,{variant:"error",onDismiss:r,className:"mb-4",children:t}),s.jsxs(ct,{title:"Policy",description:"Coordinator safety defaults and session cleanup behavior.",children:[s.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[[{label:"Checkpoint before task",key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:he=>he?"yes":"no",parse:he=>he==="yes"},{label:"Checkpoint after task",key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:he=>he?"yes":"no",parse:he=>he==="yes"},{label:"Push approval",key:"requireApprovalForPush",opts:[["required","Require approval before push"],["not_required","Do not require approval"]],val:he=>he?"required":"not_required",parse:he=>he==="required"},{label:"Submodule main auto-publish",key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled","Require explicit approval"],["enabled","Allow Refinery non-force publish"]],val:he=>he?"enabled":"disabled",parse:he=>he==="enabled"},{label:"Destructive git approval",key:"requireApprovalForDestructiveGit",opts:[["required","Require approval"],["not_required","Do not require approval"]],val:he=>he?"required":"not_required",parse:he=>he==="required"},{label:"Dirty workspace behavior",key:"dirtyWorkspaceBehavior",opts:[["warn","Warn and continue"],["block","Block task"],["checkpoint_then_continue","Checkpoint then continue"]],val:he=>he||"warn",parse:he=>he}].map(({label:he,key:Oe,opts:et,val:ze,parse:ht})=>s.jsx(jt,{label:he,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:ze(Ze[Oe]),onChange:K=>x({[Oe]:ht(K.target.value)}),disabled:g,children:et.map(([K,U])=>s.jsx("option",{value:K,children:U},K))})},Oe)),s.jsx(jt,{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(Ze.maxParallelTasks??2),onChange:he=>x({maxParallelTasks:Number(he.target.value)}),disabled:g,children:[1,2,3,4,5,6,7,8].map(he=>s.jsx("option",{value:he,children:he},he))})})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(jt,{label:"Node removal session cleanup",hint:"Separate transcript cleanup from runtime/process cleanup.",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ze.sessionCleanupOnNodeRemove||"preserve",onChange:he=>x({sessionCleanupOnNodeRemove:he.target.value}),disabled:g,children:uo.map(he=>s.jsx("option",{value:he.value,children:he.label},he.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((ft=uo.find(he=>he.value===Ze.sessionCleanupOnNodeRemove))==null?void 0:ft.description)||uo[0].description})]}),g&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),je.coordinatorPrompt&&s.jsxs(ct,{title:"Coordinator prompt",description:"Customize the system prompt for coordinator sessions. Supports placeholders: {{meshName}}, {{repo}}, {{defaultBranch}}, {{cliType}}, {{nodes}}, {{policy}}, {{tools}}, {{workflow}}, {{rules}}, {{toolExposurePreflight}}.",children:[s.jsx(jt,{label:"Override (replaces default)",hint:"When set, replaces the daemon's default base prompt. Leave empty to keep the default.",children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:k.override,onChange:he=>j({...k,override:he.target.value}),disabled:h,placeholder:"(empty — daemon default applies)"})}),s.jsx(jt,{label:"Append (added after the base)",hint:"Always added after whichever base prompt wins.",children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:4,value:k.append,onChange:he=>j({...k,append:he.target.value}),disabled:h,placeholder:"(empty — nothing appended)"})}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:v,disabled:h,children:h?"Saving…":"Save coordinator prompt"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>j({override:"",append:""}),disabled:h,title:"Clear both fields. Click Save to commit.",children:"Clear"})]})]}),je.meshHostDaemonSection&&s.jsx(Ok,{daemons:I,coordinatorDaemonId:w,onCoordinatorDaemonIdChange:he=>{b(he),m()},coordinatorCliType:C,onCoordinatorCliTypeChange:N,launchingCoordinator:S,launchResult:T,attachedDaemonIds:_,isHostNodeAttached:L,selectedHostNode:M,onLaunchCoordinator:A,onAttachSelectedHost:()=>{W(w),ge()}}),je.queueSection&&s.jsx(Nk,{queueSummary:u,queueLoading:p,queueError:f,activeDaemonId:P,onRefresh:y}),s.jsxs(ct,{title:"Visualization",description:"Live mesh topology: branches, worktrees, sessions, and orphan detection.",children:[s.jsxs("div",{className:"mb-4 flex flex-wrap items-center justify-between gap-3",children:[s.jsx("div",{className:"text-[12px] text-text-muted max-w-2xl",children:je.meshHostDaemonSection?s.jsxs(s.Fragment,{children:["Direct aggregate mesh_status from the selected Mesh Host is preferred. Refresh asks the host for the latest peer git provenance.",d==="settling"&&s.jsx("span",{className:"ml-1 text-amber-300",children:"Refreshing peer provenance..."})]}):s.jsxs("div",{className:"flex items-center gap-3",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.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>m(!0),disabled:i||je.meshHostDaemonSection&&!P,children:[s.jsx(sa,{size:13}),i?"Loading...":"Refresh Graph"]})]}),c&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:c}),o?s.jsx(km,{status:o,emptyMessage:je.meshHostDaemonSection?"No mesh graph data is available yet. Refresh after the selected Mesh Host is reachable.":"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology.",daemonId:P,sendDaemonCommand:Je}):s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:i?"Loading graph...":je.meshHostDaemonSection?"No mesh graph data is available yet. Refresh after the selected Mesh Host is reachable.":"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology."})]}),je.reviewInbox&&s.jsx(Tk,{items:ae,loading:Pe,error:$e,remoteNodesExcluded:Re,meshId:e.id,activeDaemonId:P,onRefresh:Ge,onDismiss:Ye,onRefineNode:Xe,onRequeueLast:at,sendCommand:Je}),s.jsx(Ek,{nodes:dt,meshQueue:D,activeDaemon:H,daemons:I,selectedMeshId:e.id,userName:O,features:{addNodeDaemonPicker:je.addNodeDaemonPicker,nodeInstruction:je.nodeInstruction},coordinatorDaemonId:w,nodeProviderPriorityDrafts:R,onNodeProviderPriorityDraftChange:B,availableCliProviders:E,savingNodePolicyId:F,onUpdateNodeProviderPriority:Q,nodeSystemPromptDrafts:Z,onNodeSystemPromptDraftChange:Y,savingNodeSystemPromptId:te,onSaveNodeSystemPrompt:fe,selectedNodeId:Ne,onSelectNode:X,showAddNode:we,onShowAddNode:ge,onCancelAddNode:be,nodeWorkspace:de,onNodeWorkspaceChange:Ie,nodeProviderPriority:ee,onNodeProviderPriorityChange:ve,nodeDaemonId:ce,onNodeDaemonIdChange:W,nodeCustomPath:ne,onNodeCustomPathChange:ue,nodePickerWorkspaces:me,nodePickerProviders:J,attachableDaemons:q,onAddNode:$,onRemoveNode:re}),je.hermesMcpConfig&&s.jsx(Fk,{meshId:e.id,availableCliAgents:xe}),je.meshHostDaemonSection&&s.jsxs(ns,{variant:"info",className:"mt-4",children:[s.jsx("strong",{children:"MCP Mode:"})," ",s.jsxs("code",{className:"bg-bg-secondary px-1 rounded text-xs",children:["adhdev mcp --repo-mesh ",e.id]})," · The mesh MCP server can be used directly from your CLI agent."]})]})}function Kk({daemons:e,primaryDaemonId:t,sendCommand:r,unwrapResult:n,normalizeMesh:a,features:o}){const[i,c]=l.useState([]),[d,m]=l.useState(null),[u,p]=l.useState(!0),[f,y]=l.useState(null),[g,x]=l.useState(!1),[k,j]=l.useState(""),[h,v]=l.useState(""),[I,w]=l.useState(""),[b,C]=l.useState(""),[N,S]=l.useState(""),T=l.useMemo(()=>e.find(D=>D.id===b),[e,b]),_=(T==null?void 0:T.workspaces)||[],L=l.useMemo(()=>Tr((T==null?void 0:T.availableProviders)||[]),[T]),M=l.useCallback(async()=>{p(!0);try{if(o.createDaemonPicker){const D=await Promise.allSettled(e.map(async R=>{if(!R.id)return[];const B=await r(R.id,"list_meshes",{}),E=n(B);if((E==null?void 0:E.success)===!1)throw new Error(E.error||"Failed to load meshes");return(Array.isArray(E==null?void 0:E.meshes)?E.meshes:[]).map(F=>a(F,R.id)).filter(F=>F.id)})),O=new Map;for(const R of D)if(R.status==="fulfilled")for(const B of R.value)O.has(B.id)||O.set(B.id,B);c(Array.from(O.values()))}else{if(!t)return;const D=await r(t,"list_meshes");D!=null&&D.success?(c((D.meshes||[]).map(O=>a(O,t))),y(null)):y((D==null?void 0:D.error)||"Failed to load meshes")}}catch(D){y((D==null?void 0:D.message)||"Failed to load meshes")}finally{p(!1)}},[e,t,r,n,a,o.createDaemonPicker]);async function A(){var B,E;const D=o.createDaemonPicker?b:t;if(!D||!k.trim())return;const O=I.trim(),R=h.trim();if(!(!O&&!R))try{const F={name:k.trim()};O&&(F.repoRemoteUrl=O),R&&(F.repoIdentity=R);const Q=await r(D,"create_mesh",F),Z=n(Q);if((Z==null?void 0:Z.success)===!1)throw new Error(Z.error||"Create failed");const Y=typeof((B=Z==null?void 0:Z.mesh)==null?void 0:B.id)=="string"?Z.mesh.id:"";if(Y&&o.createDaemonPicker&&N){const te=await r(D,"add_mesh_node",{meshId:Y,daemonId:D,machineId:T==null?void 0:T.machineId,workspace:N,role:"host",providerPriority:_r(L)}),fe=n(te);if((fe==null?void 0:fe.success)===!1)throw new Error(fe.error||"Mesh created but failed to attach workspace")}x(!1),j(""),v(""),w(""),S(""),await M(),(E=Z==null?void 0:Z.mesh)!=null&&E.id&&m(Z.mesh.id)}catch(F){y((F==null?void 0:F.message)||"Create failed")}}async function H(D){var R;if(!confirm("Delete this mesh? This cannot be undone."))return;const O=((R=i.find(B=>B.id===D))==null?void 0:R.__sourceDaemonId)||t;try{const B=await r(O,"delete_mesh",{meshId:D}),E=n(B);if((E==null?void 0:E.success)===!1)throw new Error(E.error||"Failed to delete");d===D&&m(null),await M()}catch(B){y((B==null?void 0:B.message)||"Delete failed")}}function P(){x(!1),j(""),v(""),w("")}return{meshes:i,setMeshes:c,selectedMeshId:d,setSelectedMeshId:m,loading:u,error:f,setError:y,showCreate:g,setShowCreate:x,createName:k,setCreateName:j,createRepoIdentity:h,setCreateRepoIdentity:v,createRepoRemoteUrl:I,setCreateRepoRemoteUrl:w,newMeshDaemonId:b,setNewMeshDaemonId:C,newMeshWorkspace:N,setNewMeshWorkspace:S,createPickerWorkspaces:_,createPickerProviders:L,loadMeshes:M,handleCreate:A,handleDelete:H,cancelCreate:P}}function Uk({selectedMesh:e,selectedMeshId:t,primaryDaemonId:r,activeDaemonId:n,daemons:a,availableCliProviders:o,sendCommand:i,unwrapResult:c,loadLiveMesh:d,resolveCommandTarget:m,launchCoordinator:u,features:p,loadMeshes:f,loadQueue:y,queueSection:g,setError:x}){const[k,j]=l.useState({}),[h,v]=l.useState(null),[I,w]=l.useState(null),[b,C]=l.useState(!1),[N,S]=l.useState(""),[T,_]=l.useState([]),[L,M]=l.useState(""),[A,H]=l.useState(!1),[P,D]=l.useState(""),[O,R]=l.useState(!1),[B,E]=l.useState(null),[F,Q]=l.useState(!1),[Z,Y]=l.useState({override:"",append:""}),[te,fe]=l.useState(!1),[Ne,X]=l.useState({}),[we,ge]=l.useState(null),be=l.useMemo(()=>a.find(J=>J.id===L),[a,L]),de=(be==null?void 0:be.workspaces)||[],Ie=l.useMemo(()=>Tr((be==null?void 0:be.availableProviders)||[]),[be]);async function ee(){const J=(e==null?void 0:e.__sourceDaemonId)||r;if(!t||!J)return;const q=N.trim();if(q)try{const $={meshId:t,workspace:q};p.addNodeDaemonPicker&&L?($.daemonId=L,$.machineId=be==null?void 0:be.machineId,$.providerPriority=Cn(T,Ie)):$.providerPriority=Cn(T,o);const re=await i(J,"add_mesh_node",$),xe=c(re);if((xe==null?void 0:xe.success)===!1)throw new Error(xe.error||"Add node failed");C(!1),S(""),_([]),M(""),H(!1),await f(),g||await y(t)}catch($){x(($==null?void 0:$.message)||"Add node failed")}}async function ve(J){var xe;if(!e)return;const q=Oo(e),$=((xe=[{value:"preserve",label:"Preserve history and runtimes"},{value:"stop",label:"Stop live runtimes only"},{value:"delete_stopped",label:"Delete stopped sessions only"},{value:"stop_and_delete",label:"Stop and delete sessions"}].find(je=>je.value===q.sessionCleanupOnNodeRemove))==null?void 0:xe.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
111
+
112
+ Node removal cleanup policy: ${$}`))return;const re=e.__sourceDaemonId||r;try{const je=await i(re,"remove_mesh_node",{meshId:e.id,nodeId:J}),ae=c(je);if((ae==null?void 0:ae.success)===!1)throw new Error(ae.error||"Remove failed");I===J&&w(null),await f(),g||await y(t)}catch(je){x((je==null?void 0:je.message)||"Remove node failed")}}async function ce(J){if(!e)return;const q={...Oo(e),...J},$=e.__sourceDaemonId||r;try{Q(!0),x(null);const re=await i($,"update_mesh",{meshId:e.id,policy:q}),xe=c(re);if((xe==null?void 0:xe.success)===!1)throw new Error(xe.error||"Policy update failed");await f()}catch(re){x((re==null?void 0:re.message)||"Policy update failed")}finally{Q(!1)}}async function W(J){if(!t)return;const q=(e==null?void 0:e.__sourceDaemonId)||r,$=p.addNodeDaemonPicker?Ie:o,re=k[J.id]||zk(J),xe=$.length>0?Cn(re,$):Wr(re),je={...J.policy||{}};delete je.provider_priority,xe.length?je.providerPriority=xe:delete je.providerPriority;try{v(J.id),x(null);const ae=await i(q,"update_mesh_node",{meshId:t,nodeId:J.id,policy:je,providerPriority:xe}),Pe=c(ae);if((Pe==null?void 0:Pe.success)===!1){x(Pe.error||"Node policy update failed");return}await f()}catch(ae){x((ae==null?void 0:ae.message)||"Node policy update failed")}finally{v(null)}}async function ne(){if(!r||!t)return;const q={...(e==null?void 0:e.coordinator)||{}};Z.override.trim()?q.systemPromptOverride=Z.override:delete q.systemPromptOverride,Z.append.trim()?q.systemPromptAppend=Z.append:delete q.systemPromptAppend,delete q.systemPromptSuffix;try{fe(!0),x(null);const $=await i(r,"update_mesh",{meshId:t,coordinator:q}),re=c($);if((re==null?void 0:re.success)===!1){x(re.error||"Coordinator prompt save failed");return}await f()}catch($){x(($==null?void 0:$.message)||"Coordinator prompt save failed")}finally{fe(!1)}}async function ue(J){if(!r||!t)return;const q=(Ne[J.id]||"").trim();try{ge(J.id),x(null);const $=await i(r,"update_mesh_node",{meshId:t,nodeId:J.id,systemPrompt:q}),re=c($);if((re==null?void 0:re.success)===!1){x(re.error||"Node instruction save failed");return}await f()}catch($){x(($==null?void 0:$.message)||"Node instruction save failed")}finally{ge(null)}}async function me(){if(e){x(null),E(null);try{R(!0);const J=d?await d(n,e.id,e):null,q=m(n,e.id,e,e.nodes||[],J);if("error"in q)throw new Error(q.error);const $=await u(q.targetDaemonId,{meshId:e.id,inlineMesh:q.inlineMesh,coordinatorNodeId:q.coordinatorNodeId,cliType:P.trim()||void 0});E($.message)}catch(J){x((J==null?void 0:J.message)||"Coordinator launch failed")}finally{R(!1)}}}return{nodeProviderPriorityDrafts:k,setNodeProviderPriorityDrafts:j,savingNodePolicyId:h,selectedNodeId:I,setSelectedNodeId:w,showAddNode:b,setShowAddNode:C,nodeWorkspace:N,setNodeWorkspace:S,nodeProviderPriority:T,setNodeProviderPriority:_,nodeDaemonId:L,setNodeDaemonId:M,nodeCustomPath:A,setNodeCustomPath:H,nodePickerWorkspaces:de,nodePickerProviders:Ie,coordinatorCliType:P,setCoordinatorCliType:D,launchingCoordinator:O,launchResult:B,savingPolicy:F,coordinatorPromptDraft:Z,setCoordinatorPromptDraft:Y,savingCoordinatorPrompt:te,nodeSystemPromptDrafts:Ne,setNodeSystemPromptDrafts:X,savingNodeSystemPromptId:we,handleAddNode:ee,handleRemoveNode:ve,handleUpdatePolicy:ce,handleUpdateNodeProviderPriority:W,handleSaveCoordinatorPrompt:ne,handleSaveNodeSystemPrompt:ue,handleLaunchCoordinator:me}}function zk(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 Gk(e){const t=e.filter(n=>n.status==="pending"||n.status==="assigned"),r=e.filter(n=>n.status==="completed"||n.status==="failed"||n.status==="cancelled");return{active:t.length,historical:r.length,activeCounts:{pending:t.filter(n=>n.status==="pending").length,assigned:t.filter(n=>n.status==="assigned").length},historicalCounts:{completed:r.filter(n=>n.status==="completed").length,failed:r.filter(n=>n.status==="failed").length},counts:{pending:e.filter(n=>n.status==="pending").length,assigned:e.filter(n=>n.status==="assigned").length,completed:e.filter(n=>n.status==="completed").length,failed:e.filter(n=>n.status==="failed").length},staleAssignedCount:e.filter(n=>n.staleAssigned).length,recent:e.slice(0,20)}}function Vk({primaryDaemonId:e,activeDaemonId:t,sendCommand:r,unwrapResult:n,loadLiveMesh:a,resolveCommandTarget:o}){const[i,c]=l.useState([]),[d,m]=l.useState(null),[u,p]=l.useState(!1),[f,y]=l.useState(null),g=l.useCallback(async k=>{if(!e||!k){c([]);return}try{const j=await r(e,"get_mesh_queue",{meshId:k});c(j!=null&&j.success?Array.isArray(j.queue)?j.queue:[]:[])}catch{c([])}},[e,r]);async function x(k){var j,h;if(k){p(!0),y(null);try{const v=a?await a(t,k.id,k):null,I=o(t,k.id,k,k.nodes||[],v);if("error"in I)throw new Error(I.error);const w=await r(I.targetDaemonId,"get_mesh_queue",{meshId:k.id}),b=n(w);if((b==null?void 0:b.success)===!1)throw new Error(b.error||"Queue load failed");const C=Array.isArray(((j=b==null?void 0:b.result)==null?void 0:j.rows)??(b==null?void 0:b.rows)??(b==null?void 0:b.queue))?((h=b==null?void 0:b.result)==null?void 0:h.rows)??(b==null?void 0:b.rows)??(b==null?void 0:b.queue):[];m(Gk(C))}catch(v){y((v==null?void 0:v.message)||"Queue load failed")}finally{p(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:d,queueLoading:u,queueError:f,loadQueue:g,handleLoadQueue:x}}function qk({selectedMeshId:e,loadMeshStatus:t,extractStatus:r,normalizeNode:n}){const[a,o]=l.useState(null),[i,c]=l.useState(!1),[d,m]=l.useState(null),[u,p]=l.useState("idle");async function f(y,g=e,x=!1){if(!(!y||!g))try{c(!x&&a===null),p(x?"settling":"first_paint"),m(null);const k=await t(y,g,{refresh:x,retryProfile:x?"settled":"interactive"}),j=r(k),h=n&&j?{...j,nodes:(j.nodes??[]).map(v=>n(v,j.meshId??g,""))}:j;h?(o(h),p("settled")):(o(null),m("mesh_status returned an unexpected payload."),p("idle"))}catch(k){a||o(null),m((k==null?void 0:k.message)||"Failed to load mesh graph"),p("idle")}finally{c(!1)}}return{meshGraphStatus:a,setMeshGraphStatus:o,graphLoading:i,graphError:d,setGraphError:m,graphProvenance:u,loadGraph:f}}function Yk({primaryDaemonId:e,sendCommand:t}){const[r,n]=l.useState([]),[a,o]=l.useState(!1),[i,c]=l.useState(null),[d,m]=l.useState(!1),[u,p]=l.useState(new Set),f=l.useCallback(async x=>{if(!e||!x){n([]);return}o(!0),c(null);try{const k=await t(e,"get_mesh_review_inbox",{meshId:x});k!=null&&k.success?(n(Array.isArray(k.inbox)?k.inbox:[]),m(k.remoteNodesExcluded===!0)):(c((k==null?void 0:k.error)||"Failed to load review inbox"),n([]))}catch(k){c((k==null?void 0:k.message)||"Failed to load review inbox"),n([])}finally{o(!1)}},[e,t]),y=l.useCallback(x=>{p(k=>new Set([...k,x]))},[]);return{items:r.filter(x=>!u.has(x.nodeId)),allItems:r,loading:a,error:i,remoteNodesExcluded:d,dismissedNodeIds:u,loadInbox:f,dismissItem:y}}function Xk(){const e=yk(),{sendCommand:t,sendData:r,daemons:n,userName:a,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:d,unwrapResult:m,normalizeMesh:u,normalizeNode:p,resolveCommandTarget:f,features:y}=e,g=n[0],x=(g==null?void 0:g.id)||"",k=l.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(We=>We.category==="cli").map(We=>({id:We.type||We.id,name:We.displayName||We.name||We.type,meshCoordinator:We.meshCoordinator})),[g]),j=l.useMemo(()=>Tr((g==null?void 0:g.availableProviders)||[]),[g]),{meshes:h,selectedMeshId:v,setSelectedMeshId:I,loading:w,error:b,setError:C,showCreate:N,setShowCreate:S,createName:T,setCreateName:_,createRepoIdentity:L,setCreateRepoIdentity:M,createRepoRemoteUrl:A,setCreateRepoRemoteUrl:H,newMeshDaemonId:P,setNewMeshDaemonId:D,newMeshWorkspace:O,setNewMeshWorkspace:R,createPickerWorkspaces:B,loadMeshes:E,handleCreate:F,handleDelete:Q,cancelCreate:Z}=Kk({daemons:n,primaryDaemonId:x,sendCommand:t,unwrapResult:m,normalizeMesh:u,features:y}),Y=h.find(ye=>ye.id===v)||null,{meshGraphStatus:te,setMeshGraphStatus:fe,graphLoading:Ne,graphError:X,setGraphError:we,graphProvenance:ge,loadGraph:be}=qk({selectedMeshId:v,loadMeshStatus:o,extractStatus:d,normalizeNode:p}),[de,Ie]=l.useState(""),ee=y.meshHostDaemonSection&&de||x,{meshQueue:ve,queueSummary:ce,queueLoading:W,queueError:ne,loadQueue:ue,handleLoadQueue:me}=Vk({primaryDaemonId:x,activeDaemonId:ee,sendCommand:t,unwrapResult:m,loadLiveMesh:c,resolveCommandTarget:f}),{items:J,loading:q,error:$,remoteNodesExcluded:re,loadInbox:xe,dismissItem:je}=Yk({primaryDaemonId:x,sendCommand:t}),{nodeProviderPriorityDrafts:ae,setNodeProviderPriorityDrafts:Pe,savingNodePolicyId:$e,selectedNodeId:Re,setSelectedNodeId:Ge,showAddNode:Ye,setShowAddNode:Xe,nodeWorkspace:at,setNodeWorkspace:Je,nodeProviderPriority:Ze,setNodeProviderPriority:dt,nodeDaemonId:ft,setNodeDaemonId:he,nodeCustomPath:Oe,setNodeCustomPath:et,nodePickerWorkspaces:ze,nodePickerProviders:ht,coordinatorCliType:K,setCoordinatorCliType:U,launchingCoordinator:V,launchResult:ie,savingPolicy:pe,coordinatorPromptDraft:ke,setCoordinatorPromptDraft:z,savingCoordinatorPrompt:G,nodeSystemPromptDrafts:le,setNodeSystemPromptDrafts:Ce,savingNodeSystemPromptId:Te,handleAddNode:Me,handleRemoveNode:_e,handleUpdatePolicy:De,handleUpdateNodeProviderPriority:Ae,handleSaveCoordinatorPrompt:He,handleSaveNodeSystemPrompt:Ve,handleLaunchCoordinator:ut}=Uk({selectedMesh:Y,selectedMeshId:v,primaryDaemonId:x,activeDaemonId:ee,daemons:n,availableCliProviders:j,sendCommand:t,unwrapResult:m,loadLiveMesh:c,resolveCommandTarget:f,launchCoordinator:i,features:{addNodeDaemonPicker:y.addNodeDaemonPicker},loadMeshes:E,loadQueue:ue,queueSection:y.queueSection,setError:C}),bt=l.useMemo(()=>n.find(ye=>ye.id===ee)||g,[n,ee,g]),lt=l.useMemo(()=>new Set(((Y==null?void 0:Y.nodes)||[]).map(ye=>String(ye.daemon_id||ye.daemonId||""))),[Y]),mt=l.useMemo(()=>n.filter(ye=>ye.id&&!lt.has(ye.id)),[n,lt]),Be=(Y==null?void 0:Y.nodes)||[],Mt=l.useMemo(()=>Be.find(ye=>String(ye.daemon_id||ye.daemonId||"")===de),[Be,de]),se=y.meshHostDaemonSection?!!Mt:!0,Le=l.useMemo(()=>te?[...new Set((te.nodes??[]).map(ye=>String(ye.daemonId||ye.daemon_id||"")).filter(Boolean))]:[],[te]),oe=Nm({status:te,daemonId:ee||null,extraDaemonIds:Le,meshId:v,sendData:r});return l.useEffect(()=>{Pe(Object.fromEntries(((Y==null?void 0:Y.nodes)||[]).map(ye=>[ye.id,Jk(ye)])))},[Y]),l.useEffect(()=>{const ye=(Y==null?void 0:Y.coordinator)||{};z({override:typeof ye.systemPromptOverride=="string"?ye.systemPromptOverride:"",append:typeof ye.systemPromptAppend=="string"?ye.systemPromptAppend:typeof ye.systemPromptSuffix=="string"?ye.systemPromptSuffix:""}),Ce(Object.fromEntries(((Y==null?void 0:Y.nodes)||[]).map(We=>[We.id,typeof We.systemPrompt=="string"?We.systemPrompt:""])))},[Y]),l.useEffect(()=>{const ye=y.addNodeDaemonPicker?_r(ht):_r(j);Ye&&Ze.length===0&&ye.length>0&&dt(ye)},[Ye,j,ht,Ze.length,y.addNodeDaemonPicker]),l.useEffect(()=>{const ye=new Set(((Y==null?void 0:Y.nodes)||[]).map(We=>We.id));Re&&!ye.has(Re)&&Ge(null)},[Y,Re]),l.useEffect(()=>{if(y.meshHostDaemonSection){if(!n.length){Ie("");return}(!de||!n.some(ye=>ye.id===de))&&Ie(n[0].id)}},[n,de,y.meshHostDaemonSection]),l.useEffect(()=>{if(y.createDaemonPicker){if(!n.length){D("");return}(!P||!n.some(ye=>ye.id===P))&&D(n[0].id)}},[n,P,y.createDaemonPicker]),l.useEffect(()=>{var ye;if(!y.createDaemonPicker||!P){R("");return}if(!B.length){R("");return}B.some(We=>We.path===O)||R(((ye=B[0])==null?void 0:ye.path)||"")},[P,O,B,y.createDaemonPicker]),l.useEffect(()=>{v&&(fe(null),we(null),be(ee,v))},[v,ee]),l.useEffect(()=>{y.queueSection||ue(v)},[v,y.queueSection]),l.useEffect(()=>{!y.reviewInbox||!v||xe(v)},[v,y.reviewInbox]),l.useEffect(()=>{E()},[E]),x?Y?s.jsx(Wk,{selectedMesh:Y,error:b,onDismissError:()=>C(null),onBack:()=>{I(null),fe(null)},onDelete:Q,displayedMeshStatus:oe,graphLoading:Ne,graphError:X,graphProvenance:ge,onRefreshGraph:()=>be(ee,v,!0),queueSummary:ce,queueLoading:W,queueError:ne,onLoadQueue:()=>me(Y),savingPolicy:pe,onUpdatePolicy:De,coordinatorPromptDraft:ke,onCoordinatorPromptDraftChange:z,savingCoordinatorPrompt:G,onSaveCoordinatorPrompt:He,daemons:n,coordinatorDaemonId:de,onCoordinatorDaemonIdChange:ye=>{Ie(ye),fe(null)},coordinatorCliType:K,onCoordinatorCliTypeChange:U,launchingCoordinator:V,launchResult:ie,attachedDaemonIds:lt,isHostNodeAttached:se,selectedHostNode:Mt,onLaunchCoordinator:ut,activeDaemon:bt,activeDaemonId:ee,meshQueue:ve,userName:a,nodeProviderPriorityDrafts:ae,onNodeProviderPriorityDraftChange:(ye,We)=>Pe(vt=>({...vt,[ye]:We})),availableCliProviders:j,savingNodePolicyId:$e,onUpdateNodeProviderPriority:Ae,nodeSystemPromptDrafts:le,onNodeSystemPromptDraftChange:(ye,We)=>Ce(vt=>({...vt,[ye]:We})),savingNodeSystemPromptId:Te,onSaveNodeSystemPrompt:Ve,selectedNodeId:Re,onSelectNode:Ge,showAddNode:Ye,onShowAddNode:()=>Xe(!0),onCancelAddNode:()=>Xe(!1),nodeWorkspace:at,onNodeWorkspaceChange:Je,nodeProviderPriority:Ze,onNodeProviderPriorityChange:dt,nodeDaemonId:ft,onNodeDaemonIdChange:he,nodeCustomPath:Oe,onNodeCustomPathChange:et,nodePickerWorkspaces:ze,nodePickerProviders:ht,attachableDaemons:mt,onAddNode:Me,onRemoveNode:_e,availableCliAgents:k,features:{coordinatorPrompt:y.coordinatorPrompt,meshHostDaemonSection:y.meshHostDaemonSection,queueSection:y.queueSection,hermesMcpConfig:y.hermesMcpConfig,addNodeDaemonPicker:y.addNodeDaemonPicker,nodeInstruction:y.nodeInstruction,reviewInbox:y.reviewInbox??!1},reviewInboxItems:J,reviewInboxLoading:q,reviewInboxError:$,reviewInboxRemoteNodesExcluded:re,onLoadReviewInbox:()=>v&&void xe(v),onDismissReviewInboxItem:je,onRefineNode:async ye=>{v&&(await t(ee,"refine_mesh_node",{meshId:v,nodeId:ye,inlineMesh:Y}),xe(v))},onRequeueLast:async ye=>{v&&(await t(ee,"requeue_mesh_queue_task",{meshId:v,nodeId:ye}),xe(v))},sendCommand:t}):s.jsx(Sk,{meshes:h,loading:w,error:b,onDismissError:()=>C(null),daemons:n,features:{createDaemonPicker:y.createDaemonPicker},showCreate:N,onToggleCreate:()=>S(!N),createName:T,onCreateNameChange:_,createRepoIdentity:L,onCreateRepoIdentityChange:M,createRepoRemoteUrl:A,onCreateRepoRemoteUrlChange:H,newMeshDaemonId:P,onNewMeshDaemonIdChange:D,newMeshWorkspace:O,onNewMeshWorkspaceChange:R,createPickerWorkspaces:B,onSelectMesh:I,onCreate:F,onCancelCreate:Z}):s.jsx(Kr,{icon:s.jsx(Jt,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})})}function Jk(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 Qk({children:e}){const{sendCommand:t,sendData:r}=it(),{ides:n}=qt(),a=l.useMemo(()=>n.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[n]),o=l.useMemo(()=>({sendCommand:t,sendData:r,daemons:a,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var f;const d={meshId:c.meshId};c.cliType&&(d.cliType=c.cliType);const m=await t(i,"launch_mesh_coordinator",d),u=(m==null?void 0:m.result)??m;if((u==null?void 0:u.success)===!1)throw new Error(u.error||"Coordinator launch failed");const p=(u==null?void 0:u.sessionId)||((f=u==null?void 0:u.session)==null?void 0:f.id)||(u==null?void 0:u.targetSessionId);return{sessionId:p,message:p?`Coordinator launched (${p})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:bm,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:gk}),[t,r,a]);return s.jsx(_m.Provider,{value:o,children:e})}function Ri(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Zk(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=Ri();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 Kt(e,t){return await fetch(Zk(e),{credentials:"same-origin",...t})}function Rm(){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 eS{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 Kt(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const i=await o.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Wt=new eS;function tS(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Ri();return r?`${t}?token=${encodeURIComponent(r)}`:t}const jn=tS(),Dc=3e3,sS=3e4;let Et=null,rS=0;const ra=new Map;let ms=null,Sr=null;function $c(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function ur(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function nS(e){return e==="connected"?"connected":e}async function Nr(e,t,r){const n=au(e,r||{}),a=Et;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++rS}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{ra.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);ra.set(o,{resolve:m=>{clearTimeout(d),i(m)},reject:m=>{clearTimeout(d),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 Fo(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 Dm(e,t,r){const n=Et;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=au(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}}Wt.registerPtyInputSender(Dm);class aS{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 Nr(this.daemonId,t,r)}async sendInput(t,r){return Nr(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,ms&&(clearInterval(ms),ms=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Nr(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());Wt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ms=setInterval(r,2e3)}stopScreenshots(t){ms&&(clearInterval(ms),ms=null)}}let _t=null;function oS(e){return(!_t||_t.daemonId!==e)&&(_t=new aS(e)),_t}function iS({children:e}){const t=l.useRef(Ir()),r=Ir();t.current=r;const{setUserName:n}=qt(),a=l.useRef(n);a.current=n;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((x,k)=>{c(x),Sr==null||Sr(x,k)},[]),m=l.useRef(null),u=l.useRef(),p=l.useRef(Dc),f=l.useRef(!0),y=l.useRef(!1),g=l.useRef("initial_connect");return l.useEffect(()=>{f.current=!0,y.current=!1;function x(){var h,v;if(!f.current||((h=m.current)==null?void 0:h.readyState)===WebSocket.OPEN||((v=m.current)==null?void 0:v.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${jn}...`),ur("connect_attempt",{url:jn,reason:g.current,delayMs:p.current});let j;try{j=new WebSocket(jn)}catch(I){console.error("[Standalone WS] Failed to create WebSocket:",I),k();return}m.current=j,j.onopen=()=>{if(!f.current){j.close();return}d("connected"),p.current=Dc,ur("open",{url:jn,reason:g.current}),Vt.resubscribeAll({sendData:Fo}),console.log("[Standalone WS] Connected")},Et=j,j.onmessage=I=>{var w,b;try{const C=JSON.parse(I.data);if((C.type==="command_result"||C.type==="error")&&C.requestId){const N=ra.get(C.requestId);N&&(ra.delete(C.requestId),C.type==="error"?N.reject(new Error(((w=C.data)==null?void 0:w.message)||"Command failed")):N.resolve(C.data));return}if(C.type==="session_output"){const N=C.sessionId||C.cliId||C.cliType;N&&Wt.emitSessionOutput(N,typeof C.data=="string"?C.data:"",typeof C.seq=="number"?C.seq:void 0);return}if(C.type==="runtime_snapshot"){Wt.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 N=C.update;N&&Vt.publish(N);return}if(C.type==="status"||C.type==="initial_state"){const N=C.data;if(!N)return;const{injectEntries:S,markLoaded:T,getIdes:_}=t.current,L=N.instanceId||"standalone",M=_().find(P=>P.id===L),A=oS(L);Wt.register(L,A),Wt.setState(L,"connected"),d("connected",L),Wt.emitStatus(L,N);const H=Wn(N,{daemonId:L,existingDaemon:M,existingEntries:_()});$c("ws_status",{type:C.type,daemonId:L,sessions:(N.sessions||[]).map(P=>({id:P.id,parentId:P.parentId,providerType:P.providerType,kind:P.kind,transport:P.transport,unread:P.unread,inboxBucket:P.inboxBucket,lastSeenAt:P.lastSeenAt,lastUpdated:P.lastUpdated,title:P.title})),recentLaunches:(N.recentLaunches||[]).map(P=>({id:P.id,providerType:P.providerType,kind:P.kind,workspace:P.workspace,lastLaunchedAt:P.lastLaunchedAt}))}),$c("entries",{daemonId:L,entries:H.filter(P=>P.type!=="adhdev-daemon").map(P=>({id:P.id,type:P.type,unread:P.unread,inboxBucket:P.inboxBucket,lastSeenAt:P.lastSeenAt,lastUpdated:P.lastUpdated,sessionId:P.sessionId}))}),H.length>0&&S(H,{authoritativeDaemonIds:[L]}),T(),i.current!==L&&((b=o.current)==null||b.call(o),i.current=L,o.current=Vt.subscribe({sendData:Fo},L,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${L}`,params:{includeSessions:!0}},P=>{if(P.topic!=="daemon.metadata")return;const D=t.current.getIdes(),O=D.find(B=>B.id===L),R=Wn(P.status,{daemonId:L,existingDaemon:O,existingEntries:D,timestamp:P.timestamp});R.length>0&&t.current.injectEntries(R,{authoritativeDaemonIds:[L]}),P.userName&&a.current&&a.current(P.userName)}))}}catch(C){console.error("[Standalone WS] Parse error:",C)}},j.onclose=I=>{f.current&&(_t==null||_t.stopScreenshots(),_t&&Wt.setState(_t.daemonId,"disconnected"),d("disconnected"),m.current=null,g.current=`close:${I.code}${I.wasClean?":clean":":unclean"}`,ur("close",{code:I.code,reason:I.reason||"",wasClean:I.wasClean}),k())},j.onerror=I=>{y.current||!f.current||(g.current="error",ur("error",{message:I instanceof Event?"event":String(I),readyState:j.readyState}),console.warn("[Standalone WS] Error, will reconnect:",I))}}function k(){if(!f.current)return;clearTimeout(u.current);const j=p.current;console.log(`[Standalone WS] Reconnecting in ${j}ms...`),ur("schedule_reconnect",{reason:g.current,delayMs:j}),u.current=setTimeout(()=>{p.current=Math.min(p.current*1.5,sS),x()},j)}return x(),()=>{var j;f.current=!1,y.current=!0,(j=o.current)==null||j.call(o),o.current=null,i.current=null,clearTimeout(u.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,Et=null),_t&&(_t.stopScreenshots(),Wt.unregister(_t.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function lS({children:e}){const[t,r]=l.useState("disconnected"),[n,a]=l.useState(null);l.useEffect(()=>(Sr=(i,c)=>{r(i),c&&a(c)},()=>{Sr=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=nS(t),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d}},[t,n]);return s.jsx(Kp,{connectionOverrides:o,children:s.jsx(iS,{children:e})})}const $m="adhdev_standalone_font_preferences",ws={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},xa=[{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"}],Rr=[{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"}],cS=new Set(xa.map(e=>e.id)),dS=new Set(Rr.map(e=>e.id));function zt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Dn("chat",t.chat),code:Dn("code",t.code),terminal:Dn("terminal",t.terminal)}}function Dn(e,t){const r=ws[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"?cS:dS).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function $n(e,t){var a;const r=Dn(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?xa:Rr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function uS(e){const t=zt(e),r=$n("chat",t.chat),n=$n("code",t.code),a=$n("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function hs(e,t=document.documentElement){const r=zt(e),n=uS(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function Ho(e){const t=zt(e);try{localStorage.setItem($m,JSON.stringify(t))}catch{}return t}function mS(){try{const e=localStorage.getItem($m);if(e)return zt(JSON.parse(e))}catch{}return ws}function pS(){return hs(mS())}function mr(e,t){var n;const r=e==="chat"?xa:Rr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const hS=[{id:"dashboard",path:"/dashboard",icon:s.jsx(qc,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(as,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(Hs,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(aa,{}),label:"Settings"}];function fS({children:e}){const t=Dr(),r=Ko(),n=l.useMemo(()=>hS.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(Xc,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Jc,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(kg,{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 xS=[{icon:s.jsx(as,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ns,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Qc,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Ft,{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(Xc,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],bS=[{icon:s.jsx(ch,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(qc,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx($r,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(rh,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Yc,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(ah,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],gS=[{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 yS(){return s.jsxs(Kr,{icon:s.jsx(Jc,{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:xS.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:ou.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:lu.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:iu.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:bS.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:gS.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(ma,{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(gh,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function mo(e,t,r){return{...e,[t]:r}}function po({surface:e,title:t,description:r,value:n,options:a,onChange:o}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("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:$n(e,n)})]})]})]})}function vS({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:d}){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(po,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:xa,onChange:u=>o(mo(e,"chat",u))}),s.jsx(po,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Rr,onChange:u=>o(mo(e,"code",u))}),s.jsx(po,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Rr,onChange:u=>o(mo(e,"terminal",u))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",mr("chat",e.chat.preset)," · Code: ",mr("code",e.code.preset)," · Terminal: ",mr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",mr("chat",ws.chat.preset)," / ",mr("code",ws.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:d,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function wS(){const{ides:e}=qt(),t=e.find(X=>X.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=it(),{userName:a}=qt(),[o,i]=l.useState(a||""),[c,d]=l.useState(null),[m,u]=l.useState(null),[p,f]=l.useState(ws),[y,g]=l.useState(!1),[x,k]=l.useState(""),[j,h]=l.useState(""),[v,I]=l.useState("127.0.0.1"),[w,b]=l.useState(""),[C,N]=l.useState(""),[S,T]=l.useState(""),[_,L]=l.useState(""),[M,A]=l.useState(""),[H,P]=l.useState(!1),D=async()=>{const we=await(await Kt("/auth/session")).json();d(we)},O=async()=>{const we=await(await Kt("/api/v1/standalone/preferences")).json();u(we),I(we.standaloneBindHost);const ge=zt(we.standaloneFontPreferences);f(ge),hs(ge),Ho(ge)};l.useEffect(()=>{a!==void 0&&i(a)},[a]),l.useEffect(()=>{Promise.all([D(),O()]).catch(X=>{L(X instanceof Error?X.message:String(X))})},[]),l.useEffect(()=>{hs(p)},[p]);const R=X=>{const we=X.target.value.trim();t!=null&&t.id&&we!==a&&n(t.id,"set_user_name",{userName:we}).catch(console.error)},[B,E]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),F=X=>{E(X);try{localStorage.setItem("adhdev_sound",X?"1":"0")}catch{}},Q=async()=>{k(""),h(""),g(!0);try{const X=zt(p),we=await Kt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:X})}),ge=await we.json();if(!we.ok)throw new Error((ge==null?void 0:ge.error)||"Failed to save standalone font preferences");const be=zt(ge.standaloneFontPreferences);u(ge),f(be),hs(be),Ho(be),h("Standalone chat fonts saved for this self-hosted dashboard.")}catch(X){k(X instanceof Error?X.message:String(X))}finally{g(!1)}},Z=()=>{const X=zt(m==null?void 0:m.standaloneFontPreferences);k(""),h(""),f(X),hs(X)},Y=()=>{k(""),h(""),f(ws),hs(ws)},te=async()=>{L(""),A(""),P(!0);try{const X=await Kt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:v})}),we=await X.json();if(!X.ok)throw new Error((we==null?void 0:we.error)||"Failed to save standalone network preference");u(we),I(we.standaloneBindHost),A(we.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(X){L(X instanceof Error?X.message:String(X))}finally{P(!1)}},fe=async()=>{if(L(""),A(""),C.trim().length<4){L("Password must be at least 4 characters.");return}if(C!==S){L("New password and confirmation do not match.");return}P(!0);try{const X=await Kt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,newPassword:C})}),we=await X.json();if(!X.ok)throw new Error((we==null?void 0:we.error)||"Failed to save password");d(we),await O(),b(""),N(""),T(""),A(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Rm()}catch(X){L(X instanceof Error?X.message:String(X))}finally{P(!1)}},Ne=async()=>{L(""),A(""),P(!0);try{const X=await Kt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,clear:!0})}),we=await X.json();if(!X.ok)throw new Error((we==null?void 0:we.error)||"Failed to clear password");d(we),await O(),b(""),N(""),T(""),A("Standalone password disabled.")}catch(X){L(X instanceof Error?X.message:String(X))}finally{P(!1)}};return s.jsxs(Kr,{icon:s.jsx(aa,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(ns,{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(ns,{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:v==="127.0.0.1",onChange:()=>I("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:v==="0.0.0.0",onChange:()=>I("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:()=>{te()},disabled:H,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:H?"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."}),_&&s.jsx(ns,{variant:"error",children:_}),M&&s.jsx(ns,{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:w,onChange:X=>b(X.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:X=>N(X.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:S,onChange:X=>T(X.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{fe()},disabled:H,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:H?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{Ne()},disabled:H,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(X=>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 ${X.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:X.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:X.type})]},X.type))})}),s.jsx(ct,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Lg,{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($g,{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(Bg,{})]}),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(Gg,{})]}),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(vS,{value:p,savedValue:zt(m==null?void 0:m.standaloneFontPreferences),saving:y,error:x,notice:j,onChange:f,onSave:()=>{Q()},onResetToSaved:Z,onResetToDefaults:Y})]}),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(Yg,{})]})]})}),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(Ag,{}),s.jsx(ps,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(bh,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:B,onChange:F})]})}),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(sh,{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:X=>i(X.target.value),onBlur:R,onKeyDown:X=>{X.key==="Enter"&&X.currentTarget.blur()}})]})})})]})}const jS=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],xr="adhdev_onboarding_done",kS=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],SS={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function NS({onDone:e}){const[t,r]=l.useState([]),[n,a]=l.useState(new Set(jS)),[o,i]=l.useState(!0),[c,d]=l.useState(null),[m,u]=l.useState(!1),[p,f]=l.useState(null),[y,g]=l.useState("all");l.useEffect(()=>{let w=!1;const b=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${b}/providers?sort=popular&limit=100`).then(C=>{if(!C.ok)throw new Error(`HTTP ${C.status}`);return C.json()}).then(C=>{w||r(C.providers??[])}).catch(C=>{w||d(C instanceof Error?C.message:String(C))}).finally(()=>{w||i(!1)}),()=>{w=!0}},[]);const x=t.filter(w=>y==="all"||w.category===y),k=["cli","ide","extension","acp"].map(w=>({category:w,items:x.filter(b=>b.category===w)})).filter(w=>w.items.length>0),j=l.useCallback(w=>{a(b=>{const C=new Set(b);return C.has(w)?C.delete(w):C.add(w),C})},[]),h=l.useCallback(async()=>{if(n.size===0){localStorage.setItem(xr,"1"),e();return}u(!0);const w=[];for(const b of n)try{const N=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:b})})).json().catch(()=>({}));w.push({type:b,ok:!!N.success,error:N.error})}catch(C){w.push({type:b,ok:!1,error:C instanceof Error?C.message:String(C)})}f(w),u(!1),w.every(b=>b.ok)&&localStorage.setItem(xr,"1")},[n,e]),v=l.useCallback(()=>{localStorage.setItem(xr,"1"),e()},[e]),I=l.useCallback(()=>{p&&p.every(w=>w.ok)?e():m||v()},[p,m,e,v]);return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60",onClick:I,children:s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-2xl max-w-2xl w-full p-6 flex flex-col gap-5 max-h-[85vh] overflow-y-auto",onClick:w=>w.stopPropagation(),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Welcome to ADHDev"}),s.jsxs("div",{className:"text-[12px] text-text-muted mt-1",children:["Pick the providers you want to use. Defaults to the four officially supported CLI providers; you can install IDE, ACP, or extension providers from the tabs below or later from ",s.jsx("span",{className:"text-text-secondary",children:"Burrow → Providers → Add provider"}),"."]})]}),!o&&!c&&t.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:kS.map(w=>{const b=w.key==="all"?t.length:t.filter(C=>C.category===w.key).length;return b===0&&w.key!=="all"?null:s.jsxs("button",{onClick:()=>g(w.key),className:`machine-btn text-[10px] px-2 py-0.5 ${y===w.key?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:[w.label," ",s.jsxs("span",{className:"opacity-60",children:["(",b,")"]})]},w.key)})}),o&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"Loading registry…"}),!o&&c&&s.jsxs("div",{className:"rounded-xl border border-red-500/30 bg-red-500/5 px-3 py-2 text-[12px] text-red-400",children:["Failed to load registry: ",c]}),!o&&!c&&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:k.map(w=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:SS[w.category]??w.category}),s.jsx("div",{className:"grid gap-1.5",children:w.items.map(b=>{var _,L;const C=n.has(b.type),N=p==null?void 0:p.find(M=>M.type===b.type),S=((_=b.manifest)==null?void 0:_.icon)??"📦",T=((L=b.manifest)==null?void 0:L.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:()=>j(b.type),disabled:m,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:S}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:b.displayName}),T&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:T})]}),N&&s.jsx("span",{className:`text-[10px] font-semibold ${N.ok?"text-green-400":"text-red-400"}`,children:N.ok?"✓ installed":`✗ ${N.error??"failed"}`})]},b.type)})})]},w.category))}),s.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-border-subtle",children:[s.jsxs("div",{className:"text-[11px] text-text-muted",children:[n.size," provider",n.size!==1?"s":""," selected"]}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx("button",{onClick:v,disabled:m,className:"machine-btn text-[11px] px-3 py-1",children:"Skip"}),s.jsx("button",{onClick:()=>{p?(localStorage.setItem(xr,"1"),e()):h()},disabled:m||!p&&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…":p?"Done":`Install ${n.size}`})]})]})]})})}function CS(){try{return localStorage.getItem(xr)==="1"}catch{return!1}}wg();Ug();pS();const IS=Uc({baseUrl:"",getToken:Ri});function MS({children:e}){const[t,r]=l.useState(null),[n,a]=l.useState(!0),[o,i]=l.useState(""),[c,d]=l.useState(""),[m,u]=l.useState(!1),p=async()=>{a(!0),d("");try{const g=await(await Kt("/auth/session")).json();r(g)}catch(y){d(y instanceof Error?y.message:String(y))}finally{a(!1)}};l.useEffect(()=>{p()},[]),l.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let y=!1;return(async()=>{try{const g=await Kt("/api/v1/standalone/preferences");if(!g.ok)return;const x=await g.json();if(y)return;const k=zt(x.standaloneFontPreferences);hs(k),Ho(k)}catch{}})(),()=>{y=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const f=async y=>{y.preventDefault(),u(!0),d("");try{const g=await Kt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),x=await g.json();if(!g.ok)throw new Error((x==null?void 0:x.error)||"Login failed");r(x),i(""),Rm()}catch(g){d(g instanceof Error?g.message:String(g))}finally{u(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit: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 Ec(){const{ides:e,initialLoaded:t}=qt();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(xo,{to:`/machines/${r.id}`,replace:!0}):s.jsx(xo,{to:"/dashboard",replace:!0})}function AS(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let r=!1;if(!CS())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(NS,{onDone:()=>t(!1)}):null}function TS(){const{ides:e}=qt(),t=l.useMemo(()=>{for(const m of e)if(m.activeInteractivePrompt)return m.instanceId??m.id;return null},[e]),{promptSession:r,hasActivePrompt:n,responseError:a,isSubmitting:o,submit:i,cancel:c,reopen:d}=gu(t);return n?s.jsxs("div",{className:"relative",children:[!r&&s.jsx("button",{type:"button",onClick:d,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:"Awaiting your input ↑"}),s.jsx(pd,{promptSession:r,isSubmitting:o,error:a,onSubmit:i,onCancel:c})]}):null}function _S(){const e=l.useMemo(()=>({sendCommand:Nr,sendData:Fo,sendPtyInput:Dm}),[]);return s.jsx(Ip,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Gp,{client:IS,children:s.jsx(MS,{children:s.jsx(lS,{children:s.jsx(qp,{value:e,children:s.jsxs(Qp,{sendDaemonCommand:Nr,children:[s.jsx(TS,{}),s.jsxs(fS,{children:[s.jsx(AS,{}),s.jsxs(Mp,{children:[s.jsx(ts,{path:"/dashboard",element:s.jsx(l1,{})}),s.jsx(ts,{path:"/machine",element:s.jsx(Ec,{})}),s.jsx(ts,{path:"/machines/:id",element:s.jsx(bk,{})}),s.jsx(ts,{path:"/machines",element:s.jsx(Ec,{})}),s.jsx(ts,{path:"/about",element:s.jsx(yS,{})}),s.jsx(ts,{path:"/settings",element:s.jsx(wS,{})}),s.jsx(ts,{path:"/mesh",element:s.jsx(Qk,{children:s.jsx(Xk,{})})}),s.jsx(ts,{path:"*",element:s.jsx(xo,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}Cb({connectionManager:Wt});Ap(document.getElementById("root")).render(s.jsx(_S,{}));