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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,99 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-C45SzZMr.js","assets/vendor-DNk1FT1R.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
- var km=Object.defineProperty;var Sm=(e,t,r)=>t in e?km(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var We=(e,t,r)=>Sm(e,typeof t!="symbol"?t+"":t,r);import{r as l,j as s,M as _o,a as Nm,b as Cm,c as Im,R as ft,d as jr,t as Mm,e as Tm,u as Tr,D as Am,f as ro,g as no,E as _m,i as Lm,C as Pm,h as Rm,B as Dm,k as Em,l as $m,m as Bm,n as Om,H as qr,P as Yr,o as Fm,p as Hm,q as Wm,s as Km,v as Um,w as Lo,x as zm,y as Gm,z as Vm,A as qm,F as Jt,N as ao,G as Ym}from"./vendor-DNk1FT1R.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 Xm(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 Ds=Xm();function Ti(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 Jm(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Ai(e){return Array.isArray(e)?[...e]:[]}function pc(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?Ai(e.messages):i?[]:t.messages,activeModal:n?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...r?{messages:Ai(e.messages)}:{},...n?{activeModal:e.activeModal??null}:{}}}function cr(e,t){const r=Jm(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:pc(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 fc(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?cr(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 _i(e){return!!e&&typeof e=="object"&&"text"in e}function Po(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:_i(o)?String(o.text||""):"").join(r):_i(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Es(e){return Po(e,{normalizeWhitespace:!0})}const xc=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}),bc=l.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Li(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 gc(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 Qm(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 ua(e){if(!e||typeof e!="object")return"";const t=e,r=Qm(Es(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 Zm(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=ua(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:ua(e[0]),last:ua(e[e.length-1])}}function oo(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function io(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(oo(e)&&oo(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)io(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"&&io(n[i],a[i],r)}function hr(e,t){return Array.isArray(e)?e.map(r=>hr(r,t)):!e||typeof e!="object"?e:oo(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Zm(a,t):hr(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,hr(n,t)]))}function eh(e,t){try{const r=new WeakSet;return io(e,t,r),JSON.stringify(hr(e,r))===JSON.stringify(hr(t,r))}catch{return!1}}function lo(e,t,r){return eh(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function yc(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function th(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Pi(e,t,r,n){var c;const a=(c=t.chats)!=null&&c.length?t.chats:e.chats,o=fc(e.childSessions,t.childSessions,{preserveMissing:n}),i=pc(t.activeChat,e.activeChat);return gc(e,t,{...e,...t,chats:a,childSessions:o,activeChat:i,_lastUpdate:r})}function sh(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=fc(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"])th(n,t,i);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function rh(e,t,r,n){const a=sh(e,t,n),o=Object.keys(a).length>0?gc(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return lo(e,o,r)}function nh(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=yc(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 ah(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 oh(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function ih(e,t,r){var u,h;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(f=>({...f,_lastUpdate:n}));const o=new Map;for(const f of t)o.set(f.id,f);const{incomingIds:i,incomingDaemonIds:c,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:m}=nh(e);for(const f of e){const y=o.get(f.id);if(!y){o.set(f.id,{...f,_lastUpdate:n});continue}const b=Li(f),x=Li(y),k=yc(f),j=!a.has(k);if(b>x){const C=Pi(y,f,n,j);o.set(f.id,lo(y,C,n));continue}if(b<x){o.set(f.id,rh(y,f,n,j));continue}const p=f.timestamp||n,w=y._lastUpdate||y.timestamp||0;if(p>=w){const C=Pi(y,f,n,j);o.set(f.id,lo(y,C,n));continue}(u=f.chats)!=null&&u.length&&!((h=y.chats)!=null&&h.length)&&o.set(f.id,{...y,chats:f.chats})}for(const[f,y]of o){const b=y.daemonId||f.split(":")[0];if(!c.has(b))continue;if(a.has(b)&&m.has(b)&&!i.has(f)){o.delete(f);continue}const x=n-(y._lastUpdate||y.timestamp||0);ah(y,b,x,i,a,d)&&o.delete(f)}for(const[f,y]of o){const b=y.daemonId||f.split(":")[0];if(oh(y,b,c,d,o))continue;n-(y._lastUpdate||y.timestamp||0)>3e5&&y.status!=="online"&&o.delete(f)}return Array.from(o.values())}function lh(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 ch({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 h=l.useCallback((j,p)=>{n(w=>{let C=!1;const v=w.map(g=>g.id!==j||g.chats===p?g:(C=!0,{...g,chats:p}));return C?v:w})},[]),f=l.useCallback((j,p)=>{n(w=>{const C=w.length===0?j:ih(j,w,p),v=!lh(w,C);return v&&Ds.record({kind:"dashboard.entries_applied",payload:{incoming:Ti(j),next:Ti(C)}}),v?C:w})},[]),y=l.useCallback(()=>o(!0),[]),b=l.useMemo(()=>({injectEntries:f,markLoaded:y,getIdes:()=>u.current}),[f,y]),x=t,k=l.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:a,toasts:i,setToasts:c,wsStatus:(x==null?void 0:x.wsStatus)??"connected",isConnected:(x==null?void 0:x.isConnected)??!0,connectionStates:(x==null?void 0:x.connectionStates)??{},connectionTransports:(x==null?void 0:x.connectionTransports)??{},showReconnected:(x==null?void 0:x.showReconnected)??!1,retryConnection:x==null?void 0:x.retryConnection,retryServerConnection:x==null?void 0:x.retryServerConnection,connectionLoginUrl:x==null?void 0:x.connectionLoginUrl,isP2PActive:(x==null?void 0:x.isP2PActive)??!1,p2pStates:(x==null?void 0:x.p2pStates)??{},userRole:x==null?void 0:x.userRole,connectionRetryStatuses:x==null?void 0:x.connectionRetryStatuses,userName:d,setUserName:m}),[r,h,a,i,x==null?void 0:x.wsStatus,x==null?void 0:x.isConnected,x==null?void 0:x.connectionStates,x==null?void 0:x.connectionTransports,x==null?void 0:x.showReconnected,x==null?void 0:x.retryConnection,x==null?void 0:x.retryServerConnection,x==null?void 0:x.connectionLoginUrl,x==null?void 0:x.isP2PActive,x==null?void 0:x.p2pStates,x==null?void 0:x.userRole,x==null?void 0:x.connectionRetryStatuses,d]);return s.jsx(bc.Provider,{value:b,children:s.jsx(xc.Provider,{value:k,children:e})})}function qt(){return l.useContext(xc)}function kr(){return l.useContext(bc)}function vc(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 h=a(c),f=new AbortController,y=setTimeout(()=>f.abort(),15e3);try{const b=await fetch(h,{...d,headers:m,signal:f.signal});if(b.status===401)throw n==null||n(),new Error("Unauthorized");if(!b.ok){const x=await b.json().catch(()=>({error:b.statusText}));throw new Error(x.error||`API Error: ${b.status}`)}return b.json()}finally{clearTimeout(y)}}return{getDaemons:()=>i("/api/v1/daemons"),getDaemonStatus:c=>i(`/api/v1/daemons/${c}/status`),sendCommand:(c,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 dh=vc({baseUrl:"http://localhost:3847"}),uh=l.createContext(dh);function mh({client:e,children:t}){return s.jsx(uh.Provider,{value:e,children:t})}const hh={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},wc=l.createContext(hh);function ph({value:e,children:t}){return s.jsx(wc.Provider,{value:e,children:t})}function it(){return l.useContext(wc)}function jc(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function fh(e){const t=jc(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 xh(e){const[t,r]=l.useState(null),n=l.useCallback(async(i,c)=>{const d=h=>e(i,"launch_cli",{...c,...h}),m=await d({}),u=fh(m);return u?new Promise(h=>{r({providerType:u.providerType||String(c.cliType??"?"),sourceName:u.sourceName,description:u.description,retry:()=>d({confirmExternalUntrusted:!0}),resolve:f=>{f.cancelled?h({success:!1,error:"user_cancelled_untrusted_launch"}):h(f.response)}})}):m},[e]),a=l.useCallback(async()=>{const i=t;if(i){r(null);try{const c=await i.retry(),d=jc(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 bh({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 kc=l.createContext(null);function gh({sendDaemonCommand:e,children:t}){const r=xh(e),n=l.useMemo(()=>({launchCli:r.launchCli}),[r.launchCli]);return s.jsxs(kc.Provider,{value:n,children:[t,r.pending&&s.jsx(bh,{providerType:r.pending.providerType,sourceName:r.pending.sourceName,description:r.pending.description,onConfirm:r.confirm,onCancel:r.cancel})]})}function Zn(){const e=l.useContext(kc);return e||{launchCli:async()=>{throw new Error("useLaunchCli must be used inside <LaunchCliProvider>")}}}function yh(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 vh(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function wh(e){return e?yh([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),vh(e.content)]):""}const Be={size:18};function Sc({size:e=Be.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 Ro({size:e=Be.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 ts({size:e=Be.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 Nc({size:e=Be.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 jh({size:e=Be.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 kh({size:e=Be.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 Cc({size:e=Be.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 Sh({size:e=Be.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 ea({size:e=Be.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 Ic({size:e=Be.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 Nh({size:e=Be.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 ws({size:e=Be.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 Bt({size:e=Be.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 Do({size:e=Be.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 $s({size:e=Be.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 ta({size:e=Be.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 Bs({size:e=Be.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 Os({size:e=Be.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 Zt({size:e=Be.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 Ch({size:e=Be.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 Mc({size:e=Be.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 Eo({size:e=Be.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 Tc({size:e=Be.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=Be.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 $o({size:e=Be.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 Mh({size:e=Be.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 Ac({size:e=Be.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 _c({size:e=Be.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 xt({size:e=Be.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 Th({size:e=Be.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 Ah({size:e=Be.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 _h({size:e=Be.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 Lh({size:e=Be.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 Ar({size:e=Be.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=Be.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 Rh({size:e=Be.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 Dh({size:e=Be.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 Lc({size:e=Be.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 Eh({size:e=Be.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 $h({size:e=Be.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 Bh({size:e=Be.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 Oh({size:e=Be.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 Fh({size:e=Be.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 Hh({size:e=Be.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 Wh({size:e=Be.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=Be.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 Pc="adhdev_chat_activity_visible",Ri=new Set(["hidden","debug","internal"]),Di=new Set(["visible","user","chat"]),Uh=new Set(["debug","trace","internal"]),zh=new Set(["tool_call","terminal_command","runtime_activity"]),Gh=new Set(["runtime_status","provider_chrome","control"]),Vh=new Set(["thought","tool","terminal"]);function Rc(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Cs(e){return typeof e=="string"?e.trim().toLowerCase():""}function ma(e,t,r){return e[r]??(t==null?void 0:t[r])}function Ei(e,t,r){const n=e;return r.some(a=>n[a]===!0||(t==null?void 0:t[a])===!0)}function qh(e,t){const r=Cs(e.kind);return r||(t==="tool"?"tool":"standard")}function ha(e,t,r){const n=Rc(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 Yh(e){const t=e.content;return Array.isArray(t)&&t.some(r=>!!r&&typeof r=="object"&&r.type!=="text")}function Bo(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=Rc(e),r=Cs(e.role),n=qh(e,r),a=Cs(ma(e,t,"visibility")),o=Cs(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),i=Cs(ma(e,t,"audience")),c=Cs(ma(e,t,"source")),d=Ri.has(a)||Ri.has(o)||Uh.has(i)||Ei(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),m=Di.has(a)||Di.has(o)||i==="chat"||Ei(e,t,["userFacing"]),u=Vh.has(n)||zh.has(c);if(d)return{surface:u?"activity":"internal",isUserFacing:!1,isActivityFacing:u,isInternal:!u,role:r,kind:n,label:ha(e,n,c)};if(m)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:ha(e,n,c)};if((r==="system"||n==="system")&&Yh(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:"Chat"};if(Gh.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:ha(e,n,c)};const h=(r==="user"||r==="human"||r==="assistant")&&(n==="standard"||n==="");return{surface:h?"chat":"internal",isUserFacing:h,isActivityFacing:!1,isInternal:!h,role:r,kind:n,label:h?"Chat":"Internal"}}function Xh(e){return(Array.isArray(e)?e:[]).filter(t=>Bo(t).isUserFacing)}function Dc(e){return(Array.isArray(e)?e:[]).filter(t=>Bo(t).isActivityFacing)}function Jh(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 $i(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(Pc))==="1"}catch{return!1}}const Ec=[Nm,{singleTilde:!1}],$c=[Ec,Cm,Im],Qh=[Ec],Oo=200,Zh=80,Bi=650,qs=new Map;function Ln(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function ep(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}:${wh(n)}`}function tp(e,t,r,n){return e||!t?!1:Ln(r,n)}function sp({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=Zh,bottomThresholdPx:a=Oo}){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 rp(e){return sp({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function dr(e,t=Oo){return!!e&&e.fromBottom>=t}function np(e,t){return Ln(e,t)?!dr(e):!0}function ap({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function op({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function pa(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function Bc(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function ip(e,t,r){return Number(e.receivedAt||r[Pn(e,t)]||0)||0}function Oc(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function lp(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function Ys(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 fa(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 Xr(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 Oi(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Oc(e)?s.jsx(_o,{remarkPlugins:$c,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function Xs({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:Oi(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=fa(r),o=r.alt||r.description||Ys(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:Xr("Image",o,r.mimeType)},`image-fallback-${n}`)}if(r.type==="audio"){const a=fa(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:Xr("Audio",Ys(r.uri,"audio"),r.transcript||r.mimeType)},`audio-fallback-${n}`)}if(r.type==="video"){const a=fa(r),o=r.title||r.name||r.alt||Ys(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"}):Xr("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||Ys(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}):Xr("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=Ys(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}),Oi(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return s.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${n}`)}return null})})}function Pn(e,t){const r=e,n=Po(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 cp=l.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(_o,{remarkPlugins:Qh,children:t.text}),s.jsx("span",{className:"action-time",children:Bc(t.timestamp)})]})},(e,t)=>e.log===t.log),dp=l.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:i,onToggleTextExpanded:c}){var I,S,T;const d=(t.role||"").toLowerCase(),m=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),h=Bo(t),f=lp(t.content)?t.content:null,y=!!(f!=null&&f.some(P=>P.type!=="text")),b=Po(t.content,{joiner:`
6
- `});if(h.isActivityFacing&&u!=="thought"&&u!=="tool"&&u!=="terminal"){const P=h.label||"Activity";return s.jsxs("div",{className:"self-start chat-msg-activity","data-chat-activity-row":"true",children:[s.jsxs("div",{className:"chat-msg-activity-meta","aria-label":"Activity message",children:[s.jsx("span",{className:"activity-dot"}),s.jsx("span",{children:P})]}),y&&f?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(Xs,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:b})]})}if(u==="thought"){const P=typeof((I=t.meta)==null?void 0:I.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":h.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(_h,{size:13}),s.jsx("span",{children:P})]}),s.jsx("div",{className:"chat-msg-body",children:b})]})}if(u==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":h.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-tool-meta","aria-label":"Tool message",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),s.jsx("span",{className:"tool-label",children:"Tool"})]}),y&&f?s.jsx("div",{className:"tool-text w-full",children:s.jsx(Xs,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:b})]});if(u==="terminal"){const P=(S=t.meta)!=null&&S.isRunning?"⏳":"✅",A=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":h.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:P}),s.jsx("span",{children:A})]}),y&&f?s.jsx("div",{className:"chat-msg-body",children:s.jsx(Xs,{parts:f,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:b})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:y&&f?s.jsx(Xs,{parts:f,renderAsPreformatted:!1}):b.slice(0,100)});const x=t.meta,j=(typeof(x==null?void 0:x.renderMode)=="string"?x.renderMode.trim():"")==="preformatted",p=b,w=!1,C=p,v=j,g=!v&&Oc(C),N=["chat-message-row",m?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:N,children:(p||y||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${p||y?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:m?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:Bc(r)})]}),(p||y)&&s.jsx("div",{className:"chat-markdown",children:y&&f?s.jsx(Xs,{parts:f,renderAsPreformatted:v}):v?s.jsx("pre",{className:"chat-preformatted",children:C}):g?s.jsx(_o,{remarkPlugins:$c,children:C}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:C})}),w]})})},(e,t)=>e.message===t.message&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),up=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:h,onLoadMore:f,isLoadingMore:y,hasMoreHistory:b,hiddenLiveCount:x=0,loadError:k,scrollToBottomRequestNonce:j,isVisible:p=!0},w){const C=l.useRef(null),v=l.useRef(null),g=l.useRef(null),N=l.useRef(0),I=l.useRef(""),S=l.useRef(""),T=l.useRef(!1),P=l.useRef(null),A=l.useRef(!1),D=l.useRef(null),L=l.useRef(!1),[O,_]=l.useState(new Set),[M,$]=l.useState({showTop:!1,showBottom:!1}),W=l.useRef(!1),B=l.useRef(!1),F=l.useRef(p),K=l.useRef(p),Y=l.useRef(null);K.current=p;const re=()=>{const oe=C.current;return oe?oe.scrollHeight-oe.scrollTop-oe.clientHeight<Oo:!0},ae=l.useCallback(()=>{const oe=C.current,R=oe?rp(oe):{showTop:!1,showBottom:!1};$(pe=>pe.showTop===R.showTop&&pe.showBottom===R.showBottom?pe:R)},[]),he=l.useCallback((oe="auto")=>{var pe;const R=C.current;R&&(R.scrollTo({top:R.scrollHeight,behavior:oe}),(pe=R.ownerDocument.defaultView)==null||pe.requestAnimationFrame(()=>ae()))},[ae]),we=l.useCallback((oe="auto")=>{var pe;const R=C.current;R&&(R.scrollTo({top:0,behavior:oe}),(pe=R.ownerDocument.defaultView)==null||pe.requestAnimationFrame(()=>ae()))},[ae]),Ce=l.useCallback(()=>{var Me;const oe=C.current,R=(Me=window.getSelection)==null?void 0:Me.call(window);if(!oe||!R||R.rangeCount===0||R.isCollapsed){L.current=!1;return}const pe=R.anchorNode,Se=R.focusNode;L.current=!!(pe&&Se&&oe.contains(pe)&&oe.contains(Se))},[]),V=l.useMemo(()=>{const oe=Xh(t),R=Dc(t);return Jh(oe,R,u)},[t,u]),q=V.length===t.length?m:void 0,ue=ep(V,q),me=l.useCallback(()=>{const oe=C.current;if(!oe||!c||!K.current)return;const R={top:oe.scrollTop,fromBottom:Math.max(0,oe.scrollHeight-oe.scrollTop-oe.clientHeight),messageFingerprint:ue};Y.current={contextKey:c,snapshot:R},qs.set(c,R)},[c,ue]),le=l.useCallback((oe="auto")=>{P.current!=null&&cancelAnimationFrame(P.current),P.current=requestAnimationFrame(()=>{P.current=null,he(oe)})},[he]),je=l.useCallback(()=>{W.current=!1,A.current=!0,B.current=!0,D.current!=null&&window.clearTimeout(D.current),D.current=window.setTimeout(()=>{A.current=!1,D.current=null},Bi)},[]);l.useEffect(()=>{const oe=!T.current,R=S.current!==c;if(S.current=c,oe||R){T.current=!0;const Se=c?qs.get(c):null,Me=!!Se&&Ln(Se,ue);W.current=Me?dr(Se):!1,A.current=np(Se,ue),L.current||(Me?requestAnimationFrame(()=>{const ee=C.current;ee&&(pa(ee,Se),W.current=dr(Se),ae(),B.current=!0)}):le("auto")),N.current=V.length,I.current=ue;return}V.length>N.current;const pe=ue!==I.current;ap({hasSelection:L.current,userScrolledUp:W.current,hasChatContentChanged:pe})&&le("auto"),N.current=V.length,I.current=ue},[ue,c,V.length,le,ae]),l.useEffect(()=>{j&&(je(),L.current||le("auto"))},[je,le,j]),l.useEffect(()=>{const oe=F.current;oe&&!p&&me(),K.current=p,F.current=p;const R=c?qs.get(c):null;if(tp(oe,p,R,ue)){if(!R)return;W.current=dr(R),A.current=!1,L.current||requestAnimationFrame(()=>{const pe=C.current;pe&&(pa(pe,R),ae())});return}},[p,c,ue,je,me,le,ae]),l.useEffect(()=>()=>{const oe=Y.current;oe&&qs.set(oe.contextKey,oe.snapshot),P.current!=null&&cancelAnimationFrame(P.current),D.current!=null&&window.clearTimeout(D.current)},[]),l.useEffect(()=>{const oe=v.current,R=C.current;if(!oe||!R)return;const pe=()=>{D.current!=null&&window.clearTimeout(D.current),D.current=window.setTimeout(()=>{A.current=!1,D.current=null},Bi)},Se=new ResizeObserver(()=>{ae();const Me=A.current;op({hasSelection:L.current,userScrolledUp:W.current,contextAutoScrollActive:Me})&&(le("auto"),Me&&pe())});return Se.observe(oe),R!==oe&&Se.observe(R),()=>{Se.disconnect(),D.current!=null&&(window.clearTimeout(D.current),D.current=null)}},[le,c,ae]),l.useImperativeHandle(w,()=>({scrollToBottom:(oe="smooth")=>{he(oe)}}),[he]),l.useEffect(()=>{const oe=C.current;if(!oe)return;let R;const pe=()=>{me(),clearTimeout(R),R=setTimeout(()=>{W.current=!re(),ae()},50)};return oe.addEventListener("scroll",pe,{passive:!0}),()=>{oe.removeEventListener("scroll",pe),clearTimeout(R)}},[me,ae]),l.useEffect(()=>(document.addEventListener("selectionchange",Ce),()=>document.removeEventListener("selectionchange",Ce)),[Ce]);const X=l.useRef(0),ye=l.useRef(!1);l.useEffect(()=>{const oe=C.current;if(!oe||!ye.current||X.current===0)return;const R=oe.scrollHeight-X.current;R>0&&(oe.scrollTop=R),ae(),me(),X.current=0,ye.current=!1},[V.length,me,ae]),l.useEffect(()=>{if(B.current||!c)return;const oe=qs.get(c),R=C.current;if(!(!oe||!R)){if(!Ln(oe,ue)){he("auto"),B.current=!0;return}pa(R,oe),W.current=dr(oe),ae(),B.current=!0}},[c,ue,V.length,he,ae]);const de=()=>{const oe=C.current;oe&&(X.current=oe.scrollHeight),ye.current=!0,f==null||f()},ve=()=>{W.current=!0,we("smooth"),me()},fe=()=>{je(),he("smooth"),me()},ge=l.useMemo(()=>{const oe=V.map((Me,ee)=>({type:"message",data:Me,index:ee,ts:ip(Me,ee,d)}));if(!r||r.length===0)return oe;const R=[...r].sort((Me,ee)=>Me.timestamp-ee.timestamp).map((Me,ee)=>({type:"action",data:Me,index:ee,ts:Me.timestamp})),pe=[];let Se=0;for(const Me of oe){for(;Se<R.length&&Me.ts>0&&R[Se].ts<Me.ts;)pe.push(R[Se++]);pe.push(Me)}for(;Se<R.length;)pe.push(R[Se++]);return pe},[V,r,d]),ce=x>0||!!b,be=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:C,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:v,className:"chat-container-content",children:[y&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),ce&&!y&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:de,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${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:be})}),ge.length===0&&!ce&&(h||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),ge.map(oe=>{if(oe.type==="action"){const De=oe.data;return s.jsx(cp,{log:De},`action-${oe.index}`)}const R=oe.data,pe=oe.index,Se=Pn(R,pe),Me=R.receivedAt||d[Se],ee=`${c}-${Se}`,Ne=O.has(ee);return s.jsx(dp,{message:R,receivedAt:Me,agentName:n,userName:a,isCliMode:o,isTextExpanded:Ne,onToggleTextExpanded:()=>_(De=>{const Ee=new Set(De);return Ne?Ee.delete(ee):Ee.add(ee),Ee})},`msg-${Se}`)}),i&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),s.jsx("div",{className:"min-h-10",ref:g})]})}),(M.showTop||M.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[M.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:ve,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),M.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:fe,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),mp=l.memo(up,(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),hp="modulepreload",pp=function(e){return"/"+e},Fi={},fp=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=pp(d),d in Fi)return;Fi[d]=!0;const m=d.endsWith(".css"),u=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const h=document.createElement("link");if(h.rel=m?"stylesheet":hp,m||(h.as="script"),h.crossOrigin="",h.href=d,c&&h.setAttribute("nonce",c),document.head.appendChild(h),m)return new Promise((f,y)=>{h.addEventListener("load",f),h.addEventListener("error",()=>y(new Error(`Unable to preload CSS for ${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 Hi=!1;const Fc=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([]),h=l.useRef(!1),f=l.useRef(!1),y=l.useRef(!1),b=l.useRef(!1),x=()=>{const k=c.current;if(k){h.current&&(k.clear(),h.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),b.current&&(k.scrollToTop(),b.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=[],h.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(u.current=[],h.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():b.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 fp(()=>import("./terminal-C45SzZMr.js"),__vite__mapDeps([0,1,2])).then(j=>{Hi||(Hi=!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"}})});Fc.displayName="CliTerminal";function Jr({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 Wi({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 xp({cursorPos:e,viewportRef:t,imgRef:r}){var p;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(p=t.current)==null?void 0:p.getBoundingClientRect();if(!o)return null;const i=n.naturalWidth||a.width,c=n.naturalHeight||a.height,d=i/c,m=a.width/a.height;let u,h,f,y;d>m?(u=a.width,h=a.width/d,f=0,y=(a.height-h)/2):(h=a.height,u=a.height*d,f=(a.width-u)/2,y=0);const b=a.left-o.left+f+u*e.nx,x=a.top-o.top+y+h*e.ny,k=Math.max(8,Math.min(o.width-8,b)),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 bp({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:i,setImeText:c,handleImeSubmit:d,isConnActive:m,zoom:u,isMobile:h,mobileFillZoom:f,onZoomOut:y,onZoomReset:b,onZoomIn:x,transportType:k,screenshotUsage:j,lastActionStatus:p}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:w=>w.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[s.jsxs("div",{onClick:t,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{n(w=>!w),o(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&s.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:s.jsx("input",{type:"text",placeholder:"Type & Enter...",value:i,autoFocus:!0,onTouchStart:w=>w.stopPropagation(),onChange:w=>c(w.target.value),onKeyDown:w=>{d(w)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{o(w=>!w),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:m?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:m?"#22c55e":"#eab308",boxShadow:m?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:m?"#22c55e":"#eab308"},children:m?"Connected":"WS"})]}),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`}),p&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:p})]})]}),a&&s.jsxs("div",{onTouchStart:w=>w.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",u<=(h?f:1)+.01?h?"FILL":"FIT":`${Math.round(u*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:w=>{w.stopPropagation(),y()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:w=>{w.stopPropagation(),b()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:h?"FILL":"FIT"}),s.jsx("button",{onClick:w=>{w.stopPropagation(),x()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function gp({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 yp(){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 Ki(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 _r(e,t){const r=l.useRef(null),n=l.useRef(0);l.useEffect(()=>{if(!yp())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,Ki(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,Ki(t[i])]))}),r.current=t})}function vp({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:i,panXRef:c,panYRef:d,setPanX:m,setPanY:u,setZoom:h,lastWheelTimeRef:f,onAction:y,setLastActionStatus:b,spawnRippleFromNormalized:x,clampPan:k,isMobile:j,mobileFillZoom:p}){const[w,C]=l.useState(null),v=l.useRef(null),g=l.useRef(null),N=l.useRef(null),I=l.useRef(!1),S=l.useRef(null),T=l.useRef(0),P=l.useRef(null),A=l.useRef(1),D=l.useRef({x:0,y:0}),L=l.useRef(!1),O=l.useRef(n),_=l.useRef(y),M=30,$=550,W=18,B=60,F=400,K=12,Y=()=>{if(v.current)return;const he={nx:.5,ny:.5};v.current=he,C(he)};return l.useEffect(()=>{O.current=n,n==="mouse"&&Y()},[n]),l.useEffect(()=>{_.current=y},[y]),l.useEffect(()=>{const he=e.current;if(!he)return;const we=le=>{if(!r.current)return null;const je=r.current.getBoundingClientRect();return!je.width||!je.height?null:{nx:Math.max(0,Math.min(1,(le.clientX-je.left)/je.width)),ny:Math.max(0,Math.min(1,(le.clientY-je.top)/je.height))}},Ce=(le,je)=>{if(!r.current)return{dnx:0,dny:0};const X=r.current,ye=X.getBoundingClientRect(),de=X.naturalWidth||ye.width,ve=X.naturalHeight||ye.height,fe=de/ve,ge=ye.width/ye.height;let ce,be;return fe>ge?(ce=ye.width,be=ye.width/fe):(be=ye.height,ce=ye.height*fe),{dnx:le/ce,dny:je/be}},V=(le,je,X)=>{if(X<=1.05)return;const ye=-(le-.5)*100,de=-(je-.5)*100,ve=k(ye,de,X);(Math.abs(ve.x-c.current)>.1||Math.abs(ve.y-d.current)>.1)&&(m(ve.x),u(ve.y),c.current=ve.x,d.current=ve.y)},q=le=>{const je=t.current;if(je&&le.target instanceof Node&&je.contains(le.target))le.preventDefault();else return;if(le.touches.length===1){const X=le.touches[0];g.current={x:X.clientX,y:X.clientY,time:Date.now()},N.current={x:X.clientX,y:X.clientY},L.current||(I.current=!1),S.current=setTimeout(()=>{if(!I.current&&!L.current)if(I.current=!0,O.current==="mouse"){const ye=v.current||{nx:.5,ny:.5};b("Right Click"),x(ye.nx,ye.ny,"right"),_.current("input_click",{...ye,button:"right"}).catch(()=>{})}else{const ye=we(X);ye&&(b("Right Click"),x(ye.nx,ye.ny,"right"),_.current("input_click",{...ye,button:"right"}).catch(()=>{}))}},500);return}if(le.touches.length===2){S.current&&clearTimeout(S.current),I.current=!0,L.current=!0;const X=le.touches[1].clientX-le.touches[0].clientX,ye=le.touches[1].clientY-le.touches[0].clientY;P.current=Math.sqrt(X*X+ye*ye),A.current=i.current,D.current={x:(le.touches[0].clientX+le.touches[1].clientX)/2,y:(le.touches[0].clientY+le.touches[1].clientY)/2}}},ue=le=>{const je=t.current;if(je&&le.target instanceof Node&&je.contains(le.target)&&le.preventDefault(),le.touches.length===1&&N.current){const X=le.touches[0],ye=X.clientX-N.current.x,de=X.clientY-N.current.y;if(!I.current&&g.current){const ve=X.clientX-g.current.x,fe=X.clientY-g.current.y;Math.sqrt(ve*ve+fe*fe)>8&&(I.current=!0,S.current&&clearTimeout(S.current))}if(I.current)if(O.current==="mouse"){const ve=Ce(ye,de),fe=v.current||{nx:.5,ny:.5},ge=Math.max(0,Math.min(1,fe.nx+ve.dnx)),ce=Math.max(0,Math.min(1,fe.ny+ve.dny));v.current={nx:ge,ny:ce},C({nx:ge,ny:ce}),b(`Cursor: ${Math.round(ge*100)}%, ${Math.round(ce*100)}%`),V(ge,ce,i.current);const be=Date.now();be-f.current>=30&&(f.current=be,_.current("input_mouseMoved",{nx:ge,ny:ce}).catch(()=>{}))}else if(i.current>1){const ve=t.current;if(ve){const fe=ve.clientWidth,ge=ve.clientHeight,ce=c.current+ye/fe*100,be=d.current+de/ge*100,oe=k(ce,be,i.current);m(oe.x),u(oe.y),c.current=oe.x,d.current=oe.y}}else{const ve=we(X);if(ve){const fe=Date.now();fe-f.current>=40&&(f.current=fe,b("Scroll"),_.current("input_wheel",{nx:ve.nx,ny:ve.ny,deltaX:Math.round(-ye*2.5),deltaY:Math.round(-de*2.5)}).catch(()=>{}))}}N.current={x:X.clientX,y:X.clientY};return}if(le.touches.length===2&&P.current!==null){const X=le.touches[1].clientX-le.touches[0].clientX,ye=le.touches[1].clientY-le.touches[0].clientY,ve=Math.sqrt(X*X+ye*ye)/P.current,fe=(le.touches[0].clientX+le.touches[1].clientX)/2,ge=(le.touches[0].clientY+le.touches[1].clientY)/2,ce=fe-D.current.x,be=ge-D.current.y,oe=Math.abs(ve-1)>.03;if(O.current==="mouse"){if(oe){const R=Math.max(o,Math.min(5,A.current*ve));h(R),i.current=R}else if(Math.abs(ce)>2||Math.abs(be)>2){const R=v.current||{nx:.5,ny:.5},pe=Date.now();pe-f.current>=30&&(f.current=pe,b("Scroll"),_.current("input_wheel",{nx:R.nx,ny:R.ny,deltaX:Math.round(-ce*3),deltaY:Math.round(-be*3)}).catch(()=>{}))}}else{const R=Math.max(o,Math.min(5,A.current*ve));h(R),i.current=R;const pe=t.current;if(pe&&R>1){const Se=pe.clientWidth,Me=pe.clientHeight,ee=c.current+ce/Se*100,Ne=d.current+be/Me*100,De=k(ee,Ne,R);m(De.x),u(De.y),c.current=De.x,d.current=De.y}}D.current={x:fe,y:ge}}},me=le=>{var je;if(S.current&&clearTimeout(S.current),P.current=null,le.touches.length===1&&L.current){const X=le.touches[0];g.current={x:X.clientX,y:X.clientY,time:Date.now()},N.current={x:X.clientX,y:X.clientY},I.current=!0;return}if(le.touches.length===0){if(L.current){L.current=!1,I.current=!1;return}if(le.changedTouches.length===1){const X=le.changedTouches[0],ye=Date.now(),de=ye-(((je=g.current)==null?void 0:je.time)||0),ve=g.current?X.clientX-g.current.x:0,fe=g.current?X.clientY-g.current.y:0,ge=Math.sqrt(ve*ve+fe*fe);if(O.current==="mouse"){if(de<M||de>$||ge>W){I.current=!1;return}const ce=v.current||we(X);ce&&(b(`Click: ${Math.round(ce.nx*100)}%, ${Math.round(ce.ny*100)}%`),x(ce.nx,ce.ny,"left"),_.current("input_click",{...ce}).catch(()=>{}))}else{if(I.current){I.current=!1;return}if(de<B||de>F||ge>K){I.current=!1;return}const ce=we(X);if(!ce)return;ye-T.current<300?(b("Double tap"),x(ce.nx,ce.ny,"double"),_.current("input_click",{...ce,clickCount:2}).catch(()=>{}),T.current=0):(b(`Tap: ${Math.round(ce.nx*100)}%, ${Math.round(ce.ny*100)}%`),x(ce.nx,ce.ny,"left"),_.current("input_click",{...ce}).catch(()=>{}),T.current=ye)}}I.current=!1}};return he.addEventListener("touchstart",q,{passive:!1}),he.addEventListener("touchmove",ue,{passive:!1}),he.addEventListener("touchend",me,{passive:!1}),()=>{he.removeEventListener("touchstart",q),he.removeEventListener("touchmove",ue),he.removeEventListener("touchend",me),S.current&&clearTimeout(S.current)}},[e,t,r,o,i,c,d,m,u,h,f,b,x,k]),{cursorPos:w,cursorPosRef:v,handleToggleInputMode:()=>{a(he=>{const we=he==="touch"?"mouse":"touch";return we==="mouse"&&Y(),we})},handleZoomReset:()=>{const he=j?p:1;h(he),i.current=he,m(0),u(0),c.current=0,d.current=0}}}function Hc({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),[h,f]=l.useState(""),[,y]=l.useState(!1),[b,x]=l.useState([]),k=l.useRef(0),[j,p]=l.useState(!1),[w,C]=l.useState(!1),v=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[g,N]=l.useState(v?"mouse":"touch"),[I,S]=l.useState(1),T=l.useRef(!1),[P,A]=l.useState(1),[D,L]=l.useState(0),[O,_]=l.useState(0);_r("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:g,zoom:P,panX:D,panY:O,isMenuOpen:j,isImeOpen:w});const M=l.useRef(0),$=l.useRef(P),W=l.useRef(D),B=l.useRef(O);l.useEffect(()=>{$.current=P},[P]),l.useEffect(()=>{W.current=D},[D]),l.useEffect(()=>{B.current=O},[O]),l.useEffect(()=>{var de;(de=i.current)==null||de.focus()},[]);const F=r==="connected",K=n,Y=F?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",re=F?"The remote stream is warming up":"Waiting for the remote stream to catch up";l.useEffect(()=>{if(!v||T.current||!K)return;const de=d.current,ve=c.current;if(!de||!ve)return;const fe=()=>{const ge=ve.clientWidth,ce=ve.clientHeight,be=de.naturalWidth,oe=de.naturalHeight;if(!be||!oe||!ge||!ce)return;const R=Math.min(ge/be,ce/oe),Se=Math.max(ge/be,ce/oe)/R;Se>1.01&&(S(Se),A(Se),$.current=Se),T.current=!0};de.complete&&de.naturalWidth?fe():de.addEventListener("load",fe,{once:!0})},[K,v]);const ae=.5;l.useEffect(()=>{P<=ae&&(L(0),_(0))},[P,ae]);const he=(de,ve,fe)=>{if(fe<=ae)return{x:0,y:0};const ge=(fe-1)/(2*fe)*100,ce=(fe-1)/(2*fe)*100;return{x:Math.max(-ge,Math.min(ge,de)),y:Math.max(-ce,Math.min(ce,ve))}},we=(de,ve)=>{if(!d.current)return null;const fe=d.current.getBoundingClientRect();return!fe.width||!fe.height?null:{nx:Math.max(0,Math.min(1,(de-fe.left)/fe.width)),ny:Math.max(0,Math.min(1,(ve-fe.top)/fe.height))}},Ce=(de,ve,fe)=>{const ge=c.current;if(!ge)return;const ce=ge.getBoundingClientRect(),be=++k.current;x(oe=>[...oe,{id:be,x:de-ce.left,y:ve-ce.top,type:fe}]),setTimeout(()=>x(oe=>oe.filter(R=>R.id!==be)),600)},V=(de,ve,fe)=>{const ge=d.current,ce=c.current;if(!ge||!ce)return;const be=ge.getBoundingClientRect(),oe=ce.getBoundingClientRect(),R=ge.naturalWidth||be.width,pe=ge.naturalHeight||be.height,Se=R/pe,Me=be.width/be.height;let ee,Ne,De,Ee;Se>Me?(ee=be.width,Ne=be.width/Se,De=0,Ee=(be.height-Ne)/2):(Ne=be.height,ee=be.height*Se,De=(be.width-ee)/2,Ee=0);const ze=be.left-oe.left+De+ee*de,Qe=be.top-oe.top+Ee+Ne*ve,Ze=++k.current;x(rt=>[...rt,{id:Ze,x:ze,y:Qe,type:fe}]),setTimeout(()=>x(rt=>rt.filter(et=>et.id!==Ze)),600)},q=async de=>{var fe;const ve=we(de.clientX,de.clientY);if(ve){u(`Click: ${Math.round(ve.nx*100)}%, ${Math.round(ve.ny*100)}%`),Ce(de.clientX,de.clientY,"left"),(fe=i.current)==null||fe.focus();try{const ge=await e("input_click",{nx:ve.nx,ny:ve.ny});ge!=null&&ge.success||t(`❌ Click failed: ${ge==null?void 0:ge.error}`)}catch(ge){t(`❌ Click error: ${ge.message||ge}`)}}},ue=async(de,ve,fe,ge=0)=>{try{await e("input_key",{type:fe?"char":"keyDown",key:de,code:ve,text:fe?de:void 0,unmodifiedText:fe?de:void 0,modifiers:ge})}catch(ce){t(`❌ Key error: ${ce.message||ce}`)}},me=async de=>{if(de.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(de.key)&&de.preventDefault();let fe=0;de.altKey&&(fe|=1),de.ctrlKey&&(fe|=2),de.metaKey&&(fe|=4),de.shiftKey&&(fe|=8),u(`Key: ${de.key}`),await ue(de.key,de.code,de.key.length===1,fe)},le=async de=>{if(de.key==="Enter"){if(de.nativeEvent.isComposing)return;if(h){const ve=h;f(""),u(`IME Sent: ${ve}`);try{const fe=await e("input_type",{text:ve});fe!=null&&fe.success||t(`❌ IME error: ${fe==null?void 0:fe.error}`)}catch(fe){t(`❌ IME error: ${fe.message}`)}}else u("Key: Enter"),await ue("Enter","Enter",!1)}};l.useEffect(()=>{const de=i.current;if(!de)return;const ve=fe=>{var ge;if((ge=d.current)!=null&&ge.contains(fe.target)){fe.preventDefault();const ce=Date.now();if(ce-M.current<40)return;M.current=ce;const be=we(fe.clientX,fe.clientY);if(!be)return;u(`Scroll: ${Math.round(fe.deltaY)}`),e("input_wheel",{nx:be.nx,ny:be.ny,deltaX:Math.round(fe.deltaX),deltaY:Math.round(fe.deltaY)}).catch(()=>{})}};return de.addEventListener("wheel",ve,{passive:!1}),()=>de.removeEventListener("wheel",ve)},[e]);const{cursorPos:je,handleToggleInputMode:X,handleZoomReset:ye}=vp({containerRef:i,viewportRef:c,imgRef:d,inputMode:g,setInputMode:N,minZoom:ae,zoomRef:$,panXRef:W,panYRef:B,setPanX:L,setPanY:_,setZoom:A,lastWheelTimeRef:M,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:V,clampPan:he,isMobile:v,mobileFillZoom:I});return s.jsxs("div",{ref:i,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:me,onContextMenu:de=>de.preventDefault(),onFocus:()=>y(!0),onBlur:()=>y(!1),tabIndex:0,children:[s.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[K?s.jsx("img",{ref:d,src:K,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${P}) translate(${D}%, ${O}%)`,transformOrigin:"center center",cursor:g==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:q,onContextMenu:de=>de.preventDefault(),onDragStart:de=>de.preventDefault()}):s.jsx(gp,{waitingLabel:Y,waitingHint:re,transportType:o}),g==="mouse"&&K&&s.jsx(xp,{cursorPos:je,viewportRef:c,imgRef:d}),b.map(de=>{const fe={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[de.type];return s.jsxs("div",{style:{position:"absolute",left:de.x,top:de.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${fe}, 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(${fe}, 0.9)`,boxShadow:`0 0 12px rgba(${fe}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},de.id)})]}),s.jsx(bp,{inputMode:g,onToggleInputMode:X,isImeOpen:w,setIsImeOpen:C,isMenuOpen:j,setIsMenuOpen:p,imeText:h,setImeText:f,handleImeSubmit:le,isConnActive:F,zoom:P,isMobile:v,mobileFillZoom:I,onZoomOut:()=>A(de=>Math.max(.5,de-.25)),onZoomReset:ye,onZoomIn:()=>A(de=>Math.min(5,de+.25)),transportType:o,screenshotUsage:a,lastActionStatus:m}),s.jsx("style",{children:`
7
- @keyframes slideUp {
8
- from { opacity: 0; transform: translateY(6px); }
9
- to { opacity: 1; transform: translateY(0); }
10
- }
11
- @keyframes slideUpSidebar {
12
- from { opacity: 0; transform: translateY(6px); }
13
- to { opacity: 1; transform: translateY(0); }
14
- }
15
- @keyframes click-ripple-ring {
16
- 0% { transform: scale(0.3); opacity: 1; }
17
- 100% { transform: scale(2.2); opacity: 0; }
18
- }
19
- @keyframes click-ripple-dot {
20
- 0% { transform: scale(1); opacity: 0.9; }
21
- 50% { transform: scale(1.8); opacity: 0.6; }
22
- 100% { transform: scale(0.5); opacity: 0; }
23
- }
24
- @keyframes remote-float {
25
- 0% { transform: translateY(0px); }
26
- 50% { transform: translateY(-7px); }
27
- 100% { transform: translateY(0px); }
28
- }
29
- `})]})}function Ui(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 wp(e){var t;return Ui(e.activeInteractivePrompt)||Ui((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function jp(e){return e.sessionId||e.instanceId||e.id}function kp(e,t){for(const r of e){const n=wp(r);if(!n)continue;const a=jp(r);return{daemonId:r.daemonId||r.id.split(":")[0]||r.id,sessionId:a,routeId:r.id,providerType:r.type,title:r.title||r.cliName||r.type,prompt:n}}return null}function Wc(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 zi(e){const t={};for(const r of(e==null?void 0:e.prompt.questions)||[])t[r.questionId]={selectedLabels:[],freeformText:""};return t}function Sp(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 Np({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-white":"border-border-secondary"}`,children:r?s.jsx(Lc,{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 Cp({promptSession:e,isSubmitting:t=!1,error:r,onSubmit:n,onCancel:a}){const[o,i]=l.useState(()=>zi(e));l.useEffect(()=>{i(zi(e))},[e==null?void 0:e.prompt.promptId]);const c=l.useMemo(()=>e?e.prompt.questions.every(f=>Sp(f,o[f.questionId])):!1,[e,o]);if(!e)return null;const d=(f,y)=>{i(b=>{const x=b[f.questionId]||{selectedLabels:[]},k=x.selectedLabels||[],j=f.multiSelect?k.includes(y)?k.filter(p=>p!==y):[...k,y]:[y];return{...b,[f.questionId]:{...x,selectedLabels:j}}})},m=(f,y)=>{i(b=>({...b,[f]:{...b[f]||{selectedLabels:[]},freeformText:y}}))},u=()=>{!c||t||n(o)},h=Wc(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(Bs,{size:15})," Action Required"]}),s.jsx("h2",{className:"mt-1 text-lg font-bold text-text-primary",children:e.title||e.providerType})]}),s.jsx("button",{type:"button",onClick:a,className:"btn btn-ghost btn-sm h-8 w-8 p-0","aria-label":"Cancel interactive prompt",children:s.jsx(xt,{size:16})})]}),s.jsxs("div",{className:"max-h-[70vh] space-y-5 overflow-auto px-5 py-4",children:[e.prompt.questions.map((f,y)=>{var x;const b=h.answers[f.questionId];return s.jsxs("section",{className:"space-y-3",children:[s.jsxs("div",{children:[f.header&&s.jsx("div",{className:"mb-1 text-xs font-semibold uppercase tracking-normal text-text-muted",children:f.header}),s.jsxs("div",{className:"text-sm font-semibold text-text-primary",children:[e.prompt.questions.length>1?`${y+1}. `:"",f.question]})]}),s.jsx("div",{className:"grid gap-2",children:f.options.map(k=>s.jsx(Np,{label:k.label,description:k.description||k.preview,selected:b.selectedLabels.includes(k.label),disabled:t,onClick:()=>d(f,k.label)},k.label))}),f.allowFreeform&&s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-semibold text-text-muted",children:"Other"}),s.jsx("textarea",{value:((x=o[f.questionId])==null?void 0:x.freeformText)||"",disabled:t,onChange:k=>m(f.questionId,k.currentTarget.value),className:"w-full min-h-20 rounded-md border border-border-primary bg-surface-secondary px-3 py-2 text-sm text-text-primary outline-none focus:border-accent-primary"})]})]},f.questionId)}),r&&s.jsx("div",{className:"rounded-md border border-status-error/30 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:r})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-border-primary px-5 py-4",children:[s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:a,disabled:t,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:u,disabled:!c||t,children:t?"Submitting...":"Submit"})]})]})})}function sa(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 Kc=e=>sa(e);function Ip(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 Ks(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 Mp(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...Ip(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 Rn(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 ra(e,t,r){const n=Rn(e,t),a=Ks(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 Tp(e,t,r){return ra(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Uc({activeConv:e,onModalButton:t}){const[r,n]=l.useState(null);if(l.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Ks(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(Bs,{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),h=/^(reject|deny|delete|remove|abort)/.test(m),f=r===c,y=r!==null;return s.jsx("button",{onClick:()=>o(c),disabled:y,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${u?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${y&&!f?"opacity-40":"opacity-100"} ${y?"cursor-not-allowed":"cursor-pointer"}`,style:u?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:h?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:f?"⏳ ...":i(c)},d)})})]})]})}const Fo="adhdev_controls_bar_visible",co="adhdev:controlsbarvisibilitychange";function xa(e){if(!e)return!1;try{return e.getItem(Fo)==="1"}catch{return!1}}function Ap(e,t){if(t)try{t.setItem(Fo,e?"1":"0")}catch{}}function _p(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(co,{detail:{visible:e}}))}function Ho(){const[e,t]=l.useState(()=>typeof window>"u"?!1:xa(window.localStorage)),r=l.useRef(e),n=l.useCallback((i,c=!0)=>{r.current=i,t(i),typeof window<"u"&&Ap(i,window.localStorage),c&&_p(i)},[]);l.useEffect(()=>{const i=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:xa(window.localStorage);r.current=u,t(u)},c=d=>{if(d.key!==Fo)return;const m=xa(window.localStorage);r.current=m,t(m)};return window.addEventListener(co,i),window.addEventListener("storage",c),()=>{window.removeEventListener(co,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 Lp=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Pp(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function Tt(e,t){if(Pp(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":Lp.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 uo(e){return Tt(e)==="generating"}function Gi(e,t){return Tt(e,t)==="waiting_approval"}function bt(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Rp(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 ba(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function zc(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 Dp(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 Ep(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function $p(e){return Dp(e.trim().replace(/\.local$/i,""))}function Bp(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function Gc(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&&!Ep(i));if(r&&r!=="Unknown")return $p(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Ct(e,t={}){return Bp(e)||Gc(e,t)}function Vc(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 qc(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 gs(e,t){return Vc(e).join(" · ")}function Sr(e){return e.transport==="pty"}function Ls(e){return e.transport==="acp"}function Op(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:bt(e)}function Vi(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),i=bt(r||"").trim().toLowerCase();return n===a||n===o||n===i}function Fp(e,t=[],r=[]){var d,m,u,h;const n=Tt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(n==="waiting_approval")return"waiting_approval";if(n==="generating")return"generating";const a=t.find(f=>Gi(f.status,{activeModal:f.activeModal})||uo(f.status));if(a)return Tt(a.status,{activeModal:a.activeModal});const o=r.find(f=>Gi(f.status,{activeModal:f.activeModal})||uo(f.status));if(o)return Tt(o.status,{activeModal:o.activeModal});if(n&&n!=="idle")return n;const i=Tt((d=t[0])==null?void 0:d.status,{activeModal:(m=t[0])==null?void 0:m.activeModal});if(i!=="idle")return i;const c=Tt((u=r[0])==null?void 0:u.status,{activeModal:(h=r[0])==null?void 0:h.activeModal});return c!=="idle"?c:"idle"}function Hp(e){return Tt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Wp(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),o=t.get(a),i=Tt(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 Kp(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 Up(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&&Kp(t.receivedAt)||0}function zp(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function mo(e){return Math.max(zp(e),Up(e.activeChat))}function Gp(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 Wo(e,t){return Gp(mo(e),mo(t),Ct(e,{fallbackId:e.id}),Ct(t,{fallbackId:t.id}),e.id,t.id)}const Yc="adhdev_notification_prefs",qi={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Vp(){try{const e=localStorage.getItem(Yc);if(e){const t=JSON.parse(e);return{...qi,...t}}}catch{}return{...qi}}function qp(e){try{localStorage.setItem(Yc,JSON.stringify(e))}catch{}}let Ut=Vp(),gn=[];function Yp(){gn.forEach(e=>e())}function Xp(e){Ut={...Ut,...e},qp(Ut),Yp()}function Jp(){const[,e]=l.useState(0);l.useEffect(()=>{const r=()=>e(n=>n+1);return gn.push(r),()=>{gn=gn.filter(n=>n!==r)}},[]);const t=l.useCallback(r=>{Xp(r)},[]);return[{...Ut},t]}function pr(e){if(!Ut.globalEnabled)return!1;switch(e){case"disconnect":return Ut.disconnectAlert;case"completion":return Ut.completionAlert;case"approval":return Ut.approvalAlert;case"browser":return Ut.browserNotifications;default:return!0}}const Qp={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Xc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Jc(){return"Notification"in window&&Notification.permission==="granted"}let as=null;function Zp(e){return e!==!1}async function ef(){if(as!==null)return as;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return as=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(as=!!await e.pushManager.getSubscription(),as):(as=!1,!1)}catch{return as=!1,!1}}function ho(e,t,r){if(Jc())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 tf(e,t={}){const r={...Qp,...t},n=l.useRef(new Map),a=l.useRef(0),[o,i]=l.useState(null);l.useEffect(()=>{let d=!1;return ef().then(m=>{d||i(m)}),()=>{d=!0}},[]);const c=l.useCallback((d,m,u)=>{const h=Date.now();h-a.current<r.throttleMs||(a.current=h,ho(d,m,u))},[r.throttleMs]);l.useEffect(()=>{var d;if(!(!r.enabled||!Jc())&&pr("browser")&&!Zp(o)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,Tt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const u=n.current.get(m.id),h=Tt(m.status,{activeModal:m.activeModal}),f=m.name||m.id;if(r.onApproval&&pr("approval")&&h==="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&&pr("completion")&&uo(u)&&h==="idle"&&c(`✅ ${f} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&h==="error"&&u!=="error"&&c(`⚠️ ${f} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,h)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,c])}const sf=/^(run|approve|accept|yes|allow|always)/,rf=/^(run|approve|accept|yes|allow|always|proceed|save)/,nf=/^(reject|deny|delete|remove|abort|cancel|no)/;function Ko(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function af(e){const t=Ko(e).toLowerCase();return sf.test(t)?"primary":nf.test(t)?"danger":"default"}function of(e){return rf.test(Ko(e).toLowerCase())?"approve":"reject"}function lf(e){return e.map((t,r)=>({label:Ko(t),variant:af(t),action:of(t),button:t,buttonIndex:r}))}function cf(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function df(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 uf{constructor(){We(this,"dedupMap",new Map);We(this,"DEDUP_WINDOW_MS",5e3);We(this,"DEDUP_MAX_SIZE",50);We(this,"DEDUP_CLEANUP_AGE_MS",1e4);We(this,"toastCallbacks",[]);We(this,"statusEventCallbacks",[]);We(this,"resolveActionFn",null);We(this,"viewRequestRespondFn",null);We(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,o]of this.dedupMap)r-o>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(o=>o.id===t.daemonId&&o.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const o=this.ides.find(i=>i.id===a&&i.type==="adhdev-daemon");if(o)return o}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}handleRawEvent(t,r){var b;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),o=n||t.daemonId||"",i=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),c=`${o}:${t.event}:${i}`;if(this.isDuplicate(c))return;for(const x of this.statusEventCallbacks)x(t);const d=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(d==null?void 0:d.type)||"";let u=bt(m);const h=this.resolveOwningDaemon(t);if(h){const x=Ct(h,{fallbackId:h.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",(b=t.modalButtons)!=null&&b.length&&this.resolveActionFn){const x=this.resolveActionRouteTarget(t);if(!x)return;const k=this.resolveActionFn,j=lf(t.modalButtons).map(C=>({label:C.label,variant:C.variant,onClick:()=>{k(x,"resolve_action",{action:C.action,button:C.button,buttonIndex:C.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),p=cf(u,t.modalMessage,f),w=Date.now();this.emitToast({id:w,message:p,type:y,timestamp:w,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",pr("browser")&&!document.hasFocus()&&ho(`⚠️ ${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 p=Date.now(),w=df(j,k,this.viewRequestRespondFn,(C,v)=>console.error(`[EventManager] ${C} view request failed:`,v));this.emitToast({id:p,message:f,type:y,timestamp:p,actions:w,duration:3e4}),f=""}pr("browser")&&!document.hasFocus()&&ho("👁️ 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 Je=new uf,Yi=new Map;function Dn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ps(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function na(e){return Dn(e)?Dn(e.result)?e.result:e:null}function mf(e){const t=na(e);return!t||!Dn(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function Qr(e){const t=na(e);return!t||!Dn(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Js(e){const t=na(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Zr(e){const t=na(e);return!!t&&t.success===!1}function hf(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";Je.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";Je.showToast(n.notification.body,a)}}}function pf(e,t){return e&&Ps(e.currentValue)?e.currentValue:t}function ff(e,t){return Ps(t)?Ps(e)?typeof e=="string"&&e.trim()==="":!0:!1}function xf(e,t){var o,i;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if(Ps(c))return c}const n=(o=t.controlValues)==null?void 0:o[e];if(Ps(n))return n;const a=(i=t.defaultValues)==null?void 0:i[e];return Ps(a)?a:void 0}function yn(e,t){return e.options||t[e.id]||[]}const bf={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 gf(e,t,r){var n;return((n=bf[t])==null?void 0:n.has(r.id))===!0}function Uo(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!gf(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function ga(e,t){return{value:t}}function yf(e,t,r){var a;return r?((a=yn(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const vf={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function wf({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:i}){const{sendCommand:c}=it(),d=`${e}:${t||n}`,m=vf[n]||"#94a3b8",[u,h]=l.useState({}),f=l.useRef({}),y=l.useRef(i);f.current=u,y.current=i;const b=l.useRef(0),x={};for(const M of o||[])M.defaultValue!==void 0&&(x[M.id]=M.defaultValue);const k={...x,...i||{},...Date.now()<b.current?u:{}};l.useEffect(()=>{i&&Date.now()>b.current&&h({})},[i]);const[j,p]=l.useState(Yi.get(d)||{}),[w,C]=l.useState(null),[v,g]=l.useState(null),N=l.useCallback(async(M,$={})=>{const W={...$,...t&&{targetSessionId:t}};return await c(e,M,W)},[e,t,c]),I=l.useCallback(async(M,$={})=>{const W=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await N("invoke_provider_script",{...W,scriptName:M,...$})},[N,n,r,t]),S=l.useCallback((M,$,W)=>{const B=pf(W,$);h(F=>({...F,[M.id]:B})),hf(W==null?void 0:W.effects)},[]),T=l.useCallback((M,$)=>{h(W=>{const B={...W};return $===void 0?delete B[M.id]:B[M.id]=$,B}),b.current=0},[]);if(!o||o.length===0)return null;const P=Uo(o,{hostIdeType:r,providerType:n});if(P.length===0)return null;const A=async M=>{if(w===M.id){C(null);return}if(yn(M,j).length>0){C(M.id);return}if(M.dynamic&&M.listScript){g(M.id);try{const W=await I(M.listScript,{}),B=mf(W);if(!B){const Y=Js(W);Y&&Je.showToast(Y,"warning");return}const F=B.options;p(Y=>{const re={...Y,[M.id]:F};return Yi.set(d,re),re});const K=xf(M.id,{localOverrideUntil:b.current,localValues:f.current,controlValues:y.current,defaultValues:x});if(ff(K,B.currentValue)){const Y=B.currentValue;h(re=>({...re,[M.id]:Y}))}C(M.id)}catch(W){const B=W instanceof Error?W.message:`Could not load ${M.label}`;Je.showToast(B,"warning")}finally{g(null)}}},D=async(M,$)=>{C(null);const W=(i==null?void 0:i[M.id])??x[M.id];h(B=>({...B,[M.id]:$})),b.current=Date.now()+5e3;try{if(!M.setScript)return;const B=await I(M.setScript,ga(M,$)),F=Qr(B);if(F&&!F.ok||Zr(B))throw new Error((F==null?void 0:F.error)||Js(B)||`Could not update ${M.label}`);S(M,$,F)}catch(B){T(M,W);const F=B instanceof Error?B.message:`Could not update ${M.label}`;Je.showToast(F,"warning")}},L=async M=>{const $=yn(M,j).map(re=>re.value);if($.length===0)return;const W=String(k[M.id]||""),F=($.indexOf(W)+1)%$.length,K=$[F];if(typeof K!="string")return;const Y=(i==null?void 0:i[M.id])??x[M.id];h(re=>({...re,[M.id]:K})),b.current=Date.now()+5e3;try{if(!M.setScript)return;const re=await I(M.setScript,ga(M,K)),ae=Qr(re);if(ae&&!ae.ok||Zr(re))throw new Error((ae==null?void 0:ae.error)||Js(re)||`Could not update ${M.label}`);S(M,K,ae)}catch(re){T(M,Y);const ae=re instanceof Error?re.message:`Could not update ${M.label}`;Je.showToast(ae,"warning")}},O=async M=>{const W=!k[M.id],B=(i==null?void 0:i[M.id])??x[M.id];h(F=>({...F,[M.id]:W})),b.current=Date.now()+5e3;try{if(!M.setScript)return;const F=await I(M.setScript,ga(M,W)),K=Qr(F);if(K&&!K.ok||Zr(F))throw new Error((K==null?void 0:K.error)||Js(F)||`Could not update ${M.label}`);S(M,W,K)}catch(F){T(M,B);const K=F instanceof Error?F.message:`Could not update ${M.label}`;Je.showToast(K,"warning")}},_=async M=>{if(!M.invokeScript)return;if(M.confirmMessage){const W=[M.confirmTitle,M.confirmMessage,M.confirmLabel].filter(F=>typeof F=="string"&&F.trim().length>0);if(!window.confirm(W.join(`
30
-
31
- `)))return}const $=(i==null?void 0:i[M.id])??x[M.id];try{const W=await I(M.invokeScript),B=Qr(W);if(B&&!B.ok||Zr(W))throw new Error((B==null?void 0:B.error)||Js(W)||`Could not run ${M.label}`);B&&S(M,$??!0,B)}catch(W){T(M,$);const B=W instanceof Error?W.message:`Could not run ${M.label}`;Je.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}),P.map(M=>{const $=String(k[M.id]||""),W=yf(M,j,$),B=w===M.id,F=v===M.id,K=yn(M,j),Y="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(M.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${Y} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:B?`${m}55`:"var(--border-default)",background:B?`${m}10`:"var(--surface-tertiary)",color:$?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void A(M),title:M.label,children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:F?"Loading…":W||M.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),B&&K.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>C(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:M.label}),K.map(re=>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:re.value===$?`${m}14`:"transparent",color:re.value===$?"var(--text-primary)":"var(--text-secondary)",borderLeft:re.value===$?`2px solid ${m}`:"2px solid transparent"},title:re.description||re.label,onMouseEnter:ae=>{ae.currentTarget.style.background=`${m}10`},onMouseLeave:ae=>{ae.currentTarget.style.background=re.value===$?`${m}14`:"transparent"},onClick:()=>void D(M,re.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:re.label}),re.value===$&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},re.value))]})]})]},M.id);case"cycle":return s.jsxs("button",{type:"button",className:`${Y} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:$?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void L(M),title:`Click to cycle: ${K.map(re=>re.label).join(" → ")}`,children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:W||M.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},M.id);case"toggle":return s.jsxs("button",{type:"button",className:`${Y} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:$?`${m}44`:"var(--border-default)",background:$?`${m}14`:"var(--surface-tertiary)",color:$?m:"var(--text-muted)"},onClick:()=>void O(M),"aria-pressed":!!$,children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),M.label]},M.id);case"action":return s.jsxs("button",{type:"button",className:`${Y} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void _(M),children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:M.resultDisplay==="inline"&&$?`${M.label}: ${$}`:M.label})]},M.id);case"display":return s.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:$?"var(--text-primary)":"var(--text-muted)"},children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:$?`${M.label}: ${$}`:M.label})]},M.id);default:return null}})]})})}function jf({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:c,controlValues:d}){const{isVisible:m}=Ho(),u=Uo(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(wf,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:u,controlValues:d})})}const Qs=5,Qc=10*1024*1024;function kf({hasDraft:e,isBusy:t=!1}){return!e||t}function Sf(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 Nf(e){if(e.size>Qc)return null;const t=await Sf(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 Cf(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const Zc=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:h=!0,onControlsToggle:f,messageInput:y}){const b=l.useRef(null),x=l.useRef(null),[k,j]=l.useState(""),[p,w]=l.useState([]),[C,v]=l.useState(null),[g,N]=l.useState(!1),I=l.useRef(!1),{isVisible:S,toggleVisibility:T}=Ho(),P=Cf(y),A=!!k.trim()||p.length>0;l.useEffect(()=>{j(""),w([]),v(null)},[t]),l.useEffect(()=>{var B;m&&((B=b.current)==null||B.focus({preventScroll:!0}))},[t,m]);const D=l.useCallback(async B=>{v(null);const F=Array.from(B).filter(we=>we.type.startsWith("image/"));if(F.length===0)return;const K=Qs-p.length;if(K<=0){v(`Max ${Qs} images`);return}const Y=F.slice(0,K);if(Y.filter(we=>we.size>Qc).length>0){v("Image too large (max 10 MB)");return}const he=(await Promise.all(Y.map(Nf))).filter(we=>we!==null);w(we=>[...we,...he])},[p.length]),L=l.useCallback(B=>{w(F=>F.filter((K,Y)=>Y!==B))},[]),O=l.useCallback(async()=>{const B=k.trim();if(!B&&p.length===0||a||I.current)return;I.current=!0;const F=p.length>0?[...p]:void 0;try{await i(B,F)!==!1&&(j(""),w([]),v(null))}finally{I.current=!1}},[k,p,a,i]),_=l.useCallback(async()=>{if(!d||!c)return;const B=k.trim();if(!B&&p.length===0||I.current)return;I.current=!0;const F=p.length>0?[...p]:void 0;try{await c(B,F)!==!1&&(j(""),w([]),v(null))}finally{I.current=!1}},[p,d,k,c]),M=l.useCallback(B=>{P&&(B.preventDefault(),N(!0))},[P]),$=l.useCallback(()=>N(!1),[]),W=l.useCallback(B=>{P&&(B.preventDefault(),N(!1),B.dataTransfer.files.length>0&&D(B.dataTransfer.files))},[P,D]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",h?"transition-all duration-200 ease-out":"",g?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:m?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:m?200:0,opacity:m?1:0,transform:m?"translateY(0)":"translateY(10px)",padding:m?"10px 12px":"0 12px",pointerEvents:m?"auto":"none"},"aria-hidden":!m,onDragOver:M,onDragLeave:$,onDrop:W,children:[p.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:p.map((B,F)=>s.jsxs("div",{className:"relative group w-14 h-14 rounded-lg overflow-hidden border border-border-subtle shrink-0",style:{background:"var(--surface-secondary)"},children:[s.jsx("img",{src:B.previewUrl,alt:B.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>L(F),className:"absolute top-0.5 right-0.5 w-4 h-4 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-[10px] leading-none","aria-label":`Remove ${B.name}`,children:"✕"})]},F))}),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"})]})}),P&&s.jsxs(s.Fragment,{children:[s.jsx("input",{ref:x,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:B=>{B.target.files&&D(B.target.files),B.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var B;return(B=x.current)==null?void 0:B.click()},disabled:p.length>=Qs,title:p.length>=Qs?`Max ${Qs} 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("input",{ref:b,type:"text",placeholder:o||(P&&p.length>0?"Add a message (optional)...":`Send message to ${r}...`),value:k,onChange:B=>j(B.target.value),onPaste:B=>{if(P&&B.clipboardData.files.length>0&&Array.from(B.clipboardData.files).some(Y=>Y.type.startsWith("image/"))){B.preventDefault(),D(B.clipboardData.files);return}const F=B.clipboardData.getData("text");F&&j(K=>K+F),B.preventDefault()},onKeyDown:B=>{if(B.key==="Enter"){if(B.nativeEvent.isComposing){B.preventDefault();return}B.preventDefault(),O()}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),s.jsx("button",{onClick:()=>{O()},disabled:kf({hasDraft:A,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${A&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:A&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":"Send message",children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:A?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})}),d&&s.jsx("button",{type:"button",onClick:()=>{_()},disabled:!A,className:`h-10 px-3 rounded-full text-[11px] font-medium border border-border-subtle shrink-0 transition-colors ${A?"bg-bg-secondary text-text-primary hover:bg-[var(--surface-tertiary)]":"bg-bg-secondary text-text-muted cursor-default opacity-60"}`,"aria-label":"Force send message now",title:"Force send message now",children:"Force"})]}),(C||P&&g)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${C?"text-red-400":"text-[var(--accent-primary)]"}`,children:C||"Drop image here"}),o&&!C&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:o})]})});function Xi(e){if(!e||!Number.isFinite(e))return"—";try{return`${new Date(e).toLocaleString()} (${e})`}catch{return String(e)}}function Ji(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 If({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 h=await n(t,"get_session_info",{targetSessionId:e}),f=h&&typeof h=="object"?h:{},y=f.result&&typeof f.result=="object"?f.result:f;y!=null&&y.success?c(y):(m((y==null?void 0:y.error)||"Failed to load session info"),c(null))}catch(h){m((h==null?void 0:h.message)||String(h)),c(null)}finally{o(!1)}},[n,t,e]);return l.useEffect(()=>{u()},[u]),l.useEffect(()=>{const h=f=>{f.key==="Escape"&&r()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[r]),s.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Session info",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onClick:r,style:{pointerEvents:"auto"},children:s.jsxs("div",{className:"bg-[var(--surface-primary)] text-text-primary border border-border-default rounded-lg shadow-xl max-w-2xl w-full max-h-[85vh] flex flex-col",onClick:h=>h.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-border-subtle px-4 py-3",children:[s.jsx("h2",{className:"text-base font-semibold",children:"Session info"}),s.jsx("button",{type:"button",onClick:r,className:"text-text-secondary hover:text-text-primary px-2 py-1 rounded","aria-label":"Close",children:"×"})]}),s.jsxs("div",{className:"overflow-y-auto px-4 py-3 text-sm space-y-4",children:[a&&s.jsx("div",{className:"text-text-secondary",children:"Loading…"}),d&&s.jsx("div",{className:"text-red-500",children:d}),(i==null?void 0:i.session)&&s.jsxs(Qi,{title:"Session",children:[s.jsx(Lt,{k:"Session ID",v:s.jsx(Zs,{children:i.session.sessionId})}),s.jsx(Lt,{k:"Provider",v:`${i.session.providerName||i.session.providerType} (${i.session.providerType})`}),i.session.transport&&s.jsx(Lt,{k:"Transport",v:i.session.transport}),i.session.workspace&&s.jsx(Lt,{k:"Workspace",v:s.jsx(Zs,{children:i.session.workspace})}),s.jsx(Lt,{k:"Spawned at",v:s.jsxs(s.Fragment,{children:[Xi(i.session.spawnedAtMs),i.session.spawnedAtMs?s.jsx("span",{className:"text-text-secondary ml-2",children:Ji(i.session.spawnedAtMs)}):null]})}),i.session.providerSessionId&&s.jsx(Lt,{k:"Provider session ID",v:s.jsx(Zs,{children:i.session.providerSessionId})})]}),(i==null?void 0:i.coordinator)&&s.jsxs(Qi,{title:"Mesh coordinator",children:[s.jsx(Lt,{k:"Mesh ID",v:s.jsx(Zs,{children:i.coordinator.meshId})}),i.coordinator.cliType&&s.jsx(Lt,{k:"Coordinator CLI",v:i.coordinator.cliType}),s.jsx(Lt,{k:"Started at",v:s.jsxs(s.Fragment,{children:[Xi(i.coordinator.startedAt),i.coordinator.startedAt?s.jsx("span",{className:"text-text-secondary ml-2",children:Ji(i.coordinator.startedAt)}):null]})}),i.coordinator.injection&&s.jsx(Lt,{k:"Prompt injection",v:`${i.coordinator.injection.mode}${i.coordinator.injection.target?` → ${i.coordinator.injection.target}`:""}`}),i.coordinator.mcpConfigPath&&s.jsx(Lt,{k:"MCP config",v:s.jsx(Zs,{children:i.coordinator.mcpConfigPath})}),i.coordinator.extraSystemPrompt&&s.jsx(Zi,{title:"Per-launch extra prompt",body:i.coordinator.extraSystemPrompt,defaultOpen:!0}),i.coordinator.systemPrompt&&s.jsx(Zi,{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 Qi({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 Lt({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 Zs({children:e}){return s.jsx("code",{className:"font-mono text-xs",children:e})}function Zi({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 Mf({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(If,{sessionId:e,daemonId:t,onClose:()=>n(!1)})]})}const Ye=e=>e.transport==="pty",Us=(e,t)=>Ye(e)?e.mode||"terminal":"chat",ed=(e,t)=>Ye(e)&&Us(e)==="terminal",Ve=e=>e.transport==="acp",Tf=180;function ss(e){return e.streamSource!=="agent-stream"}function js(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function td(e){return e.machineName||""}function Lr(e){return js(e)}function Kt(e){return e.agentType||""}function En(e){return e.hostIdeType||""}function zo(e){return e.displayPrimary||e.agentName||"Agent"}function sd(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Af(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function rd(e){const t=Af(e),r=Es(t==null?void 0:t.content),n=Es(e.lastMessagePreview);return r||n||""}function _f(e,t=Tf){const r=Es(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 Lf(e){return _f(rd(e)||e.displaySecondary||"")}function nd(e){return[e.displaySecondary,td(e)].filter(Boolean)}function Fs(e){return e.agentName||bt(Kt(e))}function Pf(e){var t,r;if(!ss(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return bt(En(e)||Kt(e))}function ad(e){return ss(e)?e.sessionId:e.nativeSessionId}function el(e){return ss(e)?"native":e.tabKey}function Rf(e){return e.sessionId}function Df(e,t){if(t)return ss(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function Ef(e,t){const r=Kt(e),n=ss(e),a=Ye(e)||Ve(e),o=n?a?Fs(e)||(t==null?void 0:t.cliName)||bt(En(e)||r):t!=null&&t.type?bt(t.type):bt(En(e)||r):Fs(e);return{isNativeConversation:n,isCli:Ye(e),isAcp:Ve(e),isCliTerminal:ed(e),providerType:r,displayLabel:o,targetEntry:Df(e,t)}}function ds(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:Ye(e)||Ve(e)?{agentType:Kt(e)}:e.streamSource==="agent-stream"?{agentType:Kt(e)}:t}function us(e){return e?Lr(e):""}function er(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Go(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function tl(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 od(){return"select_session"}function $f(){return"open_panel"}function Bf({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function sl(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function en(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function fr(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Vo(e){return e instanceof Error?e.message:String(e||"")}function rl(e){const t=Vo(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function nl(e,t){const r=Vo(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function al(e,t,r,n={}){const a=ds(r);if(!t||t.length===0)return{message:e,...n.force?{force:!0}:{},...a};const o=t.map(i=>({type:"image",mimeType:i.mimeType,data:i.data,alt:i.name}));return e&&o.push({type:"text",text:e}),{message:e,input:{parts:o,textFallback:e},...n.force?{force:!0}:{},...a}}function aa({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,o]=l.useState(!1),[i,c]=l.useState(!1),[d,m]=l.useState(null),u=l.useRef(!1),h=l.useRef(null);l.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const f=l.useCallback(async(j,p)=>{if(!t||u.current)return!1;const w=j.trim(),C=Go(t);if(Bf({hasMessage:!!w,blockedMessage:C,sendInFlight:u.current}))return C&&m(C),!1;const v=Date.now(),g={tabKey:t.tabKey,message:w,timestamp:v};if(sl(h.current,g))return m(null),!0;u.current=!0,c(!0),m(null),h.current=g;try{const N=us(t);if(!N)return h.current=en(h.current,g),m("Unable to send message right now."),!1;const I=await e(N,"send_chat",al(w,p,t)),S=fr(I);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(N){const I=Vo(N);return I.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",I):console.warn("Send blocked/failed",N),h.current=en(h.current,g),m(tl(N)),!1}finally{u.current=!1,c(!1)}},[t,e]),y=l.useCallback(async(j,p)=>{if(!t||u.current)return!1;const w=j.trim();if(!w&&(!p||p.length===0))return!1;const C=Date.now(),v={tabKey:t.tabKey,message:`force:${w}`,timestamp:C};if(sl(h.current,v))return m(null),!0;u.current=!0,c(!0),m(null),h.current=v;try{const g=us(t);if(!g)return h.current=en(h.current,v),m("Unable to send message right now."),!1;const N=await e(g,"send_chat",al(w,p,t,{force:!0})),I=fr(N);if((I==null?void 0:I.success)===!1||(I==null?void 0:I.sent)===!1)throw new Error((I==null?void 0:I.error)||"Send failed");return m(null),!0}catch(g){return console.warn("Force send blocked/failed",g),h.current=en(h.current,v),m(tl(g)),!1}finally{u.current=!1,c(!1)}},[t,e]),b=l.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(j){console.error("Relaunch failed",j)}},[t,e]),x=l.useCallback(async j=>{if(t)try{const w=(t.modalButtons||[]).indexOf(j),C=j.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),v=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(C),g=us(t);if(!g)return;const N=await e(g,"resolve_action",{button:j,action:v?"approve":"reject",...w>=0&&{buttonIndex:w},...ds(t)}),I=fr(N);I.success||r(S=>[...S,{routeId:t.tabKey,text:nl(j,I==null?void 0:I.error),timestamp:Date.now()}])}catch(p){rl(p)||console.error("[ModalButton] Error:",p),r(w=>[...w,{routeId:t.tabKey,text:rl(p)?nl(j,p):`❌ **${j}** error`,timestamp:Date.now()}])}},[t,e,r]),k=l.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,$f(),{...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:b,handleModalButton:x,handleFocusAgent:k}}const Of=10,Ff=8e3,Hf=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function Wf(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 po(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(Hf.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=Wf(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=>po(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,po(a,n,r+1)]))}function tr(e,t){return Array.isArray(e)?e.slice(-t):[]}function Kf(e,t=Date.now()){const r=e&&t-e.firstAt<=Ff,n=r?e.count+1:1;return n>=Of?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function id(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:tr(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:tr(t.messages,10),visibleMessagesTail:tr(e.visibleMessages,5),historyMessagesTail:tr(e.chatTailState.historyMessages,5),actionLogsTail:tr(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 po(r)}function ld(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 cd(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 ya(e,t){return`${e}:${t}`}function Uf(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function sr(e,t){Uf()&&console.debug(`[subscription-manager] ${e}`,t)}class zf{constructor(){We(this,"active",new Map);We(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var u;const i=ya(n.topic,n.key),c=this.active.get(i);let d=!0;if(c)c.handlers.add(a),c.lastUpdate&&a(c.lastUpdate);else{const h={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,h),sr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((u=t.sendData)==null?void 0:u.call(t,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(i,t,o.retryIntervalMs)}const m=()=>{var y;this.clearRetry(i);const h=this.active.get(i);if(!h||(h.handlers.delete(a),h.handlers.size>0))return;this.active.delete(i);const f={type:"unsubscribe",topic:n.topic,key:n.key};sr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(y=t.sendData)==null||y.call(t,r,f)};return m.initialSendAccepted=d,m}publish(t){const r=ya(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Ds.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),Ds.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=ya(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;sr("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);sr("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;sr("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 Gt=new zf;function Gf(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 Vf(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 va(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function qf(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function Yf(e){qf()&&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 $n(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}=Vf(d),h=Gf(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"),b=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=h.get(k.id),p=cr(k,j),w=(u.get(k.id)||[]).map(C=>cr(C,h.get(C.id)));r.push({id:`${n}:ide:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:p.parentId,sessionKind:p.kind,transport:p.transport,sessionCapabilities:p.capabilities,type:p.providerType,status:p.cdpConnected?"online":"detected",daemonId:n,instanceId:va(n,k.id),workspace:p.workspace,terminals:0,childSessions:w,agents:w.map(C=>({id:C.id,name:C.providerName||C.providerType,type:C.providerType,status:C.status})),activeChat:p.activeChat,...p.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:p.activeInteractivePrompt},chats:[],cdpConnected:p.cdpConnected,...p.lastMessagePreview!==void 0&&{lastMessagePreview:p.lastMessagePreview},...p.lastMessageRole!==void 0&&{lastMessageRole:p.lastMessageRole},...p.lastMessageAt!==void 0&&{lastMessageAt:p.lastMessageAt},...p.lastMessageHash!==void 0&&{lastMessageHash:p.lastMessageHash},lastUpdated:p.lastUpdated,unread:p.unread,lastSeenAt:p.lastSeenAt,inboxBucket:p.inboxBucket,completionMarker:p.completionMarker,seenCompletionMarker:p.seenCompletionMarker,surfaceHidden:p.surfaceHidden,...p.controlValues!==void 0&&{controlValues:p.controlValues},...p.providerControls!==void 0&&{providerControls:p.providerControls},...p.summaryMetadata!==void 0&&{summaryMetadata:p.summaryMetadata},...p.settings!==void 0&&{settings:p.settings},...p.messageInput!==void 0&&{messageInput:p.messageInput},timestamp:c})}for(const k of b){const j=h.get(k.id),p=cr(k,j);r.push({id:`${n}:cli:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:p.parentId,sessionKind:p.kind,transport:p.transport,sessionCapabilities:p.capabilities,type:p.providerType,agentType:p.providerType,status:p.status||"running",daemonId:n,instanceId:va(n,k.id),cliName:p.providerName||p.providerType,mode:p.mode||(j==null?void 0:j.mode)||"terminal",workspace:p.workspace||"",activeChat:p.activeChat,...p.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:p.activeInteractivePrompt},...p.resume!==void 0&&{resume:p.resume},...p.runtimeKey!==void 0&&{runtimeKey:p.runtimeKey},...p.runtimeDisplayName!==void 0&&{runtimeDisplayName:p.runtimeDisplayName},...p.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:p.runtimeWorkspaceLabel},...p.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:p.runtimeWriteOwner},...p.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:p.runtimeAttachedClients},...p.lastMessagePreview!==void 0&&{lastMessagePreview:p.lastMessagePreview},...p.lastMessageRole!==void 0&&{lastMessageRole:p.lastMessageRole},...p.lastMessageAt!==void 0&&{lastMessageAt:p.lastMessageAt},...p.lastMessageHash!==void 0&&{lastMessageHash:p.lastMessageHash},lastUpdated:p.lastUpdated,unread:p.unread,lastSeenAt:p.lastSeenAt,inboxBucket:p.inboxBucket,completionMarker:p.completionMarker,seenCompletionMarker:p.seenCompletionMarker,surfaceHidden:p.surfaceHidden,...p.controlValues!==void 0&&{controlValues:p.controlValues},...p.providerControls!==void 0&&{providerControls:p.providerControls},...p.summaryMetadata!==void 0&&{summaryMetadata:p.summaryMetadata},...p.settings!==void 0&&{settings:p.settings},...p.messageInput!==void 0&&{messageInput:p.messageInput},timestamp:c,_isCli:!0})}for(const k of x){const j=h.get(k.id),p=cr(k,j);r.push({id:`${n}:acp:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:p.parentId,sessionKind:p.kind,transport:p.transport,sessionCapabilities:p.capabilities,type:p.providerType,agentType:p.providerType,status:p.status||"running",daemonId:n,instanceId:va(n,k.id),cliName:p.providerName||p.providerType,mode:"chat",workspace:p.workspace||"",activeChat:p.activeChat,...p.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:p.activeInteractivePrompt},...p.runtimeKey!==void 0&&{runtimeKey:p.runtimeKey},...p.runtimeDisplayName!==void 0&&{runtimeDisplayName:p.runtimeDisplayName},...p.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:p.runtimeWorkspaceLabel},...p.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:p.runtimeWriteOwner},...p.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:p.runtimeAttachedClients},...p.lastMessagePreview!==void 0&&{lastMessagePreview:p.lastMessagePreview},...p.lastMessageRole!==void 0&&{lastMessageRole:p.lastMessageRole},...p.lastMessageAt!==void 0&&{lastMessageAt:p.lastMessageAt},...p.lastMessageHash!==void 0&&{lastMessageHash:p.lastMessageHash},lastUpdated:p.lastUpdated,unread:p.unread,lastSeenAt:p.lastSeenAt,inboxBucket:p.inboxBucket,completionMarker:p.completionMarker,seenCompletionMarker:p.seenCompletionMarker,surfaceHidden:p.surfaceHidden,...p.controlValues!==void 0&&{controlValues:p.controlValues},...p.providerControls!==void 0&&{providerControls:p.providerControls},...p.summaryMetadata!==void 0&&{summaryMetadata:p.summaryMetadata},...p.settings!==void 0&&{settings:p.settings},...p.messageInput!==void 0&&{messageInput:p.messageInput},timestamp:c,_isAcp:!0})}return Yf(r),r}const Xf=15e3,Jf=15e3,Qf=6e4,Zf=1200,ol=12,ex=8e3,tx=4e3,wa=new Map,ja=new Map,tn=new Set,xr=new Map;function sx(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 il(e,t){const r=xr.get(e);!r||r.size===0||(xr.delete(e),r.forEach(n=>n(t)))}function rx(e,t){return new Promise(r=>{const n=xr.get(e)||new Set;xr.set(e,n);const a=i=>{clearTimeout(o),n.delete(a),n.size===0&&xr.delete(e),r(i)},o=setTimeout(()=>a(!1),t);n.add(a)})}function Pr(){const{sendCommand:e,sendData:t}=it(),{injectEntries:r,getIdes:n}=kr();return l.useCallback(async(a,o)=>{if(!a)return;const i=(o==null?void 0:o.minFreshMs)??Qf,c=ja.get(a)||0;if(!(o!=null&&o.force)&&tn.has(a)&&c>0||!(o!=null&&o.force)&&c>0&&Date.now()-c<i)return;const d=wa.get(a);if(d)return d;const m=(async()=>{if(t&&!tn.has(a)){const x=Gt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},k=>{const j=n(),p=j.find(C=>C.id===a),w=$n(k.status,{daemonId:a,existingDaemon:p,existingEntries:j,timestamp:k.timestamp});w.length>0&&r(w),ja.set(a,Date.now()),il(a,!0)});if(x.initialSendAccepted?tn.add(a):tn.delete(a),!(o!=null&&o.force)&&x.initialSendAccepted&&await rx(a,Zf))return}const u=await e(a,"get_status_metadata"),h=sx(u);if(!h)return;const f=n(),y=f.find(x=>x.id===a),b=$n(h,{daemonId:a,existingDaemon:y,existingEntries:f,timestamp:h.timestamp||Date.now()});b.length>0&&r(b,{authoritativeDaemonIds:[a]}),ja.set(a,Date.now()),il(a,!0)})().finally(()=>{wa.delete(a)});return wa.set(a,m),m},[n,r,e,t])}function nx(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const ax=60,ox=50;function ud(e={}){return e.isCliLike?ox:ax}function ix(e={}){return ud(e)}function gt(e){return(typeof e=="string"?e.trim():"")||void 0}function zt(e,t){const r=gt(t);return r?`${e}:${r}`:void 0}function es(e,t,r){const n=zt(t,r),a=gt(r);n&&e.push(n),a&&e.push(a)}function As(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function md(e){return gt(e.providerSessionId)||gt(e.sessionId)||gt(e.tabKey)||gt(e.routeId)}function oa(e){return As([gt(e.historySessionId),gt(e.providerSessionId),gt(e.sessionId)])}function Vt(e){const t=[];return es(t,"provider",e.providerSessionId),es(t,"session",e.sessionId),es(t,"tab",e.tabKey),es(t,"route",e.routeId),As(t)}function lx(e){const t=[];return gt(e.providerSessionId)?(es(t,"provider",e.providerSessionId),As(t)):gt(e.sessionId)?(es(t,"session",e.sessionId),As(t)):gt(e.tabKey)?(es(t,"tab",e.tabKey),As(t)):gt(e.routeId)?(es(t,"route",e.routeId),As(t)):[]}function Nr(e){return zt("provider",e.providerSessionId)||zt("session",e.sessionId)||zt("tab",e.tabKey)||zt("route",e.routeId)||"unknown:"}function Rr(e){return oa(e)[0]}function cx(e){const t=gt(e.providerSessionId),r=gt(e.sessionId),n=gt(e.tabKey),a=gt(e.routeId),o=[zt("provider",t),zt("session",r),zt("tab",n),zt("route",a)].filter(d=>typeof d=="string"),i=Vt({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),c=Nr({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:c,targetKey:c,targetValue:md({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:Rr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:i}}function fo(e,t){const r=cx(e);return lx(t).some(n=>r.lookupKeys.includes(n))}const Dr=60,dx=1e3,qo=12e4,ux=new Set(["generating","waiting_approval","starting","streaming","working"]),xo=new Map;function Yo(e,t,r){return`${e}::${t}::${r||t}`}function Bn(e=Dr){return{liveMessages:[],hasLiveSnapshot:!1,cursor:mx([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function mx(e,t=Dr){return{tailLimit:t}}function ll(e,t){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function bo(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(bo).join(`
41
- `);if(typeof e=="object"){const t=e;return bo(t.text??t.content??t.value??"")}return String(e)}function hx(e){return bo(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function px(e){return e.length===0||e.every(hx)}function fx(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="generating"||t==="long_generating"||t==="streaming"||t==="working"||t==="starting"}function xx(e,t){return Math.max(Math.max(0,t),Array.isArray(e.liveMessages)?e.liveMessages.length:0)}function bx(e,t,r,n,a){if(!fx(n))return!1;const o=xx(e,t);if(o<=0)return!1;if(px(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 gx(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}function cl(e,t){const r=e[t];return typeof r=="string"?r:""}class yx{constructor(t){We(this,"manager");We(this,"sendData");We(this,"daemonId");We(this,"sessionId");We(this,"historySessionId");We(this,"subscriptionKey");We(this,"fallbackRecentCount");We(this,"snapshot");We(this,"transportSubscription",null);We(this,"listeners",new Set);We(this,"retainCount",0);We(this,"loadHistoryPromise",null);We(this,"pendingDisconnectTimer",null);this.manager=t.manager||Gt,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=Bn(Math.max(0,t.tailLimit??Dr))}updateOptions(t){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 r=Math.max(0,t.tailLimit);r!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect()))}}getSnapshot(){return this.snapshot}clearLiveSnapshot(){this.snapshot={...Bn(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:dx}))}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=cl(t,"sessionId");if(r&&r!==this.sessionId)return;const n=cl(t,"historySessionId");if(n&&this.historySessionId&&n!==this.historySessionId)return;const a=gx(t),o=t.messageSource;if(bx(this.snapshot,this.fallbackRecentCount,a,t.status,o))return;const i={tailLimit:this.snapshot.cursor.tailLimit};ll(this.snapshot.liveMessages)===ll(a)&&this.snapshot.cursor.tailLimit===i.tailLimit||(this.snapshot={...this.snapshot,liveMessages:a,hasLiveSnapshot:!0,cursor:i,messageSource:o},this.emit())}}function hd(e){const t=Yo(e.daemonId,e.sessionId,e.historySessionId),r=xo.get(t);if(r)return r.updateOptions(e),r;const n=new yx(e);return xo.set(t,n),n}function vx(e,t,r){if(!e||!t)return;const n=`${e}::${t}::`,a=Yo(e,t,r);for(const[o,i]of xo.entries())(o===a||o.startsWith(n))&&i.clearLiveSnapshot()}function wx(e,t){return{...e,loadHistoryPage:t}}function jx(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function kx(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??qo)),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 Sx(e=qo){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Nx(e,t={}){const r=new Set,n=[];for(const a of e){if(!kx(a,t))continue;const o=Lr(a),i=a.sessionId||"";if(!o||!i)continue;const c=Rr(a),d=Yo(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(jx),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Cx(e,t){const{sendData:r,sendCommand:n}=it(),a=(t==null?void 0:t.enabled)!==!1,o=Lr(e),i=e.sessionId||"",c=Rr(e)||i,d=`daemon:${o}:session:${i}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??Dr),u=l.useMemo(()=>!a||!o||!i?null:hd({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]),[h,f]=l.useState(()=>(u==null?void 0:u.getSnapshot())||Bn(m));l.useEffect(()=>{if(!u){f(Bn(m));return}u.retain(),f(u.getSnapshot());const b=u.subscribe(x=>{f(x)});return()=>{b(),u.release()}},[u,m]);const y=l.useCallback(async()=>{!u||!o||!i||await u.loadHistoryPage(async({offset:b,excludeRecentCount:x})=>{const k=e.agentType,j=await n(o,"chat_history",{agentType:k,offset:b,limit:30,targetSessionId:i,historySessionId:c,excludeRecentCount:x}),p=j&&typeof j=="object"&&"result"in j?j.result||{}:j||{};return{messages:Array.isArray(p.messages)?p.messages:[],hasMore:p.hasMore===!0}})},[e.agentType,u,o,c,n,i]);return l.useMemo(()=>wx(h,y),[y,h])}function Ix(e,t){const{sendData:r}=it(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??Dr),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??qo)),i=Sx(o),[c,d]=l.useState(0);l.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(h=>h+1)},i);return()=>{clearInterval(u)}},[e.length,n,i]);const m=l.useMemo(()=>Nx(e,{recentActivityMs:o}),[e,o,c]);l.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const u=m.descriptors.map(h=>hd({...h,sendData:r,tailLimit:a}));return u.forEach(h=>{h.retain()}),()=>{u.forEach(h=>h.release())}},[m.signature,n,r,a])}function Mx(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function dl(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 Tx(e,t){if(e.length===0)return[];if(t.some(dl))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||!dl(o))continue;const i=String(o.role||"").toLowerCase();n.has(i)||(n.add(i),r.unshift(o))}return r}function Ax(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=Tx(o,i),d=c.length>0?[...c,...i]:i;return t.length===0?d:[...t,...d]}function _x(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Lx(e){return _x(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const vn=new Map,go=new Set;function ul(e,t){!e||vn.get(e)===t||(t?vn.set(e,!0):vn.delete(e),go.forEach(n=>n(e,t)))}function Px(e){return e?vn.get(e)===!0:!1}function Rx(e){return go.add(e),()=>{go.delete(e)}}function Dx(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function Ex(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function $x(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function pd(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function fd(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 Bx(e){return pd(e)?!1:e.inboxBucket==="task_complete"&&fd(e).length>0}function ml(e){return e.branch||"detached HEAD"}function Ox(e){if(e.error)return`${ml(e)} · Git error: ${e.error}`;const t=[ml(e)];return e.changedFiles>0?t.push(Dx(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 Fx(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${Ox(t)}`}function Hx(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function Wx(e,t={}){if(t.enabled===!1)return[];if(!$x(e))return[];const r=pd(e)?"working":Bx(e)?"complete":null;if(!r)return[];const n=r==="complete"?fd(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${Ex(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:Fx(r,e.git),timestamp:Hx(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 Kx=60;function Ux(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 yo({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:h=!0,isVisible:f=!0}){var X,ye,de,ve,fe,ge,ce;const y=l.useRef(new Map),b=l.useRef(void 0),x=Pr(),{sendCommand:k}=it(),{isVisible:j}=Ho();_r("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:d.length,isSendingChat:a});const p=ft.useMemo(()=>Ks(e),[e.status,e.connectionState]);ft.useEffect(()=>{const be=e.sessionId;if(be)return ul(be,p.isGenerating),()=>{ul(be,!1)}},[e.sessionId,p.isGenerating]);const w=l.useMemo(()=>Ef(e,t),[e,t]),C=l.useMemo(()=>{var be;return Uo((be=w.targetEntry)==null?void 0:be.providerControls,{hostIdeType:e.hostIdeType,providerType:w.providerType})},[e.hostIdeType,w.providerType,(X=w.targetEntry)==null?void 0:X.providerControls]),v=ud({isCliLike:w.isCli||w.isAcp}),g=ix({isCliLike:w.isCli||w.isAcp}),N=Cx(e,{enabled:f&&!!e.sessionId,tailLimit:g}),[I,S]=l.useState(v),[T,P]=l.useState(()=>$i()),A=e.tabKey,D=N.historyMessages,L=N.hasMoreHistory,O=N.historyError,_=Mx(e,N),M=Dc(_).length;l.useEffect(()=>{S(v)},[v,A]);const $=Math.max(0,_.length-I),W=zo(e),B=Lr(e),F=Lx(e),K=Go(e),Y=Ux(e),re=o||K||Y,ae=!!K,[he,we]=l.useState(!1);l.useEffect(()=>{const be=w.targetEntry;B&&(!be||be.providerControls===void 0||be.controlValues===void 0)&&x(B,{minFreshMs:3e4}).catch(()=>{})},[B,w.isAcp,(ye=w.targetEntry)==null?void 0:ye.providerControls,(de=w.targetEntry)==null?void 0:de.controlValues,x]);const Ce=l.useCallback(async()=>{if(!he){if(_.length>I){S(be=>Math.min(_.length,be+Kx));return}we(!0);try{await N.loadHistoryPage()}finally{we(!1)}}},[N,he,_.length,I]),{allMessages:V,receivedAtMap:q}=l.useMemo(()=>{const be=Ax({historyMessages:D,liveMessages:_,visibleLiveCount:I}),oe=Wx(e),R=oe.length>0?[...be,...oe]:be,pe={};return R.forEach((Se,Me)=>{const ee=`${e.tabKey}:${Pn(Se,Me)}`;let Ne=nx(Se)||y.current.get(ee)||0;Ne||(Ne=Date.now(),y.current.set(ee,Ne)),pe[Pn(Se,Me)]=Ne}),{allMessages:R,receivedAtMap:pe}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,$,D,_,I]),ue=l.useMemo(()=>d.filter(be=>be.routeId===e.tabKey).sort((be,oe)=>be.timestamp-oe.timestamp),[d,e.tabKey]),me=l.useCallback(async()=>{var Me,ee;if(!B)return;const be=id({activeConv:e,visibleMessages:V,actionLogs:d,controls:(Me=w.targetEntry)==null?void 0:Me.providerControls,controlValues:(ee=w.targetEntry)==null?void 0:ee.controlValues,visibleBarControlCount:C.length,chatTailState:{liveMessages:N.liveMessages,hasLiveSnapshot:N.hasLiveSnapshot,hasMoreHistory:L,historyError:O,historyMessages:D},ui:{controlsVisible:j,visibleLiveCount:I,activityVisible:T,activityCount:M,hiddenLiveCount:$,isInputActive:h,isVisible:f}}),oe=await k(B,"get_chat_debug_bundle",{agentType:w.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:be}),R=fr(oe),pe=dd(R),Se=await cd(pe);Se==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),Je.showToast(ld(R,{locatorCopyStatus:Se}),Se==="failed"?"warning":"success")},[e,d,M,V,j,N.hasLiveSnapshot,N.liveMessages,w.providerType,(ve=w.targetEntry)==null?void 0:ve.controlValues,(fe=w.targetEntry)==null?void 0:fe.providerControls,B,L,$,D,h,f,O,k,T,C.length,I]);l.useEffect(()=>{const be=oe=>{oe.key===Pc&&P($i())};return window.addEventListener("storage",be),()=>window.removeEventListener("storage",be)},[]);const le=l.useCallback(()=>{const be=Kf(b.current);b.current=be.state,be.shouldCollect&&me().catch(oe=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",oe),Je.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[me]),je=l.useMemo(()=>{if(_.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((p.isGenerating||e.status==="streaming")&&we(!1),e.status==="not_monitored"&&F)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(Os,{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($s,{size:14})," Open ",W," 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"&&F)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(Mc,{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($s,{size:14})," Open ",W," 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"&&!he)return!L&&D.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,F,i,L,D.length,c,he,_.length,W,p.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[s.jsx("div",{className:"chat-activity-toggle-bar",children:s.jsx("div",{className:"ml-auto flex items-center gap-1",children:s.jsx(Mf,{sessionId:e.sessionId,daemonId:e.daemonId})})}),s.jsx(mp,{messages:V,actionLogs:ue,agentName:Fs(e)||W||"Agent",userName:m,isCliMode:w.isCli||w.isAcp,isWorking:p.isGenerating,contextKey:e.tabKey,receivedAtMap:q,lastMessageHash:e.lastMessageHash,showActivityMessages:T,onLoadMore:Ce,isLoadingMore:he,hasMoreHistory:L,hiddenLiveCount:$,loadError:O??void 0,emptyState:je,scrollToBottomRequestNonce:u,isVisible:f}),s.jsx(jf,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:w.providerType,displayLabel:w.displayLabel,controls:(ge=w.targetEntry)==null?void 0:ge.providerControls,controlValues:(ce=w.targetEntry)==null?void 0:ce.controlValues,isActive:h,isCliTerminal:w.isCliTerminal}),!w.isCliTerminal&&s.jsx(Zc,{contextKey:e.tabKey,panelLabel:W,isSending:a,isBusy:ae,statusMessage:re,onSend:r,onForceSend:n,canForceSend:!!n&&p.isGenerating&&!ae,isActive:h,showControlsToggle:C.length>0,onControlsToggle:le,messageInput:e.messageInput})]})}let xd=qt;function bd(){return xd()}class zx{constructor(){We(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 gd=new zx;class Gx{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 at=new Gx;function Vx(e){e.dashboardWS&&(gd=e.dashboardWS),e.connectionManager&&(at=e.connectionManager),e.useDaemonsHook&&(xd=e.useDaemonsHook)}const qx=.5,Yx=1.25;function nt(e){return zo(e)}function ys(e){return nd(e).join(" · ")}function yd(e){const t=rd(e);return t||(e.title?e.title:ys(e)||"No messages yet")}function vd(e,t){const{isReconnecting:r,isConnecting:n}=Ks(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function Xx(e,t){const r=["Chat",...nd(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function ms(e){return vd(e)||ys(e)}function Jx(e){return`${nt(e)} · ${yd(e)}`}function Qx(e){const t=En(e),r=t?bt(t):Fs(e);return`${nt(e)} — ${r||"Agent"}`}function Zx(e){return Fs(e)||"CLI"}function wd(e){return sd(e)}function jd(e){return e?`Remote · ${nt(e)||e.workspaceName||"Session"}`:"Remote"}function eb({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var te;qt();const{sendPtyInput:d}=it(),[m,u]=l.useState(!1),h=l.useRef(!1);h.current=m;const[f,y]=l.useState("Runtime terminal unavailable"),[b,x]=l.useState(!1),[k,j]=l.useState(null),[p,w]=l.useState(!1),[C,v]=l.useState(!1),[g,N]=l.useState(1),[I,S]=l.useState(!1),[T,P]=l.useState({width:0,height:0}),[A,D]=l.useState({width:0,height:0}),[L,O]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[_,M]=l.useState(null),$=l.useRef(null),W=l.useRef(null),B=l.useRef(!1),F=l.useRef(!1),K=l.useRef(i),Y=l.useRef(0),re=l.useRef(!1),ae=l.useRef(""),he=l.useRef(null),we=l.useRef(!1),Ce=l.useRef(!1),V=l.useRef(null),q=l.useRef(null),ue=l.useRef(null),me=32*1024,le=()=>{var H,G,Z,ne;return((G=(H=$.current)==null?void 0:H.ownerDocument)==null?void 0:G.defaultView)||((ne=(Z=W.current)==null?void 0:Z.ownerDocument)==null?void 0:ne.defaultView)||window},je=H=>{const G=le();return{ownerWindow:G,frameId:G.requestAnimationFrame(H)}},X=()=>{const H=V.current;if(H){try{H.ownerWindow.cancelAnimationFrame(H.frameId)}catch{}V.current=null}},ye=()=>{const H=q.current;if(H){try{H.ownerWindow.clearTimeout(H.timeoutId)}catch{}q.current=null}},de=()=>{const H=ue.current;if(H){try{H.ownerWindow.clearTimeout(H.timeoutId)}catch{}ue.current=null}},ve=()=>{i&&V.current===null&&(V.current=je(()=>{et()}))},fe=e.tabKey,ge=e.sessionId||"",ce=e.daemonId||((te=e.routeId)==null?void 0:te.split(":")[0])||e.routeId||"",be=Go(e),oe=m?o||be:f,R=qx,pe=Yx,Se=.05,Me=()=>{const H=A.width,G=A.height;if(!Number.isFinite(T.width)||T.width<=0||!Number.isFinite(T.height)||T.height<=0||!Number.isFinite(H)||H<=0||!Number.isFinite(G)||G<=0)return 1;const Z=T.width/H,ne=T.height/G;return Number(Math.min(pe,Math.max(R,Math.min(Z,ne))).toFixed(2))},ee=Me(),Ne=B.current&&g>ee,De=Number.isFinite(A.width)&&A.width>0?Math.max(T.width,Math.round(A.width*g)):T.width,Ee=Number.isFinite(A.height)&&A.height>0?Math.max(T.height,Math.round(A.height*g)):T.height,ze=()=>{je(()=>{const H=W.current;H&&(H.scrollLeft=0,H.scrollTop=H.scrollHeight-H.clientHeight)})},Qe=()=>{var H,G;Y.current=0,re.current=!1,ae.current="",he.current=null,we.current=!1,Ce.current=!1,B.current||(F.current=!1,N(1)),V.current!==null&&X(),u(!1),y("Runtime terminal unavailable"),de(),ye(),j(null),M(null),S(!1),x(!1),w(!1),v(!1),(G=(H=r.current)==null?void 0:H.reset)==null||G.call(H)},Ze=()=>{var H,G;Y.current=0,re.current=!1,ae.current="",he.current=null,we.current=!1,Ce.current=!1,V.current!==null&&X(),u(!0),y(""),de(),ye(),j(null),M(null),S(!1),x(!1),w(!1),v(!1),(G=(H=r.current)==null?void 0:H.reset)==null||G.call(H)},rt=()=>{Ce.current&&(Ce.current=!1,je(()=>{var H,G;(G=(H=r.current)==null?void 0:H.scrollToTop)==null||G.call(H)}))},et=()=>{if(V.current=null,!i)return;const H=ae.current;if(!H)return;const G=H.slice(0,me);ae.current=H.slice(G.length);const Z=r.current;if(!Z){ae.current=G+ae.current,ve();return}Z.write(G,()=>{if(ae.current.length>0){ve();return}rt()})},ct=H=>{H&&(ae.current+=H,ve())},Xe=(H,G=0,Z,ne,E={})=>{var xe,ke,Ie,$e;const ie=!!E.force;!ie&&G>0&&Y.current>=G||!ie&&G===0&&re.current||(Y.current=G,G>0&&w(!0),u(!0),y(""),typeof Z=="number"&&typeof ne=="number"&&Z>0&&ne>0&&((ke=(xe=r.current)==null?void 0:xe.resize)==null||ke.call(xe,Z,ne)),ae.current="",($e=(Ie=r.current)==null?void 0:Ie.reset)==null||$e.call(Ie),H?ct(H):rt())};l.useEffect(()=>{Qe()},[ge]),l.useEffect(()=>{var G;if(!ge)return;const H=((G=at.onRuntimeEvent)==null?void 0:G.call(at,ge,Z=>{if(!(!Z||Z.sessionId!==ge)){if(Z.type==="runtime_snapshot"){if(!i){he.current={text:Z.text||"",seq:Z.seq||0,cols:Z.cols,rows:Z.rows,force:!!Z.force};return}Xe(Z.text||"",Z.seq||0,Z.cols,Z.rows,{force:!!Z.force});return}if(Z.type==="session_output"){re.current=!0,typeof Z.seq=="number"&&(Y.current=Math.max(Y.current,Z.seq),Z.seq>0&&w(!0)),h.current||u(!0),h.current||y(""),typeof Z.data=="string"&&ct(Z.data);return}if(Z.type==="session_cleared"){if(!i){we.current=!0,ae.current="",he.current=null;return}Ze();return}if(Z.type==="session_io_error"){const ne=typeof Z.error=="string"&&Z.error?Z.error:typeof Z.reason=="string"&&Z.reason?Z.reason:"unknown error";u(!1),y(`Runtime input failed: ${ne}`);return}}},ce))||(()=>{});return()=>{H()}},[ce,ge,r,i]);const pt=async(H={})=>{var G;if(!ce||!ge)return{success:!1,error:"daemonId and sessionId are required"};H.preserveStatus||y(H.loadingMessage||"Loading runtime terminal...");try{const Z=await((G=at.requestRuntimeSnapshot)==null?void 0:G.call(at,ce,ge,{sinceSeq:H.sinceSeq,force:H.force}));return Z&&Z.success===!1?(H.preserveStatus||(u(!1),y(`Runtime terminal unavailable: ${Z.error}`)),Z):Z||{success:!0}}catch(Z){const ne=(Z==null?void 0:Z.message)||String(Z);return H.preserveStatus||(u(!1),y(`Runtime terminal unavailable: ${ne}`)),{success:!1,error:ne}}},Ae=async H=>{var ie,xe;const G=((ie=$.current)==null?void 0:ie.ownerDocument)||document,Z=G.defaultView||window,ne=(xe=Z.navigator)==null?void 0:xe.clipboard;if(ne!=null&&ne.writeText&&Z.isSecureContext)try{return await ne.writeText(H),!0}catch{}let E=null;try{return E=G.createElement("textarea"),E.value=H,E.setAttribute("readonly","true"),E.style.position="fixed",E.style.left="-9999px",E.style.top="0",G.body.appendChild(E),E.focus(),E.select(),G.execCommand("copy")}catch{return!1}finally{E==null||E.remove()}},Fe=H=>{ye(),M(H);const G=le();q.current={ownerWindow:G,timeoutId:G.setTimeout(()=>{q.current=null,M(Z=>Z===H?null:Z)},2200)}},st=H=>{de(),j(H);const G=le();ue.current={ownerWindow:G,timeoutId:G.setTimeout(()=>{ue.current=null,j(Z=>Z===H?null:Z)},2200)}},qe=async()=>{var E,ie,xe,ke;const H=((ie=(E=r.current)==null?void 0:E.getSelection)==null?void 0:ie.call(E))||"",G=((ke=(xe=r.current)==null?void 0:xe.getVisibleText)==null?void 0:ke.call(xe))||"",Z=H.trimEnd()||G.trimEnd();if(!Z){Fe("Nothing to copy");return}if(!await Ae(Z)){Fe("Copy failed");return}Fe(H.trimEnd()?"Copied selection":"Copied visible terminal")},Ke=H=>{if(!m||!i)return;((d==null?void 0:d(ce,ge,H))??!1)||Fe("Terminal input failed")},U=async()=>{if(b)return;x(!0),j("Loading older terminal output..."),Ce.current=!0;const H=await pt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(x(!1),(H==null?void 0:H.success)===!1){Ce.current=!1,j(`Older terminal output unavailable: ${H.error}`);return}v(!0),st("Older terminal output loaded"),je(()=>{var G;(G=r.current)==null||G.bumpResize()})};l.useEffect(()=>{var G,Z;if(!ge)return;ce&&((G=at.getState)==null?void 0:G.call(at,ce))==="connected"&&pt();const H=(Z=at.onStateChange)==null?void 0:Z.call(at,(ne,E)=>{ne!==ce||E!=="connected"||pt()});return()=>{H==null||H()}},[ce,ge,r]),l.useEffect(()=>{t&&Qe()},[t,fe,r]),l.useEffect(()=>{var ne,E;const H=$.current,G=(E=(ne=H==null?void 0:H.ownerDocument)==null?void 0:ne.defaultView)==null?void 0:E.ResizeObserver;if(!H||!G)return;const Z=new G(ie=>{const xe=ie[0];if(!xe)return;const{width:ke,height:Ie}=xe.contentRect;P($e=>{const Te=Math.round(ke),Le=Math.round(Ie);return $e.width===Te&&$e.height===Le?$e:{width:Te,height:Le}})});return Z.observe(H),()=>Z.disconnect()},[]),l.useEffect(()=>{if(B.current)return;const H=Me();!Number.isFinite(H)||H<=0||N(G=>F.current?H<G-Se?H:G:(F.current=!0,H))},[A.height,A.width,T.height,T.width]),l.useEffect(()=>{Ne&&ze()},[Ne,Ee,De]),l.useEffect(()=>{var Z;const H=K.current;if(K.current=i,!i)return;H||v(!1),we.current&&(we.current=!1,Ze());const G=he.current;G&&(he.current=null,Xe(G.text,G.seq,G.cols,G.rows,{force:!!G.force})),ce&&ge&&((Z=at.getState)==null?void 0:Z.call(at,ce))==="connected"&&pt(),ae.current&&V.current===null&&ve(),je(()=>{var ne;(ne=r.current)==null||ne.bumpResize()})},[ce,i,ge]),l.useEffect(()=>()=>{V.current!==null&&X(),ye(),de()},[]),l.useEffect(()=>{const H=ne=>{var ie;const E=ne.detail;E!=null&&E.sessionId&&E.sessionId!==ge||m&&((ie=r.current)==null||ie.bumpResize())},G=le(),Z=G===window?[window]:[window,G];for(const ne of Z)ne.addEventListener("adhdev:fit-cli-terminal",H);return()=>{for(const ne of Z)ne.removeEventListener("adhdev:fit-cli-terminal",H)}},[m,ge,r]);const J=m&&p&&!C&&(L.atTop||!L.canScroll)||b||!!k;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:$,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[J&&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:()=>{U()},disabled:!ge||b,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:b?"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:[_&&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:_}),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:()=>{qe()},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(H=>!H),disabled:!m,"aria-label":"Open terminal control keys","aria-expanded":I,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),I&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":"Terminal control keys",className:"absolute right-0 top-10 w-56 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>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:()=>Ke("\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:()=>Ke(" "),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:()=>Ke("\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:()=>Ke("\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:()=>Ke("\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:()=>Ke("\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:()=>Ke("\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:()=>Ke(""),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:()=>Ke(""),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:()=>Ke(""),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:()=>{B.current=!0,N(H=>{const G=Math.max(ee,Number((H-.1).toFixed(2)));return G>ee&&ze(),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:()=>{B.current=!0,N(H=>{const G=Math.min(pe,Number((H+.1).toFixed(2)));return G>ee&&ze(),G})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:W,className:Ne?"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:De>0?`${De}px`:"100%",height:Ee>0?`${Ee}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:A.width>0?`${A.width}px`:"100%",height:A.height>0?`${A.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:g},children:s.jsx(Fc,{ref:r,readOnly:!m||!i,sizingMode:"measured",onViewportMetrics:D,onScrollMetrics:O,onInput:H=>{!m||(d==null||d(ce,ge,H))}})})})}),!m&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:f})]}),s.jsx(Zc,{contextKey:e.tabKey,panelLabel:nt(e),isSending:a,isBusy:!!be,statusMessage:oe,onSend:async H=>be?!1:n(H),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1})]})}const tb=5e3,sb=12e3;function rb(e){return e==="disconnected"||e==="reconnecting"}function nb({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=tb,reconnectActionDelayMs:o=sb}){const i=rb(e),[c,d]=l.useState(()=>!i||a<=0),[m,u]=l.useState(()=>!i||o<=0),h=l.useRef(!1);l.useEffect(()=>{if(!i){d(!1);return}if(h.current=!1,a<=0){h.current=!0,d(!0);return}d(!1);const v=setTimeout(()=>{h.current=!0,d(!0)},a);return()=>clearTimeout(v)},[a,i]),l.useEffect(()=>{if(!i){u(!1);return}if(o<=0){u(!0);return}u(!1);const v=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(v)},[o,i]);const f=i?c:e==="offline"||e==="auth_failed",y=!!(n&&e!=="auth_failed"&&(!i||m)),b=l.useMemo(()=>!t||e!=="connected"?!1:a<=0||h.current,[a,t,e]),x=e==="auth_failed"?"red":e==="offline"?"orange":"accent",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)"},p={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},w="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",C={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[f&&s.jsx("div",{className:w,style:C,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:k[x],border:j[x],color:p[x]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&"Network offline",e==="disconnected"&&"Reconnecting",e==="reconnecting"&&"Reconnecting",e==="auth_failed"&&(r?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),y&&s.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>n==null?void 0:n(),disabled:e==="offline",children:"Reconnect now"})]})}),b&&s.jsx("div",{className:w,style:C,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function ab({terminalBackend:e,isStandalone:t=!1,machineLabel:r,machineKey:n}){const a=l.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[o,i]=l.useState(!1);if(l.useEffect(()=>{if(!a){i(!1);return}try{i(localStorage.getItem(a)==="1")}catch{i(!1)}},[a]),!t||!e||e.backend!=="xterm"||o)return null;const c=(r==null?void 0:r.trim())||"This machine",d=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}i(!0)};return s.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[s.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[s.jsxs("span",{children:[c," is using `xterm` fallback."]}),s.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),s.jsx("button",{type:"button",onClick:d,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function kd({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($o,{size:n}):s.jsx(ws,{size:n})})}const Ht="New session",Sd="A connected machine is ready. Start a new session with any installed provider — CLI, ACP, or IDE.";function ob(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 ib(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 lb(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 On({git:e,className:t="",compact:r=!1}){const n=ob(e),a=ib(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 ${lb(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 cb({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 hl({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function pl({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const i=sa(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 db({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:h,onShowAllHidden:f,onResetPanelsToMain:y,inboxOpen:b,onInboxOpenChange:x,hiddenOpen:k,onHiddenOpenChange:j,onOpenNewSession:p,onOpenDashboardGuide:w,guideNudgeVisible:C=!1,actionShortcuts:v,notifications:g,notificationUnreadCount:N,onOpenNotification:I,onMarkNotificationRead:S,onMarkNotificationUnread:T,onDeleteNotification:P,onOpenGitDialog:A,onOpenMeshGraph:D}){var je;const{ides:L,p2pStates:O={}}=qt(),_=!!e&&Ye(e)&&!Ve(e),M=!!e&&Ve(e),$=!!(e!=null&&e.daemonId)&&!!((je=e==null?void 0:e.coordinator)!=null&&je.meshId),W=c||(e?ed(e)?"terminal":"chat":null),[B,F]=l.useState(!1),K=l.useRef(null),Y=l.useRef(null),re=L.filter(X=>X.type==="adhdev-daemon"),ae=cb({wsStatus:t,isConnected:r,daemonCount:re.length,p2pStates:O}),he=ae.subtitle,we=ae.tone==="connected"?"#22c55e":ae.tone==="limited"?"#eab308":"#ef4444",Ce=ae.tone==="connected"?"0 0 4px #22c55e80":ae.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",V=l.useMemo(()=>g.filter(X=>!X.readAt),[g]),q=l.useMemo(()=>g.filter(X=>!!X.readAt),[g]),ue=l.useMemo(()=>V.slice(0,9),[V]),me=N;l.useEffect(()=>{if(!b)return;const X=ye=>{var de;(de=K.current)!=null&&de.contains(ye.target)||x(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[b,x]),l.useEffect(()=>{if(!k)return;const X=ye=>{var de;(de=Y.current)!=null&&de.contains(ye.target)||j(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[k,j]),l.useEffect(()=>{if(!k&&!b)return;const X=ye=>{if(!ye.altKey)return;const de=ye.code.match(/^Digit([1-9])$/);if(!de)return;const ve=Number(de[1])-1,fe=k?u[ve]:void 0,ge=b?ue[ve]:void 0;if(!(!fe&&!ge)){if(ye.preventDefault(),ye.stopPropagation(),fe){h==null||h(fe),j(!1);return}ge&&(I(ge),x(!1))}};return window.addEventListener("keydown",X,!0),()=>window.removeEventListener("keydown",X,!0)},[u,k,b,ue,j,x,I,h]);const le=X=>{if(!X)return;const ye=n.find(de=>de.tabKey===X);ye&&(m==null||m(ye))};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(ws,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?nt(e):"Dashboard"}),s.jsx("span",{title:ae.title,"aria-label":ae.title,className:"header-title-status-dot",style:{background:we,boxShadow:Ce}}),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:we,boxShadow:Ce}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[he&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",he]}),p&&s.jsx("button",{type:"button",onClick:p,className:"btn btn-secondary btn-sm ml-2",title:`${Ht}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":Ht,children:s.jsx(_c,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[w&&s.jsxs("button",{type:"button",onClick:w,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:"Dashboard guide","aria-label":"Open dashboard guide",children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),C&&s.jsx("span",{children:"Guide"})]}),e&&(_||M||!Ve(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:ys(e)||nt(e),children:nt(e)}),A&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:()=>A(e.daemonId,e.workspacePath),children:s.jsx(On,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(On,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),$&&D&&s.jsxs("button",{type:"button",onClick:()=>D(e),className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",title:"Open live repo mesh graph",children:[s.jsx(Zt,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:"Mesh graph"})]}),(_||M)&&i&&s.jsxs(s.Fragment,{children:[_&&d&&W&&s.jsx(kd,{mode:W,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:M?"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(xt,{size:14})})]}),!Ve(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(Do,{size:14})}),!_&&!Ve(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Bt,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:K,children:[s.jsxs("div",{className:`dashboard-header-hidden${B?" is-drop-target":""}`,ref:Y,onDragEnter:X=>{X.dataTransfer.types.includes("text/tab-key")&&(X.preventDefault(),F(!0))},onDragOver:X=>{X.dataTransfer.types.includes("text/tab-key")&&(X.preventDefault(),X.dataTransfer.dropEffect="move",F(!0))},onDragLeave:X=>{X.currentTarget.contains(X.relatedTarget)||F(!1)},onDrop:X=>{const ye=X.dataTransfer.getData("text/tab-key");X.preventDefault(),F(!1),le(ye)},children:[s.jsxs("button",{type:"button",onClick:()=>j(!k),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(Eo,{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(hl,{value:v==null?void 0:v.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[y&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:y,children:"Reset panels"}),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(hl,{value:v==null?void 0:v.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:nt(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(X=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(X),j(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:nt(X)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(X)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(X)+1]}):null,ys(X)]})]},X.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>x(!b),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Ar,{size:16}),me>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:me})]}),b&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[V.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),V.map(X=>s.jsx(pl,{notification:X,shortcutIndex:ue.indexOf(X)>=0?ue.indexOf(X)+1:void 0,onOpen:()=>I(X),onMarkRead:()=>S(X.id),onMarkUnread:()=>T(X.id),onDelete:()=>P(X.id)},X.id))]}),q.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),q.map(X=>s.jsx(pl,{notification:X,onOpen:()=>I(X),onMarkRead:()=>S(X.id),onMarkUnread:()=>T(X.id),onDelete:()=>P(X.id)},X.id))]}),g.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function jt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function ub(e,t){return String(e||"")!==String(t||"")}function mb(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(`
42
- `).includes(r)||n&&!String(i.workspace||"").toLowerCase().includes(n)||a&&!Vc(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
43
- `).includes(a)))}function hb(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 Nd(e,t={}){return hb(mb(e,t),t.sortMode||"recent")}function Fn(e){return e?"Resume saved history":"Start fresh"}function Xo(e){return e?"Resuming saved history…":"Starting fresh…"}function pb(){return"Start fresh"}function fb(e,t=!1){return e==="cli"?Fn(t):e==="ide"?"Start IDE":"Start ACP session"}function xb(e,t=!1){return e==="cli"?Xo(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function bb(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function gb(){return"Open saved history"}function yb(){return"Saved History"}function Jo(){return"Use saved history when you want continuity in the same provider conversation."}function vb(){return"No saved history found yet."}function wb(){return"Refresh saved history"}function jb(){return"Refreshing saved history…"}function Hn(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function Wn(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 Kn(e){return e==="start-fresh"?"Start fresh":"Restart"}function Un(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Cd(e){return`Resume saved history with ${e}?`}function Id(){return"Review or change the target workspace before resuming saved history."}function kb(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 Md({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:h,onSwitchSession:f,onRefreshHistory:y,onResumeSavedSession:b}){var P;const x=t.find(A=>A.id===e.routeId),k=(x==null?void 0:x.chats)||[],j=(P=x==null?void 0:x.activeChat)==null?void 0:P.id,p=Ye(e)&&!Ve(e),[w,C]=l.useState(()=>jt()),v=c||w,g=String(d||"").trim(),N=A=>{if(m){m(A);return}C(A)},I=l.useMemo(()=>a.map(A=>{const D=String(A.workspace||"").trim();return A.canResume||D||!g?A:{...A,workspace:g,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[g,a]),S=l.useMemo(()=>Nd(I,{textQuery:v.textQuery,workspaceQuery:v.workspaceQuery,modelQuery:v.modelQuery,resumableOnly:v.resumableOnly,sortMode:v.sortMode}),[I,v.modelQuery,v.resumableOnly,v.sortMode,v.textQuery,v.workspaceQuery]),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:p?yb():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Qx(e)}),p&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Jo()})]}),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(xt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!p&&s.jsx("button",{onClick:h,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),p?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:v.textQuery,onChange:A=>N({...v,textQuery:A.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:v.workspaceQuery,onChange:A=>N({...v,workspaceQuery:A.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:v.modelQuery,onChange:A=>N({...v,modelQuery:A.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:v.sortMode,onChange:A=>N({...v,sortMode:A.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:v.resumableOnly,onChange:A=>N({...v,resumableOnly:A.target.checked})}),"Resume-ready only"]})]}),S.map(A=>{const D=e.providerSessionId===A.providerSessionId,L=D||!A.canResume||!!i,O=A.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{L||!b||b(A)},disabled:L,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${D?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${L?"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 ${D?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:A.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:A.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:kb(A.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:A.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[A.workspace||"Workspace unknown",O?" · selected workspace":"",gs(A.summaryMetadata)?` · ${gs(A.summaryMetadata)}`:"",A.messageCount>0?` · ${A.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:D?"ACTIVE":A.canResume?O?"RESUME IN SELECTED WORKSPACE":i===A.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},A.id)})]}):k.map(A=>s.jsxs("div",{onClick:()=>{f(e.routeId,A.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${j===A.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${j===A.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:A.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[A.id.substring(0,12),"..."]}),j===A.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},A.id)),(p&&!o&&S.length===0||!p&&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(Lh,{size:32})}),s.jsx("div",{className:"text-[13px]",children:p?a.length>0?"No saved history matches these filters.":vb():"No recent chat sessions found."})]}),p&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:jb()})})]}),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(ta,{size:13})," ",p?wb():"Refresh History"]})})})]})]});return typeof document>"u"?T:jr.createPortal(T,document.body)}const fl={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 Td({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=fl[n.type]||fl.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(xt,{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 Sb=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Nb(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Cb(e){return e.sessionId||e.instanceId||e.agentType}function ka(e,t){return t||e||"unknown"}function Ad(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Ct(r,{fallbackId:r.id}));return t}function _d(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 Qo(e,t={}){return Ib(e,_d(e,t))}function Ib(e,t={}){var h,f,y,b,x,k,j;const r=[],n=t.machineName,a=t.connectionState,o=Nb(e),i=e.workspace||"",c=Op(e.type,{agentName:e.cliName}),d=Ye(e)||Ve(e)?c:bt(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(p=>{var w,C,v;return{sessionId:p.id,instanceId:p.id,providerSessionId:p.providerSessionId,activeChatId:(w=p.activeChat)==null?void 0:w.id,transport:p.transport,sessionCapabilities:p.capabilities,agentType:p.providerType,agentName:p.providerName||bt(p.providerType),status:p.status,title:p.title,lastMessagePreview:p.lastMessagePreview,lastMessageRole:p.lastMessageRole,lastMessageAt:p.lastMessageAt,lastMessageHash:p.lastMessageHash,messages:((C=p.activeChat)==null?void 0:C.messages)||[],activeModal:((v=p.activeChat)==null?void 0:v.activeModal)||void 0,unread:p.unread,lastSeenAt:p.lastSeenAt,lastUpdated:p.lastUpdated,inboxBucket:p.inboxBucket,completionMarker:p.completionMarker,surfaceHidden:p.surfaceHidden,git:p.git,settings:p.settings,coordinator:p.coordinator,messageInput:p.messageInput}}):[],u=Sb(e);if(u){const p=e.sessionId||e.instanceId,w=(h=e.settings)==null?void 0:h.meshCoordinatorFor,C=(f=e.settings)==null?void 0:f.meshNodeFor,v=w?" (Coordinator)":C?" (Mesh Node)":"",g=c+v,N=(y=e.activeChat)==null?void 0:y.activeModal,I=N&&Array.isArray(N.buttons)&&N.buttons.length>0,S=Fp(e.activeChat,[{status:e.status,activeModal:(b=e.activeChat)==null?void 0:b.activeModal}],e.agents||[]),T=e.activeChat||{title:"",messages:[]};let P=T.title&&String(T.title).trim()?String(T.title).trim():"";const A=(x=e.activeChat)==null?void 0:x.id,D=e.chats;if(A&&Array.isArray(D)&&D.length>0){const W=D.find(B=>B.id===A||B.id&&String(B.id)===String(A));W!=null&&W.title&&String(W.title).trim()&&(P=String(W.title).trim())}const L=(Ye(e)||Ve(e),e.type),O=(Ye(e)||Ve(e))&&Vi(P,g,L)?"":P,_=T.messages||[],M=typeof A=="string"&&A.trim()?A:e.providerSessionId,$=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:p,providerSessionId:e.providerSessionId,historySessionId:M,nativeSessionId:p,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:Ye(e)?e.mode||"terminal":"chat",agentName:g,agentType:L,status:S,title:O,messages:_,resume:e.resume,hostIdeType:!Ye(e)&&!Ve(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:O||o||(Ye(e)?e.mode==="chat"?g:`Terminal${v}`:g),displaySecondary:Ye(e)&&o?g:d,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:I?N.buttons:void 0,modalMessage:I?N.message:void 0,streamSource:"native",tabKey:ka(p,e.id),machineName:n,connectionState:a,settings:e.settings,coordinator:$,messageInput:e.messageInput})}if(u&&(Ye(e)||Ve(e)))return r;for(const p of m){const w=p.activeModal&&Array.isArray(p.activeModal.buttons)&&p.activeModal.buttons.length>0,C=Hp(p),v=Cb(p),g=`${e.id}:${v}`,N=p.title&&String(p.title).trim()||"",I=Vi(N,p.agentName,p.agentType)?"":N,S=p.messages||[];if(!(p.transport==="cdp-webview"||!!p.sessionId||!!p.providerSessionId||S.length>0||w||!!I||!["idle","panel_hidden","disconnected","not_monitored"].includes(C)))continue;const P=p.coordinator||(typeof((j=p.settings)==null?void 0:j.meshCoordinatorFor)=="string"&&p.settings.meshCoordinatorFor?{meshId:p.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:p.sessionId||p.instanceId,providerSessionId:p.providerSessionId,historySessionId:p.activeChatId||p.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:p.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:p.sessionCapabilities,mode:"chat",agentName:p.agentName,agentType:p.agentType,status:C,title:I,messages:S,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:p.git||e.git,displayPrimary:I||o||p.agentName||d,displaySecondary:`${d} · ${p.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:p.lastMessagePreview,lastMessageRole:p.lastMessageRole,lastMessageAt:p.lastMessageAt,lastMessageHash:p.lastMessageHash,lastUpdated:p.lastUpdated||e.lastUpdated,inboxBucket:p.inboxBucket,completionMarker:p.completionMarker,modalButtons:w?p.activeModal.buttons:void 0,modalMessage:w?p.activeModal.message:void 0,streamSource:"agent-stream",tabKey:ka(p.sessionId||p.instanceId,g),machineName:n,connectionState:a,settings:p.settings,coordinator:P,messageInput:p.messageInput})}return r.length===0&&r.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:ka(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function Ld(e){return String(e.type||e.id||"").trim()}function Mb(e){var t;return e.category!=="cli"||!Ld(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 Tb(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!Mb(a))continue;const o=Ld(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 Er(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 vo(e,t){const r=new Set(t.map(n=>n.type));return Er(e).filter(n=>r.has(n))}function Ab(e){return e.map(t=>t.type)}function _b(e,t){const r=Er(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function Lb(e,t){return Er(e).filter(r=>r!==t)}function xl(e,t,r){const n=Er(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 bl({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 gl({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(()=>vo(e,t),[e,t]),m=e.length-d.length,u=t.filter(f=>!d.includes(f.type)),h=()=>{o&&(r(_b(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 b=c.get(f);return s.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border-subtle bg-bg-primary px-3 py-2 sm:flex-row sm:items-center sm:justify-between",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",y+1]}),(b==null?void 0:b.icon)&&s.jsx("span",{"aria-hidden":"true",children:b.icon}),s.jsx("span",{className:"font-mono text-[12px] text-text-primary",children:f}),s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:"available"})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:b?`${b.label} · ${b.statusLabel}`:f})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:n||y===0,title:"Move up",onClick:()=>r(xl(d,f,"up")),children:s.jsx(bl,{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(xl(d,f,"down")),children:s.jsx(bl,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(Lb(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:h,children:"Add provider"}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Inventory is filtered to CLI providers detected on this machine. New launches use this order; existing running sessions may need restart.",m>0?` ${m} provider${m===1?"":"s"} from the saved policy are not detected now and will be omitted when saved.`:""]})]})}function Pb(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 Pd(e,t){const r=Pb(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Rd=[{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:"🏄"}],Dd=[{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:"🧩"}],Ed=[{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:"🟠"}],Rb=Rd,Db=Dd,Eb=Ed;function Yt(...e){return Mm(Tm(e))}function $b({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:Yt("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 br({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($b,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Yt("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const wo="adhdev:themechange";function Bb(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Is(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Ms(e){return e==="system"?Bb():e}function $d(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function wn(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(wo,{detail:{preference:e,theme:t}}))}function Ob(){const e=Is(),t=Ms(e);$d(t),wn(e,t)}function zs(){const[e,t]=l.useState(Is),[r,n]=l.useState(()=>Ms(Is()));l.useEffect(()=>{$d(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),wn("system",m)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=d=>{const m=d.detail||{},u=m.preference,h=m.theme;t(u==="dark"||u==="light"||u==="system"?u:Is()),n(h==="dark"||h==="light"?h:Ms(Is()))},c=d=>{if(d.key!=="theme")return;const m=Is(),u=Ms(m);t(m),n(u)};return window.addEventListener(wo,i),window.addEventListener("storage",c),()=>{window.removeEventListener(wo,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=Ms(i);t(i),n(c);try{localStorage.setItem("theme",i)}catch{}wn(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=Ms(c);n(d);try{localStorage.setItem("theme",c)}catch{}return wn(c,d),c})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const yl={dark:"Dark",light:"Light",system:"System"};function Fb({collapsed:e}){const{preference:t,cycleTheme:r}=zs(),n=t==="dark"?s.jsx(Rh,{size:16}):t==="light"?s.jsx(Ph,{size:16}):s.jsx(Dh,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${yl[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:yl[t]})]})}function Sa(e,t){return e?typeof e=="function"?e(t):e:null}function Hb({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),[h,f]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),y=()=>u(!0),b=()=>u(!1),x=()=>{f(w=>{const C=!w;try{localStorage.setItem(d,C?"1":"0")}catch{}return C})},k=l.useMemo(()=>({collapsed:h,mobileMenuOpen:m,openMobileMenu:y,closeMobileMenu:b,toggleCollapsed:x}),[h,m]),j=w=>`nav-item${w.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${w.className?` ${w.className}`:""}`,p=w=>s.jsxs("div",{className:j(w),id:`nav-${w.id}`,onClick:()=>{w.onSelect(),b()},title:h?w.title??(typeof w.label=="string"?w.label:void 0):w.title,children:[s.jsx("span",{className:"nav-icon",children:w.icon}),!h&&w.label]},w.id);return s.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:y,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),m&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:b,onKeyDown:w=>w.key==="Escape"&&b()}),s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:Sa(t,k)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:b,children:s.jsx(xt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(p)}),n.map(w=>s.jsxs("div",{className:w.className??"border-t border-border-subtle pt-2 mt-2",children:[!h&&w.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:w.title}):null,w.items.map(p)]},w.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(p),Sa(o,k),s.jsx(Fb,{collapsed:h}),Sa(i,k)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function lt({title:e,icon:t,description:r,accentColor:n,className:a,children:o}){return s.jsxs("div",{className:Yt("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 zn({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:Yt("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 Wb={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"},Kb={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function _s({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:Yt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Wb[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Kb[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 ht({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:Yt("mb-5",n),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),r,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function Ss(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:Yt("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 Ub={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"},zb={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Gb({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:Yt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Ub[e],r),children:[s.jsx("span",{className:Yt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",zb[e])}),n]})}function ls({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 Vb({onPrefChange:e}){const[t,r]=Jp(),[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(ls,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ar,{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(ls,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Bt,{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:()=>{Xc().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(ls,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Lc,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:i=>o("completionAlert",i)}),s.jsx(ls,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Eh,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:i=>o("approvalAlert",i)}),s.jsx(ls,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Os,{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 Gn(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function qb(e,t){const r=Gn(e),n=Gn(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 Zo(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function gr(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||qb(r,t)>=0)return!1;const n=Gn(r),a=Gn(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Yb(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Na(e,t){return e instanceof Error?e.message:t}function Xb({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(zn,{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(Qb,{ide:i,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},i.id))})}function vl({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 jr.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 Jb(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Rb,...Db,...Eb].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 Qb({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var L,O;const[o,i]=l.useState("idle"),[c,d]=l.useState(""),[m,u]=l.useState(null),[h,f]=l.useState("idle"),[y,b]=l.useState(""),x=e.version||null,k=((L=e.machine)==null?void 0:L.platform)||((O=e.system)==null?void 0:O.platform)||"",j=Ct(e,{fallbackId:e.id}),p=k==="win32"?"🪟":k==="darwin"?"🍎":"🐧",w=t.filter(_=>_.daemonId===e.id&&_.transport==="cdp-page"),C=t.filter(_=>_.daemonId===e.id&&_.transport==="pty"),v=t.filter(_=>_.daemonId===e.id&&_.transport==="acp"),g=e.p2p,N=async()=>{if(r){i("upgrading"),d("Starting upgrade...");try{const _=Yb(await r(e.id,"daemon_upgrade",{}));_.alreadyLatest?(i("done"),d(`Already on v${_.version||"latest"}.`)):_.upgraded||_.success?(i("done"),d(`Upgrade to v${_.version||"latest"} started. Daemon is restarting...`)):(i("error"),d(_.error||"Upgrade failed"))}catch(_){i("error"),d(Na(_,"Connection lost during upgrade"))}}},I=async()=>{if(u(null),!!n){f("loading");try{await n(e.id),f("done"),b("Machine disconnected.")}catch(_){f("error"),b(Na(_,"Failed to disconnect"))}}},S=async()=>{if(u(null),!!a){f("loading");try{await a(e.id),f("done"),b("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(_){f("error"),b(Na(_,"Failed to revoke token"))}}},T="0.9.82",P=Zo(e,T),A=gr(e,T),D=w.length+C.length+v.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:p}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children: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] ${P?"":"bg-bg-secondary"}`,style:P?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",x,!P&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&P&&s.jsx("button",{onClick:N,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":`${A?"↑ Update now":`↑ Update${` to v${T}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Gb,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[g&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${g.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${g.state==="connecting"||g.state==="new"?"animate-pulse":""}`,style:g.state==="connecting"||g.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",g.state==="connected"?"connected":g.state==="connecting"||g.state==="new"?"connecting...":g.state||"off"]}),g.peers!==void 0&&g.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",g.peers," peer",g.peers!==1?"s":"",")"]})]}),g&&D>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),D>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[w.map(_=>{const M=Jb(_.type),$=_.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:M.icon}),s.jsx("span",{children:M.name}),$!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${$?"bg-green-400":"animate-pulse"}`,style:$?void 0:{background:"var(--status-warning)"},title:$?"CDP connected":"CDP connecting..."})]},_.id)}),C.map(_=>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:_.cliName||"CLI"})]},_.id)),v.map(_=>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:_.cliName||"ACP"})]},_.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(c||y)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||h==="error"?"text-red-400":o==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:y||c})]}),m==="disconnect"&&s.jsx(vl,{title:"🔌 Disconnect Machine",message:`Disconnect "${j}" from ADHDev?
44
-
45
- This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
46
-
47
- Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:I,onCancel:()=>u(null)}),m==="revoke"&&s.jsx(vl,{title:"⚠️ Remove Machine",message:`Remove "${j}" from your dashboard?
48
-
49
- This will:
50
- • Immediately disconnect the machine
51
- • Delete the machine registration
52
- • Require restarting ADHDev on that machine
53
-
54
- Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:S,onCancel:()=>u(null)})]})}const Zb=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function eg({daemonId:e,knownCliTypes:t=Zb}){const{sendCommand:r}=it(),[n,a]=l.useState({}),[o,i]=l.useState({}),[c,d]=l.useState(!0),[m,u]=l.useState(null),[h,f]=l.useState(null),[y,b]=l.useState(""),x=l.useCallback(async()=>{if(e){d(!0),f(null);try{const p=await r(e,"list_coordinator_prompts",{}),w=p!=null&&p.result&&typeof p.result=="object"?p.result:p;if(!(w!=null&&w.success)){f((w==null?void 0:w.error)||"Failed to load");return}const C=w.entries||{};b(w.dir||"");const v={};for(const g of t)v[g]=C[g]||{override:"",append:""};for(const g of Object.keys(C))v[g]||(v[g]=C[g]);a(v),i(JSON.parse(JSON.stringify(v)))}catch(p){f((p==null?void 0:p.message)||String(p))}finally{d(!1)}}},[r,e,t]);l.useEffect(()=>{x()},[x]);const k=l.useCallback(async(p,w)=>{var C;if(e){u(`${p}:${w}`),f(null);try{const v=((C=n[p])==null?void 0:C[w])||"",g=await r(e,"write_coordinator_prompt",{key:p,kind:w,content:v}),N=g!=null&&g.result&&typeof g.result=="object"?g.result:g;if(!(N!=null&&N.success)){f((N==null?void 0:N.error)||"Save failed");return}i(I=>({...I,[p]:{...I[p]||{override:"",append:""},[w]:v}}))}catch(v){f((v==null?void 0:v.message)||String(v))}finally{u(null)}}},[r,e,n]),j=l.useMemo(()=>(p,w)=>{var C,v;return(((C=n[p])==null?void 0:C[w])||"")!==(((v=o[p])==null?void 0:v[w])||"")},[n,o]);return e?s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",children:[s.jsxs("p",{children:["Customize the coordinator prompt this daemon's mesh coordinator sessions get. ",s.jsx("span",{className:"font-mono text-[11px]",children:y||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx("strong",{children:"Override"})," replaces the daemon's built-in base prompt for that CLI."," ",s.jsx("strong",{children:"Append"})," stacks after whichever base wins. Leave a field empty + Save to remove it (reset to default). Supports placeholders: ","{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}",", etc."]})]}),h&&s.jsx("div",{className:"text-[12px] text-red-400 bg-red-500/10 border border-red-500/20 rounded px-3 py-2",children:h}),c&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(n).map(([p,w])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-2",children:p}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Override"}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:4,value:w.override,onChange:C=>a(v=>({...v,[p]:{...v[p],override:C.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:m===`${p}:override`}),s.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void k(p,"override"),disabled:m===`${p}:override`||!j(p,"override"),children:m===`${p}:override`?"Saving…":j(p,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Append"}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:3,value:w.append,onChange:C=>a(v=>({...v,[p]:{...v[p],append:C.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:m===`${p}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void k(p,"append"),disabled:m===`${p}:append`||!j(p,"append"),children:m===`${p}:append`?"Saving…":j(p,"append")?"Save append":"Saved"})})]},p))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const tg=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function sg(){const{preference:e,setPreference:t}=zs();return s.jsx("div",{className:"flex gap-2",children:tg.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 rg(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 ng(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Ca(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function wl(e){const{r:t,g:r,b:n}=ng(e);return .2126*Ca(t)+.7152*Ca(r)+.0722*Ca(n)}function jl(e,t){const r=wl(e),n=wl(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function Bd(e){const t=rg(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return jl(t,r)>=jl(t,n)?r:n}const jo={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},ko={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},ag=[{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"}}}],Od="adhdev-chat-theme",Fd="adhdev-chat-theme-custom";function jn(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Od)||"ember"}catch{return"ember"}}function Et(e){try{const t=localStorage.getItem(Fd);if(t){const r=JSON.parse(t);return{...e==="dark"?jo:ko,...r[e]}}}catch{}return e==="dark"?jo:ko}function sn(e,t){try{localStorage.setItem(Fd,JSON.stringify({dark:e,light:t}))}catch{}}function It(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 Vn(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 og={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function yr(e,t){var a;const r=(a=og[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",Vn(r,24)),n.style.setProperty("--accent-on-primary",Bd(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Vn(r,18)})`),n.style.setProperty("--border-accent",It(r,.35)),n.style.setProperty("--nav-active-bg",It(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${It(r,.06)}`)}function hs(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",It(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",It(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",It(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",It(e.borderSubtle,.5)),t.style.setProperty("--border-default",It(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Vn(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Bd(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Vn(e.accentColor,40)})`),t.style.setProperty("--border-accent",It(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",It(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${It(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 ${It(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 ei(){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 ig(e){try{localStorage.setItem(Od,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ps()?"dark":"light";hs(Et(t))}else ei(),yr(e,ps()?"dark":"light")}function lg(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=jn();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ps()?"dark":"light";hs(Et(t))}else ei(),yr(e,ps()?"dark":"light")}function ps(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function vt({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 rr({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 cg({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=l.useState(()=>Et(r));l.useEffect(()=>{a(Et(r))},[r]);const o=l.useCallback((i,c)=>{a(d=>{const m={...d,[i]:c},h=Et(r==="dark"?"light":"dark");return r==="dark"?sn(m,h):sn(h,m),hs(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(rr,{title:"App Background",children:[s.jsx(vt,{label:"Background",value:n.bgPrimary,onChange:i=>o("bgPrimary",i)}),s.jsx(vt,{label:"Surface",value:n.bgSecondary,onChange:i=>o("bgSecondary",i)}),s.jsx(vt,{label:"Card",value:n.surfacePrimary,onChange:i=>o("surfacePrimary",i)})]}),s.jsxs(rr,{title:"App Text",children:[s.jsx(vt,{label:"Primary",value:n.textPrimary,onChange:i=>o("textPrimary",i)}),s.jsx(vt,{label:"Secondary",value:n.textSecondary,onChange:i=>o("textSecondary",i)}),s.jsx(vt,{label:"Muted",value:n.textMuted,onChange:i=>o("textMuted",i)})]}),s.jsxs(rr,{title:"Borders & Accent",children:[s.jsx(vt,{label:"Border subtle",value:n.borderSubtle,onChange:i=>o("borderSubtle",i)}),s.jsx(vt,{label:"Border default",value:n.borderDefault,onChange:i=>o("borderDefault",i)}),s.jsx(vt,{label:"Accent",value:n.accentColor,onChange:i=>o("accentColor",i)})]})]}),s.jsxs("div",{children:[s.jsxs(rr,{title:"Chat Bubbles",children:[s.jsx(vt,{label:"User bubble",value:n.userBubble,onChange:i=>o("userBubble",i)}),s.jsx(vt,{label:"User text",value:n.userText,onChange:i=>o("userText",i)}),s.jsx(vt,{label:"Agent bubble",value:n.assistantBubble,onChange:i=>o("assistantBubble",i)}),s.jsx(vt,{label:"Agent text",value:n.assistantText,onChange:i=>o("assistantText",i)})]}),s.jsxs(rr,{title:"Chat Layout",children:[s.jsx(vt,{label:"Chat BG",value:n.containerBg,onChange:i=>o("containerBg",i)}),s.jsx(vt,{label:"Send button",value:n.sendButton,onChange:i=>o("sendButton",i)}),s.jsx(vt,{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?jo:ko,d=Et(e?"light":"dark");e?sn(i,d):sn(d,i),a(i),hs(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 dg(){const[e,t]=l.useState(jn),[r,n]=l.useState(!0),[a,o]=l.useState(()=>Et("dark"));l.useEffect(()=>{n(ps());const d=new MutationObserver(()=>{const h=ps();n(h);const f=jn();f==="custom"?hs(Et(h?"dark":"light")):yr(f,h?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const h=ps();n(h);const f=jn();f==="custom"?hs(Et(h?"dark":"light")):yr(f,h?"dark":"light")};return m.addEventListener("change",u),()=>{d.disconnect(),m.removeEventListener("change",u)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?hs(Et(r?"dark":"light")):(ei(),yr(e,r?"dark":"light"))},[e,r]),l.useEffect(()=>{o(Et(r?"dark":"light"))},[r]);const i=d=>{t(d),ig(d)},c=[...ag,{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,h=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:h},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background: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(cg,{dark:r,onColorsChange:d=>o(d)})]})}const ti="adhdev_mobileDashboardMode_v1",So="adhdev:mobile-dashboard-mode-change";function si(){try{return localStorage.getItem(ti)==="workspace"?"workspace":"chat"}catch{return"chat"}}function ug(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??si())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==ti||t()};return window.addEventListener(So,r),window.addEventListener("storage",n),()=>{window.removeEventListener(So,r),window.removeEventListener("storage",n)}}function mg(e){try{localStorage.setItem(ti,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(So,{detail:e}))}function hg(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(si()==="chat")},[]),s.jsx(ls,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ws,{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),mg(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Ia=new Map,kl=new Map;function pg(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 fg(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 Hd(){const{sendCommand:e}=it(),{injectEntries:t,getIdes:r}=kr();return l.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??Jf,i=kl.get(n)||0;if(!(a!=null&&a.force)&&i>0&&Date.now()-i<o)return;const c=Ia.get(n);if(c)return c;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=pg(m);if(!u)return;const h=r().find(y=>y.id===n),f=fg(h,n,u.machine,u.timestamp||Date.now());t([f]),kl.set(n,Date.now())})().finally(()=>{Ia.delete(n)});return Ia.set(n,d),d},[r,t,e])}function xg(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 bg(e,t){const{sendData:r}=it(),{injectEntries:n,getIdes:a}=kr(),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=>Gt.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const h=a().find(y=>y.id===d),f=xg(h,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 gg(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=Gt.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)},tx):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 yg(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Wd(e){const{sendData:t}=it(),[r,n]=l.useState({});return l.useEffect(()=>{const a=yg(e);if(!a||!e.sessionId||!t){n({});return}const o=Gt.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}),Ds.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 Kd="adhdev_hiddenTabs",Ud="adhdev_autoHiddenMeshTabs";function vg(){try{const e=localStorage.getItem(Kd);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function os(e){try{localStorage.setItem(Kd,JSON.stringify([...e]))}catch{}}function wg(){try{const e=localStorage.getItem(Ud);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function Sl(e){try{localStorage.setItem(Ud,JSON.stringify([...e]))}catch{}}function ur(e){return Nr(e)}function ia(e,t){return Vt(t).some(r=>e.has(r))}function zd(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 jg(e,t,r=new Set){return e.filter(n=>{if(!zd(n))return!1;const a=ur(n);return r.has(a)?!1:!ia(t,n)})}function kg(){const[e,t]=l.useState(vg),[r,n]=l.useState(wg),a=l.useCallback(f=>{const y=ur(f);t(b=>{const x=new Set(b);return x.has(y)?x.delete(y):x.add(y),os(x),x})},[]),o=l.useCallback(f=>{const y=ur(f);t(b=>{if(b.has(y))return b;const x=new Set(b);return x.add(y),os(x),x})},[]),i=l.useCallback(f=>{const y=ur(f);t(b=>{if(b.has(y))return b;const x=new Set(b);return x.add(y),os(x),x}),n(b=>{if(b.has(y))return b;const x=new Set(b);return x.add(y),Sl(x),x})},[]),c=l.useCallback(f=>{const y=ur(f);t(b=>{if(!b.has(y))return b;const x=new Set(b);return x.delete(y),os(x),x}),n(b=>{if(b.has(y))return b;const x=new Set(b);return x.add(y),Sl(x),x})},[]),d=l.useCallback(()=>{t(f=>{if(f.size===0)return f;const y=new Set;return os(y),y})},[]),m=l.useCallback((f,y)=>{t(b=>{const x=new Set(b);for(const k of y)x.add(k);return os(x),x})},[]),u=l.useCallback((f,y)=>{t(b=>{const x=new Set(b);for(const k of y)x.delete(k);return os(x),x})},[]),h=l.useCallback(f=>ia(e,f),[e]);return{hiddenTabs:e,autoHiddenTabs:r,toggleTarget:a,hideTarget:o,autoHideTarget:i,showTarget:c,showAllTabs:d,hideAllForDaemon:m,showAllForDaemon:u,isHidden:h}}const rn="adhdev_mutedConversations",Ma="adhdev_autoMutedMeshConversations";function Nl(e){try{const t=localStorage.getItem(e);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function nr(e,t){try{localStorage.setItem(e,JSON.stringify([...t]))}catch{}}function Sg(e,t){return Vt(t).some(r=>e.has(r))}function Ng(){const[e,t]=l.useState(()=>Nl(rn)),[r,n]=l.useState(()=>Nl(Ma)),a=l.useCallback(m=>{const u=Nr(m);t(h=>{if(h.has(u))return h;const f=new Set(h);return f.add(u),nr(rn,f),f})},[]),o=l.useCallback(m=>{const u=Vt(m);t(h=>{let f=!1;const y=new Set(h);for(const b of u)y.delete(b)&&(f=!0);return f?(nr(rn,y),y):h}),n(h=>{let f=!1;const y=new Set(h);for(const b of u)y.delete(b)&&(f=!0);return f?(nr(Ma,y),y):h})},[]),i=l.useCallback(m=>{Vt(m).some(f=>e.has(f))?o(m):a(m)},[e,a,o]),c=l.useCallback(m=>{if(!zd(m))return;const u=Nr(m);r.has(u)||(n(h=>{if(h.has(u))return h;const f=new Set(h);return f.add(u),nr(Ma,f),f}),t(h=>{if(h.has(u))return h;const f=new Set(h);return f.add(u),nr(rn,f),f}))},[r]),d=l.useCallback(m=>Sg(e,m),[e]);return{mutedTargets:e,autoMutedTargets:r,muteTarget:a,unmuteTarget:o,toggleTarget:i,autoMuteIfCoordinator:c,isMuted:d}}function Cg(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function Ig(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 Mg(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 Tg({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(!Cg(o))throw new Error(Ig(o));return}await Mg(e.sessionId,t,a)}function Ag(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),h=l.useMemo(()=>{const b=kp(t);return b?b.prompt.promptId===o?null:b:null},[o,t,e]),f=l.useCallback(async b=>{if(!h)return;const x=Wc(h.prompt,b);d(!0),u(null);try{const k=(n==null?void 0:n[h.daemonId])==="connected"||r===!0;await Tg({promptSession:h,response:x,useP2PCommand:k,sendCommand:a}),i(h.prompt.promptId)}catch(k){throw u(k instanceof Error?k.message:String(k)),k}finally{d(!1)}},[r,n,h,a]),y=l.useCallback(()=>{h&&i(h.prompt.promptId)},[h]);return{promptSession:h,responseError:m,isSubmitting:c,submit:f,cancel:y}}function Gd(e){return e instanceof Error?e.message:String(e||"")}function _g(e){const t=Gd(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 Lg(e){const t=Gd(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Vd({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!Ye(e)||Ve(e))return;const o=Us(e);if(o===t)return;const i=e.sessionId;i&&a(c=>({...c,[i]:t}));try{await n(js(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Kt(e),mode:t})}catch(c){const d=Lg(c);i&&!d&&a(m=>{const u={...m};return o===qd(r,i)?delete u[i]:u[i]=o,u}),_g(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 Cl(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 Pg(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=Cl(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(d=>Cl(d,t)):a.childSessions,c=i!==a.childSessions;return o!==a||c?(r=!0,{...o,...c?{childSessions:i}:{}}):a});return r?n:e}function qd(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 Rg(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))qd(t,a)===o&&(delete n[a],r=!0);return r?n:e}function Dg({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){l.useEffect(()=>{Xc()},[]);const a=l.useMemo(()=>e.map(o=>({id:o.tabKey,name:wd(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return tf(a),l.useEffect(()=>{if(Object.keys(t).length===0)return;const i=setTimeout(()=>{r(c=>{const d=Date.now(),m={};for(const[u,h]of Object.entries(c))d-h<5e3&&(m[u]=h);return Object.keys(m).length===Object.keys(c).length?c:m})},5500);return()=>clearTimeout(i)},[t,r]),l.useEffect(()=>{const o=setInterval(()=>{const i=Date.now()-3e5;n(c=>{const d=c.filter(m=>m.timestamp>i).slice(-100);return d.length===c.length?c:d})},6e4);return()=>clearInterval(o)},[n]),null}function Il(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 fs(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=Il(t==null?void 0:t.receivedAt)||Il(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function No(e,t=0){return fs(e)||e.lastUpdated||t||0}function Yd(e){return fs(e)||e.lastUpdated||0}function Xd(e,t,r=Yd){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 Co(e){var r;const t=Tt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function Eg(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Co(e)&&!e.title.trim()}function $g(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(Co(r))-Number(Co(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:Xd(t,r)})[0]||null}function $t(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=$g(a);return n?o&&Eg(n)?o:n:o||r[0]||null}function Bg(e){const t=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return!t||r.startsWith(`${t}:`)?r:`${t}:${r}`}function Og(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=Bg(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 Ta(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 Fg(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 Ml(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Fg(Es(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 Hg(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||""),Ml(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||""),Ml(r.activeChat)].join(":"))].join("|")}function Wg(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 Kg(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of Vt({routeId:n.routeId}))r.set(o,a);for(const o of Vt({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Vt({tabKey:n.tabKey}))r.set(o,n)}return r}function Ug(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function zg(e){const t=Ug(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=Es(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Gg({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=l.useMemo(()=>Og(e),[e]),o=l.useMemo(()=>Ad(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),m=l.useRef(new Map),u=l.useRef(new Map),h=l.useMemo(()=>{const C=new Map,v=[];for(const S of a){const{connectionState:T="new",machineName:P}=_d(S,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),A=Hg(S),D=m.current.get(S.id);if(D&&D.ide===S&&D.sourceSignature===A&&D.connectionState===T&&D.machineName===P){C.set(S.id,D),v.push(...D.conversations);continue}const L=Qo(S,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),O={ide:S,sourceSignature:A,connectionState:T,machineName:P,conversations:L};C.set(S.id,O),v.push(...L)}m.current=C;const g=new Map,N=S=>{const T=zg(S),P=u.current.get(S.tabKey);if(P&&P.signature===T)return g.set(S.tabKey,P),P.timestamp;const A={signature:T,timestamp:Yd(S)||(P==null?void 0:P.timestamp)||0};return g.set(S.tabKey,A),A.timestamp},I=[...v].sort((S,T)=>Xd(S,T,N));return u.current=g,I},[a,t,o]),f=l.useMemo(()=>{const C=Wg(h,r);return Ta(i.current,C)?i.current:(i.current=C,C)},[h,r]),y=l.useMemo(()=>{const C=new Map,v=Array.from(new Set(f.map(g=>g.routeId)));for(const g of v){const N=$t(f,g);N&&C.set(g,N)}return C},[f]),b=l.useMemo(()=>{const C=new Map;for(const v of f){const g=y.get(v.routeId),N=v.streamSource==="native"&&g?g:v;for(const I of Vt({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))C.set(I,N)}return C},[f,y]),x=l.useMemo(()=>Kg(f,y),[f,y]),k=l.useCallback(C=>{if(C)return b.get(C)},[b]),j=l.useCallback(C=>{if(C)return x.get(C)},[x]),p=l.useMemo(()=>{const C=f.filter(v=>!ia(n,v));return Ta(c.current,C)?c.current:(c.current=C,C)},[f,n]),w=l.useMemo(()=>{const C=p.map(v=>v.tabKey);return Ta(d.current,C)?d.current:(d.current=C,C)},[p]);return{chatIdes:a,conversations:f,visibleConversations:p,visibleTabKeys:w,resolveConversationBySessionId:k,resolveConversationByTarget:j}}function Vg({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 qg({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){l.useEffect(()=>{Je.setIdes(e)},[e]),l.useEffect(()=>{Je.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=Je.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=gd.on("status_event",o=>{Je.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 h=Number(c.buttonIndex),f=c.button||((x=m==null?void 0:m.modalButtons)==null?void 0:x[h])||"Approve",y=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),b=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(y);t(u,"resolve_action",{action:b?"approve":"reject",button:f,...Number.isFinite(h)&&{buttonIndex:h},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(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 Yg="adhdev_dashboardLayout_v1",Xg="adhdev_dashboardDockview_v1",Jg="adhdev_dashboardDockviewHiddenRestore_v1",ar={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function ri(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Qg(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Jd(e){return`${Yg}:${e}`}function Zg(e){const t=Jd(e);return ri(t,null)}function ey(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=Jd(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Qd(e){return`${Xg}:${e}`}function ty(e){const t=Qd(e);return ri(t,null)}function sy(e,t){try{const r=Qd(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Zd(e){return`${Jg}:${e}`}function ry(e){const t=Zd(e);return ri(t,{})}function ny(e,t){try{const r=Zd(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function ay(){return{groupAssignments:[...ar.groupAssignments],focusedGroup:ar.focusedGroup,groupActiveTabIds:{...ar.groupActiveTabIds},groupTabOrders:{...ar.groupTabOrders},groupSizes:[...ar.groupSizes]}}function oy(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function iy(){const[e]=l.useState(()=>Qg(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([]),[h,f]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[y,b]=l.useState(!1),x=l.useCallback(()=>{if(y)return;const S=Zg(e)??ay();r(new Map(S.groupAssignments)),a(S.focusedGroup),i(S.groupActiveTabIds),d(S.groupTabOrders),u(S.groupSizes),b(!0)},[y,e]);l.useEffect(()=>{y&&ey(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=P=>f(P.matches);return S.addEventListener("change",T),()=>S.removeEventListener("change",T)},[]);const k=l.useCallback(S=>{r(S)},[]),j=l.useCallback(S=>{a(S)},[]),p=l.useCallback(S=>{i(S)},[]),w=l.useCallback(S=>{d(S)},[]),C=l.useCallback(S=>{u(S)},[]),v=l.useCallback(S=>{j(S)},[j]),g=l.useCallback((S,T)=>{i(P=>(P[S]??null)===(T??null)?P:{...P,[S]:T})},[]),N=l.useCallback((S,T)=>{d(P=>{const A=P[S];return oy(A,T)?P:{...P,[S]:T}})},[]),I=l.useCallback((S,T)=>{const P=T.get(S)??0;return g(P,S),v(P),P},[v,g]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:k,focusedGroup:n,updateFocusedGroup:j,focusGroup:v,groupActiveTabIds:o,updateGroupActiveTabIds:p,setGroupActiveTab:g,groupTabOrders:c,updateGroupTabOrders:w,setGroupTabOrder:N,groupSizes:m,updateGroupSizes:C,isMobile:h,hasHydratedStoredLayout:y,hydrateStoredLayout:x,focusConversationTab:I}}function ly(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=oa(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function cy({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,ides:h,handleRefreshHistory:f}){const y=l.useRef(!1),b=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,b.current=!0,x.current!=null&&(window.clearTimeout(x.current),x.current=null),c(p=>{const w=new URLSearchParams(p);return w.delete("activeTab"),w},{replace:!0}))},[e,t,r,n,a,o,i,c]),l.useEffect(()=>{if(!(b.current||a)&&t.length!==0){if(!e){o(),b.current=!0;return}if(y.current){b.current=!0;return}if(x.current==null)return x.current=window.setTimeout(()=>{x.current=null,!(b.current||a)&&(o(),b.current=!0)},1500),()=>{x.current!=null&&(window.clearTimeout(x.current),x.current=null)}}},[e,t.length,a,o]),l.useEffect(()=>{if(!d){k.current=!1;return}if(!m||k.current||u)return;const j=h.find(p=>p.id===m.routeId);j&&(!j.chats||j.chats.length===0||ly(j.chats,m))&&(k.current=!0,f())},[d,m,u,h,f])}function Aa(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=oa(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function eu({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 b=>{try{await e("standalone","launch_ide",{ideType:b,enableCdp:!0})}catch(x){console.error("Launch failed",x)}},[e]),h=l.useCallback(async(b,x)=>{try{const k=b||(t==null?void 0:t.daemonId)||"",j=await e(k,"switch_chat",{id:x,sessionId:x,...ds(t)}),p=j==null?void 0:j.result;if((j==null?void 0:j.success)===!0||p==="switched"||p==="switched-by-title")return;p===!1||p==="not_found"?er(a,"⚠️ Session tab not found — try refreshing history"):typeof p=="string"&&p.startsWith("error:")?er(a,`⚠️ Switch error: ${p}`):er(a,"⚠️ Session switch failed")}catch(k){console.error("Switch failed",k),er(a,`❌ Switch failed: ${k.message||"connection error"}`)}},[t,e,a]),f=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const b=us(t);await e(b,"new_chat",{...ds(t)}),vx(b,t.sessionId,oa(t)[0]),o(x=>({...x,[t.tabKey]:Date.now()}))}catch(b){console.error("New chat failed",b)}finally{c(!1)}}},[t,i,e,o]),y=l.useCallback(async()=>{var b,x;if(!(!t||d)){m(!0);try{const k=us(t),j=async()=>e(k,"list_chats",{forceExpand:!0,...ds(t)});let p=await j(),w=(p==null?void 0:p.chats)||((b=p==null?void 0:p.result)==null?void 0:b.chats);Aa(w,t)&&(await new Promise(C=>setTimeout(C,450)),p=await j(),w=(p==null?void 0:p.chats)||((x=p==null?void 0:p.result)==null?void 0:x.chats)),p!=null&&p.success&&Array.isArray(w)&&(n(t.routeId,w),Aa(w,t)&&!Aa(r,t)&&er(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:h,handleNewChat:f,handleRefreshHistory:y}}function dy(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 uy(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Tl(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 nn(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 Al(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 my(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 hy(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 _l(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 Ll(e){return Array(e).fill(100/e)}function py({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),h=l.useMemo(()=>nn(e,m),[e,m]),f=h.assignments,y=l.useMemo(()=>c?1:h.groupCount,[h.groupCount,c]),b=y>1,x=l.useCallback((v,g)=>{t(N=>{const I=new Map(nn(N,m).assignments);return g===0?I.delete(v):I.set(v,g),I}),n(N=>({...N,[g]:v})),r(g)},[t,m,n,r]),k=l.useCallback(v=>{t(g=>{const N=nn(g,m).assignments,I=new Map;for(const[S,T]of N)T!==v&&(T>v?I.set(S,T-1):I.set(S,T));return I}),i(g=>{if(g.length<=1)return[];const N=[...g];N.splice(v,1);const I=N.reduce((S,T)=>S+T,0);return I>0?N.map(S=>S/I*100):[]}),r(0)},[t,m,i,r]),j=l.useCallback((v,g)=>{g.preventDefault();const N=u.current;if(!N)return;const I=g.clientX,S=N.offsetWidth,T=o.length===y?[...o]:Ll(y),P=D=>{const O=(D.clientX-I)/S*100,_=[...T];_[v]=Math.max(15,T[v]+O),_[v+1]=Math.max(15,T[v+1]-O),i(_)},A=()=>{document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",A),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",P),document.addEventListener("mouseup",A)},[o,y,i]),p=l.useCallback((v,g,N)=>{if(y>=4)return;const I=N==="left"?g:g+1;t(S=>{const T=nn(S,m).assignments,P=new Map;for(const A of d){const D=T.get(A.tabKey)??0,L=D>=I?D+1:D;L>0&&P.set(A.tabKey,L)}return I>0&&P.set(v,I),P}),i(S=>{const T=S.length===y?[...S]:Ll(y),P=T[g]??100/y,A=Math.max(15,P/2),D=Math.max(15,P/2),L=[...T];L[g]=A,L.splice(I,0,D);const O=L.reduce((_,M)=>_+M,0);return L.map(_=>_/O*100)}),n(S=>{const T=_l(S,I);return T[I]=v,T}),a(S=>{const T=_l(S,I);return T[I]=[v],T}),r(I)},[y,t,m,d,i,n,a,r]);l.useEffect(()=>{dy(e,f)||t(f)},[e,f,t]),l.useEffect(()=>{const{mapping:v,usedGroups:g}=h;n(N=>{const I=Al(N,v);return Tl(N,I)?N:I}),a(N=>{const I=Al(N,v);return Tl(N,I)?N:I}),r(N=>{const I=c?0:my(N,g,v);return N===I?N:I}),i(N=>{const I=c?[]:hy(N,g,h.groupCount);return uy(N,I)?N:I})},[h,c,n,a,r,i]);const w=l.useMemo(()=>{const v=Array.from({length:y},()=>[]);for(const g of d){const N=f.get(g.tabKey)??0,I=Math.min(N,y-1);v[I].push(g)}return v},[d,f,y]),C=l.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:f,numGroups:y,isSplitMode:b,groupedConvs:w,moveTabToGroup:x,closeGroup:k,handleResizeStart:j,splitTabRelative:p,clearAllSplits:C}}function _a(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 fy(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 an(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function ni(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=_a(t.channel)||_a(e.updateChannel)||_a(e.releaseChannel)||void 0,n=fy(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=an(t.targetVersion)||an(e.serverVersion)||void 0,o=an(t.minVersion)||void 0,i=an(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 Ts(e,t=null){return ni(e).targetVersion||t}function tu(e){return ni(e).channel||null}function su(e){const t=ni(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 xy({ides:e,sendDaemonCommand:t}){const r="0.9.82",n=l.useMemo(()=>e.filter(h=>h.type!=="adhdev-daemon"?!1:Zo(h,Ts(h,r))).sort((h,f)=>Number(gr(f,Ts(f,r)))-Number(gr(h,Ts(h,r)))),[r,e]),a=l.useMemo(()=>n.some(h=>gr(h,Ts(h,r))),[r,n]),o=l.useMemo(()=>n.map(h=>Ts(h,r)).find(h=>typeof h=="string"&&h.trim().length>0)||r,[r,n]),[i,c]=l.useState(!1),[d,m]=l.useState({}),u=l.useCallback(async h=>{var y,b;const f=e.find(x=>x.id===h);if(f){m(x=>({...x,[h]:"upgrading"}));try{const x=await t(h,"daemon_upgrade",su(f));(y=x==null?void 0:x.result)!=null&&y.upgraded||(b=x==null?void 0:x.result)!=null&&b.success?m(k=>({...k,[h]:"done"})):m(k=>({...k,[h]:"error"}))}catch{m(x=>({...x,[h]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const ru=80;function kn(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function by(e){return{...e,createdAt:kn(e.createdAt),updatedAt:kn(e.updatedAt,e.createdAt),lastEventAt:kn(e.lastEventAt,e.updatedAt||e.createdAt)}}function gy(e){const t=Nr(e);return t==="unknown:"?e.id:t}function yy(e){return[e.type,md(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function vy(e,t=ru){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=gy(n),o=r.get(a);if(!o){r.set(a,n);continue}(n.updatedAt>o.updatedAt||n.updatedAt===o.updatedAt&&n.createdAt>o.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const o=a.updatedAt-n.updatedAt;return o!==0?o:a.createdAt-n.createdAt}).slice(0,Math.max(0,t))}function wy(e,t){const r=Date.now(),n=[];for(const a of e){const o=a.sessionId?t.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden)continue;const i=ra(a,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=kn(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),m=yy({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(by({id:m,dedupKey:m,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:sd(a),preview:Lf(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return vy(n)}function jy(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function ky(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=ru}=e,a=l.useMemo(()=>wy(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=l.useMemo(()=>jy(a),[a]);return{notifications:a,unreadCount:o}}function Sy({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 Ny=l.createContext(null);function nu(){return l.useContext(Ny)}function ai(...e){const t=new Set,r=[],n=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),r.push(o))};for(const a of e){if(Array.isArray(a)){for(const o of a)n(o);continue}n(a)}return r}function Cy(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 oi(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=Cy(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 Iy(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 My(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function ii(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=My(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 Ty(e,t){const r={meshId:t.meshId||"",workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp"};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand)\s*\}\}/g,(n,a)=>r[a]||"")}function au(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:Ty(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function Ay(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 Cr(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function ou(e){return Rr(e)||e.tabKey||e.routeId||null}function iu(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=$t(e.conversations,n)||e.conversations.find(i=>i.routeId===n);if(o!=null&&o.tabKey)return o.tabKey}return t||r||n||null}function Qt(e){return String(e||"").trim()}function lu(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 _y(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Ly(e,t){const r=Qt(e.providerSessionId),n=Qt(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Qt).filter(Boolean);return!!(r&&i.includes(r)||n&&i.includes(n))});return a?a.tabKey:n||r||null}function Py(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=lu(t.daemonId);if(n&&n!==e.machineId)return null;const a=Qt(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=Qt(e.resumeSessionId),i=Qt(e.launchedSessionId),c=Qt(t.providerSessionId),d=Qt(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&&!_y(u,m))return null}return Ly(t,r)}function Pl(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Ry({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(h=>{var k,j,p,w;if(!h||h.type==="adhdev-daemon"||lu(h.daemonId||h.id)!==n.machineId||(Sr(h)?"cli":Ls(h)?"acp":"ide")!==n.kind)return!1;const b=String(h.agentType||h.type||"");if(n.providerType&&b!==n.providerType)return!1;if(n.resumeSessionId)return String(h.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const C=String(n.launchedSessionId||"");return[h.providerSessionId,h.sessionId,h.instanceId,h.id].map(g=>String(g||"")).filter(Boolean).includes(C)}if(d){const C=qn(h.workspace||h.runtimeWorkspaceLabel);return C?C===d:!1}return Number(h.lastUpdated||h._lastUpdate||h.timestamp||((w=(p=(j=(k=h.activeChat)==null?void 0:k.messages)==null?void 0:j.at)==null?void 0:p.call(j,-1))==null?void 0:w.timestamp)||0)>=n.startedAt-5e3});if(!m)return;const u=iu({entrySessionId:m.sessionId,entryInstanceId:m.instanceId,entryRouteId:m.id,conversations:t});u&&(i(),r(u))},[i,t,e,r,n]),l.useEffect(()=>Je.onStatusEvent(d=>{const m=o.current;if(!m)return;const u=Py(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 Dy({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const i=nu(),{launchCli:c}=Zn(),d=l.useCallback(async(k,j)=>ii(e,k,j),[e]),m=l.useCallback(async(k,j)=>{if(!j.trim())return{ok:!1,error:"Choose a workspace path first."};try{const p=await e(k,"workspace_add",{path:j.trim()});return p!=null&&p.success?{ok:!0}:{ok:!1,error:(p==null?void 0:p.error)||"Could not save workspace"}}catch(p){return{ok:!1,error:p instanceof Error?p.message:"Could not save workspace"}}},[e]),u=l.useCallback(async(k,j,p)=>{var w;try{const C={ideType:j,enableCdp:!0};(w=p==null?void 0:p.workspacePath)!=null&&w.trim()&&(C.workspace=p.workspacePath.trim());const v=await e(k,"launch_ide",C);return!(v!=null&&v.success)&&(v==null?void 0:v.success)!==void 0?{ok:!1,error:(v==null?void 0:v.error)||"Could not launch IDE"}:(t({machineId:k,kind:"ide",providerType:j,workspacePath:(p==null?void 0:p.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(C){return{ok:!1,error:C instanceof Error?C.message:"Could not launch IDE"}}},[e,t]),h=l.useCallback(async(k,j,p,w)=>{var v,g,N;const C=Date.now();try{const I={cliType:p};(v=w==null?void 0:w.workspacePath)!=null&&v.trim()?I.dir=w.workspacePath.trim():w!=null&&w.workspaceId&&(I.workspaceId=w.workspaceId),(g=w==null?void 0:w.resumeSessionId)!=null&&g.trim()&&(I.resumeSessionId=w.resumeSessionId.trim()),Array.isArray(w==null?void 0:w.cliArgs)&&w.cliArgs.length>0&&(I.cliArgs=w.cliArgs),(N=w==null?void 0:w.initialModel)!=null&&N.trim()&&(I.initialModel=w.initialModel.trim());const S=await c(k,I),T=(S==null?void 0:S.result)||S,P=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);return S!=null&&S.success&&P?(t({machineId:k,kind:j,providerType:p,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,launchedSessionId:P,startedAt:C}),{ok:!0}):S!=null&&S.success?(t({machineId:k,kind:j,providerType:p,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:(S==null?void 0:S.error)||(T==null?void 0:T.error)||`Could not launch ${j.toUpperCase()} session`}}catch(I){return Pl(I)?(t({machineId:k,kind:j,providerType:p,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:I instanceof Error?I.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 p=await e(k,"list_meshes",{}),w=(p==null?void 0:p.result)??p;if((w==null?void 0:w.success)===!1)throw new Error((w==null?void 0:w.error)||"Could not load meshes");return(Array.isArray(w==null?void 0:w.meshes)?w.meshes:Array.isArray((j=w==null?void 0:w.result)==null?void 0:j.meshes)?w.result.meshes:[]).map(v=>{var g;return{id:String((v==null?void 0:v.id)||""),name:String((v==null?void 0:v.name)||(v==null?void 0:v.id)||"Untitled mesh"),repoIdentity:(v==null?void 0:v.repoIdentity)||(v==null?void 0:v.repo_identity)||null,workspace:Array.isArray(v==null?void 0:v.nodes)&&v.nodes.length>0?String(((g=v.nodes[0])==null?void 0:g.workspace)||""):null,nodesCount:Array.isArray(v==null?void 0:v.nodes)?v.nodes.length:void 0,status:(v==null?void 0:v.status)||null}}).filter(v=>v.id)}catch(p){throw console.error("List meshes failed",p),p}},[i,e]),y=l.useCallback(async(k,j,p)=>{if(!j.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(k,j,p);const w=Date.now();try{const C={meshId:j.trim()};p.trim()&&(C.cliType=p.trim());const v=await e(k,"launch_mesh_coordinator",C),g=(v==null?void 0:v.result)??v;if((g==null?void 0:g.success)===!1||(v==null?void 0:v.success)===!1){const I=String((g==null?void 0:g.code)||(v==null?void 0:v.code)||""),S=Ay((g==null?void 0:g.meshCoordinatorSetup)||(g==null?void 0:g.manualSetup)||(v==null?void 0:v.meshCoordinatorSetup)||(v==null?void 0:v.manualSetup));return{ok:!1,error:(g==null?void 0:g.error)||(v==null?void 0:v.error)||"Could not launch mesh coordinator",code:I||void 0,manualSetup:S}}const N=(g==null?void 0:g.sessionId)||(g==null?void 0:g.id);return N?r(N):t({machineId:k,kind:"cli",providerType:(g==null?void 0:g.cliType)||p.trim()||void 0,workspacePath:(g==null?void 0:g.workspace)||null,startedAt:w}),{ok:!0}}catch(C){return Pl(C)?(t({machineId:k,kind:"cli",providerType:p.trim()||void 0,startedAt:w}),{ok:!0}):{ok:!1,error:C instanceof Error?C.message:"Could not launch mesh coordinator"}}},[i,r,e,t]),b=l.useCallback(async(k,j)=>{if(!k||!j)return[];try{const p=await e(k,"list_saved_sessions",{providerType:j,kind:"cli",limit:30}),w=(p==null?void 0:p.result)??p;return Array.isArray(w==null?void 0:w.sessions)?w.sessions:[]}catch(p){return console.error("List saved sessions failed",p),[]}},[e]),x=l.useCallback(async k=>{await Vd({conversation:n,mode:k,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:m,handleLaunchMachineIde:u,handleLaunchMachineProvider:h,handleListMachineMeshes:f,handleLaunchMeshCoordinator:y,handleListMachineSavedSessions:b,setActiveCliViewMode:x}}function Ey(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 $y(e,t,r=Date.now()){return!e||!Ey(t)?null:{tabKey:e,nonce:r}}function By({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),h=l.useMemo(()=>{var k,j;if(!e){if(c){const p=t.find(w=>w.tabKey===c);if(p)return p}return r[0]}const x=n[a];if(x){const p=t.find(w=>w.tabKey===x);if(p)return p}return((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),p=Rf(x);return p?j.set("activeTab",p):j.delete("activeTab"),j},{replace:!0})},[i]),b=l.useCallback((x,k)=>{const j=$y(x,k);j&&u(j)},[]);return{activeConv:h,openDesktopConversation:y,requestScrollToBottom:b,scrollToBottomRequest:m,setDesktopActiveTab:f}}function Oy(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 Fy(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 Hy({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=Rn(e,r),h=Fy({tabKey:e.tabKey,historySessionId:Rr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:fs(e),liveState:u}),f=h.autoReadKey,y=Oy({autoReadKey:f,shouldMarkSeen:h.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!h.shouldMarkSeen){y.shouldCancelPending&&m(),a.current=f;return}if(!y.shouldSchedule)return;y.shouldCancelPending&&m();const b=()=>{if(document.visibilityState!=="visible"||a.current===f)return;a.current=f,o.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const k=h.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:k,completionMarker:h.completionMarker}).catch(()=>{})};if(o.current=y.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(b,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(b,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 La(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 Wy({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var $;const{launchCli:m}=Zn(),[u,h]=l.useState(!1),[f,y]=l.useState([]),[b,x]=l.useState(()=>jt()),[k,j]=l.useState(!1),[p,w]=l.useState(null),C=l.useRef(null),v=l.useMemo(()=>r||t||e,[e,r,t]),g=!!v&&Ye(v)&&!Ve(v),N=l.useMemo(()=>{if(!v||!g)return null;const W=v.daemonId||v.routeId||"",B=Kt(v),F=La(v);return`${W}:${B}:${v.providerSessionId||""}:${F}`},[v,g]),I=l.useMemo(()=>!v||!g?"":La(v),[v,g]),{isCreatingChat:S,isRefreshingHistory:T,handleSwitchSession:P,handleNewChat:A,handleRefreshHistory:D}=eu({sendDaemonCommand:a,activeConv:v,chats:($=n.find(W=>W.id===(v==null?void 0:v.routeId)))==null?void 0:$.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),L=l.useCallback(()=>{h(!0)},[]),O=l.useCallback(()=>{h(!1)},[]),_=l.useCallback(async()=>{if(!(!v||!g||k)){j(!0);try{const W=v.daemonId||v.routeId,B=Kt(v),F=La(v),K=await a(W,"list_saved_sessions",{agentType:B,providerType:B,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},...F?{workspace:F}:{}}),Y=(K==null?void 0:K.result)??K;y(Array.isArray(Y==null?void 0:Y.sessions)?Y.sessions:[])}catch(W){console.error("Refresh saved sessions failed",W),y([])}finally{j(!1)}}},[v,k,g,a]);l.useEffect(()=>{if(!u){C.current=null;return}if(!g){C.current=null,y([]),j(!1);return}!N||k||C.current!==N&&(C.current=N,_())},[_,u,k,g,N]);const M=l.useCallback(async W=>{if(!v||!g||!W.providerSessionId||!W.workspace)return;const B=v.daemonId||v.routeId,F=Kt(v);try{w(W.providerSessionId);const K=await m(B,{cliType:F,dir:W.workspace,resumeSessionId:W.providerSessionId,initialModel:qc(W.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Y=(K==null?void 0:K.result)??K,re=typeof(Y==null?void 0:Y.sessionId)=="string"?Y.sessionId:typeof(Y==null?void 0:Y.id)=="string"?Y.id:"";re&&d(ae=>{const he=new URLSearchParams(ae);return he.set("activeTab",re),he},{replace:!0}),O()}catch(K){console.error("Resume saved session failed",K)}finally{w(null)}},[O,v,g,a,d]);return{historyModalOpen:u,openHistoryModal:L,closeHistoryModal:O,historyTargetConv:v,isSavedSessionHistoryTarget:g,isHistoryCreatingChat:S,isHistoryRefreshingHistory:T,handleHistorySwitchSession:P,handleHistoryNewChat:A,handleHistoryRefresh:D,savedHistorySessions:f,savedHistoryFilters:b,setSavedHistoryFilters:x,missingWorkspaceResumePath:I,isSavedHistoryLoading:k,resumingSavedHistorySessionId:p,handleRefreshSavedHistory:_,handleResumeSavedHistorySession:M}}function Ky({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}){const[d,m]=l.useState(null),[u,h]=l.useState(null),f=l.useMemo(()=>{if(e||!n)return null;const j=c(n);return j&&!Ye(j)&&!Ve(j)?j:null},[e,n,c]),y=l.useMemo(()=>{const j=d==null?void 0:d.routeId;if(!j)return null;const p=d!=null&&d.tabKey?o.find(w=>w.tabKey===d.tabKey):a?o.find(w=>w.tabKey===a):null;return(p==null?void 0:p.routeId)===j?p:$t(o,j)},[o,d,a]),b=l.useMemo(()=>{if(y)return i.find(j=>j.id===y.routeId)},[i,y]);l.useEffect(()=>{f&&(m({routeId:f.routeId,tabKey:el(f)}),h(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:el(j)}),h(j))},[]),k=l.useCallback(()=>{m(null),h(null)},[]);return{remoteDialogConv:y,remoteDialogIdeEntry:b,remoteDialogActiveConv:u,setRemoteDialogActiveConv:h,openRemoteDialog:x,closeRemoteDialog:k}}function Uy({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:f,setRemoteDialogActiveConv:y,openRemoteDialog:b,closeRemoteDialog:x}=Ky({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}),[k,j]=l.useState(!1),[p,w]=l.useState(null),C=l.useCallback(async N=>{const I=N||d;!I||!Ye(I)&&!Ve(I)||(w(I),j(!0))},[d]),v=l.useCallback(()=>{j(!1),w(null)},[]),g=l.useCallback(async N=>{const I=p||d;if(!I||!Ye(I)&&!Ve(I)){v();return}j(!1);try{const S=Kt(I),T=I.routeId||I.daemonId||"";await m(T,"stop_cli",{cliType:S,targetSessionId:I.sessionId,mode:N})}catch(S){console.error("Stop CLI failed:",S)}finally{w(null)}},[d,v,p,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:f,setRemoteDialogActiveConv:y,openRemoteDialog:b,closeRemoteDialog:x,cliStopDialogOpen:k,cliStopTargetConv:p,requestCliStop:C,cancelCliStop:v,confirmCliStop:g}}function cu({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var w,C,v;const i=Tr(),c=js(e),d=o?null:td(e),m=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!o&&e.streamSource==="agent-stream"&&!!e.agentName,h=!o&&!u&&(e.transport==="pty"||e.transport==="acp"),f=Fs(e),y=Pf(e),b=(w=e.settings)==null?void 0:w.meshNodeFor,x=e.meshQueueStats,k=((C=e.coordinator)==null?void 0:C.meshId)||((v=e.settings)==null?void 0:v.meshCoordinatorFor),j=l.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),p=l.useCallback(()=>{if(r){r();return}const g=ou(e);g&&i(Cr(g))},[e,i,r]);return!m&&!u&&!h&&!d&&!b&&!x?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[m&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:p,title:y,children:[s.jsx(Bt,{size:12}),s.jsx("span",{children:y})]}):s.jsxs("span",{className:"conversation-meta-chip",title:y,children:[s.jsx(Bt,{size:12}),s.jsx("span",{children:y})]})),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[s.jsx(Os,{size:12}),s.jsx("span",{children:f})]}),h&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[s.jsx(Os,{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(ts,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(ts,{size:12}),s.jsx("span",{children:d})]})),b&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(ts,{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(Ch,{size:12}),s.jsxs("span",{children:[x.pending," Pending"]})]})]})}function Pa(e,t=!0){return(e??!0)&&t}const li=l.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:d,handleForceSendChat:m,isSendingChat:u,sendFeedbackMessage:h=null,handleFocusAgent:f,isFocusingAgent:y,actionLogs:b,userName:x,scrollToBottomRequestNonce:k,isInputActive:j=!0,isVisible:p=!0}){const w=n,C=!n,v=Pa(p,w),g=Pa(p,C),N=Pa(p),I=Wd(t),S=I.status||I.modalMessage||I.modalButtons?{...t,...I.status?{status:I.status}:{},...I.modalMessage!==void 0?{modalMessage:I.modalMessage}:{},...I.modalButtons!==void 0?{modalButtons:I.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Uc,{activeConv:S,onModalButton:i}),s.jsx(cu,{conversation:S,className:"chat-pane-meta-row mx-3 mt-1",meshOnly:!0}),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(Bs,{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:w?"visible":"hidden",pointerEvents:w?"auto":"none"},children:s.jsx(eb,{activeConv:S,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:h,isVisible:v,isInputActive:j&&v})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(yo,{activeConv:S,ideEntry:a,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:h,handleFocusAgent:f,isFocusingAgent:y,actionLogs:b,userName:x,scrollToBottomRequestNonce:k,isInputActive:j&&g,isVisible:g})})]}):s.jsx(yo,{activeConv:S,ideEntry:a,handleSendChat:d,handleForceSendChat:m,isSendingChat:u,sendFeedbackMessage:h,handleFocusAgent:f,isFocusingAgent:y,actionLogs:b,userName:x,scrollToBottomRequestNonce:k,isInputActive:j&&N,isVisible:N})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.handleForceSendChat===t.handleForceSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function zy({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:m,onOpenNativeConversation:u,onOpenMachine:h,onOpenHistory:f,onOpenRemote:y,onOpenMeshGraph:b,onStopCli:x,cliViewMode:k,onSetCliViewMode:j,handleSendChat:p,handleForceSendChat:w,handleFocusAgent:C,handleModalButton:v,handleRelaunch:g}){var A,D;const N=l.useRef(null),I=Ye(e)&&!t,S=I&&k==="terminal",T=!!e.daemonId&&!!((A=e.coordinator)!=null&&A.meshId||(D=e.settings)!=null&&D.meshCoordinatorFor),P=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 ${P} 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(Ro,{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:nt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(cu,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>h(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[I&&k&&s.jsx(kd,{mode:k,onChange:j,compact:!0}),I&&x&&s.jsx("button",{onClick:()=>{x(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(xt,{size:14})}),T&&b&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>b(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(Zt,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(Do,{size:14})}),!t&&!I&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(e),type:"button",children:s.jsx(Bt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(li,{activeConv:e,clearToken:0,isCliTerminal:S,ideEntry:n,terminalRef:N,handleModalButton:v,handleRelaunch:g,handleSendChat:p,handleForceSendChat:w,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:C,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const Ra={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 Gy(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function du(){const[e,t]=l.useState("unix"),[r,n]=l.useState("powershell"),[a,o]=l.useState(!1),i=e==="unix"?"unix":r;l.useEffect(()=>{t(Gy())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(Ra[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:Ra[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Ra[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 uu({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Bt},{key:"chats",label:"Chats",icon:ws}];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 on({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 Ns({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 or({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 Vy({conversation:e,onCancel:t,onConfirm:r}){const n=nt(e),a=ys(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(xt,{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 ln({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onOpenMeshGraph:o,onCollectChatDebugBundle:i,isMuted:c,onToggleMute:d}){var A,D;const m=t==="needs_attention"||t==="task_complete",u=t==="working",h=t==="earlier",f=t==="task_complete",{isReconnecting:y,isConnecting:b}=Ks(e.conversation),x=nt(e.conversation),k=ys(e.conversation),j=vd(e.conversation,{requiresAction:t==="needs_attention"}),p=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%)]":h?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",w=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":h?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",C=h?"text-text-secondary":"text-text-primary",v=h?"text-text-muted":"text-text-secondary",g=h?"text-text-secondary opacity-80":"text-text-muted",N=h?"text-text-muted opacity-80":"text-text-muted",I=!u&&!f,S=!!e.conversation.daemonId&&!!((A=e.conversation.coordinator)!=null&&A.meshId||(D=e.conversation.settings)!=null&&D.meshCoordinatorFor),T="text-[color:var(--status-warning)]",P=L=>{if(!i)return;L.preventDefault(),L.stopPropagation();const O=i==null?void 0:i(e.conversation);Promise.resolve(O).catch(_=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",_)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${p}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||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 ${w}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:r(x)}),a&&s.jsxs("button",{type:"button",className:"mobile-inbox-hide-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-border-subtle bg-bg-primary/70 px-2 text-[10px] font-semibold text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:L=>{L.preventDefault(),L.stopPropagation(),a()},"aria-label":`Hide ${x}`,title:"Hide conversation",children:[s.jsx(Eo,{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:L=>{L.preventDefault(),L.stopPropagation(),d()},"aria-label":c?`Unmute ${x}`:`Mute ${x}`,title:c?"Unmute (resume notifications)":"Mute notifications",children:[s.jsx(Ar,{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:L=>{L.preventDefault(),L.stopPropagation(),o(e.conversation)},"aria-label":`Open mesh graph for ${x}`,title:"Open live repo mesh graph",children:[s.jsx(Zt,{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:P,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 ${C}`,children:x}),I&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${N}`,children:Kc(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${v}`,children:[s.jsx("span",{className:"truncate",children:k}),s.jsx(On,{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…"})]}):b?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] ${g}`,children:e.preview})]}),m&&!f&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),f&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),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 Rl({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 qy({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:h,onHideConversation:f,onOpenMeshGraph:y,onOpenNewSession:b,onOpenMachine:x,onOpenSettings:k,onSectionChange:j,wsStatus:p="connected",isStandalone:w=!1,onCollectChatDebugBundle:C,isConversationMuted:v,onToggleMuteConversation:g}){const[N,I]=l.useState(null),S=p==="disconnected"||p==="reconnecting"||p==="offline"||p==="auth_failed",T=i.length>0,P=t.length>0||r.length>0||n.length>0||a.length>0,A=e==="machines"?"Machines":"Chats",D=w?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",L=w?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",O=l.useCallback(async $=>{const W=us($);if(!W)return;const B=Array.isArray($.messages)?$.messages:[],F=id({activeConv:$,visibleMessages:B,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:B.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),K=await m(W,"get_chat_debug_bundle",{...ds($),delivery:"daemon_file",frontendSnapshot:F}),Y=fr(K),re=dd(Y),ae=await cd(re);ae==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),Je.showToast(ld(Y,{locatorCopyStatus:ae}),ae==="failed"?"warning":"success")},[d,m]),_=C||O,M=l.useCallback(()=>{N&&(f==null||f(N),I(null))},[N,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 ${D}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:A}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||r.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(Ar,{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(ea,{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] ${L}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:S?s.jsx(or,{icon:s.jsx(Rl,{}),title:p==="offline"?"Network offline":p==="auth_failed"?"Session expired":"Reconnecting",subtitle:p==="offline"?"Waiting for network…":p==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):i.length===0?s.jsx(or,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:w?"Waiting for your daemon":"Connect your machines",subtitle:w?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can launch sessions with any installed provider.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!w&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(du,{})})}):s.jsx(Ns,{children:i.map(($,W)=>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] ${W>0?"border-t border-border-subtle/70":""}`,onClick:()=>x($.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($.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:$.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:$.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[$.unread," new"]}):$.total>0?`${$.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:$.subtitle}),$.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[$.total," chat",$.total!==1?"s":"",$.unread>0?` · ${$.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},$.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(on,{title:"Needs attention",className:"mb-0"}),s.jsx(Ns,{children:t.map(($,W)=>s.jsx("div",{className:W>0?"border-t border-border-subtle/70":"",children:s.jsx(ln,{item:$,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>I($.conversation):void 0,onOpenMeshGraph:y,onCollectChatDebugBundle:_,isMuted:v==null?void 0:v($.conversation),onToggleMute:g?()=>g($.conversation):void 0})},$.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(on,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(Ns,{children:r.map(($,W)=>s.jsx("div",{className:W>0?"border-t border-border-subtle/70":"",children:s.jsx(ln,{item:$,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>I($.conversation):void 0,onOpenMeshGraph:y,onCollectChatDebugBundle:_,isMuted:v==null?void 0:v($.conversation),onToggleMute:g?()=>g($.conversation):void 0})},$.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(on,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(Ns,{children:n.map(($,W)=>s.jsx("div",{className:W>0?"border-t border-border-subtle/70":"",children:s.jsx(ln,{item:$,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>I($.conversation):void 0,onOpenMeshGraph:y,onCollectChatDebugBundle:_,isMuted:v==null?void 0:v($.conversation),onToggleMute:g?()=>g($.conversation):void 0})},$.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(on,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(Ns,{children:a.map(($,W)=>s.jsx("div",{className:W>0?"border-t border-border-subtle/70":"",children:s.jsx(ln,{item:$,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>I($.conversation):void 0,onOpenMeshGraph:y,onCollectChatDebugBundle:_,isMuted:v==null?void 0:v($.conversation),onToggleMute:g?()=>g($.conversation):void 0})},$.conversation.tabKey))}):P?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):S?s.jsx(or,{icon:s.jsx(Rl,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):T?s.jsx(or,{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(ws,{size:20})}),title:"No conversations yet",subtitle:Sd,children:b&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:b,"aria-label":Ht,title:Ht,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:Ht})]})}):s.jsx(or,{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(Ns,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[o.length," collapsed ",o.length===1?"conversation":"conversations"]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:h,children:"Restore all"})]})})})]}),e==="chats"&&b&&P&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:b,"aria-label":Ht,title:Ht,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),N&&s.jsx(Vy,{conversation:N,onCancel:()=>I(null),onConfirm:M}),s.jsx(uu,{section:e,onSectionChange:j})]})}function Yy(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 mu(e){const t=[e.workspace||"Workspace unknown"],r=gs(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Yy(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function ci({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,h]=l.useState(r);l.useEffect(()=>{h(r)},[r]);const f=Iy(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(xt,{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(Ro,{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:b=>h(b.target.value),onKeyDown:b=>{b.key!=="Enter"||!y||a||(b.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(b=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(b.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx($s,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:b.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:b.path})]})]},b.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(y||r),disabled:!y&&!r||a,children:i})]})]})})}function hu({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:h,showModelInput:f,modelValue:y,onModelChange:b,historyProviderNode:x,onConfirm:k,onCancel:j}){const p=n==null?void 0:n.find(w=>w.key===a);return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:j,"aria-label":"Close launch confirmation",children:s.jsx(xt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:w=>o(w.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:n.map(w=>s.jsx("option",{value:w.key,children:w.label},w.key))}),(p==null?void 0:p.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:p.description})]}),x,r.map(w=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:w.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:w.value})]},`${w.label}:${w.value}`)),f&&b&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:y||"",onChange:w=>b(w.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),m&&h&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:w=>h(w.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled: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(Ac,{size:14}),d?c:i]})]})]})})}function Dl(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function pu(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?"⭐ ":""}${Dl(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:Dl(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 Xy(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Jy(e){return[Xy(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Qy(e){return e.lastLaunchedAt?sa(e.lastLaunchedAt):""}function fu(e){return{metaText:Jy(e),updatedLabel:Qy(e)}}function Da(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Zy({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var et,ct,Xe,pt;const i=Pr(),[c,d]=l.useState(!1),m=(((et=e.detectedIdes)==null?void 0:et.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(Ae=>({id:Ae.id,path:Ae.path,label:Ae.label})),[e]),h=e.defaultWorkspaceId||null,[f,y]=l.useState(h||((ct=u[0])==null?void 0:ct.id)||""),[b,x]=l.useState(""),[k,j]=l.useState(""),[p,w]=l.useState([]),[C,v]=l.useState(!1),[g,N]=l.useState(""),[I,S]=l.useState(!1),[T,P]=l.useState(Da(m,t.length,r.length)),A=l.useRef(null),[D,L]=l.useState(null),O=l.useRef("__home__"),[_,M]=l.useState("__home__"),[$,W]=l.useState(""),[B,F]=l.useState(""),[K,Y]=l.useState(""),[re,ae]=l.useState([]),[he,we]=l.useState(()=>jt().textQuery),[Ce,V]=l.useState(()=>jt().workspaceQuery),[q,ue]=l.useState(()=>jt().modelQuery),[me,le]=l.useState(()=>jt().resumableOnly),[je,X]=l.useState(()=>jt().sortMode),[ye,de]=l.useState(!1),[ve,fe]=l.useState(!1),ge=l.useRef(null),ce=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const be=f==="__custom__"?b.trim():((Xe=u.find(Ae=>Ae.id===f))==null?void 0:Xe.path)||"",oe=f==="__custom__"&&!!be&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),R=f!=="__custom__"&&((pt=u.find(Ae=>Ae.id===f))==null?void 0:pt.path)||"",pe=l.useMemo(()=>(e.recentLaunches||[]).map(Ae=>Ae.workspace),[e]),Se=l.useCallback(async Ae=>{v(!0),N("");try{const Fe=await a(Ae);j(Fe.path),x(Fe.path),w(Fe.directories)}catch(Fe){N(Fe instanceof Error?Fe.message:"Could not load folder")}finally{v(!1)}},[a]),Me=l.useCallback(()=>{var Fe;y("__custom__"),S(!0);const Ae=oi(e.platform,ai(b.trim(),R,pe,e.defaultWorkspacePath,(Fe=u.find(st=>st.id===h))==null?void 0:Fe.path,u.map(st=>st.path)));Se(Ae)},[b,h,Se,pe,R,e.platform,u]),ee=l.useCallback(Ae=>{if(Ae!=null&&Ae.workspaceId){y(Ae.workspaceId),x("");return}if(Ae!=null&&Ae.workspacePath){y("__custom__"),x(Ae.workspacePath);return}y(""),x("")},[]),Ne=l.useCallback(Ae=>{if(y(Ae),Ae==="__custom__"){Me();return}x("")},[Me]),De=l.useCallback(Ae=>{y("__custom__"),x(Ae)},[]),Ee=l.useCallback((Ae,Fe)=>{A.current=Fe,O.current=Ae.selectedWorkspaceKey||"__home__",M(Ae.selectedWorkspaceKey||"__home__"),W(Ae.initialArgs||""),F(Ae.initialModel||""),Y(""),ae([]);const st=Ae.providerType?`${e.id}:${Ae.providerType}`:null;if(ub(ce.current,st)){const qe=jt();we(qe.textQuery),V(qe.workspaceQuery),ue(qe.modelQuery),le(qe.resumableOnly),X(qe.sortMode)}ce.current=st,L(Ae),Ae.providerType&&o&&(de(!0),o(Ae.providerType).then(qe=>ae(qe||[])).catch(qe=>console.warn("Failed to load saved sessions",qe)).finally(()=>de(!1)))},[o,e.id]),ze=l.useMemo(()=>Nd(re,{textQuery:he,workspaceQuery:Ce,modelQuery:q,resumableOnly:me,sortMode:je}),[q,me,re,je,he,Ce]);l.useEffect(()=>{K&&(ze.some(Ae=>Ae.providerSessionId===K)||Y(""))},[ze,K]);const Qe=l.useCallback(()=>{A.current&&(fe(!0),A.current().finally(()=>{A.current=null,fe(!1),L(null)}))},[]),Ze=l.useCallback(()=>{A.current=null,L(null)},[]),rt=l.useCallback(Ae=>{O.current=Ae,M(Ae)},[]);return l.useEffect(()=>{var Ae;ge.current!==e.id&&(ge.current=e.id,y(h||((Ae=u[0])==null?void 0:Ae.id)||"__custom__"),x(""),j(""),w([]),N(""),S(!1),we(jt().textQuery),V(jt().workspaceQuery),ue(jt().modelQuery),le(jt().resumableOnly),X(jt().sortMode),ce.current=null,P(Da(m,t.length,r.length)))},[r.length,t.length,h,m,e.id,u]),l.useEffect(()=>{var Ae;f!=="__custom__"&&(f&&u.some(Fe=>Fe.id===f)||y(h||((Ae=u[0])==null?void 0:Ae.id)||"__custom__"))},[h,f,u]),l.useEffect(()=>{T==="ide"&&m||T==="cli"&&t.length>0||T==="acp"&&r.length>0||P(Da(m,t.length,r.length))},[T,r.length,t.length,m]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:m,workspaceRows:u,defaultWorkspaceId:h,workspaceChoice:f,customWorkspacePath:b,browseCurrentPath:k,browseDirectories:p,browseBusy:C,browseError:g,browseDialogOpen:I,activeLauncherKind:T,launchConfirm:D,launchConfirmWorkspaceKeyRef:O,launchConfirmWorkspaceKey:_,launchConfirmArgs:$,launchConfirmModel:B,launchConfirmResumeId:K,launchConfirmSavedSessions:re,launchConfirmTextFilter:he,launchConfirmWorkspaceFilter:Ce,launchConfirmModelFilter:q,launchConfirmResumableOnly:me,launchConfirmSortMode:je,filteredLaunchConfirmSavedSessions:ze,launchConfirmSessionsLoading:ye,launchConfirmBusy:ve,resolvedWorkspacePath:be,canCreateMissingWorkspace:oe,openBrowseDialog:Me,loadBrowsePath:Se,handleWorkspaceChoiceChange:Ne,chooseCustomWorkspacePath:De,setCustomWorkspacePath:x,setBrowseDialogOpen:S,setActiveLauncherKind:P,openLaunchConfirm:Ee,handleConfirmLaunch:Qe,closeLaunchConfirm:Ze,setWorkspaceSelectionFromOption:ee,setLaunchConfirmWorkspaceKeyAndSync:rt,setLaunchConfirmArgs:W,setLaunchConfirmModel:F,setLaunchConfirmResumeId:Y,setLaunchConfirmTextFilter:we,setLaunchConfirmWorkspaceFilter:V,setLaunchConfirmModelFilter:ue,setLaunchConfirmResumableOnly:le,setLaunchConfirmSortMode:X}}function e0({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:d,section:m,showBottomNav:u,onBack:h,onSectionChange:f,onOpenConversation:y,onOpenRecent:b,onOpenMachineDetails:x,onMachineUpgrade:k,onLaunchDetectedIde:j,onAddWorkspace:p,onBrowseDirectory:w,onLaunchWorkspaceProvider:C,onListSavedSessions:v}){const g=_=>_==="ide"?"Workspace":_==="cli"?"CLI":"ACP",N=r.slice(0,4),I=t.slice(0,3),S=Zy({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:c,onBrowseDirectory:w,onListSavedSessions:v}),T=l.useMemo(()=>N.map(_=>{const{metaText:M,updatedLabel:$}=fu(_);return{key:`recent-launch:${_.id}`,primary:_.label,secondary:M,updatedLabel:$,onClick:()=>{const{options:W,selectedKey:B}=pu({machine:{workspaces:S.workspaceRows,defaultWorkspaceId:S.defaultWorkspaceId},currentWorkspacePath:_.workspace});S.openLaunchConfirm({title:_.kind==="ide"?Hn("restart-ide",_.label):_.providerSessionId?Cd(_.label):Hn("start-fresh",_.label),description:_.kind==="ide"?Wn("restart-ide"):_.providerSessionId?Id():Wn("start-fresh"),confirmLabel:_.kind==="ide"?Kn("restart-ide"):_.providerSessionId?Fn(!0):Kn("start-fresh"),busyLabel:_.kind==="ide"?Un("restart-ide"):_.providerSessionId?Xo(!0):Un("start-fresh"),workspaceOptions:W,selectedWorkspaceKey:B,details:[{label:"Mode",value:g(_.kind)},..._.providerType?[{label:"Provider",value:_.providerType}]:[]]},async()=>{const F=W.find(K=>K.key===S.launchConfirmWorkspaceKeyRef.current);S.setWorkspaceSelectionFromOption(F),await b({..._,workspace:(F==null?void 0:F.workspacePath)??null})})}}}),[S,b,N]),P=l.useMemo(()=>I.map(_=>({key:`recent-chat:${_.conversation.tabKey}`,primary:nt(_.conversation),secondary:Xx(_.conversation,{timestampLabel:_.timestamp?Kc(_.timestamp):null}),unread:_.unread,onClick:()=>y(_.conversation)})),[y,I]),A=S.showAllRecent?T:T.slice(0,4),D=T.length>0,L=P.length>0,O=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 ${O} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":"Back",children:s.jsx(Ro,{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:Ct(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:[L&&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:P.map(_=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${_.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:_.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:_.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:_.secondary})]},_.key))})]}),D&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:A.map(_=>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:_.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:_.primary}),_.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:_.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:_.secondary})]},_.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(_=>!_),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(ci,{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:_=>{S.loadBrowsePath(_)},onConfirm:_=>{S.chooseCustomWorkspacePath(_),S.setBrowseDialogOpen(!1)}}),S.launchConfirm&&s.jsx(hu,{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?Fn(!!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:Jo()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:S.launchConfirmTextFilter,onChange:_=>S.setLaunchConfirmTextFilter(_.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:_=>S.setLaunchConfirmWorkspaceFilter(_.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:_=>S.setLaunchConfirmModelFilter(_.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:_=>S.setLaunchConfirmSortMode(_.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:_=>S.setLaunchConfirmResumableOnly(_.target.checked),disabled:S.launchConfirmBusy||S.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:S.launchConfirmResumeId,onChange:_=>S.setLaunchConfirmResumeId(_.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:pb()}),S.filteredLaunchConfirmSavedSessions.map(_=>s.jsxs("option",{value:_.providerSessionId,disabled:!_.canResume,children:[_.title||_.providerSessionId," ",_.canResume?"":"(workspace missing)"]},_.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 _=S.filteredLaunchConfirmSavedSessions.find($=>$.providerSessionId===S.launchConfirmResumeId);if(!_)return null;const M=mu(_);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: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})]})})()]}),onConfirm:S.handleConfirmLaunch,onCancel:S.closeLaunchConfirm}),u&&s.jsx(uu,{section:m,onSectionChange:f})]})}function Sn(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function t0(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:Sn(e)}function s0(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 r0(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:gs(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=Sr(n)?"cli":Ls(n)?"acp":"ide",o=gs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||(Sr(n)?n.cliName||n.type:Ls(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ls(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 n0(e,t){const r=new Map;for(const n of t){const a=js(n.conversation),o=r.get(a);o?o.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],o=[...a].sort((h,f)=>f.timestamp-h.timestamp)[0]||null,i=(o==null?void 0:o.conversation)||null,c=mo(n),d=a.filter(h=>h.unread||h.requiresAction).length,m=s0(n),u=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:Ct(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?Jx(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 a0(e){return e==="chat"}function cn(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 o0({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:y,setSelectedTabKey:b,setScreen:x,setSelectedMachineId:k,setSection:j,setMachineBackTarget:p,resetMachineAction:w}){const C=l.useRef(null),v=l.useCallback(g=>{if(!(g!=null&&g.sessionId))return;const N=Rn(g,i),I=Math.max(Date.now(),fs(g),N.lastUpdated||0);cn("mark_read:start",{tabKey:g.tabKey,sessionId:g.sessionId,displayPrimary:nt(g),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:fs(g),readAt:I}),c(js(g)||g.routeId,"mark_session_seen",{sessionId:g.sessionId,providerSessionId:g.providerSessionId,seenAt:I,completionMarker:N.completionMarker}).then(S=>{cn("mark_read:result",{tabKey:g.tabKey,sessionId:g.sessionId,result:S})}).catch(S=>{cn("mark_read:error",{tabKey:g.tabKey,sessionId:g.sessionId,error:S instanceof Error?S.message:String(S)})})},[i,c]);return l.useEffect(()=>{var N;if(!n){a0(o)&&x("inbox"),b(((N=e[0])==null?void 0:N.tabKey)||null),C.current=null;return}if(o!=="chat"){C.current=null;return}const g=`${n.tabKey}:${n.sessionId||""}`;C.current!==g&&(C.current=g,v(n))},[e,v,o,n,x,b]),l.useEffect(()=>{if(!d)return;const g=e.find(N=>N.tabKey===d);g&&(b(g.tabKey),x("chat"),m==null||m())},[e,m,d,x,b]),l.useEffect(()=>{if(!u)return;const g=t.find(N=>N.id===u);g&&(k(g.id),w(),j("machines"),p("inbox"),x("machine"),h==null||h())},[t,h,u,w,p,x,j,k]),l.useEffect(()=>{f&&(j(f),x("inbox"),y==null||y())},[y,f,x,j]),l.useEffect(()=>{const g=r.filter(N=>N.inboxBucket==="task_complete"||N.unread);g.length!==0&&cn("inbox_state",{screen:o,selectedTabKey:a,items:g.map(N=>{const I=Rn(N.conversation,i);return{liveState:I,tabKey:N.conversation.tabKey,sessionId:N.conversation.sessionId,displayPrimary:nt(N.conversation),serverBucket:I.inboxBucket,computedBucket:N.inboxBucket,serverUnread:I.unread,computedUnread:N.unread,lastSeenAt:I.lastSeenAt,lastUpdated:I.lastUpdated,activityAt:fs(N.conversation)}})})},[r,i,o,a]),{markConversationRead:v}}function i0(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function El(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function l0(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function c0({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const{launchCli:a}=Zn(),[o,i]=l.useState("idle"),[c,d]=l.useState(""),[m,u]=l.useState(null),h=l.useCallback(()=>{i("idle"),d(""),u(null)},[]),f=l.useCallback(async(w,C,v)=>{var g;try{i("loading"),d(`Launching ${C}…`);const N={ideType:C,enableCdp:!0};(g=v==null?void 0:v.workspacePath)!=null&&g.trim()&&(N.workspace=v.workspacePath.trim()),await e(w,"launch_ide",N),i("done"),d(`${C} launch requested`)}catch(N){i("error"),d(N instanceof Error?N.message:"Launch IDE failed"),console.error("Launch IDE failed",N)}},[e]),y=l.useCallback(async(w,C,v)=>{if(C.trim())try{i("loading"),d(v!=null&&v.createIfMissing?"Creating folder…":"Saving workspace…");const g=await e(w,"workspace_add",{path:C.trim(),createIfMissing:(v==null?void 0:v.createIfMissing)===!0});if(g!=null&&g.success){i("done"),d(v!=null&&v.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((g==null?void 0:g.error)||"Could not save workspace")}catch(g){i("error"),d(g instanceof Error?g.message:"Could not save workspace")}},[e]),b=l.useCallback(async w=>{var C,v,g,N,I,S;try{i("loading"),d("Starting daemon upgrade…");const T=await e(w,"daemon_upgrade",{});if((C=T==null?void 0:T.result)!=null&&C.alreadyLatest){i("done"),d(`Already on v${((v=T==null?void 0:T.result)==null?void 0:v.version)||"latest"}.`);return}if((g=T==null?void 0:T.result)!=null&&g.upgraded||(N=T==null?void 0:T.result)!=null&&N.success){i("done"),d(`Upgrade to v${((I=T==null?void 0:T.result)==null?void 0:I.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(w,C,v,g)=>{var S,T,P;const N=Date.now(),I={machineId:w,kind:C,providerType:v,workspaceId:(g==null?void 0:g.workspaceId)||null,workspacePath:(g==null?void 0:g.workspacePath)||null,resumeSessionId:(g==null?void 0:g.resumeSessionId)||null,startedAt:N};try{i("loading"),d(`Launching ${v}…`),u(I);const A={cliType:v};(S=g==null?void 0:g.workspacePath)!=null&&S.trim()?A.dir=g.workspacePath.trim():g!=null&&g.workspaceId&&(A.workspaceId=g.workspaceId),g!=null&&g.resumeSessionId&&(A.resumeSessionId=g.resumeSessionId),(T=g==null?void 0:g.args)!=null&&T.trim()&&(A.cliArgs=g.args.trim().split(/\s+/).filter(Boolean)),(P=g==null?void 0:g.model)!=null&&P.trim()&&(A.initialModel=g.model.trim());const D=await a(w,A),L=(D==null?void 0:D.result)||D,O=(L==null?void 0:L.sessionId)||(L==null?void 0:L.id);if(D!=null&&D.success&&O){u(null),i("done"),d(`${v} launched`),t(Cr(O));return}if(D!=null&&D.success){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d((D==null?void 0:D.error)||(L==null?void 0:L.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(A){if(l0(A)){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d(A instanceof Error?A.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),k=l.useCallback(async(w,C)=>{try{const v=await e(w,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),g=(v==null?void 0:v.result)??v;return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]}catch(v){return console.error("Failed to list saved sessions on mobile:",v),[]}},[e]),j=l.useCallback(async(w,C)=>ii(e,w,C),[e]);l.useEffect(()=>{if(!m)return;const w=El(m.workspacePath),C=r.find(g=>{var A,D,L,O;if(!g||g.type==="adhdev-daemon"||i0(g.daemonId||g.id)!==m.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==m.kind||String(g.agentType||g.type||"")!==m.providerType)return!1;const T=String(g.providerSessionId||"");if(m.resumeSessionId&&T)return T===m.resumeSessionId;if(w){const _=El(g.workspace||g.runtimeWorkspaceLabel);return _?_===w:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((O=(L=(D=(A=g.activeChat)==null?void 0:A.messages)==null?void 0:D.at)==null?void 0:L.call(D,-1))==null?void 0:O.timestamp)||0)>=m.startedAt-5e3});if(!C)return;const v=iu({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:n});v&&(u(null),i("done"),d(`${m.providerType} launched`),t(Cr(v)))},[n,r,t,m]),l.useEffect(()=>{if(!m)return;const w=window.setTimeout(()=>{u(C=>!C||C.startedAt!==m.startedAt?C:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(w)},[m]);const p=l.useCallback(async(w,C)=>{if(C.kind==="ide"&&C.providerType){await f(w,C.providerType,{workspacePath:C.workspace||null});return}(C.kind==="cli"||C.kind==="acp")&&C.providerType&&await x(w,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[f,x]);return{machineAction:{state:o,message:c},resetMachineAction:h,handleLaunchDetectedIde:f,handleAddWorkspace:y,handleMachineUpgrade:b,handleLaunchWorkspaceProvider:x,handleListSavedSessions:k,handleBrowseDirectory:j,handleOpenRecent:p}}function d0({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]),h=l.useCallback(j=>{const p=e.find(w=>w.routeId===j.routeId&&w.streamSource==="native");p&&(o(p.tabKey),i("chat"),n(p))},[e,n,i,o]),f=l.useCallback(()=>{n(t),i("inbox")},[n,t,i]),y=l.useCallback((j,p="inbox")=>{c(j),a(),d("machines"),m(p),i("machine")},[a,m,i,d,c]),b=l.useCallback(j=>{const p=js(j);p&&y(p,"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:h,backFromConversation:f,openMachine:y,openConversationMachine:b,backFromMachine:x,changeMachineSection:k}}function Hs(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function u0(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function m0({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:y,onOpenHistory:b,onOpenRemote:x,onStopCli:k,wsStatus:j,isConnected:p,onShowAllHiddenConversations:w,onHideConversation:C,onOpenMeshGraph:v,onOpenNewSession:g,liveSessionInboxState:N,setCliViewModeOverrides:I}){const[S,T]=l.useState(()=>{var ee;return((ee=e[0])==null?void 0:ee.tabKey)||null}),[P,A]=l.useState(()=>e[0]?"chat":"inbox"),[D,L]=l.useState("chats"),[O,_]=l.useState(null),[M,$]=l.useState("inbox"),W=l.useRef([]),B=Tr(),F="0.9.82",K=l.useMemo(()=>e.find(ee=>ee.tabKey===S)||e[0]||null,[e,S]),Y=l.useMemo(()=>K?r.find(ee=>ee.id===K.routeId):void 0,[r,K]),re=l.useMemo(()=>!K||Ve(K)||!Ye(K)?null:Us(K),[K]),ae=l.useMemo(()=>r.filter(ee=>ee.type==="adhdev-daemon").sort(Wo),[r]),he=l.useMemo(()=>ae.find(ee=>ee.id===O)||null,[ae,O]),we=aa({sendDaemonCommand:a,activeConv:K||void 0,setActionLogs:o,isStandalone:i}),Ce=c0({sendDaemonCommand:a,navigate:B,ides:r,conversations:e}),V=l.useMemo(()=>e.map(ee=>{const Ne=P==="chat"&&(K==null?void 0:K.tabKey)===ee.tabKey,De=ra(ee,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ne}),Ee=fs(ee),ze=yd(ee);return{conversation:ee,timestamp:Ee,preview:ze,unread:De.unread,requiresAction:De.requiresAction,isWorking:De.isWorking,inboxBucket:De.inboxBucket}}),[e,N,P,K]),{markConversationRead:q}=o0({conversations:e,machineEntries:ae,items:V,selectedConversation:K,selectedTabKey:S,screen:P,liveSessionInboxState:N,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:y,setSelectedTabKey:T,setScreen:A,setSelectedMachineId:_,setSection:L,setMachineBackTarget:$,resetMachineAction:Ce.resetMachineAction}),ue=d0({conversations:e,selectedConversation:K,machineBackTarget:M,markConversationRead:q,resetMachineAction:Ce.resetMachineAction,setSelectedTabKey:T,setScreen:A,setSelectedMachineId:_,setSection:L,setMachineBackTarget:$}),{isMuted:me,autoMuteIfCoordinator:le,toggleTarget:je}=Ng();l.useEffect(()=>{if(i)for(const ee of V)le(ee.conversation)},[V,i,le]);const X=l.useMemo(()=>Sn(V.filter(ee=>ee.requiresAction&&!me(ee.conversation))),[V,me]),ye=l.useMemo(()=>Sn(V.filter(ee=>ee.unread&&!ee.requiresAction&&!me(ee.conversation))),[V,me]),de=l.useMemo(()=>t0(V.filter(ee=>!ee.unread&&!ee.requiresAction&&ee.isWorking),W.current),[V]);l.useEffect(()=>{W.current=de.map(ee=>ee.conversation.tabKey)},[de]);const ve=l.useMemo(()=>Sn(V.filter(ee=>!ee.unread&&!ee.requiresAction&&!ee.isWorking)),[V]),fe=l.useMemo(()=>he?V.filter(ee=>js(ee.conversation)===he.id):[],[V,he]),ge=l.useMemo(()=>r0(he,r),[r,he]),ce=(he==null?void 0:he.version)||null,be=!!he&&!!ce&&!0&&ce!==F,oe=l.useMemo(()=>(he==null?void 0:he.availableProviders)||[],[he]),R=l.useMemo(()=>oe.filter(ee=>Hs(ee,"cli")).map(ee=>({type:ee.type,displayName:ee.displayName||ee.type,icon:ee.icon})),[oe]),pe=l.useMemo(()=>oe.filter(ee=>Hs(ee,"acp")).map(ee=>({type:ee.type,displayName:ee.displayName||ee.type,icon:ee.icon})),[oe]),Se=l.useMemo(()=>n0(ae,V),[V,ae]),Me=l.useCallback(async ee=>{he&&await Ce.handleOpenRecent(he.id,ee)},[Ce,he]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:P==="chat"&&K?s.jsx(zy,{selectedConversation:K,isAcp:Ve(K),isStandalone:i,selectedIdeEntry:Y,actionLogs:n,userName:c,isSendingChat:we.isSendingChat,sendFeedbackMessage:we.sendFeedbackMessage,isFocusingAgent:we.isFocusingAgent,handleModalButton:we.handleModalButton,handleRelaunch:we.handleRelaunch,onBack:ue.backFromConversation,onOpenNativeConversation:ue.openNativeConversation,onOpenMachine:ue.openConversationMachine,onOpenHistory:b,onOpenRemote:x,onOpenMeshGraph:v,onStopCli:k,cliViewMode:re,onSetCliViewMode:async ee=>{await Vd({conversation:K,mode:ee,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:I})},handleSendChat:we.handleSendChat,handleForceSendChat:we.handleForceSendChat,handleFocusAgent:we.handleFocusAgent}):P==="machine"&&he?s.jsx(e0,{selectedMachineEntry:he,selectedMachineConversations:fe,selectedMachineRecentLaunches:ge,cliProviders:R,acpProviders:pe,selectedMachineNeedsUpgrade:be,appVersion:F,machineAction:Ce.machineAction,isStandalone:i,section:D,showBottomNav:M==="inbox",onBack:ue.backFromMachine,onSectionChange:ue.changeMachineSection,onOpenConversation:ue.openConversation,onOpenRecent:Me,onOpenMachineDetails:()=>B(`/machines/${he.id}`),onMachineUpgrade:()=>Ce.handleMachineUpgrade(he.id),onLaunchDetectedIde:(ee,Ne)=>Ce.handleLaunchDetectedIde(he.id,ee,Ne),onAddWorkspace:(ee,Ne)=>Ce.handleAddWorkspace(he.id,ee,Ne),onBrowseDirectory:ee=>Ce.handleBrowseDirectory(he.id,ee),onLaunchWorkspaceProvider:(ee,Ne,De)=>Ce.handleLaunchWorkspaceProvider(he.id,ee,Ne,De),onListSavedSessions:ee=>Ce.handleListSavedSessions(he.id,ee)}):s.jsx(qy,{section:D,attentionItems:X,unreadItems:ye,workingItems:de,completedItems:ve,hiddenConversations:t,machineCards:Se,getAvatarText:u0,actionLogs:n,sendDaemonCommand:a,onOpenConversation:ue.openConversation,onShowAllHidden:w,onHideConversation:C,onOpenMeshGraph:v,onOpenNewSession:g,onOpenMachine:ue.openMachine,onOpenSettings:()=>B("/settings"),onSectionChange:L,wsStatus:j,isConnected:p,isStandalone:i,isConversationMuted:i?me:void 0,onToggleMuteConversation:i?je:void 0})})}function Ea(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function h0({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),h=l.useCallback(()=>{i.current=0,d(!1),u(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);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(),!Ea(t,r)){u("merge");return}const j=k.currentTarget.getBoundingClientRect(),p=k.clientX-j.left,w=j.width/3;p<w?u("split-left"):p>w*2?u("split-right"):u("merge")},[t,r]),b=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"),p=j?e.some(C=>C.tabKey===j):!1,w=m;if(u(null),o(),!!j){if(k.preventDefault(),w==="split-left"&&Ea(t,r)){r==null||r(j,"split-left");return}if(w==="split-right"&&Ea(t,r)){r==null||r(j,"split-right");return}if(p){a(j);return}n==null||n(j)}},[e,m,t,r,n,a,o]);return{dragOver:c,dropAction:m,resetDragState:h,handleDragEnter:f,handleDragOver:y,handleDragLeave:b,handleDrop:x}}function p0(e,t){const r=new Set(t.map(o=>o.tabKey)),n=e.filter(o=>r.has(o)),a=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...n,...a]}function f0({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),h=l.useRef(null),f=l.useRef(null),y=l.useRef(n),b=l.useRef(a);l.useEffect(()=>{y.current=n},[n]),l.useEffect(()=>{b.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(N=>{const I=p0(N,e);return I.length===N.length&&I.every((S,T)=>S===N[T])?N:I})},[e]);const x=l.useMemo(()=>{const N=m??c;if(N.length===0)return e;const I=new Map(N.map((S,T)=>[S,T]));return[...e].sort((S,T)=>{const P=I.get(S.tabKey)??999,A=I.get(T.tabKey)??999;return P-A})},[e,m,c]);l.useEffect(()=>{var I,S;if(x.length===0){o!==null&&(i(null),(I=y.current)==null||I.call(y,null));return}if(o&&x.some(T=>T.tabKey===o))return;const N=x[0].tabKey;N!==o&&(i(N),(S=y.current)==null||S.call(y,N))},[x,o]);const k=l.useMemo(()=>x.find(N=>N.tabKey===o),[x,o]),j=l.useCallback(N=>{var I;i(N),(I=y.current)==null||I.call(y,N)},[]),p=l.useCallback((N,I,S)=>{d(T=>{var L;const P=T.filter(O=>O!==N),A=P.indexOf(I);if(A<0)return T;const D=S==="left"?A:A+1;return P.splice(D,0,N),(L=b.current)==null||L.call(b,P),P}),u(null)},[]),w=l.useCallback((N,I,S)=>{const P=(c.length>0?c:e.map(L=>L.tabKey)).filter(L=>L!==N),A=P.indexOf(I);if(A<0)return;const D=S==="left"?A:A+1;P.splice(D,0,N),h.current=P,u(P)},[c,e]),C=l.useCallback(()=>{var I;const N=h.current;N&&(d(N),(I=b.current)==null||I.call(b,N))},[]),v=l.useCallback(()=>{h.current=null,u(null)},[]),g=l.useCallback(N=>{d(I=>{var T;const S=I.filter(P=>P!==N);return S.push(N),(T=b.current)==null||T.call(b,S),S})},[]);return{activeTabId:o,activeConv:k,sortedConversations:x,previewOrderRef:h,draggingTabRef:f,selectTab:j,handleTabReorder:p,updatePreviewOrder:w,commitPreviewOrder:C,clearPreviewOrder:v,moveTabToEnd:g,setDraggingTabKey:N=>{f.current=N}}}function x0({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 di({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?Sd: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:Ht,"aria-label":Ht,children:[s.jsx(_c,{size:14}),s.jsx("span",{children:Ht})]})}),i&&s.jsx(du,{}),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 xu="adhdev-tab-shortcuts";function bu(){try{return JSON.parse(localStorage.getItem(xu)||"{}")}catch{return{}}}function gu({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>bu()),[c,d]=l.useState(null),m=l.useCallback(h=>{const f=[];return h.metaKey&&f.push(a?"⌘":"Meta"),h.ctrlKey&&f.push("Ctrl"),h.altKey&&f.push(a?"⌥":"Alt"),h.shiftKey&&f.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(f.push(h.key.length===1?h.key.toUpperCase():h.key),f.join("+"))},[a]),u=l.useCallback(h=>{i(h);try{localStorage.setItem(xu,JSON.stringify(h))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const h=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){d(null);return}const y=m(f);if(!y)return;const b={...o};for(const[x,k]of Object.entries(b))k===y&&delete b[x];b[c]=y,u(b),d(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,c,o,u,m]),l.useEffect(()=>{if(!e)return;const h=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[y,b]of Object.entries(o))if(t.includes(y)&&m(f)===b){f.preventDefault(),r(),n(y);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,o,t,r,n,m]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const $a=e=>{e.preventDefault()},b0=l.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:h,onReorderTab:f,onCommitPreviewOrder:y,onClearPreviewOrder:b,onDragStateReset:x,onDragTabKeyChange:k,onReceiveTab:j,onOpenContextMenu:p,longPressTimer:w,isGroupActive:C}){const v=Ks(t),g=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",N=v.isReconnecting,I=l.useCallback(M=>{c.current=t.tabKey,k(t.tabKey),M.dataTransfer.setData("text/tab-key",t.tabKey),M.dataTransfer.effectAllowed="move"},[t.tabKey,c,k]),S=l.useCallback(()=>{c.current=null,k(null),y(),b(),x()},[c,k,y,b,x]),T=l.useCallback(M=>{const $=c.current;if(!(!$||$===t.tabKey)&&M.dataTransfer.types.includes("text/tab-key")){M.preventDefault(),M.stopPropagation();const W=M.currentTarget.getBoundingClientRect(),B=M.clientX<W.left+W.width/2?"left":"right";h($,t.tabKey,B)}},[t.tabKey,c,h]),P=l.useCallback(M=>{M.preventDefault(),M.stopPropagation();const $=M.dataTransfer.getData("text/tab-key");if($&&$!==t.tabKey){const W=M.currentTarget.getBoundingClientRect(),B=M.clientX<W.left+W.width/2?"left":"right";i.includes($)?f($,t.tabKey,B):j&&j($)}b()},[t.tabKey,i,f,j,b]),A=l.useCallback(M=>{M.stopPropagation(),d(),m(t.tabKey),u(t)},[t,u,d,m]),D=l.useCallback(M=>{M.preventDefault(),p(M.clientX,M.clientY,t.tabKey)},[t.tabKey,p]),L=l.useCallback(M=>{const $=M.touches[0];w.current=setTimeout(()=>{p($.clientX,$.clientY,t.tabKey)},600)},[t.tabKey,w,p]),O=l.useCallback(()=>{w.current&&clearTimeout(w.current)},[w]),_=["adhdev-dockview-tab",g,r&&"is-active",C&&"is-group-active",N&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:_,draggable:!0,onDragStart:I,onDragEnd:S,onDragOver:T,onDrop:P,onClick:A,onContextMenu:D,onTouchStart:L,onTouchEnd:O,onTouchMove:O,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:v.isGenerating?s.jsx("div",{className:"tab-spinner"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:nt(t),children:nt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:ms(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[ms(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:ms(t)}),s.jsx(On,{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 g0({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:f,onDragTabKeyChange:y,onReceiveTab:b,onHideTab:x,isGroupActive:k,allowTabShortcuts:j=!0}){const[p,w]=l.useState(null),C=l.useRef(null),v=l.useRef(null),g=l.useMemo(()=>e.map(D=>D.tabKey),[e]);_r("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(p==null?void 0:p.tabKey)||null});const{isMac:N,tabShortcuts:I,shortcutListening:S,setShortcutListening:T,saveShortcuts:P}=gu({enabled:j,sortedTabKeys:e.map(D=>D.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!p)return;const D=L=>{const O=document.querySelector("[data-pane-context-menu]");O&&O.contains(L.target)||w(null)};return window.addEventListener("mousedown",D,!0),()=>window.removeEventListener("mousedown",D,!0)},[p]),l.useEffect(()=>{const D=v.current;if(!D)return;const L=O=>{Math.abs(O.deltaY)<=Math.abs(O.deltaX)||(O.preventDefault(),D.scrollLeft+=O.deltaY)};return D.addEventListener("wheel",L,{passive:!1}),()=>D.removeEventListener("wheel",L)},[]);const A=l.useCallback((D,L,O)=>{w({x:D,y:L,tabKey:O})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:v,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(D=>s.jsx(b0,{conv:D,isActive:t===D.tabKey,isDraggedTab:a.current===D.tabKey,isTaskCompleteUnread:n.has(D.tabKey),shortcut:j?I[D.tabKey]:void 0,conversationKeys:g,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:f,onDragTabKeyChange:y,onReceiveTab:b,onOpenContextMenu:A,longPressTimer:C,isGroupActive:k},D.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),p&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:p.x,top:p.y},children:[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:$a,onClick:D=>{D.stopPropagation(),T(p.tabKey),w(null)},children:["⌨ ",I[p.tabKey]?`Change shortcut (${I[p.tabKey]})`:"Set shortcut"]}),I[p.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:$a,onClick:()=>{const D={...I};delete D[p.tabKey],P(D),w(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:$a,onClick:()=>{x(p.tabKey),w(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:D=>D.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. ",N?"⌘+1":"Ctrl+1",", ",N?"⌥+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 y0({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,userName:d,groupIndex:m,onFocus:u,isSplitMode:h,numGroups:f,onMoveTab:y,onReceiveTab:b,style:x,onActiveTabChange:k,initialActiveTabId:j,initialTabOrder:p,onTabOrderChange:w,onHideTab:C,isFocused:v,allowTabShortcuts:g=!0,onOpenNewSession:N,liveSessionInboxState:I}){const{sendCommand:S}=it(),T=l.useRef(null),{activeTabId:P,activeConv:A,sortedConversations:D,draggingTabRef:L,selectTab:O,handleTabReorder:_,updatePreviewOrder:M,commitPreviewOrder:$,clearPreviewOrder:W,moveTabToEnd:B,setDraggingTabKey:F}=f0({conversations:e,initialActiveTabId:j,initialTabOrder:p,onActiveTabChange:k,onTabOrderChange:w}),K=aa({sendDaemonCommand:a,activeConv:A,setActionLogs:o,isStandalone:i}),{dragOver:Y,dropAction:re,resetDragState:ae,handleDragEnter:he,handleDragOver:we,handleDragLeave:Ce,handleDrop:V}=h0({conversations:e,numGroups:f,onMoveTab:y,onReceiveTab:b,onOwnTabDrop:B,onClearPreviewOrder:W}),q=A&&!Ve(A)&&Us(A)==="terminal",ue=l.useMemo(()=>A?t.find(X=>X.id===A.routeId):void 0,[t,A]),me=l.useMemo(()=>A?n.filter(X=>X.routeId===A.tabKey):[],[n,A]),le=l.useMemo(()=>new Set(D.filter(X=>Tp(X,I,{isOpenConversation:X.tabKey===P})).map(X=>X.tabKey)),[P,I,D]);_r("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:P,dragOver:Y});const je=l.useCallback(X=>{X.streamSource==="agent-stream"&&X.agentType&&S(X.routeId,od(),{agentType:X.agentType,...X.sessionId&&{targetSessionId:X.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:Y?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(g0,{conversations:D,activeTabId:P,groupIndex:m,numGroups:f,unreadTabKeys:le,draggingTabRef:L,onFocus:u,onSelectTab:O,onConversationActivated:je,onPreviewReorder:M,onReorderTab:_,onCommitPreviewOrder:$,onClearPreviewOrder:W,onDragStateReset:ae,onDragTabKeyChange:F,onMoveTab:y,onReceiveTab:b,onHideTab:C,isGroupActive:v??!1,allowTabShortcuts:g}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:he,onDragOver:we,onDragLeave:Ce,onDrop:V,children:[Y&&s.jsx(x0,{dropAction:re,canSplit:!!(f<4&&y)}),A?s.jsx(li,{activeConv:A,clearToken:r[A.tabKey]||0,isCliTerminal:!!q,ideEntry:ue,terminalRef:T,handleModalButton:K.handleModalButton,handleRelaunch:K.handleRelaunch,handleSendChat:K.handleSendChat,handleForceSendChat:K.handleForceSendChat,isSendingChat:K.isSendingChat,sendFeedbackMessage:K.sendFeedbackMessage,handleFocusAgent:K.handleFocusAgent,isFocusingAgent:K.isFocusingAgent,actionLogs:me,userName:d,isInputActive:!h||!!v}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(di,{conversationsCount:e.length,isSplitMode:h,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N})})]})]})}function v0({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,userName:f,focusedGroup:y,focusGroup:b,moveTabToGroup:x,splitTabRelative:k,closeGroup:j,handleResizeStart:p,groupActiveTabIds:w,setGroupActiveTab:C,groupTabOrders:v,setGroupTabOrder:g,toggleHiddenTab:N,onOpenNewSession:I,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((P,A)=>{const D=t&&n.length===r?`${n[A]}%`:void 0;return s.jsxs(ft.Fragment,{children:[t&&A>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:L=>p(A-1,L),onDoubleClick:()=>j(A),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(y0,{style:t?{flexBasis:D??`${100/r}%`,flexGrow:D?0:1,flexShrink:D?0:1}:void 0,conversations:P,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,userName:f,groupIndex:A,isFocused:t&&y===A,onFocus:()=>b(A),isSplitMode:t,numGroups:r,onMoveTab:(L,O)=>{O==="left"&&A>0?x(L,A-1):O==="right"&&A<r-1?x(L,A+1):O==="split-left"&&r<4?k(L,A,"left"):O==="split-right"&&r<4&&k(L,A,"right")},onReceiveTab:L=>x(L,A),onActiveTabChange:L=>C(A,L),initialActiveTabId:w[A],initialTabOrder:v[A],onTabOrderChange:L=>g(A,L),onHideTab:N,onOpenNewSession:I,allowTabShortcuts:S,liveSessionInboxState:T})]},A)})})}function yu({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?at.onScreenshot("ide-page",(u,h)=>{if(u!==e)return;const f=new FileReader;f.onload=()=>o(f.result),f.readAsDataURL(h)}):void 0,[e]),l.useEffect(()=>{r!=="connected"&&o(null)},[r]),l.useEffect(()=>{var u;return e?((u=at.onStatus)==null?void 0:u.call(at,(h,f)=>{h===e&&f!=null&&f.screenshotUsage&&c(f.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const m=e?at.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 h=e?at.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(m,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:i,handleRemoteAction:d}}const vu="adhdev-dashboard-action-shortcuts",w0=1200,j0=[["toggleHiddenTabs","G H"],["openNewSession","N"],["setActiveTabShortcut","G S"],["selectPreviousGroupTab","G K"],["selectPreviousGroupTab","T ←"],["selectPreviousGroupTab","⌥+["],["selectPreviousGroupTab","Ctrl+Alt+["],["selectNextGroupTab","G J"],["selectNextGroupTab","T →"],["selectNextGroupTab","⌥+]"],["selectNextGroupTab","Ctrl+Alt+]"],["splitActiveTabDown","S ↓"],["splitActiveTabDown","⌘+⌥+-"],["splitActiveTabDown","Ctrl+Alt+-"],["splitActiveTabRight","S →"],["splitActiveTabRight","⌘+⌥+\\"],["splitActiveTabRight","⌘+⌥+="],["splitActiveTabRight","Ctrl+Alt+\\"],["focusLeftPane","F ←"],["focusLeftPane","⌘+⌥+←"],["focusLeftPane","⌘+⌥+["],["focusLeftPane","Ctrl+Alt+←"],["focusRightPane","F →"],["focusRightPane","⌘+⌥+→"],["focusRightPane","⌘+⌥+]"],["focusRightPane","Ctrl+Alt+→"],["focusUpPane","F ↑"],["focusUpPane","⌘+⌥+U"],["focusUpPane","Ctrl+Alt+↑"],["focusDownPane","F ↓"],["focusDownPane","⌘+⌥+J"],["focusDownPane","Ctrl+Alt+↓"],["moveActiveTabToLeftPane","M ←"],["moveActiveTabToLeftPane","⌘+⌥+⇧+←"],["moveActiveTabToLeftPane","⌘+⌥+,"],["moveActiveTabToLeftPane","Ctrl+Alt+Shift+←"],["moveActiveTabToRightPane","M →"],["moveActiveTabToRightPane","⌘+⌥+⇧+→"],["moveActiveTabToRightPane","⌘+⌥+."],["moveActiveTabToRightPane","Ctrl+Alt+Shift+→"],["moveActiveTabToUpPane","M ↑"],["moveActiveTabToUpPane","⌘+⌥+I"],["moveActiveTabToUpPane","Ctrl+Alt+Shift+↑"],["moveActiveTabToDownPane","M ↓"],["moveActiveTabToDownPane","⌘+⌥+K"],["moveActiveTabToDownPane","Ctrl+Alt+Shift+↓"],["triggerPrimaryApprovalAction","⌥+A"],["triggerSecondaryApprovalAction","⌥+D"],["toggleCliView","T"]];function k0(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function tt(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 wu(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:tt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:tt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:tt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:tt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:tt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:tt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:tt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:tt("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:tt("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:tt("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:tt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:tt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:tt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:tt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:tt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:tt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:tt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:tt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:tt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:tt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:tt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:tt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:tt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:tt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:tt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:tt("toggleCliView",e)}]}function Io(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Yn(e){const t=Object.fromEntries(wu(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(vu)||"{}"),n={...t,...r};for(const[a,o]of j0)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function ju(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function S0({enabled:e=!0,onTrigger:t}){const r=k0(),[n,a]=l.useState(()=>Yn(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(ju(x.key)),k.join("+"))},[r]),h=l.useCallback(x=>{a(x);try{localStorage.setItem(vu,JSON.stringify(x))}catch{}},[]);l.useEffect(()=>{const x=Yn(r),k=Object.entries(n),j=Object.entries(x);k.length===j.length&&k.every(([p,w])=>x[p]===w)||h(x)},[n,r,h]);const f=l.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),y=l.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},w0))},[]);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 w=!(k.metaKey||k.ctrlKey||k.altKey)&&/^[A-Z0-9]$/.test(j);if(c.length===0&&w){d([j]);return}const v=[...c,j].slice(0,2).join(" "),g={...n};for(const[N,I]of Object.entries(g))I===v&&delete g[N];g[o]=v,h(g),i(null),d([])};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[n,u,h,o,c]),l.useEffect(()=>{if(!e||o)return;const x=k=>{if(k.defaultPrevented)return;const j=u(k);if(!j)return;const p=k.metaKey||k.ctrlKey||k.altKey;if(Io(k.target))return;const w=m.current.parts,C=p?[j]:[...w.slice(-1),j].slice(-2),v=C.join(" "),g=C[C.length-1],N=Object.entries(n).filter(([,A])=>!!A),I=N.find(([,A])=>A===v);if(I){k.preventDefault(),f(),t(I[0]);return}if(N.some(([,A])=>A.startsWith(`${v} `))){k.preventDefault(),m.current.parts=C,y();return}const T=N.find(([,A])=>A===g);if(T){k.preventDefault(),f(),t(T[0]);return}if(N.some(([,A])=>A.startsWith(`${g} `))){k.preventDefault(),m.current.parts=[g],y();return}f()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[n,y,e,u,t,f,o]),l.useEffect(()=>()=>f(),[f]);const b=l.useMemo(()=>wu(r),[r]);return{isMac:r,actionDefinitions:b,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:h}}function N0({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 ku(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function $l({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!ku(n):!0}function C0({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:ku(r)}const Su=1e3,I0=4;function Bl(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Ol(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function M0({detachDelayMs:e=Su,stillnessThresholdPx:t=I0,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 h=()=>{m!=null&&(a(m),m=null)},f=()=>{h(),c=null},y=()=>{h(),o=null,i=null,c=null,d=null,u=!1},b=()=>{!o||!c||!d||u||m!=null||(m=n(()=>{m=null,!(!o||!c||!d||u)&&Bl(d,i)&&(Ol(c,d,t)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},x=j=>{if(!(!o||u)){if(!Bl(j,i)){d={clientX:j.clientX,clientY:j.clientY},f();return}(!c||Ol(c,j,t))&&(h(),c={clientX:j.clientX,clientY:j.clientY}),d={clientX:j.clientX,clientY:j.clientY},b()}},k=j=>{!o||u||(j&&(d={clientX:j.clientX,clientY:j.clientY}),f())};return{startDrag:j=>{h(),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 T0(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function dn(e){return e.isActive}function Fl(e){return e.isVisible}const Nu=l.createContext(null);function la(){const e=l.useContext(Nu);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Nn(e){return nt(e)||e.tabKey}function A0(e){return`remote:${e}`}function Rt(e){return e.startsWith("remote:")}function Hl(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function _0(e){e.preventDefault()}function Ba(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 Oa(e,t){e.classList.remove(ro.className,no.className),e.classList.add(t==="light"?ro.className:no.className)}function Wl(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 L0(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 P0(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:Nn(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 Kl(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])Rt(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!==Nn(a)&&o.api.setTitle(Nn(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:Nn(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 Ul(e,t,r){var d,m;const n=r?A0(r):null;for(const u of[...e.panels])Rt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=$t(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),i=jd(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=>!Rt(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 R0({params:e,api:t}){var y;const r=la(),n=l.useRef(null),[a,o]=l.useState(()=>dn(t)),[i,c]=l.useState(()=>Fl(t)),d=r.conversationsByTabKey.get(e.tabKey),m=aa({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});l.useEffect(()=>{o(dn(t)),c(Fl(t));const b=[t.onDidActiveChange(x=>o(x.isActive)),t.onDidActiveGroupChange(x=>{if(!dn(t)&&!x.isActive){o(!1);return}o(dn(t))}),t.onDidVisibilityChange(x=>c(x.isVisible))];return()=>{for(const x of b)x.dispose()}},[t]);const u=l.useMemo(()=>d?r.ides.find(b=>b.id===d.routeId):void 0,[r.ides,d]),h=l.useMemo(()=>d?r.actionLogs.filter(b=>b.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(di,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const f=!Ve(d)&&Us(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(li,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal: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:h,userName:r.userName,scrollToBottomRequestNonce:((y=r.scrollToBottomRequest)==null?void 0:y.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:i})})}function D0({params:e}){var d;const t=la(),r=l.useMemo(()=>$t([...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}=yu({doId:a,targetSessionId:r?ad(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(Hc,{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 E0(){const e=la();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(di,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function $0(e){var p,w;L0(e);const t=la(),r=l.useCallback(C=>{"button"in C&&C.button!==0||e.api.setActive()},[e.api]),n=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),a=n==null?void 0:n.sessionId,o=l.useCallback(C=>Rx(C),[]),i=l.useCallback(()=>Px(a),[a]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const C=$t([...t.conversationsByTabKey.values()],e.params.routeId),v=((p=e.api.group.activePanel)==null?void 0:p.id)===e.api.id,g=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${v?" is-active":""}${g?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(C==null?void 0:C.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:C!=null&&C.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:C.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const d=t.conversationsByTabKey.get(e.params.tabKey);if(!d)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const m=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,u=e.api.isGroupActive,h=ra(d,t.liveSessionInboxState,{isOpenConversation:m}),f=h.isReconnecting,y=h.isConnecting,b=h.isGenerating||c,x=h.isWaiting,k=h.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:nt(d),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:C=>{var v;C.preventDefault(),r(C),t.openTabContextMenu({x:C.clientX,y:C.clientY,tabKey:d.tabKey,sourceDocument:((v=C.target)==null?void 0:v.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:b?s.jsx("div",{className:"tab-spinner"}):x?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):y?s.jsx("div",{className:"tab-connecting-spinner"}):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:nt(d)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ms(d)}):y?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ms(d)}):s.jsx("span",{children:ms(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 B0({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:m,toggleHiddenTab:u,actionShortcuts:h,registerActionHandlers:f,onActiveTabChange:y,onOpenNewSession:b,onRequestScrollToBottom:x,requestedActiveTabKey:k,requestedRemoteIdeId:j,onRequestedActiveTabConsumed:p,scrollToBottomRequest:w,liveSessionInboxState:C,layoutProfile:v}){var st,qe,Ke;const{theme:g}=zs(),{sendCommand:N}=it(),I=l.useRef(null),S=l.useRef(null),T=l.useRef(null),P=l.useRef(!1),A=l.useRef(!1),D=l.useRef(!1),L=l.useRef(null),O=l.useRef([]),[_,M]=l.useState(null),[$,W]=l.useState(0),B=l.useRef(typeof window>"u"?{}:ry(v)),F=l.useMemo(()=>new Map(e.map(U=>[U.tabKey,U])),[e]),K=l.useMemo(()=>{const U=I.current;return U?U.groups.some(z=>{try{const J=z.model.location.type;return J!=="floating"&&J!=="popout"?!1:z.panels.some(te=>F.has(te.id))}catch{return!1}}):!1},[F,$,e]),Y=l.useCallback(()=>{var U;(U=I.current)==null||U.focus()},[]),re=l.useCallback((U,z)=>{x==null||x(U,z)},[x]),ae=l.useCallback(U=>{const z=document,J=U.document;for(const ne of z.querySelectorAll('link[rel="stylesheet"]')){const E=J.createElement("link");E.rel="stylesheet",E.href=ne.href,ne.crossOrigin&&(E.crossOrigin=ne.crossOrigin),J.head.appendChild(E)}for(const ne of z.querySelectorAll("style")){const E=J.createElement("style");E.textContent=ne.textContent,J.head.appendChild(E)}const te=[];for(const ne of z.styleSheets)try{for(const E of ne.cssRules)E instanceof CSSStyleRule&&(E.selectorText===":root"||E.selectorText==="html")&&te.push(E.cssText)}catch{}if(te.length>0){const ne=J.createElement("style");ne.textContent=te.join(`
55
- `),J.head.appendChild(ne)}const H=z.documentElement.getAttribute("data-theme");H&&J.documentElement.setAttribute("data-theme",H),J.documentElement.style.colorScheme=H==="light"?"light":"dark",J.body.className=z.body.className;const G=z.documentElement.getAttribute("style");G&&J.documentElement.setAttribute("style",G);const Z=J.getElementById("dv-popout-window");Z instanceof HTMLElement&&(Z.classList.add("adhdev-dockview"),Oa(Z,g))},[g]),he=l.useCallback(()=>{var z;const U=I.current;if(U)for(const J of U.groups)try{const te=(z=J.element)==null?void 0:z.ownerDocument;if(!te||te===document)continue;const H=te.getElementById("dv-popout-window");H instanceof HTMLElement&&(H.classList.add("adhdev-dockview"),Oa(H,g));const G=document.documentElement.getAttribute("data-theme");G&&te.documentElement.setAttribute("data-theme",G),te.documentElement.style.colorScheme=G==="light"?"light":"dark",te.body.className=document.body.className;const Z=document.documentElement.getAttribute("style");Z?te.documentElement.setAttribute("style",Z):te.documentElement.removeAttribute("style")}catch{}},[g]),we=l.useCallback(U=>{const z=I.current;if(!z)return;const J=z.getPanel(U);J&&z.addPopoutGroup(J,{popoutUrl:"/popout.html",onDidOpen:({window:te})=>{ae(te),ye();const H=F.get(U);te.document.title=H?`${nt(H)} — ADHDev`:"ADHDev — Popout"}})},[F,ae]),Ce=l.useCallback(U=>{const z=I.current,J=z==null?void 0:z.getPanel(U);if(!z||!J)return;const te=z.groups.filter(H=>{var G;try{return((G=H.element)==null?void 0:G.ownerDocument)===document}catch{return!0}});te.length>0?J.api.moveTo({group:te[0],position:"center"}):J.api.moveTo({position:"center"}),J.api.setActive()},[]),V=l.useCallback(U=>{var te;const z=I.current;if(!z)return!1;const J=z.getPanel(U);if(!J)return!1;try{return((te=J.group.element)==null?void 0:te.ownerDocument)!==document}catch{return!1}},[]),q=l.useCallback(U=>{V(U)&&Ce(U),u(U)},[V,Ce,u]),ue=l.useCallback(U=>{const z=I.current,J=z==null?void 0:z.getPanel(U);!z||!J||z.addFloatingGroup(J,{width:600,height:500})},[]),me=l.useCallback(U=>{var J;const z=(J=I.current)==null?void 0:J.getPanel(U);if(!z)return!1;try{return z.group.model.location.type==="floating"}catch{return!1}},[]),le=l.useCallback(()=>{var z,J;const U=(J=(z=I.current)==null?void 0:z.activePanel)==null?void 0:J.id;return!U||Rt(U)?null:F.has(U)?U:null},[F]),je=l.useCallback(U=>{const z=I.current,J=z==null?void 0:z.getPanel(U);if(!z||!J)return;const te=z.groups.filter(H=>{try{return H.model.location.type==="grid"}catch{return!0}});te.length>0?J.api.moveTo({group:te[0],position:"center"}):J.api.moveTo({position:"center"}),J.api.setActive()},[]),X=l.useCallback(()=>{var G;const U=I.current;if(!U)return;const J=U.groups.filter(Z=>{var ne;try{return((ne=Z.element)==null?void 0:ne.ownerDocument)===document&&Z.model.location.type==="grid"}catch{return!1}})[0]||null,te=[...U.panels];for(const Z of te){const ne=(G=Z.group.element)==null?void 0:G.ownerDocument,E=Z.group.model.location.type;ne===document&&E==="grid"||(J&&J.id!==Z.group.id?Z.api.moveTo({group:J,position:"center"}):Z.api.moveTo({position:"center"}))}const H=U.activePanel;H&&(H.group.model.openPanel(H),H.api.setActive()),Ba(document)},[]),ye=l.useCallback(()=>{var z,J;const U=I.current;if(U)for(const te of U.groups){const H=(z=te.element)==null?void 0:z.ownerDocument;if(!H||H===document)continue;const G=H.getElementById("dv-popout-window");if(!(G instanceof HTMLElement))continue;let Z=null,ne=H.title||"ADHDev",E="Popout workspace";const ie=te.activePanel;if(ie)if(Z=ie.id,Rt(ie.id)){const Te=((J=ie.params)==null?void 0:J.routeId)||ie.id.slice(7),Le=$t([...F.values()],Te);ne=jd(Le),E=Le!=null&&Le.machineName?`Remote view · ${Le.machineName}`:"Remote view"}else{const Te=F.get(ie.id);ne=Te?nt(Te):ie.title||ie.id,E=Te?ms(Te):"Dockview panel"}H.title=`${ne} — ADHDev`;const xe=Array.from(H.querySelectorAll("#adhdev-popout-header"));for(const Te of xe)Te.remove();const ke=H.createElement("div");ke.id="adhdev-popout-header",H.body.appendChild(ke),ke.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(";")),ke.innerHTML=`
56
- <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
57
- <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
58
- <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Hl(ne)}</div>
59
- <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Hl(E)}</div>
60
- </div>
61
- <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
62
- <button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
63
- <button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
64
- </div>
65
- `,G.style.top="52px",G.style.height="calc(100% - 52px)";const Ie=ke.querySelector("[data-adhdev-popout-focus]");Ie&&(Ie.onclick=()=>{window.focus()});const $e=ke.querySelector("[data-adhdev-popout-dock]");$e&&($e.disabled=!Z,$e.style.opacity=Z?"1":"0.5",$e.style.cursor=Z?"pointer":"default",$e.onclick=()=>{var Te;Z&&Ce(Z),(Te=H.defaultView)==null||Te.focus()})}},[F,Ce]),de=l.useCallback(U=>{var te;const z=I.current,J=z==null?void 0:z.getPanel(U);if(!(!z||!J)){J.group.model.openPanel(J),J.api.setActive(),re(U,"dockview-shortcut");try{const H=J.group.model.location;H.type==="popout"?H.getWindow().focus():Ba((te=J.group.element)==null?void 0:te.ownerDocument)}catch{}}},[re]),ve=l.useCallback(U=>{const z=I.current,J=z==null?void 0:z.activePanel,te=(z==null?void 0:z.activeGroup)||(J==null?void 0:J.group);if(!z||!J||!te)return;const H=te.panels||[];if(H.length<=1)return;const G=H.findIndex(E=>E.id===J.id);if(G<0)return;const Z=(G+U+H.length)%H.length,ne=H[Z];ne&&(ne.group.model.openPanel(ne),ne.api.setActive(),Rt(ne.id)||re(ne.id,"dockview-shortcut"))},[re]),fe=l.useCallback(U=>{var Ie;const z=I.current,J=(z==null?void 0:z.activeGroup)||((Ie=z==null?void 0:z.activePanel)==null?void 0:Ie.group);if(!z||!J)return;const te=z.groups||[],H=te.find($e=>$e.id===J.id);if(!H)return;const G=H.element.getBoundingClientRect(),Z=G.left+G.width/2,ne=G.top+G.height/2,E=($e,Te,Le,Ue)=>Math.max(0,Math.min(Te,Ue)-Math.max($e,Le)),ie=$e=>{const Te=$e.element.getBoundingClientRect(),Le=Te.left+Te.width/2,Ue=Te.top+Te.height/2;let dt=0,yt=0,ut=0,mt=!1;if(U==="left"?(mt=Le<Z,dt=Math.max(0,G.left-Te.right),yt=Math.abs(Ue-ne),ut=E(G.top,G.bottom,Te.top,Te.bottom)):U==="right"?(mt=Le>Z,dt=Math.max(0,Te.left-G.right),yt=Math.abs(Ue-ne),ut=E(G.top,G.bottom,Te.top,Te.bottom)):U==="above"?(mt=Ue<ne,dt=Math.max(0,G.top-Te.bottom),yt=Math.abs(Le-Z),ut=E(G.left,G.right,Te.left,Te.right)):(mt=Ue>ne,dt=Math.max(0,Te.top-G.bottom),yt=Math.abs(Le-Z),ut=E(G.left,G.right,Te.left,Te.right)),!mt)return Number.POSITIVE_INFINITY;const Oe=ut>0?0:120;return dt*3+yt+Oe};let xe=null,ke=Number.POSITIVE_INFINITY;for(const $e of te){if($e.id===H.id)continue;const Te=ie($e);Number.isFinite(Te)&&(Te>=ke||(ke=Te,xe=$e))}return xe||void 0},[]),ge=l.useCallback(U=>{var te;const z=fe(U);if(!z)return;const J=z.activePanel||z.panels[0];J&&(z.model.openPanel(J),J.api.setActive(),Rt(J.id)||re(J.id,"dockview-focus"),Ba((te=z.element)==null?void 0:te.ownerDocument))},[fe,re]),ce=l.useCallback((U,z)=>{const J=I.current,te=J==null?void 0:J.activePanel,H=(J==null?void 0:J.activeGroup)||(te==null?void 0:te.group);if(!J||!te||!H)return;let G=fe(U);!G&&(z!=null&&z.createGroupIfMissing)&&(G=J.addGroup({referenceGroup:H,direction:U})),G&&(te.api.moveTo({group:G,position:"center"}),te.group.model.openPanel(te),te.api.setActive(),Rt(te.id)||re(te.id,z!=null&&z.createGroupIfMissing?"dockview-split":"dockview-move"))},[fe,re]),{isMac:be,tabShortcuts:oe,shortcutListening:R,setShortcutListening:pe,saveShortcuts:Se}=gu({sortedTabKeys:e.map(U=>U.tabKey),onFocus:Y,onSelectTab:de}),Me=l.useCallback(()=>{var J;const U=I.current;if(!U)return;const z=U.activePanel;if(z){if(Rt(z.id)){const te=((J=z.params)==null?void 0:J.routeId)||z.id.slice(7),H=$t(e,te);H!=null&&H.tabKey&&pe(H.tabKey);return}F.has(z.id)&&pe(z.id)}},[F,de,pe,e]),ee=l.useCallback(U=>{const z=[];return U.metaKey&&z.push(be?"⌘":"Meta"),U.ctrlKey&&z.push("Ctrl"),U.altKey&&z.push(be?"⌥":"Alt"),U.shiftKey&&U.key.length!==1&&z.push(be?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(U.key)?null:(z.push(ju(U.key)),z.join("+"))},[be]),Ne=l.useCallback(U=>{var z,J;switch(U){case"splitActiveTabRight":ce("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":ce("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const te=le();te&&ue(te);return}case"popoutActiveTab":{const te=le();te&&we(te);return}case"dockActiveTab":{const te=le();if(!te)return;V(te)?Ce(te):me(te)&&je(te);return}case"focusLeftPane":ge("left");return;case"focusRightPane":ge("right");return;case"focusUpPane":ge("above");return;case"focusDownPane":ge("below");return;case"moveActiveTabToLeftPane":ce("left");return;case"moveActiveTabToRightPane":ce("right");return;case"moveActiveTabToUpPane":ce("above");return;case"moveActiveTabToDownPane":ce("below");return;case"selectPreviousGroupTab":ve(-1);return;case"selectNextGroupTab":ve(1);return;case"setActiveTabShortcut":Me();return;case"hideCurrentTab":{const te=(J=(z=I.current)==null?void 0:z.activePanel)==null?void 0:J.id;te&&!Rt(te)&&q(te);return}default:return}},[ve,je,ge,ue,le,q,me,V,Ce,ce,we,Me]);l.useEffect(()=>{if(!_)return;const U=_.sourceDocument,z=U.defaultView??window,J=te=>{const H=U.querySelector("[data-dockview-tab-context-menu]");H&&H.contains(te.target)||M(null)};return z.addEventListener("mousedown",J,!0),z!==window&&window.addEventListener("mousedown",()=>M(null),!0),()=>{z.removeEventListener("mousedown",J,!0),z!==window&&window.removeEventListener("mousedown",()=>M(null),!0)}},[_]);const De=l.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:F,hasDetachedConversationPanels:K,ides:r,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:b,liveSessionInboxState:C,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:q,userName:m,scrollToBottomRequest:w,tabShortcuts:oe,openTabContextMenu:({x:U,y:z,tabKey:J,sourceDocument:te})=>M({x:U,y:z,tabKey:J,sourceDocument:te??document}),popoutTab:we,moveTabBackToMain:Ce,isTabInPopout:V,floatTab:ue,isTabFloating:me}),[n,t,F,K,r,i,c,b,C,a,o,q,m,w,oe,we,Ce,V,ue,me]),Ee=_?N0({isTabInPopout:V(_.tabKey),isTabFloating:me(_.tabKey),tabShortcut:oe[_.tabKey],actionShortcuts:h}):[],ze=l.useCallback(U=>{var te;const z=I.current;if((((te=z==null?void 0:z.activePanel)==null?void 0:te.id)??null)===U.id){U.group.model.openPanel(U);return}U.group.model.openPanel(U),U.api.setActive()},[]),Qe=l.useCallback((U,z="requested-tab")=>{if(!U)return!1;const J=I.current;if(!J)return!1;const te=J.getPanel(U);return te?(ze(te),re(U,z),p==null||p(),!0):!1},[ze,p,re]),Ze=l.useCallback(()=>{if(D.current)return!1;const U=Qe(L.current,"stored-layout-restore");return U&&(D.current=!0),U},[Qe]),rt=l.useCallback(()=>{var z;const U=I.current;U&&sy(v,{activeTabId:((z=U.activePanel)==null?void 0:z.id)??null,layout:U.toJSON()})},[v]),et=l.useCallback(()=>{ny(v,B.current)},[v]),ct=l.useCallback(U=>{var te,H,G,Z;const z=I.current;if(!z)return{kind:"grid"};const J=z.toJSON();for(const ne of J.floatingGroups||[])if((H=(te=ne.data)==null?void 0:te.views)!=null&&H.includes(U)&&ne.position)return{kind:"floating",position:ne.position};for(const ne of J.popoutGroups||[])if((Z=(G=ne.data)==null?void 0:G.views)!=null&&Z.includes(U))return{kind:"popout",position:ne.position,popoutUrl:ne.url};return{kind:"grid"}},[]),Xe=l.useCallback(U=>{const z=I.current;if(!z)return;const J=z.getPanel(U),te=B.current[U];if(!J||!te||te.kind==="grid")return;if(J.group.model.location.type===te.kind){delete B.current[U],et();return}if(te.kind==="floating"){z.addFloatingGroup(J,{x:te.position.left??24,y:te.position.top??24,width:te.position.width,height:te.position.height}),delete B.current[U],et();return}delete B.current[U],et()},[et]);l.useEffect(()=>(f==null||f({setShortcutForActiveTab:Me,restoreHiddenTabToSavedLocation:Xe,activateConversationTab:de,resetAllPanelsToMain:X,activatePreviousTabInGroup:()=>ve(-1),activateNextTabInGroup:()=>ve(1),floatActiveTab:()=>{const U=le();U&&ue(U)},popoutActiveTab:()=>{const U=le();U&&we(U)},dockActiveTab:()=>{const U=le();U&&(V(U)?Ce(U):me(U)&&je(U))},splitActiveTabRight:()=>ce("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>ce("below",{createGroupIfMissing:!0}),focusLeftPane:()=>ge("left"),focusRightPane:()=>ge("right"),focusUpPane:()=>ge("above"),focusDownPane:()=>ge("below"),moveActiveTabToLeftPane:()=>ce("left"),moveActiveTabToRightPane:()=>ce("right"),moveActiveTabToUpPane:()=>ce("above"),moveActiveTabToDownPane:()=>ce("below")}),()=>f==null?void 0:f(null)),[ve,je,ue,ge,le,me,V,ce,Ce,we,f,X,Xe,de,Me]),l.useEffect(()=>()=>{var U;(U=T.current)==null||U.call(T),T.current=null},[]);const pt=l.useCallback(U=>{var J,te;I.current=U.api,(J=T.current)==null||J.call(T),T.current=null;const z=ty(v);if(L.current=(z==null?void 0:z.activeTabId)??null,z!=null&&z.layout&&U.api.fromJSON(z.layout,{reuseExistingPanels:!1}),A.current=$l({hasStoredLayout:!!(z!=null&&z.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),A.current||(Kl(U.api,e),Ul(U.api,e,j)),U.api.totalPanels===0&&e.length>0){const H=P0(U.api,e,k);if(H){const G=U.api.getPanel(H);G&&ze(G)}}else!A.current&&!Qe(k)&&Ze();if(P.current=!0,U.api.onDidActivePanelChange(H=>{var Z;if(L.current=(H==null?void 0:H.id)??null,D.current=!0,ye(),H&&Rt(H.id)){const ne=((Z=H.params)==null?void 0:Z.routeId)||H.id.slice(7),E=$t(e,ne);y((E==null?void 0:E.tabKey)??null),rt();return}if(y((H==null?void 0:H.id)??null),rt(),!H)return;const G=F.get(H.id);(G==null?void 0:G.streamSource)==="agent-stream"&&G.agentType&&N(G.routeId,od(),{agentType:G.agentType,...G.sessionId&&{targetSessionId:G.sessionId}}).catch(()=>{})}),U.api.onDidLayoutChange(()=>{rt(),ye(),W(H=>H+1)}),T0()){const H=ke=>({clientX:ke.clientX,clientY:ke.clientY}),G=ke=>{const Ie=ke==null?void 0:ke.getBoundingClientRect();return Ie?{left:Ie.left,right:Ie.right,top:Ie.top,bottom:Ie.bottom}:null},Z=ke=>{var $e;const Ie=($e=S.current)==null?void 0:$e.getBoundingClientRect();return Ie?ke.clientX<Ie.left||ke.clientX>Ie.right||ke.clientY<Ie.top||ke.clientY>Ie.bottom:!1},ne=M0({detachDelayMs:Su,onDetach:({panelId:ke,clientX:Ie,clientY:$e})=>{var ut,mt;const Te=U.api.getPanel(ke);if(!Te)return;try{if(Te.group.model.location.type!=="grid")return}catch{return}const Le=(ut=S.current)==null?void 0:ut.getBoundingClientRect(),Ue=(mt=Te.group.element)==null?void 0:mt.getBoundingClientRect(),dt=Math.round(Math.min(Math.max((Ue==null?void 0:Ue.width)??600,360),720)),yt=Math.round(Math.min(Math.max((Ue==null?void 0:Ue.height)??500,260),640));U.api.addFloatingGroup(Te,{x:Le?Math.max(0,Ie-Le.left-32):void 0,y:Le?Math.max(0,$e-Le.top-18):void 0,width:dt,height:yt}),Te.api.setActive(),rt(),ye(),W(Oe=>Oe+1)}}),E=[U.api.onWillDragPanel(ke=>{if(!(ke.nativeEvent.defaultPrevented||ke.nativeEvent.shiftKey)){try{if(ke.panel.group.model.location.type!=="grid")return}catch{return}ne.startDrag({panelId:ke.panel.id,selfPanelBounds:G(ke.panel.group.element),...H(ke.nativeEvent)})}}),U.api.onWillShowOverlay(ke=>{if(ne.hasDetached()){ke.preventDefault();return}ne.markDockTarget(H(ke.nativeEvent))}),U.api.onWillDrop(ke=>{if(ne.hasDetached()){ke.preventDefault(),ne.endDrag();return}ne.markDockTarget(H(ke.nativeEvent))}),U.api.onDidDrop(()=>ne.endDrag()),U.api.onUnhandledDragOverEvent(ke=>{ne.isDragging()&&ne.markSelfPanel(H(ke.nativeEvent))})],ie=ke=>{if(!ne.isDragging())return;const Ie=H(ke);Z(Ie)&&ne.markNonSelfPanel(Ie)},xe=()=>ne.endDrag();window.addEventListener("dragover",ie,!0),window.addEventListener("drop",xe,!0),window.addEventListener("dragend",xe,!0),T.current=()=>{ne.dispose();for(const ke of E)ke.dispose();window.removeEventListener("dragover",ie,!0),window.removeEventListener("drop",xe,!0),window.removeEventListener("dragend",xe,!0)}}U.api.onDidAddGroup(H=>{requestAnimationFrame(()=>{var G,Z;try{const ne=(G=H.element)==null?void 0:G.ownerDocument;if(!ne||ne===document)return;(Z=ne.getElementById("dv-popout-window"))==null||Z.classList.add("adhdev-dockview");const E=document.documentElement.getAttribute("data-theme");E&&ne.documentElement.setAttribute("data-theme",E),ne.body.className=document.body.className;const ie=document.documentElement.getAttribute("style");ie&&ne.documentElement.setAttribute("style",ie)}catch{}ye(),W(ne=>ne+1)})}),y(((te=U.api.activePanel)==null?void 0:te.id)??null)},[ze,Qe,F,r,d,v,y,rt,k,j,N,ye,e]);l.useLayoutEffect(()=>{const U=I.current;if(!U||!P.current||A.current&&$l({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;A.current&&(A.current=!1);const z=O.current,J=new Set(z),te=e.map(xe=>xe.tabKey),H=new Set(te),G=C0({previousVisibleConversationCount:z.length,visibleConversationCount:e.length,ides:r});let Z=!1;for(const xe of z)H.has(xe)||G||(B.current[xe]=ct(xe),Z=!0);Z&&et(),G||(Kl(U,e),Ul(U,e,j));const ne=te.filter(xe=>!J.has(xe));let E=!1;for(const xe of ne){const ke=U.getPanel(xe),Ie=B.current[xe];if(!ke||!Ie||Ie.kind==="grid")continue;if(ke.group.model.location.type===Ie.kind){delete B.current[xe],E=!0;continue}if(Ie.kind==="floating"){U.addFloatingGroup(ke,{x:Ie.position.left??24,y:Ie.position.top??24,width:Ie.position.width,height:Ie.position.height}),delete B.current[xe],E=!0;continue}}if(E&&et(),O.current=te,k&&Qe(k))return;!U.activePanel&&U.panels[0]&&ze(U.panels[0]),!!(U.activePanel&&U.getPanel(U.activePanel.id))||Ze()},[ze,Qe,Ze,r,d,et,ct,k,j,e]),l.useEffect(()=>{P.current&&Qe(k)},[Qe,k]),l.useEffect(()=>{const U=J=>{const te=J.target;if(!te)return;const H=te.querySelector("[data-tab-key]")||te.closest("[data-tab-key]");if(H){const G=H.getAttribute("data-tab-key");if(G&&J.dataTransfer){const Z=te.closest(".dv-tab")||H.closest(".dv-tab")||H;J.dataTransfer.effectAllowed="move",J.dataTransfer.setData("text/tab-key",G),Z instanceof HTMLElement&&J.dataTransfer.setDragImage(Z,Math.max(12,Math.round(Z.clientWidth/2)),Math.max(10,Math.round(Z.clientHeight/2)))}}};window.addEventListener("dragstart",U);const z=Wl(I.current);for(const J of z)J.addEventListener("dragstart",U);return()=>{window.removeEventListener("dragstart",U);for(const J of z)J.removeEventListener("dragstart",U)}},[$]),l.useEffect(()=>{var z;const U=(z=S.current)==null?void 0:z.querySelector(".adhdev-dockview");U instanceof HTMLElement&&Oa(U,g),he(),ye()},[ye,he,g]),l.useEffect(()=>{ye()},[ye]),l.useEffect(()=>{const U=z=>{if(z.defaultPrevented||R)return;const J=ee(z);if(!J)return;const te=z.metaKey||z.ctrlKey||z.altKey;Io(z.target)&&!te||Yn(be).setActiveTabShortcut!==J||(z.preventDefault(),z.stopPropagation(),Me())};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[ee,be,R,Me]),l.useEffect(()=>{const U=S.current;if(!U)return;const z=J=>{var ne,E;if(!J.isTrusted)return;const te=(E=(ne=J.target)==null?void 0:ne.closest)==null?void 0:E.call(ne,".dv-scrollable");if(!te)return;J.preventDefault(),J.stopPropagation();const H=Math.abs(J.deltaX),G=Math.abs(J.deltaY),Z=H>G?J.deltaX:J.deltaY;te.dispatchEvent(new WheelEvent("wheel",{deltaY:Z,deltaMode:J.deltaMode,bubbles:!1,cancelable:!0}))};return U.addEventListener("wheel",z,{passive:!1,capture:!0}),()=>U.removeEventListener("wheel",z,{capture:!0})},[]),l.useEffect(()=>{const U=Wl(I.current);if(U.length===0)return;const z=U.map(J=>{let te=[],H=null;const G=()=>{H!=null&&J.clearTimeout(H),H=null,te=[]},Z=()=>{H!=null&&J.clearTimeout(H),H=J.setTimeout(()=>{H=null,te=[]},1200)},ne=ie=>{if(!ie.ctrlKey&&!ie.metaKey&&!ie.altKey)return;const xe=ee(ie);if(!xe)return;const ke=bu();for(const[Ie,$e]of Object.entries(ke))if(e.some(Te=>Te.tabKey===Ie)&&$e===xe){ie.preventDefault(),de(Ie);return}},E=ie=>{if(ie.defaultPrevented||R)return;const xe=ee(ie);if(!xe)return;const ke=ie.metaKey||ie.ctrlKey||ie.altKey;if(Io(ie.target))return;const Ie=Yn(be),$e=Object.entries(Ie).filter(([Oe,Xt])=>!!Xt&&(Oe==="splitActiveTabRight"||Oe==="splitActiveTabDown"||Oe==="floatActiveTab"||Oe==="popoutActiveTab"||Oe==="dockActiveTab"||Oe==="focusLeftPane"||Oe==="focusRightPane"||Oe==="focusUpPane"||Oe==="focusDownPane"||Oe==="moveActiveTabToLeftPane"||Oe==="moveActiveTabToRightPane"||Oe==="moveActiveTabToUpPane"||Oe==="moveActiveTabToDownPane"||Oe==="selectPreviousGroupTab"||Oe==="selectNextGroupTab"||Oe==="setActiveTabShortcut"||Oe==="hideCurrentTab")),Te=ke?[xe]:[...te.slice(-1),xe].slice(-2),Le=Te.join(" "),Ue=Te[Te.length-1],dt=$e.find(([,Oe])=>Oe===Le);if(dt){ie.preventDefault(),G(),Ne(dt[0]);return}if($e.some(([,Oe])=>Oe.startsWith(`${Le} `))){ie.preventDefault(),te=Te,Z();return}const ut=$e.find(([,Oe])=>Oe===Ue);if(ut){ie.preventDefault(),G(),Ne(ut[0]);return}if($e.some(([,Oe])=>Oe.startsWith(`${Ue} `))){ie.preventDefault(),te=[Ue],Z();return}G()};return J.addEventListener("keydown",ne),J.addEventListener("keydown",E),()=>{G(),J.removeEventListener("keydown",ne),J.removeEventListener("keydown",E)}});return()=>{for(const J of z)J()}},[ee,be,$,de,R,Ne,e]);const Ae=g==="light"?ro:no,Fe=((Ke=(qe=(st=I.current)==null?void 0:st.activePanel)==null?void 0:qe.group.element)==null?void 0:Ke.ownerDocument)??document;return s.jsxs(Nu.Provider,{value:De,children:[s.jsx("div",{ref:S,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(Am,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:R0,remote:D0},defaultTabComponent:$0,watermarkComponent:E0,onReady:pt,singleTabMode:"default",tabAnimation:"smooth",theme:Ae,popoutUrl:"/popout.html"})}),_&&jr.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:_.x,top:_.y},children:Ee.map(U=>{if(U.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},U.id);let z=s.jsx(Hh,{size:13,className:"shrink-0 opacity-70"}),J=()=>{};switch(U.id){case"dockInWindow":case"dockBackToGrid":z=s.jsx(Kh,{size:13,className:"shrink-0 opacity-70"}),J=()=>{je(_.tabKey),M(null)};break;case"moveBackToMain":z=s.jsx(Fh,{size:13,className:"shrink-0 opacity-70"}),J=()=>{Ce(_.tabKey),M(null)};break;case"floatAsPanel":z=s.jsx(Wh,{size:13,className:"shrink-0 opacity-70"}),J=()=>{ue(_.tabKey),M(null)};break;case"openInNewWindow":z=s.jsx(Oh,{size:13,className:"shrink-0 opacity-70"}),J=()=>{we(_.tabKey),M(null)};break;case"setShortcut":J=te=>{te.stopPropagation(),pe(_.tabKey),M(null)};break;case"removeShortcut":z=s.jsx(xt,{size:13,className:"shrink-0 opacity-70"}),J=()=>{const te={...oe};delete te[_.tabKey],Se(te),M(null)};break;case"hideTab":z=s.jsx(Eo,{size:13,className:"shrink-0 opacity-70"}),J=()=>{q(_.tabKey),M(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${U.tone==="muted"?"text-text-muted":""}`,onMouseDown:_0,onClick:J,children:[z,s.jsx("span",{className:"flex-1 min-w-0",children:U.label}),U.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:U.shortcut}):null]},U.id)})}),_.sourceDocument.body),R&&jr.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:()=>pe(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:U=>U.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",be?"⌘+1":"Ctrl+1",", ",be?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),Fe.body)]})}const Cu="adhdev-recent-launch-args-v1",O0=8;function F0(e){return String(e||"").trim().replace(/\s+/g," ")}function Iu(e,t){return`${e.trim()}::${t.trim()}`}function Mu(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Cu)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function H0(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Cu,JSON.stringify(e))}catch{}}function W0(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=Mu().byKey[Iu(r,n)])==null?void 0:o.items)||[]}function K0(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=F0(r);if(!n||!a||!o)return;const i=Mu(),c=Iu(n,a),d=((u=i.byKey[c])==null?void 0:u.items)||[],m=[o,...d.filter(h=>h!==o)].slice(0,O0);i.byKey[c]={items:m},H0(i)}function U0(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Cn({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 z0({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 G0({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:i,onOpenHistory:c,onClearSelection:d}){const m=o?mu(o):null,u=z0({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Cn,{title:"Saved history",description:Jo(),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:gb()})]}),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 Tu({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 V0({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 Fa(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>Hs(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>Hs(a,"acp"))?"acp":null}function un(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function q0({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Oe,Xt;const u=Pr(),h=l.useMemo(()=>[...e].sort(Wo),[e]),[f,y]=l.useState(((Oe=h[0])==null?void 0:Oe.id)||""),b=l.useMemo(()=>h.find(Q=>Q.id===f)||h[0],[f,h]),x=l.useMemo(()=>((b==null?void 0:b.workspaces)||[]).map(Q=>({id:Q.id,path:Q.path,label:Q.label})),[b]),k=(b==null?void 0:b.defaultWorkspaceId)||null,[j,p]=l.useState("workspace"),[w,C]=l.useState(""),[v,g]=l.useState(""),[N,I]=l.useState([]),[S,T]=l.useState(""),[P,A]=l.useState(!1),[D,L]=l.useState(null),[O,_]=l.useState(""),[M,$]=l.useState(Fa(h[0])),[W,B]=l.useState(""),[F,K]=l.useState(""),[Y,re]=l.useState([]),[ae,he]=l.useState(""),[we,Ce]=l.useState([]),[V,q]=l.useState(!1),[ue,me]=l.useState(!1),[le,je]=l.useState(""),[X,ye]=l.useState(!1),[de,ve]=l.useState(()=>jt()),[fe,ge]=l.useState(null),[ce,be]=l.useState(!1),[oe,R]=l.useState(""),[pe,Se]=l.useState(null),[Me,ee]=l.useState(!1),[Ne,De]=l.useState(""),[Ee,ze]=l.useState([]),[Qe,Ze]=l.useState(!1),[rt,et]=l.useState(""),[ct,Xe]=l.useState(!1),pt=l.useRef(null),Ae=l.useRef(0);l.useEffect(()=>{var Q;!f&&((Q=h[0])!=null&&Q.id)&&y(h[0].id)},[f,h]),l.useEffect(()=>{!b||!(!b.workspaces||!b.availableProviders||!b.detectedIdes||!b.recentLaunches)||u(b.id,{minFreshMs:3e4}).catch(()=>{})},[u,b]);const Fe=l.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(Q=>Hs(Q,"cli")),[b]),st=l.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(Q=>Hs(Q,"acp")),[b]),qe=l.useMemo(()=>((b==null?void 0:b.detectedIdes)||[]).map(Q=>({id:Q.type,label:Q.name||Q.type,meta:Q.running?"Detected locally":"Available to open"})),[b]),Ke=l.useMemo(()=>M==="cli"?Fe.map(Q=>({id:Q.type,label:Q.displayName||Q.type,meta:"CLI provider"})):M==="acp"?st.map(Q=>({id:Q.type,label:Q.displayName||Q.type,meta:"ACP provider"})):qe,[st,M,Fe,qe]),U=l.useMemo(()=>N.find(Q=>Q.id===S)||null,[N,S]),z=l.useMemo(()=>Fe.find(Q=>Q.type===W)||null,[Fe,W]),J=l.useMemo(()=>au(z==null?void 0:z.meshCoordinator,{meshId:(U==null?void 0:U.id)||"",workspace:(U==null?void 0:U.workspace)||""}),[z,U]),te=pe||J,H=l.useCallback(async Q=>{A(!0),_("");try{const Pe=await c(Q);I(Pe),T(se=>{var Re;return Pe.some(kt=>kt.id===se)?se:((Re=Pe[0])==null?void 0:Re.id)||""}),L(Q)}catch(Pe){I([]),T(""),L(Q),_(Pe instanceof Error?Pe.message:"Could not load meshes")}finally{A(!1)}},[c]);l.useEffect(()=>{var Pe;if(!b)return;if(pt.current!==b.id){pt.current=b.id,p("workspace"),C(k||((Pe=x[0])==null?void 0:Pe.id)||"__home__"),g(""),I([]),T(""),L(null),_(""),$(Fa(b)),B(""),K(""),he(""),Ce([]),me(!1),je(""),ve(jt()),R(""),Se(null);return}C(se=>{var Re;return se==="__custom__"||se==="__home__"||x.some(kt=>kt.id===se)?se:k||((Re=x[0])==null?void 0:Re.id)||"__home__"}),$(se=>se==="ide"&&qe.length>0||se==="cli"&&Fe.length>0||se==="acp"&&st.length>0?se:Fa(b))},[st.length,Fe.length,k,qe.length,b,x]),l.useEffect(()=>{!b||j!=="mesh"||D===b.id||P||H(b.id)},[H,D,P,b,j]),l.useEffect(()=>{j==="mesh"&&M!=="cli"&&Fe.length>0&&$("cli")},[M,Fe.length,j]),l.useEffect(()=>{var Q;M&&(Ke.some(Pe=>Pe.id===W)||B(((Q=Ke[0])==null?void 0:Q.id)||""))},[M,Ke,W]),l.useEffect(()=>{Se(null)},[b==null?void 0:b.id,S,W,j]);const G=l.useCallback(async(Q,Pe)=>{const se=Ae.current+1;return Ae.current=se,q(!0),je(""),m(Q,Pe).then(Re=>{Ae.current===se&&Ce(Re)}).catch(Re=>{Ae.current===se&&(Ce([]),je(Re instanceof Error?Re.message:"Could not load saved sessions"))}).finally(()=>{Ae.current===se&&(q(!1),me(!0))})},[m]),Z=l.useCallback((Q,Pe)=>{re(W0(Q,Pe))},[]);l.useEffect(()=>{Ae.current+=1,he(""),ve(jt()),!b||!W||M==="ide"?re([]):Z(b.id,W),me(!1),Ce([]),je(""),q(!1)},[M,Z,G,b,W]),l.useEffect(()=>{if(!ae)return;const Q=we.find(Pe=>Pe.providerSessionId===ae);Q!=null&&Q.canResume||he("")},[we,ae]);const ne=w==="__custom__"?v.trim():w==="__home__"?"":((Xt=x.find(Q=>Q.id===w))==null?void 0:Xt.path)||"",E=l.useMemo(()=>b?t.filter(Q=>Q.id!==b.id&&Q.daemonId===b.id).map(Q=>Q.workspace):[],[t,b]),ie=l.useMemo(()=>((b==null?void 0:b.recentLaunches)||[]).map(Q=>Q.workspace),[b]),xe=l.useCallback(Q=>{const Pe=String(Q.workspace||"").trim();if(!Pe)return;const se=x.find(Re=>un(Re.path)===un(Pe));if(se){C(se.id),g("");return}C("__custom__"),g(Pe)},[x]),ke=l.useCallback(Q=>{const Pe=String(Q.workspace||"").trim();if(!Pe)return{workspaceId:null,workspacePath:null};const se=x.find(Re=>un(Re.path)===un(Pe));return se?{workspaceId:se.id,workspacePath:null}:{workspaceId:null,workspacePath:Pe}},[x]),Ie=l.useMemo(()=>we.find(Q=>Q.providerSessionId===ae)||null,[we,ae]),$e=l.useMemo(()=>{var Pe;if(M!=="cli"||!b||!W)return null;const Q=((Pe=Fe.find(se=>se.type===W))==null?void 0:Pe.displayName)||W;return{routeId:b.id,daemonId:b.id,providerSessionId:ae||void 0,transport:"pty",mode:"chat",agentName:Q,agentType:W,status:"idle",title:Q,messages:[],ideType:W,workspaceName:ne,workspacePath:ne,displayPrimary:Q,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${b.id}:${W}`,machineName:Ct(b,{fallbackId:b.id})}},[M,Fe,ne,b,ae,W]),Te=l.useCallback(()=>{var Pe;if(!b)return;C("__custom__"),ee(!0),et("");const Q=oi(b.platform,ai(v.trim(),ne,E,ie,b.defaultWorkspacePath,(Pe=x.find(se=>se.id===k))==null?void 0:Pe.path,x.map(se=>se.path)));Ze(!0),n(b.id,Q).then(se=>{De(se.path),g(se.path),ze(se.directories)}).catch(se=>{et(se instanceof Error?se.message:"Could not load folder")}).finally(()=>Ze(!1))},[v,k,ie,E,n,ne,b,x]),Le=l.useCallback(Q=>{b&&(Ze(!0),et(""),n(b.id,Q).then(Pe=>{De(Pe.path),g(Pe.path),ze(Pe.directories)}).catch(Pe=>{et(Pe instanceof Error?Pe.message:"Could not load folder")}).finally(()=>Ze(!1)))},[n,b]),Ue=l.useCallback(async()=>{if(!b||!ne)return;Xe(!0),R("");const Q=await a(b.id,ne);if(Xe(!1),!Q.ok){R(Q.error||"Could not save workspace");return}R("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,ne,b]),dt=l.useCallback(async()=>{if(!b)return;if(j==="mesh"){if(!S||!W)return;be(!0),R(""),Se(null);const se=await d(b.id,S,W);if(be(!1),!se.ok){if(se.code==="mesh_coordinator_manual_mcp_setup_required"&&se.manualSetup){Se(se.manualSetup),R("Manual MCP setup required before this provider can act as mesh coordinator.");return}R(se.error||"Could not start mesh coordinator");return}r();return}if(!M||!W)return;be(!0),R("");const Q=F.trim()?F.trim().split(/\s+/).filter(Boolean):[],Pe=M==="ide"?await o(b.id,W,{workspacePath:ne||null}):await i(b.id,M,W,{workspaceId:w!=="__home__"&&w!=="__custom__"?w:null,workspacePath:w==="__custom__"&&ne||null,resumeSessionId:M==="cli"&&ae?ae:null,cliArgs:Q});if(be(!1),!Pe.ok){R(Pe.error||"Could not start session");return}M!=="ide"&&F.trim()&&(K0(b.id,W,F),Z(b.id,W)),r()},[M,F,Z,r,o,d,i,ne,b,S,ae,W,w,j]),yt=j==="mesh"?"Start mesh coordinator":M?fb(M,M==="cli"&&!!ae):"Start",ut=j==="mesh"?"Starting coordinator…":M?xb(M,M==="cli"&&!!ae):"Starting…",mt=h.length>5;return b?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(xt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[h.length>1&&s.jsx(Cn,{title:"Machine",children:mt?s.jsx("select",{"aria-label":"Machine",value:b.id,onChange:Q=>y(Q.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:ce,children:h.map(Q=>s.jsx("option",{value:Q.id,children:Ct(Q,{fallbackId:Q.id})},Q.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:h.map(Q=>{const Pe=Ct(Q,{fallbackId:Q.id}),se=b.id===Q.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${Pe}`,"aria-pressed":se,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${se?"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(Q.id),disabled:ce,title:Pe,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${Q.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:Pe})]},Q.id)})})}),s.jsxs(Cn,{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:Te,disabled:ce,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(Q=>s.jsxs("button",{type:"button",role:"radio","aria-checked":j===Q.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${j===Q.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{p(Q.id),R(""),Q.id==="mesh"&&b&&D!==b.id&&!P&&H(b.id)},disabled:ce,children:[s.jsx("div",{className:"text-sm font-semibold",children:Q.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:Q.desc})]},Q.id))}),j==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:w,onChange:Q=>{const Pe=Q.target.value;C(Pe),Pe==="__custom__"?Te():R("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:ce,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),x.map(Q=>s.jsxs("option",{value:Q.id,children:[Q.id===k?"⭐ ":"",zc(Q.path,Q.label)||Q.path]},Q.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:w==="__home__"?"Launch without a workspace.":ne||"Select a workspace folder."}),w==="__custom__"&&ne&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Te,disabled:ce,children:[s.jsx($s,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ue,disabled:ce||ct,children:ct?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[P&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!P&&O&&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:O}),!P&&!O&&N.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."}),N.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:N.map(Q=>s.jsxs("button",{type:"button",role:"radio","aria-checked":S===Q.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${S===Q.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>T(Q.id),disabled:ce,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Q.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[Q.repoIdentity||"Repo mesh",typeof Q.nodesCount=="number"?` · ${Q.nodesCount} node${Q.nodesCount===1?"":"s"}`:""]}),Q.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",Q.workspace]})]},Q.id))}),U&&s.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),s.jsx(V0,{workspaceMode:j,activeKind:M,cliEnabled:Fe.length>0,ideEnabled:qe.length>0,acpEnabled:st.length>0,busy:ce,onSelect:$}),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:M==="ide"?"Choose IDE":M==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Ke.map(Q=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${W===Q.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>B(Q.id),disabled:ce,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Q.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Q.meta})]},Q.id)),Ke.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"&&te&&s.jsx(Tu,{setup:te,providerName:(z==null?void 0:z.displayName)||(z==null?void 0:z.name)||W}),j!=="mesh"&&M!=="ide"&&s.jsxs(Cn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:F,onChange:Q=>K(Q.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:ce}),Y.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:Y.map(Q=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>K(Q),disabled:ce,title:Q,children:Q},Q))})]}),j!=="mesh"&&M==="cli"&&s.jsx(G0,{busy:ce,savedSessionsLoading:V,savedSessionsError:le,selectedSession:Ie,onRefresh:()=>{!b||!W||G(b.id,W)},onOpenHistory:()=>{!b||!W||(ye(!0),U0({hasLoadedInitialResults:ue,isLoading:V})&&G(b.id,W))},onClearSelection:()=>he("")}),oe&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${oe.includes("saved")||oe.includes("requested")||oe.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:oe})]}),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:ce,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:dt,disabled:ce||(j==="mesh"?!S||!W||M!=="cli"||P:!M||!W||w==="__custom__"&&!ne),children:[s.jsx(Ac,{size:14}),ce?ut:yt]})]})]})}),Me&&s.jsx(ci,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:Ne,directories:Ee,busy:Qe,error:rt,onClose:()=>ee(!1),onNavigate:Le,onConfirm:Q=>{g(Q),De(Q),C("__custom__"),ee(!1)}}),X&&$e&&s.jsx(Md,{activeConv:$e,ides:[],isCreatingChat:!1,isRefreshingHistory:V,savedSessions:we,isSavedSessionsLoading:V,isResumingSavedSessionId:fe,savedHistoryFilters:de,missingWorkspaceResumePath:ne||null,onSavedHistoryFiltersChange:ve,onClose:()=>ye(!1),onNewChat:()=>{he(""),ye(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!b||!W||G(b.id,W)},onResumeSavedSession:Q=>{if(!b||!W||fe||!Q.canResume)return;const Pe=ke(Q);he(Q.providerSessionId),xe(Q),ge(Q.providerSessionId),ye(!1),be(!0),R(""),i(b.id,"cli",W,{workspaceId:Pe.workspaceId,workspacePath:Pe.workspacePath,resumeSessionId:Q.providerSessionId}).then(se=>{if(!se.ok){R(se.error||"Could not resume session");return}r()}).finally(()=>{be(!1),ge(se=>se===Q.providerSessionId?null:se)})}})]}):null}function Au(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 Xn(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=Au(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 ui(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function _u(e){var t;return!ui(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 mn(e){return[...new Set(e.filter(t=>!!t))]}function Y0(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?mn([t==null?void 0:t.id,...n.map(i=>i.id)]):a.length>0?mn(a.map(i=>i.id)):o.length>0?mn(o.map(i=>i.id)):mn(e.nodes.map(i=>i.id))}function Lu(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 X0(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${Lu(e)}::${n}x${a}`}const J0={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"},Q0={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"},Z0={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"},ev={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 Gs(e){return e==="light"?{theme:e,isDark:!1,flowColorMode:"light",textPrimary:"text-slate-900",textSecondary:"text-slate-700",textMuted:"text-slate-500",graphShellClass:"relative w-full min-w-0 overflow-hidden rounded-2xl border border-slate-200 bg-[radial-gradient(circle_at_top,_rgba(14,165,233,0.16),_rgba(248,250,252,0.98)_42%,_rgba(255,255,255,1))]",graphStatChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-slate-700 shadow-sm",graphHintChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-[10px] text-slate-500 shadow-sm",graphControlsClass:"!bottom-4 !left-4 !shadow-md",graphBackgroundDotColor:"rgba(148, 163, 184, 0.34)",edgeLabelTextColor:"#334155",edgeLabelBackgroundColor:"rgba(255, 255, 255, 0.96)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.45)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[rgba(148,163,184,0.22)] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"flex h-[100dvh] w-full flex-col overflow-hidden bg-white md:h-[min(90vh,960px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-slate-200 md:bg-white/98 md:shadow-[0_28px_120px_rgba(148,163,184,0.28)]",dialogHeaderClass:"flex shrink-0 flex-col gap-3 border-b border-slate-200 bg-white/96 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-slate-900 md:text-xl",dialogKickerClass:"rounded-full border border-slate-300 bg-slate-50 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-600",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-500",dialogRefreshedChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1.5 text-xs text-slate-600",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-300 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",dialogBodyClass:"min-h-0 flex-1 overflow-y-auto bg-[linear-gradient(180deg,rgba(248,250,252,0.98),rgba(241,245,249,0.96))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-slate-300 bg-white/90 px-6 text-center text-sm text-slate-500",cardClass:"rounded-2xl border border-slate-200 bg-white/95 shadow-sm",cardHeaderClass:"border-b border-slate-200 px-4 py-3",cardTitleClass:"text-sm font-semibold text-slate-900",cardSubtitleClass:"mt-1 text-xs text-slate-500",rowClass:"flex items-start justify-between gap-3 border-b border-slate-200/80 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"text-slate-500",rowValueClass:"max-w-[65%] break-all text-right text-slate-800",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-slate-200 bg-white/95 p-4 shadow-md md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-slate-200 bg-white/95 p-4 text-xs text-slate-500 shadow-sm md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-900",panelCloseButtonClass:"text-xs text-slate-500 hover:text-slate-900",panelFieldRowClass:"flex justify-between gap-3 border-b border-slate-200/80 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-500",panelFieldValueClass:"break-all text-right font-medium text-slate-700",infoCalloutClass:"mt-1 rounded border border-sky-300 bg-sky-50 px-2 py-1.5 text-[10px] text-sky-700",badge:t=>Q0[t],actionButton:t=>ev[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative w-full min-w-0 overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",graphStatChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-slate-200",graphHintChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-[10px] text-slate-300",graphControlsClass:"!bottom-4 !left-4 !shadow-lg",graphBackgroundDotColor:"rgba(148, 163, 184, 0.22)",edgeLabelTextColor:"#cbd5e1",edgeLabelBackgroundColor:"rgba(2, 6, 23, 0.86)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.2)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[#030617]/[0.58] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"flex h-[100dvh] w-full flex-col overflow-hidden bg-slate-950 md:h-[min(90vh,960px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-white/10 md:bg-slate-950/96 md:shadow-[0_28px_120px_rgba(2,6,23,0.46)]",dialogHeaderClass:"flex shrink-0 flex-col gap-3 border-b border-white/10 bg-slate-950/92 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-white md:text-xl",dialogKickerClass:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-300",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-400",dialogRefreshedChipClass:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 bg-white/6 text-slate-300 transition hover:bg-white/10 hover:text-white",dialogBodyClass:"min-h-0 flex-1 overflow-y-auto bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-white/10 bg-white/[0.03] px-6 text-center text-sm text-slate-400",cardClass:"rounded-2xl border border-white/10 bg-white/[0.04]",cardHeaderClass:"border-b border-white/10 px-4 py-3",cardTitleClass:"text-sm font-semibold text-white",cardSubtitleClass:"mt-1 text-xs text-slate-400",rowClass:"flex items-start justify-between gap-3 border-b border-white/5 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"text-slate-400",rowValueClass:"max-w-[65%] break-all text-right text-slate-100",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-white/10 bg-white/[0.04] p-4 shadow-lg md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-white/10 bg-white/[0.04] p-4 text-xs text-slate-400 md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-100",panelCloseButtonClass:"text-xs text-slate-400 hover:text-slate-100",panelFieldRowClass:"flex justify-between gap-3 border-b border-white/6 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-400",panelFieldValueClass:"break-all text-right font-medium text-slate-200",infoCalloutClass:"mt-1 rounded bg-blue-500/10 border border-blue-500/20 px-2 py-1.5 text-[10px] text-blue-300",badge:t=>J0[t],actionButton:t=>Z0[t]}}const xs={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,layerGap:220,nodeGap:82,edgeLabelBuffer:180,placeholderTopOffset:0},Rs={worktreeCardWidth:188,submoduleCardWidth:164,minWorktreeCardHeight:68,minSubmoduleCardHeight:56,maxEstimatedCardHeight:120,layerGap:160,nodeGap:52,edgeLabelBuffer:120},tv={maxWidth:180},sv="RIGHT",mi={"elk.algorithm":"layered","elk.direction":sv,"elk.edgeRouting":"ORTHOGONAL","elk.spacing.nodeNode":String(xs.nodeGap),"elk.layered.spacing.nodeNodeBetweenLayers":String(xs.layerGap),"elk.layered.spacing.edgeNodeBetweenLayers":String(xs.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"},rv={...mi,"elk.spacing.nodeNode":String(Rs.nodeGap),"elk.layered.spacing.nodeNodeBetweenLayers":String(Rs.layerGap),"elk.layered.spacing.edgeNodeBetweenLayers":String(Rs.edgeLabelBuffer)},nv=new _m;function hn(e,t,r){const n=(e||"").trim();return n?Math.max(1,Math.min(r,Math.ceil(n.length/t))):0}const av=6.2,ov=20;function iv(e){return Math.ceil(e.length*av)+ov}function lv(e,t){const r=t-32,n=[];n.push(e.health.replace(/_/g," ")),e.type==="submoduleNode"?n.push("submodule"):n.push(e.locality==="remote"?"remote":"local"),e.branch&&e.type!=="submoduleNode"&&n.push(e.branch),e.submoduleCommit&&e.type==="submoduleNode"&&n.push(e.submoduleCommit.slice(0,7)),e.dirty&&n.push(e.type==="submoduleNode"?"local changes":`${e.dirtyFiles} dirty`),e.outOfSync&&n.push("out of sync"),e.hasConflicts&&n.push("conflicts"),e.type!=="submoduleNode"&&e.upstream&&e.upstreamStatus!=="fresh"&&n.push("upstream unverified"),e.isOrphan&&n.push("needs follow-up");let a=0,o=0;for(const i of n){const c=iv(i)+6;o>0&&o+c>r?(a+=1,o=c):o+=c}return o>0&&(a+=1),Math.max(1,a)}function Ir(e,t=!1){const r=t?Rs:xs;return e.type==="submoduleNode"?r.submoduleCardWidth:r.worktreeCardWidth}function In(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=Au(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 Pu(e,t=!1){const r=t?Rs:xs;if(t){const b=Xn(e),x=e.type==="defaultBranchNode",k=!b&&e.branch&&e.type!=="submoduleNode",j=36+(x?0:14)+(b?24:k?16:0),p=e.type==="submoduleNode"?r.minSubmoduleCardHeight:r.minWorktreeCardHeight;return Math.min(r.maxEstimatedCardHeight,Math.max(p,Math.ceil(j)))}const n=Ir(e),a=e.type==="submoduleNode"?24:30,o=lv(e,n),i=hn(e.label,a,2),c=hn(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,a,2),d=hn(In(e),a+4,3),m=Xn(e),u=_u(e)?ui(e):null,h=hn(u,Math.max(24,Math.floor(n/8)),4),f=52+i*18+c*14+(m?30:0)+o*24+Math.max(22,d*18)+(h>0?22+h*16:0),y=e.type==="submoduleNode"?r.minSubmoduleCardHeight:r.minWorktreeCardHeight;return Math.min(r.maxEstimatedCardHeight,Math.max(y,Math.ceil(f)))}function cv(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 dv(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function uv(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 mv(e,t,r){return{id:e.id,x:t,y:r,width:Ir(e),height:Pu(e)}}function hv(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:[],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 Ru(e){const t=[...e.nodes].sort(cv),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,hv(r,e)]}function pv(e,t=mi,r=!1){const n=Ru(e),a=new Set(n.map(c=>c.id)),o=n.map(c=>({id:c.id,width:Ir(c,r),height:Pu(c,r)})),i=e.edges.filter(c=>a.has(c.source)&&a.has(c.target)).sort(dv).map(c=>({id:c.id,sources:[c.source],targets:[c.target]}));return{id:`${e.meshId||"mesh"}__elk_root`,layoutOptions:{...t},children:o,edges:i}}function fv(e,t=!1){const r=[...new Set(e.map(a=>Math.round(a.x)))].sort((a,o)=>a-o),n=t?Rs.layerGap:xs.layerGap;return r.length<2?n:Math.min(...r.slice(1).map((a,o)=>a-r[o]))}async function xv(e,t=!1){const r=t?rv:mi,n=Ru(e),a=new Map(n.map(m=>[m.id,m])),i=((await nv.layout(pv(e,r,t))).children??[]).map(m=>{const u=a.get(m.id);return u?uv(u,Math.round(m.x??0),Math.round(m.y??xs.placeholderTopOffset),!m.id.endsWith("__placeholder")):null}).filter(Boolean),c=new Map(n.map((m,u)=>[m.id,u]));i.sort((m,u)=>(c.get(m.id)??0)-(c.get(u.id)??0));const d=i.map(m=>mv(m.graphNode,m.position.x,m.position.y));return{nodes:i,bounds:d,columnGap:fv(d,t),layoutOptions:{...r}}}function bv(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.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 Du(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function gv(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(bv),...e.edges.map(Du)].join("::")}function yv(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(Du)].join("::")}const vv=7,hi=l.createContext(Gs("dark")),Eu=l.createContext(!1),$u={overflowWrap:"anywhere",wordBreak:"break-word"},wv={...$u,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},jv={...$u,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function Bu(e){return e.activeSessionCount>0}function kv(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function zl(e,t,r){const n=Bu(e),a=kv(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=Xn(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 Pt(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 Gl(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 Vl(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 Sv(e){return e.replace(/_/g," ")}function Ha(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function Nv(e){return e.locality==="remote"?"meta":"health"}function Cv({data:e,selected:t}){const r=l.useContext(hi),n=l.useContext(Eu),a=e.graphNode,o=a.type==="defaultBranchNode",i=a.type==="submoduleNode",c=_u(a),d=o?"default branch anchor":i?a.submodulePath||"submodule checkout":[a.machineLabel,Ha(a.locality)].filter(Boolean).join(" · ")||a.workspace,m=a.submoduleCommit?a.submoduleCommit.slice(0,7):null,u=Xn(a),h=ui(a),f=Bu(a);return n?s.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${zl(a,t,r.isDark)}`,style:{width:Ir(a,!0)},title:[a.label,a.branch?`Branch: ${a.branch}`:null,a.machineLabel?`Machine: ${a.machineLabel}`:null,a.workspace?`Workspace: ${a.workspace}`:null,u?`Status: ${u.label}`:null,In(a)].filter(Boolean).join(`
66
- `),children:[s.jsx(qr,{type:"target",position:Yr.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:a.label}),!o&&s.jsx("div",{className:`truncate text-[10px] leading-3.5 ${r.textMuted}`,children:d})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[f&&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:Vl(a.health)},"aria-hidden":!0})]})]}),u&&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] ${Gl(u.tone,r.isDark)}`,title:u.label,children:s.jsx("span",{className:"truncate",children:u.label})}),!u&&a.branch&&!i&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[10px] ${Pt("meta",r.isDark)} rounded-full border px-2 py-0.5 inline-block`,title:a.branch,children:a.branch}),s.jsx(qr,{type:"source",position:Yr.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]}):s.jsxs("div",{className:`rounded-2xl border px-4 py-3.5 backdrop-blur-sm transition-all ${zl(a,t,r.isDark)}`,style:{width:Ir(a)},title:[a.machineLabel?`Machine: ${a.machineLabel}`:null,a.machineId?`Machine id: ${a.machineId}`:null,a.daemonId?`Daemon: ${a.daemonId}`:null,`Locality: ${Ha(a.locality)}`,a.workspace?`Workspace: ${a.workspace}`:null].filter(Boolean).join(`
67
- `),children:[s.jsx(qr,{type:"target",position:Yr.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:a.label}),s.jsx("div",{className:`truncate text-[11px] ${r.textMuted}`,children:d})]}),s.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 shrink-0",children:[f&&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:Vl(a.health)},"aria-hidden":!0})]})]}),u&&s.jsx("div",{className:`mt-3 inline-flex min-w-0 max-w-full items-center rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] ${Gl(u.tone,r.isDark)}`,title:u.label,children:s.jsx("span",{className:"truncate",children:u.label})}),s.jsxs("div",{className:"mt-3 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 ${Pt("health",r.isDark)}`,children:Sv(a.health)}),i&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Pt("submodule",r.isDark)}`,children:"submodule"}),!o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Pt(Nv(a),r.isDark)}`,children:Ha(a.locality)}),a.branch&&!i&&s.jsx("span",{className:`min-w-0 max-w-full rounded-full border px-2 py-0.5 ${Pt("meta",r.isDark)}`,title:a.branch,children:s.jsx("span",{className:"block truncate",children:a.branch})}),m&&i&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Pt("meta",r.isDark)}`,children:m}),a.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Pt("dirty",r.isDark)}`,children:i?"local changes":`${a.dirtyFiles} dirty`}),a.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Pt("conflict",r.isDark)}`,children:"out of sync"}),a.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Pt("conflict",r.isDark)}`,children:"conflicts"}),!i&&a.upstream&&a.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Pt("orphan",r.isDark)}`,children:"upstream unverified"}),a.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Pt("orphan",r.isDark)}`,children:"needs follow-up"})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,style:wv,title:In(a),children:In(a)}),c&&h&&s.jsx("div",{className:`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${r.isDark?"border-cyan-400/15 bg-cyan-500/8 text-cyan-50/90":"border-sky-300 bg-sky-50 text-sky-700"}`,style:jv,title:h,children:h}),s.jsx(qr,{type:"source",position:Yr.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const Iv={meshNode:Cv};function Mv(e){const t={sourceX:e.sourceX,sourceY:e.sourceY,sourcePosition:e.sourcePosition,targetX:e.targetX,targetY:e.targetY,targetPosition:e.targetPosition},r=e.data.graphEdge;return r.type==="parentBranch"?Wm(t):r.type==="worktreeLink"||r.type==="submoduleLink"||r.type==="cloneLink"?Km(t):Um(t)}function Tv(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 Av(e){const t=l.useContext(hi),r=e.data.graphEdge,[n,a,o]=Mv(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(Bm,{id:e.id,path:n,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(Om,{children:s.jsx("div",{className:Tv(r,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${a}px, ${o}px)`,pointerEvents:"none",maxWidth:tv.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const _v={meshEdge:Av};async function Lv(e,t=Gs("dark"),r=!1){const n=await xv(e,r),a=new Set(n.nodes.map(c=>c.id)),o=n.nodes.map(c=>({id:c.id,type:c.type,position:c.position,data:{graphNode:c.graphNode,compact:r},selected:c.selected,draggable:c.draggable,selectable:c.selectable})),i=e.edges.filter(c=>a.has(c.source)&&a.has(c.target)).map(c=>({id:c.id,source:c.source,target:c.target,label:c.label,type:"meshEdge",data:{graphEdge:c},animated:c.type==="orphanLink",markerEnd:c.direction==="directed"?{type:$m.ArrowClosed,width:c.type==="submoduleLink"?16:18,height:c.type==="submoduleLink"?16:18,color:ql(c)}:void 0,style:{stroke:ql(c),strokeWidth:c.type==="orphanLink"?2.25:c.type==="submoduleLink"?1.7:c.type==="worktreeLink"?1.8:c.type==="cloneLink"?1.6:2,strokeDasharray:c.type==="orphanLink"?"5 4":c.type==="submoduleLink"?"4 3":c.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:o,edges:i}}function ql(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 Pv(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 Rv(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 Dv({data:e,viewportKey:t}){const r=Fm(),n=Hm(),a=l.useRef(null),o=l.useMemo(()=>Lu(e),[e]),i=l.useMemo(()=>Y0(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 Ev(e){return e>=16?"h-[720px] min-h-[720px] sm:h-[860px] xl:h-[980px]":e>=10?"h-[580px] min-h-[580px] sm:h-[700px] xl:h-[820px]":"h-[460px] min-h-[460px] sm:h-[560px] xl:h-[680px]"}function $v({data:e,selectedNodeId:t=null,onNodeClick:r}){const{theme:n}=zs(),a=l.useMemo(()=>Gs(n),[n]),o=l.useMemo(()=>gv(e),[e]),i=l.useMemo(()=>yv(e),[e]),c=e.nodes.length>=vv,[d,m]=l.useState({nodes:[],edges:[]}),u=l.useRef(null),[h,f]=l.useState({width:0,height:0}),y=l.useMemo(()=>X0(e,h.width,h.height),[o,e,h.height,h.width]);l.useEffect(()=>{let k=!1;return Lv(e,a,c).then(j=>{k||m(j)}),()=>{k=!0}},[e,i,a,c]);const b=l.useMemo(()=>d.nodes.map(k=>({...k,selected:k.id===t})),[d.nodes,t]);l.useEffect(()=>{const k=u.current;if(!k)return;const j=()=>{const w=Math.max(0,Math.round(k.clientWidth)),C=Math.max(0,Math.round(k.clientHeight));f(v=>v.width===w&&v.height===C?v:{width:w,height:C})};j();const p=typeof ResizeObserver=="function"?new ResizeObserver(()=>j()):null;return p==null||p.observe(k),window.addEventListener("resize",j),()=>{p==null||p.disconnect(),window.removeEventListener("resize",j)}},[]);const x=Ev(e.nodes.length);return s.jsx(hi.Provider,{value:a,children:s.jsx(Eu.Provider,{value:c,children:s.jsxs("div",{ref:u,className:a.graphShellClass,children:[s.jsxs("div",{className:`absolute inset-x-3 top-3 z-10 flex flex-wrap items-center justify-between gap-2 text-[11px] ${a.textSecondary}`,children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs("span",{className:a.graphStatChipClass,children:[e.stats.totalNodes," node",e.stats.totalNodes===1?"":"s"]}),e.stats.totalActiveSessions>0&&s.jsxs("span",{className:a.isDark?"rounded-full border border-emerald-400/25 bg-emerald-500/12 px-3 py-1 text-emerald-100":"rounded-full border border-emerald-300 bg-emerald-50 px-3 py-1 text-emerald-700",children:[e.stats.totalActiveSessions," active session",e.stats.totalActiveSessions===1?"":"s"]}),e.stats.orphanNodes>0&&s.jsxs("span",{className:a.isDark?"rounded-full border border-orange-400/25 bg-orange-500/12 px-3 py-1 text-orange-100":"rounded-full border border-orange-300 bg-orange-50 px-3 py-1 text-orange-700",children:[e.stats.orphanNodes," need attention"]}),c&&s.jsx("span",{className:a.isDark?"rounded-full border border-white/8 bg-white/[0.03] px-3 py-1 text-slate-400":"rounded-full border border-slate-200 bg-slate-50/80 px-3 py-1 text-slate-500",children:"dense view · hover for details"})]}),s.jsx("div",{className:a.graphHintChipClass,children:c?"drag or scroll to pan":"Focused on the main path first · drag or scroll to pan"})]}),s.jsx("div",{className:`w-full min-w-0 ${x}`,children:s.jsxs(Lm,{nodes:b,edges:d.edges,nodeTypes:Iv,edgeTypes:_v,minZoom:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(k,j)=>r==null?void 0:r(j.data.graphNode),className:"h-full w-full",colorMode:a.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(Dv,{data:e,viewportKey:y}),s.jsx(Pm,{className:a.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),s.jsx(Rm,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:Pv,nodeClassName:Rv,nodeStrokeWidth:3,className:a.isDark?"overflow-hidden rounded-xl border border-white/10 bg-slate-950/85":"overflow-hidden rounded-xl border border-slate-200 bg-white/95"}),s.jsx(Dm,{variant:Em.Dots,gap:18,size:1.2,color:a.graphBackgroundDotColor})]})})]})})})}function ot(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function _e(...e){for(const t of e){if(typeof t!="string")continue;const r=t.trim();if(r)return r}}function Nt(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function At(...e){for(const t of e)if(typeof t=="boolean")return t}function Wa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function pi(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 Bv(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 Ov(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=ot(n),o=_e(a.path),i=_e(a.commit),c=_e(a.repoPath,a.repo_root)??Bv(t,o);return!o||!i||!c?null:{path:o,commit:i,repoPath:c,dirty:At(a.dirty)??!1,outOfSync:At(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:Nt(a.lastCheckedAt,a.last_checked_at)??Date.now(),..._e(a.error)?{error:_e(a.error)}:{}}}).filter(n=>n!==null);return r.length>0?r:void 0}function Fv(e){return At(e.isGitRepo)!==void 0||!!_e(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||Nt(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 Mn(e,t,r){const n=At(e.isGitRepo);if(!Object.keys(e).length||!Fv(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(b=>typeof b=="string"):[],i=Nt(e.conflicts)??o.length,c=At(e.hasConflicts)??i>0,d=_e(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,m=Ov(e.submodules,d),u=_e(e.upstreamStatus,e.upstream_status),h=Nt(e.upstreamFetchedAt,e.upstream_fetched_at),f=_e(e.upstreamFetchError,e.upstream_fetch_error),y=_e(e.error);return{workspace:_e(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:a,branch:_e(e.branch)??null,headCommit:_e(e.headCommit)??null,headMessage:_e(e.headMessage)??null,upstream:_e(e.upstream)??null,upstreamStatus:u??"unchecked",...h!==void 0?{upstreamFetchedAt:h}:{},...f?{upstreamFetchError:f}:{},ahead:Nt(e.ahead)??0,behind:Nt(e.behind)??0,staged:Nt(e.staged)??0,modified:Nt(e.modified)??0,untracked:Nt(e.untracked)??0,deleted:Nt(e.deleted)??0,renamed:Nt(e.renamed)??0,hasConflicts:c,conflictFiles:o,stashCount:Nt(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??Nt(e.lastCheckedAt,e.last_checked_at)??Date.now(),...m?{submodules:m}:{},...y?{error:y}:{}}}function Hv(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+=pi(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 Wv(e){const t=ot(e.lastGit??e.last_git),r=ot(t.result),n=ot(t.status),a=ot(r.status),o=ot(e.lastProbe??e.last_probe),i=ot(o.git),c=ot(i.result),d=ot(i.status),m=ot(c.status);let u=null;for(const h of[n,a,d,m]){const f=Mn(h,e,{lastCheckedAt:Date.now()});if(!f)continue;const y=Hv(f);(!u||y>u.score)&&(u={git:f,score:y})}return u==null?void 0:u.git}function Kv(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 Uv(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 Jn(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=Kv(e);return t.outOfSync?"degraded":t.dirty||Uv(e)?"dirty":"online"}function zv(e,t){const r=t?Jn(t):void 0;return!e||e==="unknown"?r:e}function Gv(e){const t=Array.isArray(e.activeSessionDetails)?e.activeSessionDetails:Array.isArray(e.active_session_details)?e.active_session_details:null;if(t){const a=t.map(o=>{const i=ot(o),c=_e(i.sessionId,i.session_id,i.id);return c?{sessionId:c,..._e(i.providerType,i.provider)?{providerType:_e(i.providerType,i.provider)}:{},..._e(i.state,i.status)?{state:_e(i.state,i.status)}:{},..._e(i.lifecycle)?{lifecycle:_e(i.lifecycle)}:{},..._e(i.surfaceKind,i.surface_kind)?{surfaceKind:_e(i.surfaceKind,i.surface_kind)}:{},..._e(i.recoveryState,i.recovery_state)?{recoveryState:_e(i.recoveryState,i.recovery_state)}:{},..._e(i.workspace)?{workspace:_e(i.workspace)}:{},..._e(i.title)?{title:_e(i.title)}:{},..._e(i.lastActivityAt,i.last_activity_at)?{lastActivityAt:_e(i.lastActivityAt,i.last_activity_at)}:{},...At(i.isCached,i.is_cached)!==void 0?{isCached:At(i.isCached,i.is_cached)}:{}}:null}).filter(o=>o!==null);if(a.length>0)return a}const r=ot(e.activeSession??e.active_session),n=_e(r.id,r.sessionId,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id);if(n)return[{sessionId:n,..._e(r.providerType,r.provider)?{providerType:_e(r.providerType,r.provider)}:{},..._e(r.state,r.status)?{state:_e(r.state,r.status)}:{}}]}function Vv(e){const t=ot(e.connection);return Object.keys(t).length>0?t:void 0}function qv(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 fi(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 Yl(e){var n,a,o,i,c,d;let t=0;const r=e.git;return fi(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+=pi(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 Yv(e,t){var b,x,k,j;const r=Yl(e),a=Yl(t)>r?t:e,o=a===t?e:t,i=a.git??o.git,c=(((b=a.providers)==null?void 0:b.length)??0)>0?a.providers:o.providers,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,h=a.connection??o.connection,f={...o,...a,machineLabel:a.machineLabel||o.machineLabel,workspace:a.workspace||o.workspace,...a.repoRoot||o.repoRoot?{repoRoot:a.repoRoot||o.repoRoot}:{},...a.daemonId||o.daemonId?{daemonId:a.daemonId||o.daemonId}:{},...a.machineId||o.machineId?{machineId:a.machineId||o.machineId}:{},...a.machineStatus||o.machineStatus?{machineStatus:a.machineStatus||o.machineStatus}:{},health:i&&(!a.health||a.health==="unknown")?Jn(i):a.health,providers:c??[],activeSessions:d??[],...m&&m.length>0?{activeSessionDetails:m}:{},...u&&u.length>0?{providerPriority:u}:{},...h?{connection:h}:{},...i?{git:i}:{}},y=ot(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 Xv(e){const t=ot(e),r=_e(t.nodeId,t.id);if(!r)return null;const n=ot(t.cachedStatus),a=Wv(t),o=a?void 0:Mn(ot(t.git),t)??Mn(t,t),i=a??o,c=i?void 0:Mn(ot(n.git),t),d=i??c,m=_e(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),u=_e(t.health),h=a?Jn(d):zv(u,i)||(d?Jn(d):void 0)||_e(n.health)||m||_e(t.status)||"unknown",y=(a?void 0:_e(t.error))??(i?void 0:_e(n.error)),b=Gv(t),x=Wa(t.activeSessions),k=(b==null?void 0:b.map(I=>I.sessionId))??[],j=Wa(t.providerPriority),p=At(t.gitProbePending,t.git_probe_pending),w=i?void 0:p,C=Vv(t),v=ot(t.branchConvergence??t.branch_convergence),g=C==null?void 0:C.state,N=a&&(!(C!=null&&C.reported)||g==="unknown")?qv(C):C;return{nodeId:r,machineLabel:_e(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:_e(t.workspace,d==null?void 0:d.workspace)||"",..._e(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:_e(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},..._e(t.daemonId,t.daemon_id)?{daemonId:_e(t.daemonId,t.daemon_id)}:{},..._e(t.machineId,t.machine_id)?{machineId:_e(t.machineId,t.machine_id)}:{},...m?{machineStatus:m}:{},...At(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:At(t.isLocalWorktree,t.is_local_worktree)}:{},..._e(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:_e(t.worktreeBranch,t.worktree_branch)}:{},health:h,...d?{git:d}:{},...w!==void 0?{gitProbePending:w}:{},providers:Wa(t.providers),activeSessions:x.length>0?x:k,...b&&b.length>0?{activeSessionDetails:b}:{},...j.length>0?{providerPriority:j}:{},...At(t.launchReady)!==void 0?{launchReady:At(t.launchReady)}:a?{launchReady:!0}:{},..._e(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:_e(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},..._e(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:_e(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...N?{connection:N}:{},...Object.keys(v).length>0?{branchConvergence:v}:{},...y?{error:y}:{}}}function Ou(e){const t=new Map,r=[];for(const n of e){const a=t.get(n.nodeId);if(!a){t.set(n.nodeId,n),r.push(n);continue}const o=Yv(a,n);t.set(n.nodeId,o);const i=r.findIndex(c=>c.nodeId===n.nodeId);i>=0&&(r[i]=o)}return r}function Fu(e){return{...e,nodes:Ou(e.nodes??[])}}function Jv(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:fi(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 Qv(e){const t=_e(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(d=>Xv(d)).filter(d=>d!==null):null;if(!t||!n)return null;const a=Ou(n),o=_e(e.meshName,e.mesh_name,e.name),i=_e(e.repoIdentity,e.repo_identity),c=_e(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!o||!i||!c?null:{...e,meshId:t,meshName:o,repoIdentity:i,refreshedAt:c,nodes:a}}function Zv(e){var o;let t=0;const r=ot(e.sourceOfTruth),n=ot(r.directPeerTruth);_e(r.currentStatus)==="live_git_and_session_probes"&&(t+=100),r.coordinatorOwnsLiveTruth===!0&&(t+=25),n.satisfied===!0&&(t+=15);for(const i of e.nodes){const c=i.git;if(!c){i.gitProbePending&&(t-=8);continue}t+=10,c.isGitRepo===!0&&(t+=5),c.isGitRepo===!1&&(t+=1),c.branch&&(t+=4),c.upstream&&(t+=3),c.headCommit&&(t+=3),t+=pi(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 Xl(e){let t=null;for(const r of e){const n=Qv(ot(r));if(!n)continue;const a=Zv(n);(!t||a>t.score)&&(t={status:n,score:a})}return(t==null?void 0:t.status)??null}function Hu(e){const r=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,n=Xl([r==null?void 0:r.status,r]);return n||Xl([e==null?void 0:e.status,e])}const ew=5*60*1e3;function Wu(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function Ku(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function tw(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"||Wu(e)||Ku(e)?"remote":"unknown"}function sw(e){return fi(e)}function Uu(e){var t;return sw(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function rw(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function zu(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function Gu(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function xi(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function nw(e){return xi(e)?"degraded":Gu(e)?"dirty":"online"}function aw(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function Jl(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 Ka(e){return e.length===0?"unknown":e.reduce((t,r)=>Jl(r)>Jl(t)?r:t)}function ow(e){var o,i,c,d,m;const t=new Map,r=new Map;for(const u of e){const h=(i=(o=u.git)==null?void 0:o.branch)==null?void 0:i.trim();h&&(r.set(h,(r.get(h)??0)+1),(c=u.git)!=null&&c.upstream&&t.set(h,(t.get(h)??0)+1))}const n=[...t.entries()].sort((u,h)=>{if(h[1]!==u[1])return h[1]-u[1];const f=["main","master","develop","dev"],y=f.indexOf(u[0]),b=f.indexOf(h[0]);return y!==-1||b!==-1?y===-1?1:b===-1?-1:y-b:u[0].localeCompare(h[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((m=[...r.entries()].sort((u,h)=>h[1]-u[1])[0])==null?void 0:m[0])??null}function iw(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 Ql(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 lw(e){return e.reduce((t,r)=>Ql(r.status)>Ql(t.status)?r:t)}function cw(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 dw(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 uw(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 mw(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 hw(e,t){if(Uu(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=zu(a)||Gu(a),i=!!(a!=null&&a.hasConflicts)||xi(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,h=(a==null?void 0:a.upstreamStatus)??null,f=r.defaultBranch??t??null;return{status:n,needsConvergence:r.needsConvergence??n!=="merged_to_main",reason:r.reason??"provided_by_coordinator",nextStep:r.nextStep??null,branch:r.branch??m,defaultBranch:f,upstream:r.upstream??u,upstreamStatus:r.upstreamStatus??h,ahead:r.ahead??c,behind:r.behind??d,dirty:r.dirty??o,hasConflicts:r.hasConflicts??i}}function pw(e,t){const r=hw(e,t);return r?{...r,defaultBranch:r.defaultBranch??t}:null}function fw(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function xw(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(Uu(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const h=t.health==="online"||t.machineStatus==="online"||((d=t.connection)==null?void 0:d.state)==="connected"||((m=t.connection)==null?void 0:m.state)==="self";return a.push(h?`${o} is online but no peer git snapshot is visible yet.`:`${o} has no peer git snapshot visible yet.`),{snapshotCompleteness:"missing_git",snapshotWarnings:a}}const c=new Set((i.submodules??[]).map(h=>h.path));if(r.size>0){const h=[...r].filter(f=>!c.has(f));h.length>0&&a.push(`${o} is missing submodule visibility for ${h.join(", ")} even though another peer reported it.`)}return((u=t.connection)==null?void 0:u.state)!=="self"&&n!==null&&typeof i.lastCheckedAt=="number"&&n-i.lastCheckedAt>ew&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(h=>h.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(h=>h.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function bw(e){var D;const t=Fu(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??ow(t.nodes),a=rw(t.refreshedAt),o=new Set(t.nodes.flatMap(L=>{var O;return(((O=L.git)==null?void 0:O.submodules)??[]).map(_=>_.path)})),i=[],c=[],d=dw(t),m=new Map;for(const L of t.nodes){const O=L.git,_=(O==null?void 0:O.branch)??null,M=nw(O),$=zu(O)||M==="dirty",W=iw(L,n),B=pw(L,n),F=xw({nodeStatus:L,expectedSubmodulePaths:o,refreshedAtMs:a}),K=typeof L.clonedFromNodeId=="string"?L.clonedFromNodeId:null,Y={id:L.nodeId,type:W.length>0?"orphanNode":"worktreeNode",label:L.machineLabel||L.nodeId.slice(0,8),workspace:L.workspace,branch:_,upstream:(O==null?void 0:O.upstream)??null,upstreamStatus:(O==null?void 0:O.upstreamStatus)??null,daemonId:Wu(L),machineId:Ku(L),machineLabel:L.machineLabel||null,locality:tw(L),health:Ka([L.health,M]),ahead:(O==null?void 0:O.ahead)??0,behind:(O==null?void 0:O.behind)??0,dirty:$,dirtyFiles:aw(O),hasConflicts:(O==null?void 0:O.hasConflicts)??!1,activeSessionCount:((D=L.activeSessions)==null?void 0:D.length)??0,activeSessions:L.activeSessions??[],providers:L.providers??[],isOrphan:W.length>0,orphanReasons:W,error:L.error,nextStepHint:F.snapshotWarnings[0]??W[0]??(B==null?void 0:B.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:K,worktreeBranch:L.worktreeBranch??null,submodulePath:null,submoduleCommit:(O==null?void 0:O.headCommit)??null,outOfSync:xi(O),snapshotCompleteness:F.snapshotCompleteness,snapshotWarnings:F.snapshotWarnings,branchConvergence:B,source:L};if(i.push(Y),_){const re=m.get(_)??[];re.push(Y.id),m.set(_,re)}for(const re of(O==null?void 0:O.submodules)??[]){const ae=`${Y.id}::submodule::${re.path}`,he=re.path.split("/").filter(Boolean).pop()||re.path;i.push({id:ae,type:"submoduleNode",label:he,workspace:re.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:Y.daemonId,machineId:Y.machineId,machineLabel:Y.machineLabel,locality:Y.locality,health:fw(re),ahead:0,behind:0,dirty:re.dirty,dirtyFiles:re.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],error:re.error,nextStepHint:re.error||(re.outOfSync?`${re.path} is out of sync with the parent checkout`:re.dirty?`${re.path} has local changes`:`${re.path} is in sync with the parent checkout`),parentNodeId:Y.id,submodulePath:re.path,submoduleCommit:re.commit,outOfSync:re.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:Y.id,parentWorkspace:L.workspace,submodule:re}}),c.push({id:`${Y.id}--${ae}`,source:Y.id,target:ae,type:"submoduleLink",label:re.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const u=n?`__branch_${n}`:null;if(u&&n){const O=(m.get(n)??[]).map(K=>i.find(Y=>Y.id===K)).filter(Boolean),_=O.map(K=>K.branchConvergence).filter(Boolean),M=cw(t),$=O.length>0&&O.every(K=>uw(K,n)),W=(M==null?void 0:M.length)===0&&$?mw(n,O):_.length>0?lw(_):null,B=(M==null?void 0:M.length)===0&&$?0:_.filter(K=>K.needsConvergence).length,F={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:Ka(O.map(K=>K.health)),ahead:0,behind:0,dirty:O.some(K=>K.dirty),dirtyFiles:O.reduce((K,Y)=>K+Y.dirtyFiles,0),hasConflicts:O.some(K=>K.hasConflicts),activeSessionCount:O.reduce((K,Y)=>K+Y.activeSessionCount,0),activeSessions:O.flatMap(K=>K.activeSessions),providers:[...new Set(O.flatMap(K=>K.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:B>0?`${B} workspace(s) on ${n} still need follow-up`:O.length>0?`${O.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:W,source:{nodeId:u,machineLabel:n,workspace:t.repoIdentity,health:Ka(O.map(K=>K.health)),providers:[],activeSessions:[]}};i.push(F);for(const K of i)if(!(K.id===u||K.type==="submoduleNode")){if(K.branch===n){c.push({id:`${u}--${K.id}`,source:u,target:K.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(K.branch){c.push({id:`${u}--${K.id}`,source:u,target:K.id,type:K.isOrphan?"orphanLink":"parentBranch",label:K.branch,direction:"undirected"});continue}K.isOrphan&&c.push({id:`${u}--${K.id}`,source:u,target:K.id,type:"orphanLink",label:"detached",direction:"undirected"})}}for(const[L,O]of m){if(O.length<2)continue;const _=O.map(M=>i.find($=>$.id===M)).filter(Boolean);_.sort((M,$)=>M.label.localeCompare($.label));for(let M=1;M<_.length;M+=1)c.push({id:`wt_${_[M-1].id}--${_[M].id}`,source:_[M-1].id,target:_[M].id,type:"worktreeLink",label:M===1?`${L} peers`:void 0,direction:"undirected"})}const h=new Set(i.map(L=>L.id)),f=new Set;for(const L of i){if(!L.clonedFromNodeId||L.type==="submoduleNode"||!h.has(L.clonedFromNodeId))continue;const O=`clone_${L.clonedFromNodeId}--${L.id}`;if(f.has(O))continue;f.add(O);const _=L.worktreeBranch??L.branch??void 0;c.push({id:O,source:L.clonedFromNodeId,target:L.id,type:"cloneLink",label:_?`cloned · ${_}`:"cloned",direction:"directed"})}const y=i.filter(L=>L.type!=="defaultBranchNode"),b=y.filter(L=>L.isOrphan).length,x=y.filter(L=>L.hasConflicts).length,k=y.filter(L=>L.health==="offline").length,j=y.filter(L=>L.type==="submoduleNode"&&L.outOfSync).length,p=y.filter(L=>{var O;return L.type!=="submoduleNode"&&((O=L.branchConvergence)==null?void 0:O.needsConvergence)}).length,w=y.filter(L=>{var O;return((O=L.branchConvergence)==null?void 0:O.status)==="blocked_review"}).length,C=y.filter(L=>{var O;return((O=L.branchConvergence)==null?void 0:O.status)==="pushed_feature_branch_needs_merge"}).length,v=y.filter(L=>{var O;return((O=L.branchConvergence)==null?void 0:O.status)==="cleanup_candidate"}).length,g=y.filter(L=>{var O;return((O=L.branchConvergence)==null?void 0:O.status)==="not_mergeable"}).length,N=y.filter(L=>L.snapshotWarnings.length>0).length,I=y.filter(L=>L.snapshotCompleteness==="pending_git").length,S=y.filter(L=>L.snapshotCompleteness==="missing_git").length,T=y.filter(L=>L.snapshotCompleteness==="missing_submodule_report").length,P=y.filter(L=>L.snapshotCompleteness==="stale").length,A=[I>0?`${I} 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,P>0?`${P} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return p>0&&d.push(`${p} workspace(s) still need follow-up before the mesh is converged`),b>0&&d.push(`${b} workspace(s) need attention before safe coordination`),w>0&&d.push(`${w} workspace(s) are blocked on branch convergence or upstream sync`),C>0&&d.push(`${C} clean feature branch workspace(s) still need merge follow-up`),v>0&&d.push(`${v} worktree workspace(s) are ready for refine / cleanup`),g>0&&d.push(`${g} 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(...A),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(L=>L.health==="online").length,dirtyNodes:y.filter(L=>L.dirty).length,orphanNodes:b,errorNodes:y.filter(L=>!!L.error||L.outOfSync).length,offlineNodes:k,followUpNodes:p,blockedReviewNodes:w,mergeReadyNodes:C,cleanupCandidateNodes:v,notMergeableNodes:g,incompleteSnapshotNodes:N,missingGitSnapshotNodes:S,missingSubmoduleSnapshotNodes:T,staleGitSnapshotNodes:P,totalActiveSessions:y.reduce((L,O)=>L+O.activeSessionCount,0)},warnings:d,snapshotWarnings:A}}const gw={recentFailures:0,taskCompleted:0,taskFailed:0,sessionLaunched:0},bi=l.createContext(Gs("dark"));function Ge({label:e,tone:t="default"}){const r=l.useContext(bi);return s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${r.badge(t)}`,children:e})}function wt({label:e,value:t}){const r=l.useContext(bi);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 yw(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 Ua(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 vw(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 ww(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 jw(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 kw(e){return e.assignedNodeId||e.targetNodeId||null}function Zl(e){return e?e.slice(0,7):null}function Sw(e,t){var o,i,c;const r=Zl((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?[Zl(a.commit),a.message].filter(Boolean).join(" · "):null}function Nw(e,t){const r=Sw(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function Cw(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 Iw(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 Mw(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":ww(e.connection)}function Tw(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 Aw(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function _w(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,h,f,y,b,x,k,j,p,w,C,v,g,N,I,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)??"",((h=o.git)==null?void 0:h.upstreamStatus)??"",((f=o.git)==null?void 0:f.ahead)??"",((y=o.git)==null?void 0:y.behind)??"",((b=o.git)==null?void 0:b.headCommit)??"",((x=o.git)==null?void 0:x.staged)??"",((k=o.git)==null?void 0:k.modified)??"",((j=o.git)==null?void 0:j.untracked)??"",((p=o.git)==null?void 0:p.deleted)??"",((w=o.git)==null?void 0:w.renamed)??"",(C=o.git)!=null&&C.hasConflicts?1:0,((v=o.git)==null?void 0:v.lastCheckedAt)??"",((g=o.activeSessions)==null?void 0:g.join(","))??"",((N=o.activeSessionDetails)==null?void 0:N.length)??"",((I=o.providers)==null?void 0:I.join(","))??"",((S=o.providerPriority)==null?void 0:S.join(","))??"",o.error??"",(((T=o.git)==null?void 0:T.submodules)??[]).map(P=>[P.path,P.commit,P.dirty?1:0,P.outOfSync?1:0,P.error??""].join("/")).join(",")].join("|")})].join("::")}function Vu({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null}){var ae,he,we,Ce,V;const{theme:a}=zs(),o=l.useMemo(()=>Gs(a),[a]),i=l.useMemo(()=>Fu(e),[e]),c=l.useMemo(()=>_w(i),[i]),d=l.useMemo(()=>bw(i),[c]),[m,u]=l.useState(null),[h,f]=l.useState(null),[y,b]=l.useState({}),[x,k]=l.useState(null),[j,p]=l.useState(null),w=l.useMemo(()=>new Map(i.nodes.map(q=>[q.nodeId,q])),[i.nodes]),C=l.useMemo(()=>new Map(d.nodes.map(q=>[q.id,q])),[d.nodes]),v=((ae=i.queue)==null?void 0:ae.summary)??null,g=((he=i.ledger)==null?void 0:he.summary)??gw,N=l.useMemo(()=>jw(i),[i]),I=l.useMemo(()=>{const q=new Map;for(const ue of N){const me=ue.session.state||ue.session.lifecycle||"unknown";q.set(me,(q.get(me)??0)+1)}return[...q.entries()].sort((ue,me)=>me[1]-ue[1])},[N]);l.useEffect(()=>{m&&(C.has(m)||(u(null),f(q=>!q||"nodeId"in q&&q.nodeId===m?null:q)))},[C,m]);const S=m?w.get(m)??null:null,T=Aw(d,m);l.useEffect(()=>{var q,ue,me;if(m)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:i.meshId,selectedNodeId:m,canonicalNode:Jv(S),graphNode:T?{id:T.id,branch:T.branch,upstream:T.upstream,headCommit:T.submoduleCommit,submoduleCount:((ue=(q=S==null?void 0:S.git)==null?void 0:q.submodules)==null?void 0:ue.length)??0,snapshotCompleteness:T.snapshotCompleteness,snapshotWarnings:T.snapshotWarnings,branchConvergence:((me=T.branchConvergence)==null?void 0:me.status)??null}:null})}catch{}},[i.meshId,T,m,S]);const P=(h==null?void 0:h.kind)==="session"?N.find(q=>q.nodeId===h.nodeId&&q.session.sessionId===h.sessionId)??null:null,A=l.useMemo(()=>N.filter(q=>q.nodeId===m),[m,N]),D=Iw({coordinatorDaemonId:r,selectedNodeStatus:S,selectedSessionEntry:P}),L=(D==null?void 0:D.workspace)??null,O=L?y[L]??null:null,_=Nw(S,(O==null?void 0:O.entries)??[]),M=(T==null?void 0:T.daemonId)??(S==null?void 0:S.daemonId)??r??null,$=!!(T&&n&&M&&T.type!=="submoduleNode"&&T.behind>0&&T.ahead===0&&T.dirtyFiles===0&&!T.dirty&&!T.hasConflicts&&T.upstreamStatus==="fresh"),W=l.useCallback(()=>{u(null),f(null),k(null)},[]);l.useEffect(()=>{k(null)},[m]);const B=l.useCallback(async()=>{if(!(!T||!M||!n||!$)){p(T.id),k(null);try{const q=await n(M,"fast_forward_mesh_node",{meshId:i.meshId,nodeId:T.id,dryRun:!0,execute:!1});if(k({phase:"dry_run",code:typeof(q==null?void 0:q.code)=="string"?q.code:void 0,error:typeof(q==null?void 0:q.operationError)=="string"?q.operationError:null,executed:(q==null?void 0:q.executed)===!0}),!(q!=null&&q.success)||q.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${T.label}?`))return;const me=await n(M,"fast_forward_mesh_node",{meshId:i.meshId,nodeId:T.id,dryRun:!1,execute:!0});k({phase:"execute",code:typeof(me==null?void 0:me.code)=="string"?me.code:void 0,error:typeof(me==null?void 0:me.operationError)=="string"?me.operationError:null,executed:(me==null?void 0:me.executed)===!0})}catch(q){k({phase:"dry_run",error:q instanceof Error?q.message:"fast-forward failed"})}finally{p(null)}}},[$,i.meshId,T,M,n]);l.useEffect(()=>{if(!T)return;const q=ue=>{ue.key==="Escape"&&W()};return window.addEventListener("keydown",q),()=>window.removeEventListener("keydown",q)},[W,T]),l.useEffect(()=>{if(!D||!n)return;const{daemonId:q,workspace:ue}=D,me=y[ue];if(me!=null&&me.loading||me&&(me.entries.length>0||me.error))return;let le=!1;return b(je=>{var X;return{...je,[ue]:{loading:!0,error:null,entries:((X=je[ue])==null?void 0:X.entries)??[]}}}),n(q,"git_log",{workspace:ue,limit:5}).then(je=>{le||b(X=>({...X,[ue]:{loading:!1,error:null,entries:Cw(je)}}))}).catch(je=>{le||b(X=>({...X,[ue]:{loading:!1,error:je instanceof Error?je.message:"git_log failed",entries:[]}}))}),()=>{le=!0}},[y,D,n]);const F=[...d.warnings??[],...i.nodes.filter(q=>q.machineStatus&&q.machineStatus!=="online").map(q=>`${q.machineLabel}: ${q.machineStatus}`)],K=d.stats.incompleteSnapshotNodes>0,Y=d.stats.followUpNodes>0?`${d.stats.followUpNodes} need follow-up`:K?"mesh visibility incomplete":"mesh converged",re=d.stats.followUpNodes>0?"danger":K?"warn":"good";return s.jsx(bi.Provider,{value:o,children:s.jsx("div",{className:"flex min-h-0 flex-col gap-4",children:s.jsx("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-4",children:s.jsxs("div",{className:`${o.cardClass} relative min-h-0 flex-1 rounded-[28px] p-3 sm:p-4`,style:{minHeight:420},children:[s.jsxs("div",{className:`absolute inset-x-4 top-4 z-30 flex max-h-[42dvh] flex-wrap items-start justify-between gap-3 overflow-y-auto rounded-2xl px-3.5 py-3 backdrop-blur-xl sm:static sm:mb-3 sm:max-h-none sm:overflow-visible sm:backdrop-blur-none ${o.isDark?"border border-white/10 bg-slate-950/85 sm:bg-slate-950/45":"border border-slate-200 bg-white/95 shadow-lg shadow-slate-900/10 sm:bg-white/95 sm:shadow-sm"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-wrap gap-2 text-xs ${o.textSecondary}`,children:[s.jsx(Ge,{label:Y,tone:re}),d.stats.blockedReviewNodes>0&&s.jsx(Ge,{label:`${d.stats.blockedReviewNodes} blocked review`,tone:"danger"}),d.stats.notMergeableNodes>0&&s.jsx(Ge,{label:`${d.stats.notMergeableNodes} not mergeable`,tone:"danger"}),d.stats.mergeReadyNodes>0&&s.jsx(Ge,{label:`${d.stats.mergeReadyNodes} need merge`,tone:"warn"}),d.stats.cleanupCandidateNodes>0&&s.jsx(Ge,{label:`${d.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),d.stats.offlineNodes>0&&s.jsx(Ge,{label:`${d.stats.offlineNodes} offline`,tone:"danger"}),d.stats.incompleteSnapshotNodes>0&&s.jsx(Ge,{label:`${d.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),d.stats.missingGitSnapshotNodes>0&&s.jsx(Ge,{label:`${d.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),d.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Ge,{label:`${d.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),d.stats.staleGitSnapshotNodes>0&&s.jsx(Ge,{label:`${d.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((v==null?void 0:v.active)??0)>0&&s.jsx(Ge,{label:`${(v==null?void 0:v.active)??0} active queue`,tone:"info"}),s.jsx(Ge,{label:`${d.stats.totalNodes} nodes`,tone:"default"}),d.stats.totalActiveSessions>0&&s.jsx(Ge,{label:`${d.stats.totalActiveSessions} active sessions`,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(Ge,{label:`${d.stats.dirtyNodes} dirty`,tone:d.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Ge,{label:`${d.stats.orphanNodes} orphan`,tone:d.stats.orphanNodes>0?"warn":"good"}),s.jsx(Ge,{label:`${g.recentFailures} recent failures`,tone:g.recentFailures>0?"danger":"good"}),I.length===0?s.jsx(Ge,{label:"no session metadata"}):I.slice(0,2).map(([q,ue])=>s.jsx(Ge,{label:`${ue} ${q}`,tone:Ua(q)},q))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ge,{label:"Anchor = default branch",tone:"info"}),s.jsx(Ge,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Ge,{label:"Submodule link = child checkout",tone:"warn"})]}),F.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:F.map(q=>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:q},q))}),s.jsx("div",{className:`text-xs ${o.textMuted}`,children:"Click a node only when you want drill-down details. The graph itself now carries the convergence state."})]})]})]}),d.nodes.length>0?s.jsx($v,{data:d,selectedNodeId:m,onNodeClick:q=>{if((h==null?void 0:h.kind)==="node"&&m===q.id){u(null),f(null);return}u(q.id),f({kind:"node",nodeId:q.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}),T&&(h==null?void 0:h.kind)==="node"&&s.jsx("div",{className:"absolute inset-x-3 bottom-3 top-20 z-20 flex items-end justify-center p-2 sm:inset-5 sm:top-24 sm:items-start sm:justify-end",onClick:W,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:q=>q.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:T.label}),s.jsx("div",{className:`mt-1 font-mono text-[11px] ${o.textMuted}`,children:T.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[T.behind>0&&s.jsx("button",{type:"button",onClick:()=>{B()},disabled:!$||j===T.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:j===T.id?"Checking":"Heal"}),s.jsx("button",{type:"button",onClick:W,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(Ge,{label:(S==null?void 0:S.health)??T.health,tone:yw((S==null?void 0:S.health)??T.health)}),T.branch&&s.jsx(Ge,{label:T.branch,tone:"default"}),T.ahead>0&&s.jsx(Ge,{label:`ahead ${T.ahead}`,tone:"warn"}),T.behind>0&&s.jsx(Ge,{label:`behind ${T.behind}`,tone:"warn"}),T.dirtyFiles>0&&s.jsx(Ge,{label:`${T.dirtyFiles} dirty`,tone:"warn"}),(S==null?void 0:S.connection)&&s.jsx(Ge,{label:Mw(S),tone:vw(S.connection)}),A.length>0&&s.jsx(Ge,{label:`${A.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[s.jsx(wt,{label:"Machine",value:T.machineLabel??"not reported"}),s.jsx(wt,{label:"Locality",value:T.locality}),s.jsx(wt,{label:"Machine id",value:T.machineId??(S==null?void 0:S.machineId)??"not reported"}),s.jsx(wt,{label:"Daemon id",value:T.daemonId??(S==null?void 0:S.daemonId)??"not reported"}),s.jsx(wt,{label:"Workspace",value:(S==null?void 0:S.workspace)??T.workspace}),s.jsx(wt,{label:"Branch",value:T.branch??"unknown"}),s.jsx(wt,{label:"HEAD",value:_??(S!=null&&S.gitProbePending?"Pending live git probe":"not reported")}),s.jsx(wt,{label:"Upstream",value:T.upstream??"none"}),s.jsx(wt,{label:"Dirty/ahead/behind",value:`${T.dirtyFiles} dirty · ↑${T.ahead}/↓${T.behind}`}),s.jsx(wt,{label:"Source",value:String(((we=S==null?void 0:S.connection)==null?void 0:we.source)??Tw(T))}),s.jsx(wt,{label:"Transport",value:((Ce=S==null?void 0:S.connection)==null?void 0:Ce.transport)??"unknown"}),s.jsx(wt,{label:"Sessions",value:A.length>0?A.map(q=>q.session.state||q.session.lifecycle||"unknown").join(", "):"none active"})]}),A.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${o.textMuted}`,children:"Active Sessions"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:A.map(q=>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:q.session.sessionId.slice(0,14)}),s.jsx(Ge,{label:q.session.state||q.session.lifecycle||"unknown",tone:Ua(q.session.state||q.session.lifecycle)})]}),s.jsxs("div",{className:`mt-0.5 truncate ${o.textMuted}`,children:[(q.session.workspace||q.workspace).slice(0,32),q.branch?` · ${q.branch}`:""]})]},q.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(wt,{label:"Completed",value:String(g.taskCompleted)}),s.jsx(wt,{label:"Failed",value:s.jsx("span",{className:g.taskFailed>0?o.isDark?"text-rose-300":"text-rose-600":"",children:g.taskFailed})}),s.jsx(wt,{label:"Launched",value:String(g.sessionLaunched)}),s.jsx(wt,{label:"Recent failures",value:s.jsx("span",{className:g.recentFailures>0?o.isDark?"text-amber-300":"text-amber-600":"",children:g.recentFailures})})]})]}),(()=>{var me,le;const q=((me=i.queue)==null?void 0:me.tasks)??((le=i.queue)==null?void 0:le.items)??null;if(!Array.isArray(q)||q.length===0)return null;const ue=q.filter(je=>kw(je)===m).slice(0,3);return ue.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:ue.map(je=>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:je.id.slice(0,12)}),s.jsx(Ge,{label:je.status??"unknown",tone:Ua(je.status)})]}),je.message&&s.jsx("div",{className:`mt-0.5 truncate ${o.textMuted}`,children:je.message.slice(0,48)})]},je.id))})]})})(),T.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:T.snapshotWarnings[0]})]}),((V=T.branchConvergence)==null?void 0:V.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:T.branchConvergence.nextStep})]}),x&&s.jsxs("div",{className:o.isDark?"mt-3 rounded-xl border border-emerald-400/20 bg-emerald-500/10 p-3 text-xs text-emerald-100":"mt-3 rounded-xl border border-emerald-300 bg-emerald-50 p-3 text-xs text-emerald-800",children:[s.jsx("div",{className:"font-medium",children:x.phase==="execute"?"Heal result":"Heal preview"}),s.jsx("div",{className:"mt-1",children:x.code??x.error??"No result code returned."})]})]})})]})})})})}const pn=new Map;function Lw(e,t){return!e||!t?null:`${e}::${t}`}function Pw({activeConv:e,sendDaemonCommand:t,onClose:r}){var N,I;const n=((N=e.coordinator)==null?void 0:N.meshId)??(typeof((I=e.settings)==null?void 0:I.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),a=e.daemonId??null,o=Lw(a,n),i=o?pn.get(o)??null:null,c=nu(),{theme:d}=zs(),m=l.useMemo(()=>Gs(d),[d]),[u,h]=l.useState(i),[f,y]=l.useState(!1),[b,x]=l.useState(null),[k,j]=l.useState((i==null?void 0:i.refreshedAt)??null),p=l.useRef(i!==null);l.useEffect(()=>{p.current=u!==null},[u]),l.useEffect(()=>{const S=o?pn.get(o)??null:null;h(S),j((S==null?void 0:S.refreshedAt)??null),p.current=S!==null,x(null)},[o]);const w=l.useCallback(async(S=!1)=>{if(!a||!n){x("This coordinator does not expose a live mesh id."),h(null);return}if(!S&&o){const T=pn.get(o);if(T){h(T),j(T.refreshedAt||null),p.current=!0,y(!1),x(null);return}}y(!p.current),x(null);try{const T=c!=null&&c.loadMeshStatus?await c.loadMeshStatus(a,n,{refresh:S,retryProfile:S?"settled":"interactive"}):await t(a,"mesh_status",{meshId:n,refresh:S}),P=Hu(T);if(!P){x("mesh_status returned an unexpected payload.");return}o&&pn.set(o,P),h(P),p.current=!0,j(P.refreshedAt||new Date().toISOString())}catch(T){x(T instanceof Error?T.message:"Failed to load live mesh status")}finally{y(!1)}},[o,a,n,c,t]);l.useEffect(()=>{w(!1)},[w]),l.useEffect(()=>{const S=T=>{T.key==="Escape"&&r()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[r]);const C=(u==null?void 0:u.meshName)||n||"Repo Mesh",v=k?new Date(k).toLocaleTimeString():null,g=l.useMemo(()=>f?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[f]);return s.jsx("div",{className:m.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:m.dialogShellClass,onClick:S=>S.stopPropagation(),children:[s.jsxs("div",{className:m.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(Zt,{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:m.dialogTitleClass,children:C}),s.jsx("span",{className:m.dialogKickerClass,children:"Mesh observability"})]}),s.jsxs("p",{className:m.dialogSubtitleClass,children:[nt(e),e.workspaceName?` · ${e.workspaceName}`:"",u!=null&&u.repoIdentity?` · ${u.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[v&&s.jsxs("span",{className:m.dialogRefreshedChipClass,children:["Refreshed ",v]}),s.jsx("button",{type:"button",onClick:()=>{w(!0)},disabled:f,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:f?"Refreshing…":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:m.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:s.jsx(xt,{size:16})})]})]}),b&&s.jsx("div",{className:m.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:b}),s.jsx("div",{className:m.dialogBodyClass,children:u?s.jsx(Vu,{status:u,emptyMessage:g,daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:m.dialogEmptyClass,children:g})})]})})}function Rw(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=Dw(n);return{remoteUrl:n,githubUrl:c,loading:o}}function Dw(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 qu=5e3;function Ew(e){return`git:${e}`}function $w({workspace:e,includeDiffSummary:t=!1,intervalMs:r=qu}){return{type:"subscribe",topic:"workspace.git",key:Ew(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function gi(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function vs(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 Bw(e){const t=gi(e);return(t==null?void 0:t.success)===!1?{status:null,error:vs(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:vs(t,"Git status response did not include status")}}function Ow(e){const t=gi(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:vs(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:vs(t,"Git diff summary response did not include diffSummary")}}function za(e){return e===void 0||typeof e=="boolean"}function Fw(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&za(t.binary)&&za(t.truncated)&&za(t.staged)}function Hw(e){const t=gi(e);return(t==null?void 0:t.success)===!1?{diff:null,error:vs(t,"Git file diff request failed")}:Fw(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:vs(t,"Git file diff response did not include a valid diff object")}}function Ww({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=qu}){const{sendCommand:o,sendData:i}=it(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[m,u]=l.useState(null),[h,f]=l.useState(null),[y,b]=l.useState(!1),[x,k]=l.useState(null),j=l.useCallback(async()=>{if(!(!d||!e||!c)){b(!0),k(null);try{const w=Bw(await o(e,"git_status",{workspace:c}));if(w.error){u(null),f(null),k(w.error);return}if(u(w.status),!n){f(null);return}const C=Ow(await o(e,"git_diff_summary",{workspace:c}));if(C.error){f(null),k(C.error);return}f(C.diffSummary)}catch(w){k(vs(w,"Git status request failed"))}finally{b(!1)}}},[d,e,n,o,c]),p=l.useMemo(()=>c?$w({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return l.useEffect(()=>{if(!d||!e||!c||!p){u(null),f(null),b(!1),k(null);return}const w=i?Gt.subscribe({sendData:i},e,p,C=>{var v,g;C.workspace===c&&(u(C.status),f(C.diffSummary??null),k(((v=C.status)==null?void 0:v.error)||((g=C.diffSummary)==null?void 0:g.error)||null),b(!1))},{retryIntervalMs:1e3}):null;return j(),()=>{w==null||w()}},[d,e,j,p,i,c]),{status:m,diffSummary:h,loading:y,error:x,refresh:j}}const Kw={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},Uw={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 ec(e){return e.split("/").pop()??e}function zw(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function Gw({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=Kw[o.status]??"?",d=Uw[o.status]??"text-zinc-400",m=zw(o.path),u=ec(o.path),h=o.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${i?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(o),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${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:["← ",ec(o.oldPath)]}),h]}),!o.binary&&(o.insertions>0||o.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",o.insertions]}),o.insertions>0&&o.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),o.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",o.deletions]})]}),o.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${o.path}-${o.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function Vw(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 qw({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(`
68
- `);return s.jsxs("div",{ref:i,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((d,m)=>Vw(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 Yw(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(`
69
- `)}function Yu({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=it(),{status:a,diffSummary:o,loading:i,error:c,refresh:d}=Ww({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=l.useState(null),[h,f]=l.useState(null),[y,b]=l.useState(""),[x,k]=l.useState(!1),[j,p]=l.useState(!1),[w,C]=l.useState(null),[v,g]=l.useState(null),{githubUrl:N}=Rw(e,t),I=l.useCallback(async L=>{if(!((m==null?void 0:m.path)===L.path&&!m.loading)){u({path:L.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const O=await n(e,"git_diff_file",{workspace:t,path:L.path,staged:L.staged}),_=Hw(O);if(_.error||!_.diff){u({path:L.path,diff:"",binary:!1,truncated:!1,loading:!1,error:_.error??"Failed to load diff"});return}u({path:L.path,diff:_.diff.diff,binary:_.diff.binary??!1,truncated:_.diff.truncated??!1,loading:!1,error:null})}catch(O){const _=O instanceof Error?O.message:"Failed to load diff";u({path:L.path,diff:"",binary:!1,truncated:!1,loading:!1,error:_})}}},[e,n,m,t]),S=l.useCallback(L=>{b(""),k(!1),C(null),g(null),f(L)},[]),T=l.useCallback(()=>{f(null),C(null),p(!1)},[]),P=l.useCallback(async()=>{var L,O,_;if(h){p(!0),C(null);try{let M;h==="checkpoint"?M=await n(e,"git_checkpoint",{workspace:t,message:y,includeUntracked:x}):h==="stash"?M=await n(e,"git_stash_push",{workspace:t,message:y,includeUntracked:x}):h==="stash_pop"?M=await n(e,"git_stash_pop",{workspace:t}):h==="checkout_files"&&m&&(M=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const $=(M==null?void 0:M.result)??M;if(($==null?void 0:$.success)===!1||$!=null&&$.error){C(($==null?void 0:$.error)??"Action failed"),p(!1);return}h==="checkpoint"?g(`Checkpoint created: ${((O=(L=$==null?void 0:$.checkpoint)==null?void 0:L.commit)==null?void 0:O.slice(0,7))??"done"}`):h==="stash"?g(`Stashed as ${((_=$==null?void 0:$.stash)==null?void 0:_.stashRef)??"stash@{0}"}`):h==="stash_pop"?g("Stash restored"):(g("File reverted"),u(null)),f(null),await d()}catch(M){C(M instanceof Error?M.message:"Action failed")}finally{p(!1)}}},[h,n,e,t,y,x,m,d]),A=!!(a!=null&&a.hasConflicts),D=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:L=>{L.target===L.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}),N&&s.jsx("a",{href:`${N}/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(xt,{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"}),D===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(Gw,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:I}),!i&&!o&&!c&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:m?s.jsx(qw,{diff:m.diff,binary:m.binary,truncated:m.truncated,loading:m.loading,error:m.error,className:"h-full"}):s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),v&&s.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-emerald-500/10 px-4 py-2 text-xs text-emerald-400 flex items-center justify-between",children:[s.jsx("span",{children:v}),s.jsx("button",{onClick:()=>g(null),className:"ml-2 text-emerald-400 hover:text-text-primary",children:"×"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[s.jsx("button",{onClick:()=>S("checkpoint"),disabled:A,title:A?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),s.jsx("button",{onClick:()=>S("stash"),disabled:A,title:A?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),s.jsx("button",{onClick:()=>S("stash_pop"),disabled:A||!(a!=null&&a.stashCount),title:A?"Resolve conflicts before restoring a stash":a!=null&&a.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),s.jsx("button",{onClick:()=>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 L=Yw((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(L),g("Copied to clipboard"),setTimeout(()=>g(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),h&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[h==="checkpoint"&&"Create checkpoint commit",h==="stash"&&"Stash changes",h==="stash_pop"&&"Restore latest stash?",h==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(h==="checkpoint"||h==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:y,onChange:L=>b(L.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:L=>k(L.target.checked)}),"Include untracked files"]})]}),w&&s.jsx("p",{className:"text-xs text-red-400",children:w}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick: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:P,disabled:j||(h==="checkpoint"||h==="stash")&&!y.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:j?"Working…":"Confirm"})]})]})})]})})}function Xw({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),[h,f]=l.useState(!1),[y,b]=l.useState("quickstart"),[x,k]=l.useState("workspace"),j=l.useMemo(()=>!t&&!e,[t,e]),p=l.useCallback(I=>{a(I),I&&i(!1)},[]),w=l.useCallback(I=>{i(I),I&&a(!1)},[]),C=l.useCallback(()=>{b(r===0?"quickstart":"shortcuts"),k("workspace"),d(!0),a(!1),i(!1)},[r]),v=l.useCallback(()=>{d(!1)},[]),g=l.useCallback(()=>{u(!0)},[]),N=l.useCallback(()=>{u(!1)},[]);return l.useEffect(()=>{if(!j){f(!1);return}f(!0);const I=window.setTimeout(()=>{f(!1)},1e4);return()=>window.clearTimeout(I)},[j]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:m,guideNudgeVisible:h,guideTab:y,shortcutSection:x,isDesktopDashboard:j,setGuideTab:b,setShortcutSection:k,handleInboxOpenChange:p,handleHiddenOpenChange:w,handleOpenShortcutHelp:C,closeShortcutHelp:v,openNewSession:g,closeNewSession:N}}function Jw(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 Qw(e){return e instanceof Error?e.message:String(e||"")}function Zw(e){const t=Qw(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function ej({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:i,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:h,ides:f,actionLogs:y,sendDaemonCommand:b,setActionLogs:x,setCliViewModeOverrides:k,isStandalone:j,initialDataLoaded:p,userName:w,requestedMobileTabKey:C,onRequestedMobileTabConsumed:v,requestedMachineId:g,onRequestedMachineConsumed:N,requestedMobileSection:I,onRequestedMobileSectionConsumed:S,containerRef:T,isSplitMode:P,numGroups:A,groupSizes:D,groupedConvs:L,clearedTabs:O,focusedGroup:_,focusGroup:M,moveTabToGroup:$,splitTabRelative:W,closeGroup:B,handleResizeStart:F,groupActiveTabIds:K,setGroupActiveTab:Y,groupTabOrders:re,setGroupTabOrder:ae,toggleHiddenTab:he,visibleConversations:we,requestedDesktopTabKey:Ce,onRequestedDesktopTabConsumed:V,onDesktopActiveTabChange:q,onRequestScrollToBottom:ue,onHideConversation:me,onShowHiddenConversation:le,onShowAllHiddenConversations:je,scrollToBottomRequest:X,machineEntries:ye,layoutProfile:de,onBrowseMachineDirectory:ve,onSaveMachineWorkspace:fe,onLaunchMachineIde:ge,onLaunchMachineProvider:ce,onListMachineMeshes:be,onLaunchMeshCoordinator:oe,onListMachineSavedSessions:R,notifications:pe,notificationUnreadCount:Se,liveSessionInboxState:Me,onMarkNotificationRead:ee,onMarkNotificationUnread:Ne,onDeleteNotification:De}){const Ee=ft.useRef(null),{inboxOpen:ze,hiddenOpen:Qe,shortcutHelpOpen:Ze,newSessionOpen:rt,guideNudgeVisible:et,guideTab:ct,shortcutSection:Xe,isDesktopDashboard:pt,setGuideTab:Ae,setShortcutSection:Fe,handleInboxOpenChange:st,handleHiddenOpenChange:qe,handleOpenShortcutHelp:Ke,closeShortcutHelp:U,openNewSession:z,closeNewSession:J}=Xw({isMobile:t,showMobileChatMode:e,visibleConversationCount:we.length}),[te,H]=ft.useState(null),[G,Z]=ft.useState(null),ne=ft.useCallback((se,Re)=>{H({daemonId:se,workspace:Re})},[]),E=ft.useCallback(se=>{Z(se)},[]),ie=ft.useCallback(se=>{var Re;jr.flushSync(()=>{le(se)}),(Re=Ee.current)==null||Re.restoreHiddenTabToSavedLocation(se.tabKey)},[le]),xe=ft.useCallback(se=>{var kt;const Re=u.find(St=>fo(St,se))||h.find(St=>fo(St,se));Re&&(h.some(St=>St.tabKey===Re.tabKey)&&ie(Re),q(Re.tabKey),(kt=Ee.current)==null||kt.activateConversationTab(Re.tabKey),ue(Re.tabKey,"notification-open")),ee(se.id),st(!1)},[ie,h,u,q,ee,ue]),ke=ft.useCallback(()=>{var Re;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Re=Ee.current)==null||Re.resetAllPanelsToMain(),qe(!1))},[qe]),Ie=ft.useCallback(async se=>{var rs;if(!r)return;const Re=(rs=r.modalButtons)==null?void 0:rs[se];if(!Re)return;const kt=us(r);if(!kt)return;const St=Re.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),ks=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(St);try{await b(kt,"resolve_action",{button:Re,action:ks?"approve":"reject",buttonIndex:se,...ds(r)})}catch(ns){Zw(ns)||console.error("[Shortcut approval] Failed:",ns)}},[r,b]),{isMac:$e,actionDefinitions:Te,actionShortcuts:Le,shortcutListening:Ue,shortcutListeningDraft:dt,setShortcutListening:yt,setShortcutListeningDraft:ut,saveShortcuts:mt}=S0({enabled:pt&&!Ze,onTrigger:se=>{var Re,kt,St,ks,rs,ns,$r,Br,Or,Fr,Hr,Wr,Kr,Ur,zr,Gr;if(se==="openShortcutHelp"){Ke();return}if(se==="openNewSession"){z();return}if(se==="hideCurrentTab"){r&&me(r);return}if(se==="toggleHiddenTabs"){qe(!Qe);return}if(se==="openHistoryForActiveTab"){r&&!Ve(r)&&o(r);return}if(se==="openRemoteForActiveTab"){r&&!Ye(r)&&!Ve(r)&&i(r);return}if(se==="splitActiveTabRight"){(Re=Ee.current)==null||Re.splitActiveTabRight();return}if(se==="splitActiveTabDown"){(kt=Ee.current)==null||kt.splitActiveTabDown();return}if(se==="floatActiveTab"){(St=Ee.current)==null||St.floatActiveTab();return}if(se==="popoutActiveTab"){(ks=Ee.current)==null||ks.popoutActiveTab();return}if(se==="dockActiveTab"){(rs=Ee.current)==null||rs.dockActiveTab();return}if(se==="focusLeftPane"){(ns=Ee.current)==null||ns.focusLeftPane();return}if(se==="focusRightPane"){($r=Ee.current)==null||$r.focusRightPane();return}if(se==="focusUpPane"){(Br=Ee.current)==null||Br.focusUpPane();return}if(se==="focusDownPane"){(Or=Ee.current)==null||Or.focusDownPane();return}if(se==="moveActiveTabToLeftPane"){(Fr=Ee.current)==null||Fr.moveActiveTabToLeftPane();return}if(se==="moveActiveTabToRightPane"){(Hr=Ee.current)==null||Hr.moveActiveTabToRightPane();return}if(se==="moveActiveTabToUpPane"){(Wr=Ee.current)==null||Wr.moveActiveTabToUpPane();return}if(se==="moveActiveTabToDownPane"){(Kr=Ee.current)==null||Kr.moveActiveTabToDownPane();return}if(se==="triggerPrimaryApprovalAction"){Ie(0);return}if(se==="triggerSecondaryApprovalAction"){Ie(1);return}if(se==="triggerTertiaryApprovalAction"){Ie(2);return}if(se==="setActiveTabShortcut"){(Ur=Ee.current)==null||Ur.setShortcutForActiveTab();return}if(se==="selectPreviousGroupTab"){(zr=Ee.current)==null||zr.activatePreviousTabInGroup();return}if(se==="selectNextGroupTab"){(Gr=Ee.current)==null||Gr.activateNextTabInGroup();return}!r||!Ye(r)||Ve(r)||se==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),Oe=ft.useCallback(()=>{U(),yt(null),ut([])},[U,yt,ut]),Xt=ft.useMemo(()=>Xe==="all"?Te:Te.filter(se=>Jw(se)===Xe),[Te,Xe]),Q=ft.useCallback(()=>{const se=Object.fromEntries(Te.map(Re=>[Re.id,""]));mt(se)},[Te,mt]),Pe=ft.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const se=Object.fromEntries(Te.map(Re=>[Re.id,Re.defaultShortcut]));mt(se)},[Te,mt]);return ft.useEffect(()=>{const se=Re=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Re.metaKey&&Re.key.toLowerCase()==="w":Re.ctrlKey&&Re.key.toLowerCase()==="w")&&(Re.preventDefault(),r&&me&&me(r))};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[r,me]),ft.useEffect(()=>{if(!Ze||Ue)return;const se=Re=>{Re.key==="Escape"&&(Re.preventDefault(),Oe())};return window.addEventListener("keydown",se,!0),()=>window.removeEventListener("keydown",se,!0)},[Oe,Ze,Ue]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(db,{activeConv:r,wsStatus:n,isConnected:a,conversations:we,hiddenConversations:h,onOpenHistory:o,onHideConversation:me,onShowConversation:ie,onShowAllHidden:je,onResetPanelsToMain:ke,notifications:pe,notificationUnreadCount:Se,onOpenNotification:xe,onMarkNotificationRead:ee,onMarkNotificationUnread:Ne,onDeleteNotification:De,inboxOpen:ze,onInboxOpenChange:st,hiddenOpen:Qe,onHiddenOpenChange:qe,onOpenNewSession:t?void 0:z,onOpenDashboardGuide:Ke,guideNudgeVisible:et,actionShortcuts:Le,onOpenRemote:()=>{!r||Ye(r)||Ve(r)||i(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:ne,onOpenMeshGraph:E}),e?s.jsx(m0,{conversations:u,hiddenConversations:h,ides:f,actionLogs:y,sendDaemonCommand:b,setActionLogs:x,setCliViewModeOverrides:k,isStandalone:j,userName:w,requestedActiveTabKey:C,onRequestedActiveTabConsumed:v,requestedMachineId:g,onRequestedMachineConsumed:N,requestedMobileSection:I,onRequestedMobileSectionConsumed:S,onOpenHistory:o,onOpenRemote:i,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:je,onHideConversation:me,onOpenMeshGraph:E,onOpenNewSession:z,liveSessionInboxState:Me}):t?s.jsx(v0,{containerRef:T,isSplitMode:P,numGroups:A,groupSizes:D,groupedConvs:L,clearedTabs:O,ides:f,actionLogs:y,sendDaemonCommand:b,setActionLogs:x,isStandalone:j,hasRegisteredMachines:ye.length>0,userName:w,focusedGroup:_,focusGroup:M,moveTabToGroup:$,splitTabRelative:W,closeGroup:B,handleResizeStart:F,groupActiveTabIds:K,setGroupActiveTab:Y,groupTabOrders:re,setGroupTabOrder:ae,toggleHiddenTab:he,onOpenNewSession:z,allowTabShortcuts:!1,liveSessionInboxState:Me}):s.jsx(B0,{visibleConversations:we,clearedTabs:O,ides:f,actionLogs:y,sendDaemonCommand:b,setActionLogs:x,isStandalone:j,hasRegisteredMachines:ye.length>0,initialDataLoaded:p,userName:w,toggleHiddenTab:he,actionShortcuts:Le,registerActionHandlers:se=>{Ee.current=se},onActiveTabChange:q,requestedActiveTabKey:Ce,onRequestedActiveTabConsumed:V,onRequestScrollToBottom:ue,scrollToBottomRequest:X,onOpenNewSession:z,liveSessionInboxState:Me,layoutProfile:de}),rt&&s.jsx(q0,{machines:ye,ides:f,onClose:J,onBrowseDirectory:ve,onSaveWorkspace:fe,onLaunchIde:ge,onLaunchProvider:ce,onListMeshes:be,onLaunchMeshCoordinator:oe,onListSavedSessions:R}),G&&s.jsx(Pw,{activeConv:G,sendDaemonCommand:b,onClose:()=>Z(null)}),te&&s.jsx(Yu,{daemonId:te.daemonId,workspace:te.workspace,onClose:()=>H(null)}),Ze&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:Oe,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",onClick:se=>se.stopPropagation(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:Oe,"aria-label":"Close dashboard guide",children:s.jsx(xt,{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(se=>s.jsx("button",{type:"button",className:`btn btn-sm ${ct===se.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ae(se.id),children:se.label},se.id))}),ct==="overview"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",$e?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),ct==="quickstart"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),ct==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(se=>s.jsx("button",{type:"button",className:`btn btn-sm ${Xe===se.id?"btn-primary":"btn-secondary"}`,onClick:()=>Fe(se.id),children:se.label},se.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Q,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:Pe,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Xt.map(se=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Ue===se.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:se.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:se.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:se.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:Ue===se.id?dt.length>0?`${dt.join(" ")} ...`:"Listening...":Le[se.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{yt(se.id),ut([])},children:Ue===se.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Re={...Le};Re[se.id]="",mt(Re)},children:"Disable"})]})]})},se.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",$e?"⌘⇧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 Ga=[{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 tj({onClose:e}){const[t,r]=l.useState(0),n=Ga[t],a=t===Ga.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(xt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Ga.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:`
70
- @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
71
- @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
72
- `})]})}function sj({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 rj({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,i]=l.useState(()=>a||"native"),c=l.useMemo(()=>Ad(t),[t]),d=l.useMemo(()=>e?Qo(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]),h=l.useMemo(()=>e?$t(d,e.id):null,[d,e]);l.useEffect(()=>{a&&i(a)},[a]),l.useEffect(()=>{if(a||!h)return;const x=h.streamSource==="native"?"native":h.tabKey;!x||o===x||o==="native"&&i(x)},[o,h,a]),l.useEffect(()=>{var x;o!=="native"&&(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)||h||m||u[0],[o,m,h,u]),y=l.useMemo(()=>u.map(x=>({tabKey:x.tabKey,title:wd(x)||n,status:x.status})),[u,n]),b=l.useCallback(x=>{if(x)return d.find(k=>fo(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:b}}function nj({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:i,isStandalone:c,userName:d,onOpenHistory:m,onConversationChange:u,onClose:h}){const[f,y]=l.useState("split"),[b,x]=l.useState(()=>ss(e)?"native":e.tabKey),k=l.useRef(null),j=l.useMemo(()=>t||r.find(M=>M.id===e.routeId),[e.routeId,t,r]),p=l.useMemo(()=>bt((j==null?void 0:j.type)||""),[j==null?void 0:j.type]),{conversations:w,extensionTabs:C,hasExtensions:v}=rj({ideData:j,allIdes:r,connectionStates:n,ideName:p||"IDE",preferredTabKey:ss(e)?void 0:e.tabKey}),g=l.useMemo(()=>j?$t(w,j.id):null,[j,w]);l.useEffect(()=>{const M=k.current,$={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(k.current=$,!(M&&M.routeId===$.routeId&&M.tabKey===$.tabKey&&M.streamSource===$.streamSource)){if(ss(e)){x("native");return}x(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),l.useEffect(()=>{if(b==="native"){if(w.some(M=>M.streamSource==="native"))return;(g==null?void 0:g.streamSource)==="agent-stream"&&x(g.tabKey);return}if(!w.some(M=>M.tabKey===b)){if((g==null?void 0:g.streamSource)==="agent-stream"){x(g.tabKey);return}x("native")}},[w,b,g]);const N=l.useMemo(()=>b==="native"?w.find(M=>M.streamSource==="native")||e:w.find(M=>M.tabKey===b)||e,[e,w,b]),I=Wd(N),S=l.useMemo(()=>I.status||I.modalMessage||I.modalButtons?{...N,...I.status?{status:I.status}:{},...I.modalMessage!==void 0?{modalMessage:I.modalMessage}:{},...I.modalButtons!==void 0?{modalButtons:I.modalButtons}:{}}:N,[N,I]),T=Lr(S),P=aa({sendDaemonCommand:o,activeConv:S,setActionLogs:i,isStandalone:c}),{connScreenshot:A,screenshotUsage:D,handleRemoteAction:L}=yu({doId:T,targetSessionId:ad(S),connState:S.connectionState||"new",viewMode:f}),O=l.useMemo(()=>a.filter(M=>M.routeId===S.tabKey),[a,S.tabKey]);l.useEffect(()=>{u==null||u(S)},[S,u]),l.useEffect(()=>{const M=$=>{$.key==="Escape"&&h()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[h]);const _=l.useCallback(M=>{M.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:h,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:_,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(Bt,{size:16})}),s.jsx("span",{className:"truncate",children:zo(N)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(M=>{const $=f===M;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${$?"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(M),title:M==="split"?"Split view":"Remote only",children:M==="split"?s.jsx(Mh,{size:15}):s.jsx(Bt,{size:15})},M)})}),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(N),title:"Chat History",children:[s.jsx(Do,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:h,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${f==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[f!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(sj,{hasExtensions:v,ideName:p||"IDE",activeChatTab:b,extensionTabs:C,onSelectTab:x}),s.jsx(Uc,{activeConv:S,onModalButton:P.handleModalButton}),s.jsx(yo,{activeConv:S,ideEntry:j,showMetaChips:!1,handleSendChat:P.handleSendChat,handleForceSendChat:P.handleForceSendChat,isSendingChat:P.isSendingChat,sendFeedbackMessage:P.sendFeedbackMessage,handleFocusAgent:P.handleFocusAgent,isFocusingAgent:P.isFocusingAgent,actionLogs:O,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(Hc,{addLog:()=>{},connState:S.connectionState||"new",connScreenshot:A,screenshotUsage:D,transportType:S.transport,onAction:L})})]})]})})}function aj({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=Zx(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 oj({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o,interactivePrompt:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(nb,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(Md,{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(nj,{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&&(Ye(r.targetConv)||Ve(r.targetConv))&&s.jsx(aj,{activeConv:r.targetConv,canSaveAndStop:Ye(r.targetConv)&&!Ve(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(Td,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),s.jsx(Cp,{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(tj,{onClose:o.onClose})]})}function ij({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(ta,{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=Ct(i,{fallbackId:i.id}),d=n[i.id],m=i.version||i.daemonVersion||"unknown",u=i.versionUpdateRequired===!0,f=tu(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(xt,{size:16})})]})}function lj(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function cj(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 dj(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>cj(t)).map(t=>t.id)}}function uj(){var Ni,Ci,Ii,Mi;const{sendCommand:e}=it(),t=Pr(),r=Hd(),n=Lo(),a=Tr(),[o,i]=zm(),c=o.get("activeTab"),d=((Ni=n.state)==null?void 0:Ni.openRemoteForTabKey)||null,m=((Ci=n.state)==null?void 0:Ci.openMachineId)||null,u=((Ii=n.state)==null?void 0:Ii.mobileSection)||null,h=bd(),f=h.ides||[],y=h.initialLoaded??!0,{updateRouteChats:b,setToasts:x}=h,[k,j]=l.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),p=h.toasts||[],w=h.wsStatus||"connected",C=h.isConnected??!0,v=h.connectionStates||{},g=h.showReconnected||!1,{layoutProfile:N,groupAssignments:I,updateGroupAssignments:S,focusedGroup:T,updateFocusedGroup:P,focusGroup:A,groupActiveTabIds:D,updateGroupActiveTabIds:L,setGroupActiveTab:O,groupTabOrders:_,updateGroupTabOrders:M,setGroupTabOrder:$,groupSizes:W,updateGroupSizes:B,isMobile:F,hasHydratedStoredLayout:K,hydrateStoredLayout:Y,focusConversationTab:re}=iy(),[ae,he]=l.useState(()=>si());l.useEffect(()=>ug(he),[]);const we=l.useMemo(()=>lj({isMobile:F,mobileViewMode:ae}),[F,ae]),[Ce,V]=l.useState([]),[q,ue]=l.useState({}),[me,le]=l.useState({});_r("Dashboard",{ideCount:f.length,toastCount:p.length,focusedGroup:T,groupCount:Object.keys(I).length,actionLogCount:Ce.length});const je=l.useMemo(()=>f.filter(He=>He.type==="adhdev-daemon").sort(Wo),[f]),X=je[0],ye=!!X;l.useEffect(()=>{const{metadataDaemonIds:He,runtimeDaemonIds:_t}=dj(je);for(const Vs of He)t(Vs,{minFreshMs:3e4}).catch(()=>{});for(const Vs of _t)r(Vs,{minFreshMs:3e4}).catch(()=>{})},[t,r,je]);const de=(X==null?void 0:X.terminalBackend)||null,ve=X?Ct(X,{fallbackId:X.id}):null,fe=(X==null?void 0:X.id)||null,ge=l.useMemo(()=>Pg(f,q),[f,q]),{hiddenTabs:ce,autoHiddenTabs:be,autoHideTarget:oe,hideTarget:R,toggleTarget:pe,showTarget:Se,showAllTabs:Me}=kg(),{conversations:ee,visibleConversations:Ne,visibleTabKeys:De,resolveConversationBySessionId:Ee,resolveConversationByTarget:ze}=Gg({ides:ge,connectionStates:v,clearedTabs:me,hiddenTabs:ce}),Qe=l.useMemo(()=>new Map(ee.map(He=>[He.tabKey,He])),[ee]),Ze=l.useMemo(()=>jg(ee,ce,be),[ee,ce,be]);l.useEffect(()=>{for(const He of Ze)oe(He)},[Ze,oe]),Ix(Ne,we),l.useEffect(()=>{Object.keys(q).length!==0&&ue(He=>Rg(He,f))},[f,q]);const rt=l.useMemo(()=>Mp(f),[f]),{notifications:et,unreadCount:ct}=ky({conversations:ee,liveSessionInboxState:rt}),{handleMarkDashboardNotificationRead:Xe,handleMarkDashboardNotificationUnread:pt,handleDeleteDashboardNotification:Ae}=Sy({notifications:et,sendDaemonCommand:e}),{containerRef:Fe,normalizedGroupAssignments:st,numGroups:qe,isSplitMode:Ke,groupedConvs:U,moveTabToGroup:z,closeGroup:J,handleResizeStart:te,splitTabRelative:H}=py({groupAssignments:I,updateGroupAssignments:S,updateFocusedGroup:P,updateGroupActiveTabIds:L,updateGroupTabOrders:M,groupSizes:W,updateGroupSizes:B,isMobile:F,visibleConversations:Ne,visibleTabKeys:De}),{activeConv:G,openDesktopConversation:Z,requestScrollToBottom:ne,scrollToBottomRequest:E,setDesktopActiveTab:ie}=By({isMobile:F,conversations:ee,visibleConversations:Ne,groupActiveTabIds:D,focusedGroup:T,groupedConvs:U,setSearchParams:i});Hy({activeConv:G,isMobile:F,liveSessionInboxState:rt,sendDaemonCommand:e});const{requestedDesktopTabKey:xe,requestedMobileTabKey:ke,consumeRequestedActiveTab:Ie}=Vg({isMobile:F,urlActiveTab:c,resolveConversationBySessionId:Ee,setSearchParams:i}),{remoteDialogConv:$e,remoteDialogIdeEntry:Te,remoteDialogActiveConv:Le,setRemoteDialogActiveConv:Ue,openRemoteDialog:dt,closeRemoteDialog:yt,cliStopDialogOpen:ut,cliStopTargetConv:mt,requestCliStop:Oe,cancelCliStop:Xt,confirmCliStop:Q}=Uy({isMobile:F,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:xe,conversations:ee,ides:f,resolveConversationByTarget:ze,activeConv:G,sendDaemonCommand:e}),{historyModalOpen:Pe,openHistoryModal:se,closeHistoryModal:Re,historyTargetConv:kt,isSavedSessionHistoryTarget:St,isHistoryCreatingChat:ks,isHistoryRefreshingHistory:rs,handleHistorySwitchSession:ns,handleHistoryNewChat:$r,handleHistoryRefresh:Br,savedHistorySessions:Or,savedHistoryFilters:Fr,setSavedHistoryFilters:Hr,missingWorkspaceResumePath:Wr,isSavedHistoryLoading:Kr,resumingSavedHistorySessionId:Ur,handleRefreshSavedHistory:zr,handleResumeSavedHistorySession:Gr}=Wy({activeConv:G,remoteDialogConv:$e,remoteDialogActiveConv:Le,ides:f,sendDaemonCommand:e,updateRouteChats:b,setToasts:x,setClearedTabs:le,setSearchParams:i}),tm=l.useMemo(()=>Ne,[Ne]),Vr=F&&ae==="chat",sm=l.useMemo(()=>ee.filter(He=>ia(ce,He)),[ee,ce]),ji=l.useCallback(He=>{const _t=new URLSearchParams(o);_t.set("activeTab",He),i(_t,{replace:!0})},[o,i]),{trackPendingLaunch:rm}=Ry({ides:f,conversations:ee,onOpenSession:ji}),{handleBrowseMachineDirectory:nm,handleSaveMachineWorkspace:am,handleLaunchMachineIde:om,handleLaunchMachineProvider:im,handleListMachineMeshes:lm,handleLaunchMeshCoordinator:cm,handleListMachineSavedSessions:dm,setActiveCliViewMode:um}=Dy({sendDaemonCommand:e,trackPendingLaunch:rm,onOpenSession:ji,activeConv:G,ides:f,setCliViewModeOverrides:ue});Dg({visibleConversations:Ne,clearedTabs:me,setClearedTabs:le,setActionLogs:V}),qg({ides:f,sendDaemonCommand:e,setToasts:x,resolveConversationByTarget:ze});const mm=Ag(),{isRefreshingHistory:hm,handleRefreshHistory:pm}=eu({sendDaemonCommand:e,activeConv:G,chats:(Mi=f.find(He=>He.id===(G==null?void 0:G.routeId)))==null?void 0:Mi.chats,updateRouteChats:b,setToasts:x,setClearedTabs:le});cy({urlActiveTab:F&&!Vr?c:null,conversations:ee,resolveConversationBySessionId:Ee,normalizedGroupAssignments:st,hasHydratedStoredLayout:F&&!Vr?K:!0,hydrateStoredLayout:F&&!Vr?Y:()=>{},focusConversationTab:re,setSearchParams:i,historyModalOpen:Pe,activeConv:G,isRefreshingHistory:hm,ides:f,handleRefreshHistory:pm});const fm=l.useMemo(()=>!G||!Ye(G)||Ve(G)?null:Us(G),[G]),{versionMismatchDaemons:xm,hasRequiredVersionDaemons:ki,targetVersion:bm,versionBannerDismissed:gm,setVersionBannerDismissed:ym,upgradingDaemons:vm,handleBannerUpgrade:wm}=xy({ides:f,sendDaemonCommand:e}),Si=l.useCallback(He=>{Se(He),Z(He)},[Z,Se]),jm=l.useCallback(He=>{R(He)},[R]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[s.jsx(ab,{terminalBackend:de,isStandalone:ye,machineLabel:ve,machineKey:fe}),(!gm||ki)&&s.jsx(ij,{daemons:xm,targetVersion:bm,required:ki,upgradingDaemons:vm,onUpgrade:wm,onDismiss:()=>ym(!0)}),s.jsx(ej,{showMobileChatMode:Vr,isMobile:F,activeConv:G,wsStatus:w,isConnected:C,onOpenHistory:He=>{He&&Ue(He),se()},onOpenRemote:dt,onStopCli:Oe,activeCliViewMode:fm,onSetActiveCliViewMode:um,mobileChatConversations:tm,ides:f,actionLogs:Ce,sendDaemonCommand:e,setActionLogs:V,setCliViewModeOverrides:ue,isStandalone:ye,initialDataLoaded:y,userName:h.userName,requestedMobileTabKey:ke,onRequestedMobileTabConsumed:Ie,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:Fe,isSplitMode:Ke,numGroups:qe,groupSizes:W,groupedConvs:U,clearedTabs:me,focusedGroup:T,focusGroup:A,moveTabToGroup:z,splitTabRelative:H,closeGroup:J,handleResizeStart:te,groupActiveTabIds:D,setGroupActiveTab:O,groupTabOrders:_,setGroupTabOrder:$,toggleHiddenTab:He=>pe(Qe.get(He)||{tabKey:He}),visibleConversations:Ne,hiddenConversations:sm,requestedDesktopTabKey:xe,onRequestedDesktopTabConsumed:Ie,onDesktopActiveTabChange:ie,onRequestScrollToBottom:ne,onHideConversation:jm,onShowHiddenConversation:Si,onShowAllHiddenConversations:Me,scrollToBottomRequest:E,machineEntries:je,layoutProfile:N,onBrowseMachineDirectory:nm,onSaveMachineWorkspace:am,onLaunchMachineIde:om,onLaunchMachineProvider:im,onListMachineMeshes:lm,onLaunchMeshCoordinator:cm,onListMachineSavedSessions:dm,notifications:et,notificationUnreadCount:ct,liveSessionInboxState:rt,onMarkNotificationRead:Xe,onMarkNotificationUnread:pt,onDeleteNotification:Ae}),s.jsx("style",{children:`
73
- body { overflow: hidden; overscroll-behavior: none; }
74
- `}),s.jsx(oj,{historyModal:{open:Pe,targetConv:kt,ides:f,isCreatingChat:ks,isRefreshingHistory:St?!1:rs,savedSessions:Or,savedHistoryFilters:Fr,missingWorkspaceResumePath:Wr||null,onSavedHistoryFiltersChange:Hr,isSavedSessionsLoading:Kr,isResumingSavedSessionId:Ur,onClose:Re,onNewChat:$r,onSwitchSession:ns,onRefreshHistory:St?zr:Br,onResumeSavedSession:Gr},remoteDialog:{conversation:$e,ideEntry:Te,ides:f,connectionStates:v,actionLogs:Ce,sendDaemonCommand:e,setActionLogs:V,isStandalone:ye,userName:h.userName,onOpenHistory:He=>{He&&Ue(He),se()},onConversationChange:Ue,onClose:yt},cliStopDialog:{open:ut,targetConv:mt,onCancel:Xt,onStopNow:async()=>{await Q("hard")},onSaveAndStop:async()=>{await Q("save")}},connectionBanner:{wsStatus:w,showReconnected:g,loginUrl:h.connectionLoginUrl,onReconnect:h.retryServerConnection},toastOverlay:{toasts:p,onDismiss:He=>x(_t=>_t.filter(Vs=>Vs.id!==He)),onClick:He=>{if(He.targetKey){const _t=ze(He.targetKey);_t&&(re(_t.tabKey,st),Si(_t),ne(_t.tabKey,"toast-open"))}}},onboarding:{open:k,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}j(!1)}},interactivePrompt:mm})]})}function mj({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const{launchCli:o}=Zn(),[i,c]=l.useState([]),[d,m]=l.useState(null),[u,h]=l.useState(null),[f,y]=l.useState(!1),[b,x]=l.useState(null),[k,j]=l.useState(!1),[p,w]=l.useState(""),C=l.useRef(null),v=l.useCallback(B=>{C.current=B},[]),g=l.useCallback((B,F,K=!1)=>{c(Y=>[...Y.slice(-100),{timestamp:Date.now(),level:B,message:F}]),setTimeout(()=>{var Y;return(Y=a.current)==null?void 0:Y.scrollIntoView({behavior:"smooth"})},100),K&&Je.showToast(F,B==="error"||B==="warn"?"warning":"success")},[a]),N=l.useCallback(B=>{const F=B instanceof Error?B.message:String(B||"");return F.includes("P2P command timeout")||F.includes("P2P not connected")||F.includes("P2P not available")},[]),I=l.useCallback(async(B,F)=>{var K;if(!e||d)return!1;m(B),g("info",`Launching ${bt(B)}${F!=null&&F.workspace?` in ${F.workspace}`:""}...`);try{const Y={ideType:B,enableCdp:!0};(K=F==null?void 0:F.workspace)!=null&&K.trim()?Y.workspace=F.workspace.trim():F!=null&&F.useDefaultWorkspace&&(Y.useDefaultWorkspace=!0);const re=await r(e,"launch_ide",Y);return g(re!=null&&re.success?"info":"error",re!=null&&re.success?`${bt(B)} launched`:`Failed: ${re==null?void 0:re.error}`,!0),!!(re!=null&&re.success)}catch(Y){return g("error",`Launch error: ${Y.message}`,!0),!1}finally{m(null)}},[e,d,g,r]),S=l.useCallback(async B=>{if(!e)return{success:!1};const{cliType:F,dir:K,workspaceId:Y,useDefaultWorkspace:re,useHome:ae,argsStr:he,model:we,resumeSessionId:Ce}=B;if(!F)return g("warn","Select a CLI or ACP provider first",!0),{success:!1};const V=he?he.split(/\s+/).filter(Boolean):void 0,q=(K==null?void 0:K.trim())||(Y?"(saved id)":re?"(default workspace)":ae?"(home)":"");g("info",`Launching ${F}${q?` in ${q}`:""}${we?` (model: ${we})`:""}...`),h(F);try{const ue={cliType:F,cliArgs:V,initialModel:we||void 0};K!=null&&K.trim()?ue.dir=K.trim():Y?ue.workspaceId=Y:re?ue.useDefaultWorkspace=!0:ae&&(ue.useHome=!0),Ce&&(ue.resumeSessionId=Ce);const me=await o(e,ue),le=(me==null?void 0:me.result)||me;return me!=null&&me.success?(g("info",`${F} launched`,!0),(le==null?void 0:le.launchSource)==="home"?g("info","📂 Running in home directory (explicit choice)"):(le==null?void 0:le.launchSource)==="defaultWorkspace"&&g("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:le==null?void 0:le.sessionId}):(g("error",`Failed: ${(me==null?void 0:me.error)||(le==null?void 0:le.error)}`,!0),(me==null?void 0:me.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&x({cliType:F,argsStr:he,model:we}),{success:!1,sessionId:le==null?void 0:le.sessionId})}catch(ue){return N(ue)?(g("warn",`${F} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(g("error",`Launch error: ${ue.message}`,!0),{success:!1})}finally{h(null)}},[e,g,N,r]),T=l.useCallback(async(B,F,K,Y)=>e?B?F.trim()?S({cliType:B,dir:F,argsStr:K,model:Y}):(x({cliType:B,argsStr:K,model:Y}),{success:!1}):(g("warn","Select a provider",!0),{success:!1}):{success:!1},[e,g,S]),P=l.useCallback(async(B,F,K)=>{if(e&&window.confirm(`Stop ${B}?
75
- This will terminate the process.`))try{const Y=await r(e,"stop_cli",{cliType:B,dir:F,targetSessionId:K});Y!=null&&Y.success?g("info",`${B} stopped`,!0):g("error",`Stop failed: ${(Y==null?void 0:Y.error)||"Unknown error"}`,!0)}catch(Y){g("error",`Stop failed: ${Y.message}`,!0)}},[e,g,r]),A=l.useCallback(async B=>{try{await r(B.daemonId,"restart_ide",{ideType:B.type}),g("info",`${bt(B.type)} restart initiated`,!0)}catch(F){g("error",`Restart failed: ${F.message}`,!0)}},[g,r]),D=l.useCallback(async B=>{if(window.confirm(`Stop ${bt(B.type)}?
76
- This will disconnect CDP and optionally kill the process.`))try{const F=await r(B.daemonId,"stop_ide",{ideType:B.type,killProcess:!0});F!=null&&F.success?g("info",`${bt(B.type)} stopped`,!0):g("error",`Stop failed: ${(F==null?void 0:F.error)||"Unknown error"}`,!0)}catch(F){g("error",`Stop failed: ${F.message}`,!0)}},[g,r]),L=l.useCallback(async()=>{if(e)try{const B=await r(e,"detect_ides",{});g("info",`Found ${((B==null?void 0:B.result)||[]).length} IDE(s)`,!0)}catch(B){g("error",`Detection failed: ${B.message}`,!0)}},[e,g,r]),O=l.useCallback(async B=>{if(!e||!B.trim())return!1;y(!0);try{const F=await r(e,"workspace_add",{path:B.trim()});return F!=null&&F.success?(g("info",`Workspace added: ${B.trim()}`),!0):(g("error",(F==null?void 0:F.error)||"workspace_add failed"),!1)}catch(F){return g("error",F.message),!1}finally{y(!1)}},[e,g,r]),_=l.useCallback(async B=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){y(!0);try{const F=await r(e,"workspace_remove",{id:B});F!=null&&F.success?g("info","Workspace removed",!0):g("error",(F==null?void 0:F.error)||"workspace_remove failed",!0)}catch(F){g("error",F.message,!0)}finally{y(!1)}}},[e,g,r]),M=l.useCallback(async B=>{var F;if(e){y(!0);try{const K=await r(e,"workspace_set_default",B===null?{clear:!0}:{id:B});if(K!=null&&K.success){g("info",B?"Default workspace updated":"Default workspace cleared",!0);const Y=typeof K.defaultWorkspacePath=="string"?K.defaultWorkspacePath:"";Y&&((F=C.current)==null||F.call(C,Y))}else g("error",(K==null?void 0:K.error)||"workspace_set_default failed",!0)}catch(K){g("error",K.message,!0)}finally{y(!1)}}},[e,g,r]),$=l.useCallback(async B=>{var K;if(!e||!B.trim())return;const F=B.trim();y(!0);try{const Y=await r(e,"workspace_set_default",{path:F});Y!=null&&Y.success?(g("info","Default workspace set from history"),(K=C.current)==null||K.call(C,F)):g("error",(Y==null?void 0:Y.error)||"Could not set default (path missing on disk?)")}catch(Y){g("error",Y.message)}finally{y(!1)}},[e,g,r]),W=l.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:p}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:p})}catch(B){g("warn",`Live nickname updated, but account sync failed: ${B.message}`)}g("info",`Nickname set to "${p||"(cleared)"}"`),j(!1)}catch(B){g("error",`Failed: ${B.message}`)}},[e,p,t,g,n,r]);return{logs:i,launchingIde:d,launchingAgentType:u,workspaceBusy:f,launchPick:b,setLaunchPick:x,editingNickname:k,setEditingNickname:j,nicknameInput:p,setNicknameInput:w,addLog:g,handleLaunchIde:I,runLaunchCliCore:S,handleLaunchCli:T,handleStopCli:P,handleRestartIde:A,handleStopIde:D,handleDetectIdes:L,handleWorkspaceAdd:O,handleWorkspaceRemove:_,handleWorkspaceSetDefault:M,handleWorkspaceResumePath:$,handleSaveNickname:W,setOnDefaultWorkspaceChanged:v}}function hj({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(Jr,{icon:s.jsx(Tc,{size:16}),label:"Uptime",value:typeof e.uptime=="number"?Rp(e.uptime):"Waiting…"}),s.jsx(Jr,{icon:s.jsx(Bt,{size:16}),label:"IDEs",value:`${t.length}`}),s.jsx(Jr,{icon:s.jsx($o,{size:16}),label:"CLIs",value:`${r.length}`}),s.jsx(Jr,{icon:s.jsx(Ah,{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(Wi,{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(Wi,{value:i,max:100,label:"Memory",color:"#3b82f6",detail:a?`${ba(e.totalMem-o)} / ${ba(e.totalMem)}${e.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${ba(e.totalMem)} total`})]})]})]})}function pj(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 fj(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 Va(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 tc(e){if(!e||typeof e!="object")return null;if(Va(e))return e;const t=e,r=t.result;return Va(r)?r:Va(t.sourceConfig)?t.sourceConfig:null}function xj(e){const t=e.trim();return t||null}function bj({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var v;const o=t.filter(g=>g.category==="ide"),[i,c]=l.useState(((v=o[0])==null?void 0:v.type)||""),[d,m]=l.useState(""),[u,h]=l.useState(""),[f,y]=l.useState(!1),[b,x]=l.useState(""),[k,j]=l.useState(!1),p=g=>{const N=g.toLowerCase().replace(/[^a-z0-9-]/g,"");m(N),(!u||u===w(d))&&h(w(N))},w=g=>g.split("-").map(N=>N.charAt(0).toUpperCase()+N.slice(1)).join(" "),C=async()=>{if(!(!d||!u||!i)){y(!0),x("");try{const g=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:i});g!=null&&g.success||g!=null&&g.created?(j(!0),a==null||a(d)):x((g==null?void 0:g.error)||"Failed to create provider")}catch(g){x((g==null?void 0:g.message)||"Connection failed")}y(!1)}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:g=>g.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children: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(g=>s.jsxs("button",{onClick:()=>c(g.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:i===g.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:i===g.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:g.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:i===g.type?"#a78bfa":"var(--text-secondary)"},children:g.displayName})]},g.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:d,onChange:g=>p(g.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",d||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:u,onChange:g=>h(g.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),b&&s.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:b})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children: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:C,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"},gj={"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 yj({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 ${gj[e]}`,title:r,children:n})}function vj(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 wj={detected:"Detected",not_detected:"Not detected",enabled_unchecked:"Enabled (unchecked)",disabled:"Disabled"},rc={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"},jj={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 nc(e){if(!e)return"—";const t=e.ok?"OK":"Failed",r=e.message||e.path||e.command||"";return r?`${t} — ${r}`:t}function kj(e){return e==="cli"||e==="acp"}function Sj({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,h=m&&u==="disabled"?"enabled_unchecked":u||(m?"enabled_unchecked":"disabled"),f=kj(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 ${jj[e.category]??"border-border-subtle text-text-muted"}`,children:e.category.toUpperCase()}),(t==null?void 0:t.trust)&&s.jsx(yj,{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 ${rc[h]??rc.disabled}`,children:wj[h]??h}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[f&&s.jsx("button",{onClick:y=>{y.stopPropagation(),a(e.type,!m)},disabled:r===`${e.type}.enabled`,className:`machine-btn text-[10px] px-2 py-0.5 ${m?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:m?"Disable":"Enable"}),s.jsx("span",{className:"text-text-muted text-xs",children:c?"▾":"▸"})]})]}),c&&s.jsxs("div",{className:"border-t border-border-subtle px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{className:"grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Type:"})," ",s.jsx("span",{className:"font-mono",children:e.type})]}),(t==null?void 0:t.providerVersion)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Version:"})," ",t.providerVersion]}),(t==null?void 0:t.binary)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Binary:"})," ",s.jsx("span",{className:"font-mono",children:t.binary})]}),(t==null?void 0:t.status)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Status:"})," ",t.status]}),(t==null?void 0:t.details)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Details:"})," ",t.details]}),(t==null?void 0:t.sourceLayer)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Source:"})," ",t.sourceLayer,t.sourceName?` · ${t.sourceName}`:""]}),(t==null?void 0:t.trust)&&(t==null?void 0:t.trustDescription)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Trust:"})," ",t.trustDescription]}),(()=>{const y=t==null?void 0:t.links;if(!y)return null;const b=Object.entries(y).map(([x,k])=>({k:x,href:vj(k)})).filter(x=>x.href!==null);return b.length===0?null:s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Links:"})," ",b.map(({k:x,href: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:"})," ",nc(t==null?void 0:t.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Verification:"})," ",nc(t==null?void 0:t.lastVerification)]})]}),e.schema.length>0&&s.jsx("div",{className:"flex flex-col gap-1.5",children:e.schema.map(y=>s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-[11px] font-medium text-text-primary",children:[y.label||y.key,r===`${e.type}.${y.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving…"})]}),y.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:y.description})]}),s.jsx("div",{className:"shrink-0",children:y.type==="boolean"?s.jsx("button",{onClick:()=>void n(e.type,y.key,!(e.values[y.key]??y.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:e.values[y.key]??y.default?"#8b5cf6":"var(--border-subtle)"},children:s.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:e.values[y.key]??y.default?21:3}})}):y.type==="number"?s.jsx("input",{type:"number",value:Number(e.values[y.key]??y.default??0)||0,min:y.min,max:y.max,onChange:b=>{const x=parseInt(b.target.value)||0;y.min!==void 0&&x<y.min||y.max!==void 0&&x>y.max||n(e.type,y.key,x)},className:"machine-input w-20 text-center text-[11px]"}):y.type==="select"&&y.options?s.jsx("select",{value:String(e.values[y.key]??y.default??""),onChange:b=>void n(e.type,y.key,b.target.value),className:"machine-input text-[11px]",children:y.options.map(b=>s.jsx("option",{value:b,children:b},b))}):s.jsx("input",{type:"text",defaultValue:String(e.values[y.key]??y.default??""),onBlur:b=>void n(e.type,y.key,b.target.value),className:"machine-input w-[180px] text-[11px]"})})]},y.key))}),s.jsx("div",{className:"flex gap-1.5 flex-wrap pt-1 border-t border-border-subtle",children:f&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>void o(e.type),disabled:!m||r===`${e.type}.detect`,className:`machine-btn text-[10px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${m?"":"opacity-40 cursor-not-allowed"}`,title:m?"Run detection for the configured executable":"Enable provider before detection",children:"Detect"}),s.jsx("button",{onClick:()=>void i(e.type),className:"machine-btn text-[10px] px-2 py-0.5",children:"Reset command"})]})})]})]})}function fn(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function Nj({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),[h,f]=l.useState(!1),[y,b]=l.useState(""),[x,k]=l.useState("main"),[j,p]=l.useState(""),[w,C]=l.useState(!1),[v,g]=l.useState(null),[N,I]=l.useState(null),S=l.useCallback(async()=>{if(e){d(!0),u(null);try{const D=fn(await t(e,"list_provider_sources",{}));if(!(D!=null&&D.success)){u((D==null?void 0:D.error)||"Failed to load sources");return}a(D.sources||[]),i(D.conflicts||[])}catch(D){u((D==null?void 0:D.message)||String(D))}finally{d(!1)}}},[e,t]);l.useEffect(()=>{S()},[S]);const T=async()=>{if(y.trim()){C(!0),u(null);try{const D=fn(await t(e,"add_provider_source",{url:y.trim(),ref:x.trim()||"main",...j.trim()?{name:j.trim()}:{}}));D!=null&&D.success?(f(!1),b(""),k("main"),p(""),await S(),r==null||r()):u((D==null?void 0:D.error)||"Failed to add source")}catch(D){u((D==null?void 0:D.message)||String(D))}finally{C(!1)}}},P=async D=>{if(confirm(`Remove provider source ${D}? This deletes the cloned manifests and clears any active-source entries that pointed here.`)){g(D),u(null);try{const L=fn(await t(e,"remove_provider_source",{name:D}));L!=null&&L.success?(await S(),r==null||r()):u((L==null?void 0:L.error)||"Failed to remove source")}catch(L){u((L==null?void 0:L.message)||String(L))}finally{g(null)}}},A=async(D,L)=>{I(`${D}:${L}`),u(null);try{const O=fn(await t(e,"set_active_provider_source",{type:D,sourceName:L}));O!=null&&O.success?(await S(),r==null||r()):u((O==null?void 0:O.error)||"Failed to set active source")}catch(O){u((O==null?void 0:O.message)||String(O))}finally{I(null)}};return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-sky-400",children:"External sources"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"3rd-party git URLs you've added. Providers here may ship JavaScript the daemon will execute — activation requires a confirmation."})]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsxs("button",{onClick:()=>void 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(D=>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:D.name}),s.jsxs("div",{className:"text-[10px] text-text-muted truncate",children:[D.url," ",s.jsxs("span",{className:"opacity-60",children:["@ ",D.ref]})]})]}),s.jsx("button",{type:"button",onClick:()=>void P(D.name),disabled:v===D.name,className:"machine-btn text-[10px] text-red-400 hover:bg-red-500/[0.10]",children:v===D.name?"…":"Remove"})]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:Object.entries(D.providers).map(([L,O])=>s.jsxs("span",{className:"mr-3",children:[s.jsxs("span",{className:"text-text-secondary",children:[L,":"]})," ",O.length]},L))})]},D.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(D=>s.jsxs("li",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"font-mono text-[11px]",children:[D.type," ",s.jsxs("span",{className:"text-text-muted",children:["(",D.category,")"]})]}),s.jsx("div",{className:"flex gap-1.5 flex-wrap",children:D.candidates.map(L=>s.jsxs("button",{type:"button",onClick:()=>void A(D.type,L),disabled:N===`${D.type}:${L}`,className:`text-[10px] px-2 py-0.5 rounded border ${D.active===L?"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:D.active===L?"Active":`Switch active to ${L}`,children:[D.active===L?"● ":"",L]},L))})]},D.type))})]}),h&&s.jsxs("div",{className:"mt-3 rounded border border-sky-500/30 bg-sky-500/[0.06] px-3 py-3",children:[s.jsx("div",{className:"text-[11px] font-semibold text-sky-300 mb-2",children:"Add external source"}),s.jsxs("div",{className:"grid md:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[10px] text-text-secondary md:col-span-3",children:[s.jsx("span",{children:"Git URL"}),s.jsx("input",{type:"text",value:y,onChange:D=>b(D.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:D=>k(D.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:D=>p(D.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:w||!y.trim(),className:"machine-btn text-[10px] bg-sky-500/[0.10] border-sky-500/30 text-sky-200 hover:bg-sky-500/[0.18]",children:w?"Cloning…":"Clone + register"})]})]})]})}function Cj({machineId:e,providers:t,sendDaemonCommand:r}){var M;const[n,a]=l.useState([]),[o,i]=l.useState(!1),[c,d]=l.useState(null),[m,u]=l.useState("all"),[h,f]=l.useState(!1),[y,b]=l.useState(!1),[x,k]=l.useState(!1),[j,p]=l.useState(null),[w,C]=l.useState("normal"),[v,g]=l.useState(""),[N,I]=l.useState(!1),S=l.useCallback(async()=>{if(e)try{const $=await r(e,"get_provider_source_config",{}),W=tc($);W&&(p(W),C(W.sourceMode),g(W.explicitProviderDir||""))}catch{}},[e,r]),T=l.useCallback(async()=>{if(e){i(!0);try{const $=await r(e,"get_provider_settings",{}),W=pj($);if(W){const B=fj(W,t,{filterSchema:F=>F.filter(K=>K.key!=="enabled")});B.sort((F,K)=>F.category.localeCompare(K.category)||F.displayName.localeCompare(K.displayName)),a(B)}}catch{}i(!1)}},[e,t,r]);l.useEffect(()=>{n.length===0&&T(),j||S()},[]);const P=async($,W,B)=>{d(`${$}.${W}`),a(F=>F.map(K=>K.type===$?{...K,values:{...K.values,[W]:B}}:K));try{const F=await r(e,"set_provider_setting",{providerType:$,key:W,value:B});F!=null&&F.success||T()}catch{T()}d(null)},A=async($,W)=>{await P($,"enabled",W),await T()},D=async $=>{d(`${$}.detect`);try{await r(e,"detect_provider",{providerType:$})}finally{await T(),d(null)}},L=async $=>{await P($,"executablePath",""),await P($,"executableArgs",""),await T()},O=async()=>{I(!0);try{const $=await r(e,"set_provider_source_config",{providerSourceMode:w,providerDir:xj(v)}),W=tc($);W?(p(W),C(W.sourceMode),g(W.explicitProviderDir||"")):await S(),await T()}catch{await S()}I(!1)},_=n.filter($=>m==="all"||$.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($=>s.jsx("button",{onClick:()=>u($),className:`machine-btn text-[10px] px-2 py-0.5 ${m===$?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:$.toUpperCase()},$))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>b($=>!$),className:`machine-btn text-[10px] ${y?"bg-sky-500/[0.10] border-sky-500/30 text-sky-300":""}`,title:"Manage 3rd-party provider sources",children:"🌐 Sources"}),s.jsx("button",{onClick:()=>f(!0),className:"machine-btn text-[10px]",title:"Create a new provider from an existing one",children:"✨ Create"}),s.jsxs("button",{onClick:T,disabled:o,className:"machine-btn text-[10px]",children:[o?"⏳":"↻"," Refresh"]}),s.jsx("button",{onClick:()=>k($=>!$),className:"machine-btn text-[10px]",title:"Show source configuration (advanced)",children:"⚙ Advanced"})]})]}),y&&s.jsx(Nj,{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:w,onChange:$=>C($.target.value),className:"machine-input text-[11px]",children:[s.jsx("option",{value:"normal",children:"normal"}),s.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),s.jsx("input",{type:"text",value:v,onChange:$=>g($.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void O(),disabled:N,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:N?"Applying…":"Apply + Reload"})]}),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:"})," ",((M=j==null?void 0:j.providerRoots)==null?void 0:M.join(" → "))||"—"]})]})]}),o&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings…"}):_.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:_.map($=>s.jsx(Sj,{prov:$,providerInfo:t.find(W=>W.type===$.type),savingKey:c,onSetSetting:P,onEnableToggle:A,onDetect:D,onResetCommand:L},$.type))}),h&&s.jsx(bj,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>f(!1),onCreated:()=>{f(!1),T()}})]})}const Ij=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Mj({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function Tj(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function Aj(e){return e.trim().toLowerCase()}function ca(e,t){const r=Aj(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function yi(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Ws(e,t=220){const r=yi(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function _j(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 Lj(e,t){return e.filter(r=>ca([r.level,r.message],t))}function ac(e){return`${e.timestamp}:${e.level}:${e.message}`}function Pj(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const i of e.entries)n.set(ac(i),i);for(const i of t.entries)n.set(ac(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 Rj(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 Dj(e,t){return e.split(`
77
- `).map(r=>r.trimEnd()).filter(Boolean).filter(r=>ca([r],t))}function Ej(e,t){return e.filter(r=>ca([r.level,r.category,r.stage,r.interactionId,yi(r.payload)],t))}function $j(e,t){return e.filter(r=>ca([r.kind,r.topic,r.interactionId,yi(r.payload)],t))}function oc(e){return e==="warn"||e==="error"}function Bj({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=>oc(a.level)).length+r.filter(a=>oc(a.level)).length}}function Oj({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(`
78
- `)):t.length>0&&a.push(["[daemon logs]",...t].join(`
79
- `)),r.length>0&&a.push(["[trace]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${Ws(o.payload,500)}`.trim())].join(`
80
- `)),n.length>0&&a.push(["[browser events]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${Ws(o.payload,500)}`.trim())].join(`
81
- `)),a.join(`
82
-
83
- `)}function Fj({machineId:e,sendDaemonCommand:t}){const[r,n]=l.useState([]),[a,o]=l.useState("empty"),[i,c]=l.useState(""),[d,m]=l.useState([]),[u,h]=l.useState([]),[f,y]=l.useState(null),[b,x]=l.useState(!0),[k,j]=l.useState("info"),[p,w]=l.useState("all"),[C,v]=l.useState(!0),[g,N]=l.useState(!0),[I,S]=l.useState(""),[T,P]=l.useState(""),[A,D]=l.useState(0),L=l.useRef(0),O=l.useRef(0),_=l.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),M=l.useRef([]),$=l.useCallback(()=>{const ae={entries:[],kind:"empty",rawText:"",lastTs:0};_.current=ae,L.current=0,n([]),c(""),o("empty"),v(!0)},[]),W=l.useCallback(()=>{M.current=[],O.current=0,m([]),N(!0)},[]),B=l.useCallback(ae=>{ae!==k&&($(),j(ae))},[k,$]),F=l.useCallback(ae=>{w(he=>he===ae?he:ae)},[]),K=l.useCallback(()=>{$(),W(),h([]),y(null),S(""),P(""),Ds.clear()},[$,W]),Y=l.useCallback(()=>{D(ae=>ae+1)},[]),re=l.useCallback(async()=>{if(!e)return;const ae=L.current,he=O.current,[we,Ce]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:k,since:ae}),t(e,"get_debug_trace",Mj({count:120,since:he,category:p}))]);if(we.status==="fulfilled"){const V=we.value,q=(V==null?void 0:V.result)||V,ue=_j(q),me=Pj(_.current,ue,300);_.current=me,L.current=me.lastTs,v(!1),S((V==null?void 0:V.success)===!1?String((V==null?void 0:V.error)||"Could not load daemon logs"):""),o(me.kind),c(me.rawText),n(me.entries)}else v(!1),S(we.reason instanceof Error?we.reason.message:"Could not load daemon logs");if(Ce.status==="fulfilled"){const V=Ce.value,q=(V==null?void 0:V.result)||V;if((V==null?void 0:V.success)===!1)P(String((V==null?void 0:V.error)||"Could not load daemon trace"));else if(Array.isArray(q==null?void 0:q.trace)){const ue=q.trace,me=Rj(M.current,ue,120),le=ue.reduce((je,X)=>Math.max(je,Number(X.ts||0)),he);M.current=me,le>he&&(O.current=le),P(""),m(me)}else P("");N(!1)}else N(!1),P(Ce.reason instanceof Error?Ce.reason.message:"Could not load daemon trace");h(Ds.list({limit:120})),y(Date.now())},[k,e,t,p]);return l.useEffect(()=>{W()},[W,p]),l.useEffect(()=>{if(!e||(re(),!b))return;const ae=setInterval(()=>{re()},3e3);return()=>clearInterval(ae)},[b,re,e,A]),{daemonLogs:r,daemonLogKind:a,daemonRawText:i,debugTrace:d,webEvents:u,lastUpdatedAt:f,autoRefresh:b,logLevel:k,traceCategory:p,daemonLoading:C,traceLoading:g,daemonFetchError:I,traceFetchError:T,setAutoRefresh:x,setLogLevel:B,setTraceCategory:F,refresh:Y,clear:K}}function Hj({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 ic(e){return e==="warn"||e==="error"}function Wj(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 Kj(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 lc(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function Uj(e){const t=Ws(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function zj(e){const t=Ws(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function Gj({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:zj(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:Uj(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:Kj(o,i),severity:Wj(o),message:o,raw:o})}),a.sort((o,i)=>o.ts!==i.ts?o.ts-i.ts:lc(o.source)-lc(i.source))}function Vj(e){return`${e.source}:${e.severity}:${e.message}`}function qj(e){const t=e.filter(n=>ic(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!ic(n.severity))continue;const a=Vj(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 Yj(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function cc(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${Yj(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function Xj({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
84
- `)),a.push(["[source status]",...r.map(i=>`${i.label}: ${i.status} - ${i.detail}`)].join(`
85
- `)),t.latestIssue&&a.push(["[latest issue]",cc(t.latestIssue)].join(`
86
- `)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(i=>`${i.count}x ${i.severity.toUpperCase()} ${i.source} ${i.message}`)].join(`
87
- `));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(cc):["No diagnostic events captured."]].join(`
88
- `)),a.join(`
89
-
90
- `)}function Jj(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Qj(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function Zj({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:i,searchQuery:c,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:h}){const f=Tj(n,o),y=Lj(e,c),b=Dj(t,c),x=Ej(f,c),k=$j(a,c),j=Jj(y,i),p=i==="all"?b:[],w=Qj(x,i),C=i==="issues"?[]:k,v=Bj({daemonLogs:y,daemonRawLines:b,trace:x,webEvents:k}),g=Gj({daemonLogs:j,daemonRawLines:p,trace:w,webEvents:C}),N=qj(g),I=Hj({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:h,daemonLogKind:r,daemonLogsCount:y.length,daemonRawLineCount:b.length,traceCount:x.length,webEventCount:k.length});return{filteredDaemonLogs:y,filteredDaemonRawLines:b,filteredTraceEntries:x,filteredWebEvents:k,visibleDaemonLogs:j,visibleDaemonRawLines:p,visibleTraceEntries:w,visibleWebEvents:C,quickFilterCounts:v,diagnosticEvents:g,diagnosticsSummary:N,sourceStates:I}}function ek(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Xu(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Mo(e){return e==="error"?"text-red-300 border-red-500/25 bg-red-500/[0.05]":e==="warn"?"text-amber-200 border-amber-500/25 bg-amber-500/[0.05]":e==="debug"?"text-slate-300 border-slate-500/25 bg-slate-500/[0.05]":"text-text-secondary border-border-subtle bg-bg-primary"}function qa(e){return e==="good"?"border-emerald-500/20 bg-emerald-500/[0.05]":e==="warning"?"border-amber-500/20 bg-amber-500/[0.05]":e==="danger"?"border-red-500/20 bg-red-500/[0.05]":"border-border-subtle bg-bg-secondary"}function vi(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function tk({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Mo(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Xu(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:vi(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 sk({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(h=>s.jsx("button",{type:"button",onClick:()=>a(h.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===h.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:h.label},h.id))}),s.jsx("input",{value:r,onChange:h=>o(h.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:i,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick: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 rk({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:Ij.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 nk({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:i,traceFetchError:c}){var u,h;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((h=e.latestIssue)==null?void 0:h.severity)==="warn"?"warning":"good",m=i||c?"danger":o?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${qa(e.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:n.trim()?`Filtered by “${n.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${qa(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:[vi(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:Xu(e.latestIssue.ts)})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${qa(m)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:i||c?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",ek(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 ak({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()," · ",vi(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function ok({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(tk,{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,h)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${h}`)),e.daemonLogKind!=="text"&&a.map((u,h)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Mo(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-${h}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(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 ${Mo(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:Ws(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:Ws(u.payload,360)||"No payload"})]},u.id))]})]})]})}function ik({machineId:e,sendDaemonCommand:t}){const r=Fj({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),h=l.useMemo(()=>Zj({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:o,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,o,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);l.useEffect(()=>{if(r.autoRefresh&&h.diagnosticEvents.length>0){const b=u.current?"smooth":"instant";setTimeout(()=>{var x;(x=m.current)==null||x.scrollIntoView({behavior:b}),u.current=!0},50)}},[h.diagnosticEvents.length,r.autoRefresh]);const f=l.useCallback(async()=>{var x;const b=Oj({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!b.trim()){Je.showToast("No visible logs to copy.","info");return}try{await((x=navigator.clipboard)==null?void 0:x.writeText(b)),Je.showToast("Copied visible logs to clipboard.","success")}catch(k){Je.showToast(k instanceof Error?k.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),y=l.useCallback(async()=>{var x;const b=Xj({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((x=navigator.clipboard)==null?void 0:x.writeText(b)),Je.showToast("Copied diagnostic bundle to clipboard.","success")}catch(k){Je.showToast(k instanceof Error?k.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(sk,{quickFilter:n,quickFilterCounts:h.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:()=>{y()},onCopyVisible:()=>{f()},onToggleAutoRefresh:()=>r.setAutoRefresh(b=>!b),onRefresh:r.refresh,onClear:r.clear}),s.jsx(rk,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(nk,{diagnosticsSummary:h.diagnosticsSummary,diagnosticEventsCount:h.diagnosticEvents.length,sourceStates:h.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(ak,{patterns:h.diagnosticsSummary.repeatedPatterns}),s.jsx(ok,{streams:r,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:m})]})}function lk(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 Ju(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 ck(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=Ju((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 dk(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Ya(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 Xa(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Ja(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function dc(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 uk(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function mk(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 hk(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 pk({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=l.useState(""),[o,i]=l.useState(null),[c,d]=l.useState(!1),m=gg(e,{enabled:!!e,includeSessions:!0,limit:ol,intervalMs:ex}),u=m.diagnostics,h=m.loading,f=m.applyDiagnostics,y=l.useMemo(()=>lk({diagnostics:u,loading:h,refreshing:c,error:n}),[u,h,c,n]),b=l.useMemo(()=>new Map(t.map(P=>[P.sessionId||P.id,P])),[t]),x=l.useCallback(async()=>{if(e){d(!0);try{const P=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:ol}),A=Xa(P);if(!(A!=null&&A.success))throw new Error((A==null?void 0:A.error)||"Could not load hosted runtime diagnostics");f(A.diagnostics||A.result||null),a("")}catch(P){const A=P instanceof Error?P.message:"Could not load hosted runtime diagnostics";a(A)}finally{d(!1)}}},[f,e,r]);l.useEffect(()=>{!e||u||h||c||x()},[u,h,e,x,c]);const k=l.useCallback(async(P,A)=>{const D=`${P}:${A.sessionId}`;if(!(P==="session_host_stop_session"&&!window.confirm(`Stop ${A.displayName}?
91
- This will terminate the hosted runtime.`))){i(D);try{const L=await r(e,P,{sessionId:A.sessionId}),O=Xa(L);if(!(O!=null&&O.success))throw new Error((O==null?void 0:O.error)||"Session host action failed");const _=P==="session_host_resume_session"?"resumed":P==="session_host_restart_session"?"restarted":"stopped";Je.showToast(`Session host ${_}: ${A.displayName}`,"success"),await x()}catch(L){const O=L instanceof Error?L.message:"Session host action failed";Je.showToast(O,"warning"),a(O)}finally{i(L=>L===D?null:L)}}},[e,x,r]),j=l.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
92
- The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const A=await r(e,"session_host_prune_duplicate_sessions",{}),D=Xa(A);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Duplicate prune failed");const L=D.result||{},O=Array.isArray(L.prunedSessionIds)?L.prunedSessionIds.length:0,_=typeof L.duplicateGroupCount=="number"?L.duplicateGroupCount:0;Je.showToast(`Pruned ${O} duplicate runtime(s) across ${_} group(s)`,"success"),await x()}catch(A){const D=A instanceof Error?A.message:"Duplicate prune failed";Je.showToast(D,"warning"),a(D)}finally{i(A=>A==="session_host_prune_duplicate_sessions"?null:A)}}},[e,x,r]),p=l.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((P,A)=>(A.lastActivityAt||0)-(P.lastActivityAt||0)),[u==null?void 0:u.sessions]),w=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)||[]}:ck(p),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,p]),C=w.liveRuntimes,v=w.recoverySnapshots,g=w.inactiveRecords,N=l.useMemo(()=>hk(C),[C]),I=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(P=>P.level==="warn"||P.level==="error")||null,[u==null?void 0:u.recentLogs]),T=(P,A)=>{var F;const D=o===`session_host_resume_session:${P.sessionId}`,L=o===`session_host_restart_session:${P.sessionId}`,O=o===`session_host_stop_session:${P.sessionId}`,_=Ju(P.meta),M=b.get(P.sessionId),$=P.attachedClients.length===1?"1 client":`${P.attachedClients.length} clients`,W=A==="recovery"?"Recover":"Resume",B=dk(A);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:P.displayName||(M==null?void 0:M.cliName)||P.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${mk(P.lifecycle)}`,children:P.lifecycle}),_&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:_})]}),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:P.workspaceLabel||(M==null?void 0:M.runtimeWorkspaceLabel)||P.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:P.runtimeKey}),P.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",P.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((F=P.writeOwner)==null?void 0:F.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:uk(P.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(Nc,{size:11})," ",$]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",dc(P.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:[A==="recovery"&&(P.lifecycle==="interrupted"||P.lifecycle==="failed"||P.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{k("session_host_resume_session",P)},children:D?`${W}ing…`:W}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{k("session_host_restart_session",P)},children:L?"Restarting…":"Restart"}),A==="live"&&(P.lifecycle==="running"||P.lifecycle==="starting"||P.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",P)},children:O?"Stopping…":"Stop"})]})]})},P.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(ts,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:bb()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[N>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 (${N})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${y.toneClass}`,children:y.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{x()},disabled:h||c,children:[s.jsx(ta,{size:13}),h||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(Bs,{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:v.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children: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:dc(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Ja(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(Bs,{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:[Ja(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($o,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ya("live")}),C.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:C.map(P=>T(P,"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(ts,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ya("recovery")}),v.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:v.map(P=>T(P,"recovery"))})]}),g.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ya("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:g.map(P=>T(P,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),I.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:I.map(P=>{var D;const A=p.find(L=>L.sessionId===P.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(A==null?void 0:A.displayName)||((D=b.get(P.sessionId))==null?void 0:D.cliName)||P.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[P.action,P.lifecycle?` · ${P.lifecycle}`:"",P.detail?` · ${P.detail}`:"",P.error?` · ${P.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${P.success===!1?"text-red-300":"text-text-secondary"}`,children:Ja(P.timestamp)})]},`${P.sessionId}:${P.timestamp}:${P.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 fk({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 xk(e,t){const r=tu(e),n=Ts(e,t),a=Zo(e,n),o=gr(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 Qa({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 Za({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 bk({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=xk(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(Qa,{icon:s.jsx(ws,{size:13}),children:"Current Chats"}),s.jsx(Za,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(h=>{const f=No(h);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(h),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:nt(h)}),f>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:sa(f)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ys(h)})]},h.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Qa,{icon:s.jsx(Tc,{size:13}),children:"Recent Launches"}),s.jsx(Za,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(h=>{const{metaText:f,updatedLabel:y}=fu(h);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>o(h),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:h.label}),y&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:y})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:f})]},h.id)})})})]}),u.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Qa,{icon:s.jsx(Bs,{size:13}),children:"Daemon Update"}),s.jsx(Za,{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(ta,{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 gk({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:m,handleWorkspaceSetDefault:u}=o,[h,f]=l.useState(!1),[y,b]=l.useState(""),[x,k]=l.useState([]),[j,p]=l.useState(!1),[w,C]=l.useState(""),v=l.useCallback(async N=>{p(!0),C("");try{const I=await ii(i,e,N);b(I.path),k(I.directories)}catch(I){C(I instanceof Error?I.message:"Could not load folder")}finally{p(!1)}},[e,i]),g=l.useCallback(()=>{f(!0);const N=[...r.map(S=>S.workspace),...n.map(S=>S.workspace),...a.map(S=>S.workspace)],I=oi(t.platform,ai(N,t.defaultWorkspacePath,(t.workspaces||[]).map(S=>S.path)));v(I)},[a,n,r,v,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-4 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx($s,{size:14})," Workspaces"]}),s.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick:g,children:"+ Add workspace"})]}),(t.workspaces||[]).length===0?s.jsxs("div",{className:"text-[11px] text-text-muted py-4 text-center",children:["No saved workspaces yet. Click ",s.jsx("span",{className:"text-text-secondary",children:"+ Add workspace"})," to pick a folder."]}):s.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(N=>{const I=N.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${I?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:I?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void u(I?null:N.id),className:`text-base leading-none shrink-0 transition-colors ${I?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary truncate",children:zc(N.path,N.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:N.path,children:N.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void m(N.id),children:"Remove"})]},N.id)})})]}),h&&s.jsx(ci,{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:w,confirmLabel:"Add workspace",onClose:()=>f(!1),onNavigate:N=>{v(N)},onConfirm:N=>{(async()=>{if(!N)return;await d(N)&&f(!1)})()}})]})}function yk({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(gk,{machineId:t,machine:e,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function vk({onNicknameSynced:e}={}){var je,X,ye,de,ve,fe,ge,ce,be,oe;const{id:t}=Gm(),r=Tr(),n=Lo(),{sendCommand:a}=it(),o=Pr(),i=Hd(),c=bd(),d=c.ides||[],m=c.initialLoaded??!0,u=d.find(R=>R.id===t&&R.type==="adhdev-daemon"),h=d.some(R=>R.type==="adhdev-daemon"),f=t?(je=c.connectionRetryStatuses)==null?void 0:je[t]:void 0,y=!!(f!=null&&f.blocked),[b,x]=l.useState("workspace"),[k,j]=l.useState(null);l.useCallback((R,pe)=>{j({daemonId:R,workspace:pe})},[]);const[,p]=l.useState("ide"),w=l.useRef(null),[C,v]=l.useState(null),g=l.useRef("__home__"),[N,I]=l.useState("__home__"),[S,T]=l.useState(!1),P=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||b!=="overview")return;const R=u.machine;(typeof(R==null?void 0:R.cpus)!="number"||typeof(R==null?void 0:R.totalMem)!="number"||typeof(R==null?void 0:R.arch)!="string"||typeof(R==null?void 0:R.release)!="string")&&i(t,{minFreshMs:3e4}).catch(()=>{})},[b,i,u,t]),bg(t&&b==="overview"?[t]:[],{enabled:b==="overview",intervalMs:Xf});const A=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},D=mj({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:P});l.useEffect(()=>Je.onToast(pe=>{c.setToasts(Me=>{if(Me.some(De=>De.message===pe.message&&pe.timestamp-De.timestamp<3e3))return Me;const Ne={id:pe.id,message:pe.message,type:pe.type,timestamp:pe.timestamp,targetKey:pe.targetKey,actions:pe.actions};return[...Me.slice(-4),Ne]});const Se=pe.duration||5e3;setTimeout(()=>c.setToasts(Me=>Me.filter(ee=>ee.id!==pe.id)),Se)}),[c]);const L=(u==null?void 0:u.availableProviders)||[],O={};for(const R of L)O[R.type]=R.icon;const _=u?{id:u.id,hostname:Gc(u,{fallbackId:u.id}),platform:((X=u.machine)==null?void 0:X.platform)||"unknown",arch:((ye=u.machine)==null?void 0:ye.arch)||"",cpus:((de=u.machine)==null?void 0:de.cpus)||0,totalMem:((ve=u.machine)==null?void 0:ve.totalMem)||0,freeMem:(fe=u.machine)==null?void 0:fe.freeMem,availableMem:(ge=u.machine)==null?void 0:ge.availableMem,loadavg:(ce=u.machine)==null?void 0:ce.loadavg,uptime:(be=u.machine)==null?void 0:be.uptime,release:((oe=u.machine)==null?void 0:oe.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,M=d.filter(R=>R.daemonId===t&&R.type!=="adhdev-daemon").filter(R=>!Sr(R)&&!Ls(R)).map(R=>({id:R.id,sessionId:R.sessionId,type:R.type,version:R.version||"",instanceId:R.instanceId||"",status:R.status,workspace:R.workspace||null,terminals:R.terminals||0,aiAgents:Wp(R.aiAgents||(R.agents||[]).map(pe=>({id:pe.name,name:pe.name,status:pe.status,version:pe.version}))),activeChat:R.activeChat||null,chats:R.chats||[],childSessions:R.childSessions||[],cdpConnected:R.cdpConnected||!1,daemonId:t,lastMessageAt:R.lastMessageAt})),$=d.filter(R=>R.daemonId===t&&Sr(R)).map(R=>({id:R.id,sessionId:R.sessionId,type:R.type,cliName:R.cliName||R.type,status:R.status,workspace:R.workspace||"",activeChat:R.activeChat||null,providerSessionId:R.providerSessionId,mode:R.mode,runtimeKey:R.runtimeKey,runtimeDisplayName:R.runtimeDisplayName,runtimeWorkspaceLabel:R.runtimeWorkspaceLabel,runtimeWriteOwner:R.runtimeWriteOwner||null,runtimeAttachedClients:R.runtimeAttachedClients||[],daemonId:t,lastMessageAt:R.lastMessageAt})),W=d.filter(R=>R.daemonId===t&&Ls(R)).map(R=>({id:R.id,sessionId:R.sessionId,type:R.type,acpName:R.cliName||R.type,status:R.status,workspace:R.workspace||"",activeChat:R.activeChat||null,providerSessionId:R.providerSessionId,daemonId:t,lastMessageAt:R.lastMessageAt})),B=u?Ct(u,{fallbackId:t}):"",F="workspace",K=n.state,Y=K==null?void 0:K.initialMachineTab,re=K==null?void 0:K.initialWorkspaceCategory;K==null||K.initialWorkspaceId,K==null||K.initialWorkspacePath;const ae=Y==="ides"||Y==="clis"||Y==="acps"?"workspace":Y||F,he=Y==="ides"?"ide":Y==="clis"?"cli":Y==="acps"?"acp":re,we=[...M.map(R=>{var pe;return{id:`ide:${R.type}:${R.workspace||""}`,label:((pe=R.activeChat)==null?void 0:pe.title)||R.type,kind:"ide",providerType:R.type,subtitle:R.workspace||void 0,workspace:R.workspace||void 0,lastLaunchedAt:R.lastMessageAt||0}}),...$.map(R=>{var pe;return{id:`cli:${R.type}:${R.workspace||""}`,label:((pe=R.activeChat)==null?void 0:pe.title)||R.cliName,kind:"cli",providerType:R.type,providerSessionId:R.providerSessionId,subtitle:R.workspace||void 0,workspace:R.workspace||void 0,lastLaunchedAt:R.lastMessageAt||0}}),...W.map(R=>{var pe;return{id:`acp:${R.type}:${R.workspace||""}`,label:((pe=R.activeChat)==null?void 0:pe.title)||R.acpName,kind:"acp",providerType:R.type,providerSessionId:R.providerSessionId,subtitle:gs(R.summaryMetadata)||R.workspace||void 0,workspace:R.workspace||void 0,lastLaunchedAt:R.lastMessageAt||0}})].sort((R,pe)=>(pe.lastLaunchedAt||0)-(R.lastLaunchedAt||0)),Ce=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(R=>({id:R.id,label:R.title||R.providerName||R.providerType,kind:R.kind,providerType:R.providerType,providerSessionId:R.providerSessionId,subtitle:gs(R.summaryMetadata)||R.workspace||void 0,workspace:R.workspace,summaryMetadata:R.summaryMetadata,lastLaunchedAt:R.lastLaunchedAt})):we,V=l.useMemo(()=>{var pe;const R=((pe=c.connectionStates)==null?void 0:pe[t||""])||void 0;return d.filter(Se=>Se.daemonId===t&&Se.type!=="adhdev-daemon").flatMap(Se=>Qo(Se,{connectionStates:t&&R?{[t]:R}:void 0,defaultConnectionState:R})).filter(Se=>!(Se.transport==="pty"&&Se.mode==="terminal")).sort((Se,Me)=>No(Me)-No(Se))},[d,c.connectionStates,t]),q=l.useCallback(R=>{const pe=ou(R);pe&&r(Cr(pe))},[r]),ue=l.useCallback(()=>{w.current&&(T(!0),w.current().finally(()=>{w.current=null,T(!1),v(null)}))},[]),me=l.useCallback(R=>{if(!_)return;const{options:pe,selectedKey:Se}=pu({machine:_,currentWorkspacePath:R.workspace}),Me=async()=>{p(R.kind),x("workspace")};w.current=async()=>{const ee=pe.find(Ee=>Ee.key===g.current),Ne=(ee==null?void 0:ee.workspacePath)??null,De=(ee==null?void 0:ee.workspaceId)??null;if(R.kind==="ide"&&R.providerType){await D.handleLaunchIde(R.providerType,Ne?{workspace:Ne}:void 0);return}if((R.kind==="cli"||R.kind==="acp")&&R.providerType){await D.runLaunchCliCore({cliType:R.providerType,dir:De?void 0:Ne||"",workspaceId:De||void 0,model:R.kind==="acp"&&qc(R.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:R.providerSessionId});return}await Me()},g.current=Se,I(Se),v({title:R.kind==="ide"?Hn("restart-ide",R.label):R.providerSessionId?Cd(R.label):Hn("start-fresh",R.label),description:R.kind==="ide"?Wn("restart-ide"):R.providerSessionId?Id():Wn("start-fresh"),confirmLabel:R.kind==="ide"?Kn("restart-ide"):R.providerSessionId?Fn(!0):Kn("start-fresh"),busyLabel:R.kind==="ide"?Un("restart-ide"):R.providerSessionId?Xo(!0):Un("start-fresh"),workspaceOptions:pe,details:[{label:"Mode",value:R.kind.toUpperCase()},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]})},[D,_]);if(l.useEffect(()=>{x(ae)},[F,ae,t]),l.useEffect(()=>{he&&p(he)},[he,t]),!_)return m?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:A,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const le=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Bt,{size:14})," Workspace"]}),count:M.length+$.length+W.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ts,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ea,{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(Sh,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:A,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[D.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:D.nicknameInput,onChange:R=>D.setNicknameInput(R.target.value),onKeyDown:R=>{R.key==="Enter"&&D.handleSaveNickname(),R.key==="Escape"&&D.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:D.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:()=>D.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:()=>{D.setEditingNickname(!0),D.setNicknameInput(_.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:[_.platform," · ",_.arch]}),s.jsxs("span",{children:[_.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),_.p2p.available&&s.jsxs("span",{children:["P2P ",_.p2p.state==="connected"?"connected":_.p2p.state]}),_.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:_.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:le.map(R=>s.jsxs("button",{onClick:()=>x(R.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${b===R.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[R.label,R.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${b===R.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:R.count})]},R.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[b==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(bk,{machineEntry:u,providers:L,recentLaunches:Ce,currentConversations:V,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",su(u))}catch{}},onOpenRecent:me,onOpenConversation:q}),s.jsx(yk,{machine:_,machineId:t,ideSessions:M,cliSessions:$,acpSessions:W,actions:D,sendDaemonCommand:a})]}),b==="providers"&&s.jsx(Cj,{machineId:t,providers:L,sendDaemonCommand:a}),b==="overview"&&s.jsx(hj,{machine:_,ideSessions:M,cliSessions:$,acpSessions:W}),b==="session-host"&&s.jsx(pk,{machineId:t,cliSessions:$,sendDaemonCommand:a}),b==="logs"&&s.jsx(ik,{machineId:t,sendDaemonCommand:a})]})})}),D.launchPick&&_&&s.jsx(fk,{machine:_,launchPick:D.launchPick,actions:D}),C&&s.jsx(hu,{title:C.title,description:C.description,details:C.details,workspaceOptions:C.workspaceOptions,selectedWorkspaceKey:N,onWorkspaceChange:R=>{g.current=R,I(R)},confirmLabel:C.confirmLabel,busyLabel:C.busyLabel,busy:S,onConfirm:ue,onCancel:()=>{w.current=null,v(null)}}),k&&s.jsx(Yu,{daemonId:k.daemonId,workspace:k.workspace,onClose:()=>j(null)}),s.jsx(Td,{toasts:c.toasts||[],onDismiss:R=>c.setToasts(pe=>pe.filter(Se=>Se.id!==R)),onClickToast:R=>{R.targetKey&&r(Cr(R.targetKey))}}),s.jsx("style",{children:`
93
- @keyframes toast-in {
94
- from { opacity: 0; transform: translateX(40px); }
95
- to { opacity: 1; transform: translateX(0); }
96
- }
97
- `})]})}const xn=[{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."}],wk={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function Tn(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function jk(e){const t=Tn(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"launch not ready unless an explicit provider is selected"}}function kk(e){return e.isLocalWorktree===!0}function Sk(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function Nk(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 Ck(e,t){return[...Array.isArray(t==null?void 0:t.cliSessions)?t.cliSessions:[],...Array.isArray(t==null?void 0:t.acpSessions)?t.acpSessions:[],...Array.isArray(t==null?void 0:t.sessions)?t.sessions:[]].filter(n=>{var a;return((a=n==null?void 0:n.settings)==null?void 0:a.meshNodeId)===e.id||(n==null?void 0:n.workspace)===e.workspace}).map(n=>{var a;return{id:n.sessionId||n.id||n.instanceId||"unknown",provider:n.providerType||n.cliType||n.acpType||n.type||"unknown",status:n.status||((a=n.activeChat)==null?void 0:a.status)||"unknown"}})}function eo(e){return{...wk,...(e==null?void 0:e.policy)||{}}}function Ik({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const o=a.id.toLowerCase(),i=a.name.toLowerCase();return o==="hermes-cli"||o.includes("hermes")||i.includes("hermes")}),n=au(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(lt,{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(Tu,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function Mk({hideHostPairing:e=!1}={}){var te,H,G,Z,ne;const{sendCommand:t}=it(),{ides:r}=qt(),n=r.find(E=>E.daemonMode||E.type==="adhdev-daemon"),a=(n==null?void 0:n.id)||"",o=[];let i=[];if(n){const E=n.availableProviders||[];i=Tb(E);for(const ie of E)ie.category==="cli"&&o.push({id:ie.type||ie.id,name:ie.displayName||ie.name||ie.type,meshCoordinator:ie.meshCoordinator})}const[c,d]=l.useState([]),[m,u]=l.useState(null),[h,f]=l.useState(!0),[y,b]=l.useState(null),[x,k]=l.useState(!1),[j,p]=l.useState(null),[w,C]=l.useState({}),[v,g]=l.useState({override:"",append:""}),[N,I]=l.useState(!1),[S,T]=l.useState({}),[P,A]=l.useState(null),[D,L]=l.useState([]),[O,_]=l.useState(null),[M,$]=l.useState(null),[W,B]=l.useState(!1),[F,K]=l.useState(null),[Y,re]=l.useState(null),[ae,he]=l.useState(!1),[we,Ce]=l.useState(!1),[V,q]=l.useState(!1),[ue,me]=l.useState(""),[le,je]=l.useState(""),[X,ye]=l.useState(!1),[de,ve]=l.useState(""),[fe,ge]=l.useState(""),[ce,be]=l.useState(""),[oe,R]=l.useState(!1),[pe,Se]=l.useState(""),[Me,ee]=l.useState([]),Ne=c.find(E=>E.id===m)||null;l.useEffect(()=>{C(Object.fromEntries(((Ne==null?void 0:Ne.nodes)||[]).map(E=>[E.id,Tn(E)])))},[Ne]),l.useEffect(()=>{const E=(Ne==null?void 0:Ne.coordinator)||{};g({override:typeof E.systemPromptOverride=="string"?E.systemPromptOverride:"",append:typeof E.systemPromptAppend=="string"?E.systemPromptAppend:typeof E.systemPromptSuffix=="string"?E.systemPromptSuffix:""}),T(Object.fromEntries(((Ne==null?void 0:Ne.nodes)||[]).map(ie=>[ie.id,typeof ie.systemPrompt=="string"?ie.systemPrompt:""])))},[Ne]),l.useEffect(()=>{const E=Ab(i);oe&&Me.length===0&&E.length>0&&ee(E)},[oe,i,Me.length]),l.useEffect(()=>{const E=new Set(((Ne==null?void 0:Ne.nodes)||[]).map(ie=>ie.id));O&&!E.has(O)&&_(null)},[Ne,O]);const De=l.useCallback(async()=>{if(a){f(!0);try{const E=await t(a,"list_meshes");E!=null&&E.success?(d(E.meshes||[]),b(null)):b((E==null?void 0:E.error)||"Failed to load meshes")}catch(E){b((E==null?void 0:E.message)||"Failed to load meshes")}finally{f(!1)}}},[a,t]),Ee=l.useCallback(async E=>{if(!a||!E){L([]);return}try{const ie=await t(a,"get_mesh_queue",{meshId:E});ie!=null&&ie.success?L(Array.isArray(ie.queue)?ie.queue:[]):L([])}catch{L([])}},[a,t]),ze=l.useCallback(async E=>{var ie;if(!a||!E){re(null),me(""),je("");return}he(!0);try{const xe=await t(a,"get_mesh_host_pairing",{meshId:E});xe!=null&&xe.success?(re(xe),me(xe.hostAddress||((ie=xe.meshHost)==null?void 0:ie.hostAddress)||"")):re({success:!1,error:(xe==null?void 0:xe.error)||"Failed to load Mesh Host pairing"}),je("")}catch(xe){re({success:!1,error:(xe==null?void 0:xe.message)||"Failed to load Mesh Host pairing"}),je("")}finally{he(!1)}},[a,t]);l.useEffect(()=>{De()},[De]),l.useEffect(()=>{Ee(m)},[Ee,m]),l.useEffect(()=>{e||ze(m)},[ze,m,e]);async function Qe(){if(!(!a||!m))try{B(!0),K(null);const E=await t(a,"mesh_status",{meshId:m});if((E==null?void 0:E.success)===!1){$(null),K((E==null?void 0:E.error)||"mesh_status failed");return}const ie=Hu(E);ie?$(ie):($(null),K("mesh_status returned an unexpected payload."))}catch(E){$(null),K((E==null?void 0:E.message)||"Failed to load mesh graph")}finally{B(!1)}}l.useEffect(()=>{m&&($(null),K(null),Qe())},[m]);async function Ze(){var xe;if(!a||!de.trim())return;const E=ce.trim(),ie=fe.trim();if(!(!E&&!ie))try{const ke=await t(a,"create_mesh",{name:de.trim(),repoRemoteUrl:E||void 0,repoIdentity:ie||void 0});ke!=null&&ke.success?(ye(!1),ve(""),ge(""),be(""),await De(),u(((xe=ke.mesh)==null?void 0:xe.id)||null)):b((ke==null?void 0:ke.error)||"Create failed")}catch(ke){b((ke==null?void 0:ke.message)||"Create failed")}}async function rt(E){if(!(!a||!confirm("Delete this mesh?")))try{await t(a,"delete_mesh",{meshId:E}),u(null),await De()}catch(ie){b((ie==null?void 0:ie.message)||"Delete failed")}}async function et(){if(!(!a||!m||!pe.trim()))try{const E=await t(a,"add_mesh_node",{meshId:m,workspace:pe.trim(),providerPriority:vo(Me,i)});E!=null&&E.success?(R(!1),Se(""),ee([]),await De(),await Ee(m)):b((E==null?void 0:E.error)||"Add node failed")}catch(E){b((E==null?void 0:E.message)||"Add node failed")}}async function ct(E){var ke;if(!a||!m)return;const ie=eo(Ne),xe=((ke=xn.find(Ie=>Ie.value===ie.sessionCleanupOnNodeRemove))==null?void 0:ke.label)||"Preserve history and runtimes";if(confirm(`Remove this node?
98
-
99
- Node removal cleanup policy: ${xe}`))try{await t(a,"remove_mesh_node",{meshId:m,nodeId:E}),O===E&&_(null),await De(),await Ee(m)}catch(Ie){b((Ie==null?void 0:Ie.message)||"Remove node failed")}}async function Xe(E){if(!a||!m)return;const ie={...eo(Ne),...E};try{k(!0),b(null);const xe=await t(a,"update_mesh",{meshId:m,policy:ie});if((xe==null?void 0:xe.success)===!1){b(xe.error||"Policy update failed");return}await De()}catch(xe){b((xe==null?void 0:xe.message)||"Policy update failed")}finally{k(!1)}}async function pt(){if(!a||!m)return;const ie={...(Ne==null?void 0:Ne.coordinator)||{}};v.override.trim()?ie.systemPromptOverride=v.override:delete ie.systemPromptOverride,v.append.trim()?ie.systemPromptAppend=v.append:delete ie.systemPromptAppend,delete ie.systemPromptSuffix;try{I(!0),b(null);const xe=await t(a,"update_mesh",{meshId:m,coordinator:ie});if((xe==null?void 0:xe.success)===!1){b(xe.error||"Coordinator prompt save failed");return}await De()}catch(xe){b((xe==null?void 0:xe.message)||"Coordinator prompt save failed")}finally{I(!1)}}async function Ae(E){if(!a||!m)return;const ie=(S[E.id]||"").trim();try{A(E.id),b(null);const xe=await t(a,"update_mesh_node",{meshId:m,nodeId:E.id,systemPrompt:ie});if((xe==null?void 0:xe.success)===!1){b(xe.error||"Node instruction save failed");return}await De()}catch(xe){b((xe==null?void 0:xe.message)||"Node instruction save failed")}finally{A(null)}}async function Fe(){var E;if(!(!a||!m||!ue.trim()||!le.trim())){Ce(!0);try{const ie=await t(a,"configure_mesh_host_pairing",{meshId:m,hostAddress:ue.trim(),token:le.trim()});ie!=null&&ie.success?(re(ie),me(ie.hostAddress||((E=ie.meshHost)==null?void 0:E.hostAddress)||ue.trim()),await De()):re({success:!1,error:(ie==null?void 0:ie.error)||"Failed to save Mesh Host pairing"})}catch(ie){re({success:!1,error:(ie==null?void 0:ie.message)||"Failed to save Mesh Host pairing"})}finally{Ce(!1)}}}async function st(){if(!(!a||!m||!le.trim())){q(!0);try{const E=await t(a,"join_mesh_host_pairing",{meshId:m,token:le.trim()});E!=null&&E.success?(re(E),je(""),await De(),await ze(m),await Qe()):re({success:!1,meshHost:E==null?void 0:E.meshHost,manualPairing:E==null?void 0:E.manualPairing,error:(E==null?void 0:E.error)||"Failed to apply Mesh Host join"})}catch(E){re({success:!1,error:(E==null?void 0:E.message)||"Failed to apply Mesh Host join"})}finally{q(!1)}}}async function qe(E){if(!a||!m)return;const ie=w[E.id]||Tn(E),xe=i.length>0?vo(ie,i):Er(ie),ke={...E.policy||{}};delete ke.provider_priority,xe.length?ke.providerPriority=xe:delete ke.providerPriority;try{p(E.id),b(null);const Ie=await t(a,"update_mesh_node",{meshId:m,nodeId:E.id,policy:ke,providerPriority:xe});if((Ie==null?void 0:Ie.success)===!1){b(Ie.error||"Node policy update failed");return}await De()}catch(Ie){b((Ie==null?void 0:Ie.message)||"Node policy update failed")}finally{p(null)}}if(!a)return s.jsx(br,{icon:s.jsx(Zt,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})});if(!Ne)return s.jsxs(br,{icon:s.jsx(Zt,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>ye(!0),children:"+ Create Mesh"}),children:[y&&s.jsx(_s,{variant:"error",className:"mb-4",children:y}),X&&s.jsx(lt,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(ht,{label:"Name",children:s.jsx(Ss,{value:de,onChange:E=>ve(E.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(ht,{label:"Repo remote URL (optional)",hint:"Provide a remote URL OR a stable identity. Mesh nodes use this to match the same project across machines.",children:s.jsx(Ss,{value:ce,onChange:E=>be(E.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(ht,{label:"Repo identity (optional)",hint:"Provide a remote URL OR a stable identity. Mesh nodes use this to match the same project across machines.",children:s.jsx(Ss,{value:fe,onChange:E=>ge(E.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:Ze,disabled:!de.trim()||!ce.trim()&&!fe.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>{ye(!1),ve(""),ge(""),be("")},children:"Cancel"})]})]})}),h?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):c.length===0?s.jsx(zn,{icon:s.jsx(Zt,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:c.map(E=>s.jsxs("button",{className:"text-left w-full p-4 rounded-xl border border-border-subtle bg-bg-panel hover:border-accent-primary/40 transition-colors",onClick:()=>u(E.id),children:[s.jsx("div",{className:"font-semibold text-sm",children:E.name}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:E.repoIdentity||"No repo identity"}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[E.nodes.length," node(s)"]})]},E.id))})]});const Ke=eo(Ne),U=(Y==null?void 0:Y.meshHost)||Ne.meshHost||{},z=((te=Y==null?void 0:Y.manualPairing)==null?void 0:te.status)||((H=U.pairing)==null?void 0:H.status)||"not_configured",J=((G=Y==null?void 0:Y.manualPairing)==null?void 0:G.description)||"Manual address/token config is saved locally; Apply join sends the token once to the Mesh Host command endpoint. P2P runtime signaling remains outside this slice.";return s.jsxs(br,{icon:s.jsx(Zt,{}),title:Ne.name,subtitle:Ne.repoIdentity||"Repo Mesh",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>u(null),children:"← Back"}),s.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>rt(Ne.id),children:"Delete"})]}),children:[y&&s.jsx(_s,{variant:"error",className:"mb-4",children:y}),!e&&s.jsx(lt,{title:"Mesh Host pairing",description:"Standalone manual pairing. Save a Mesh Host address/token, apply the join to the host command endpoint, then check persisted status.",children:s.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(280px,420px)]",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-4 text-sm",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"text-text-muted",children:"Local role"}),s.jsx("span",{className:"rounded-full border border-accent-primary/25 bg-accent-primary/10 px-2 py-0.5 text-xs font-semibold text-accent-primary",children:U.role||"host"}),s.jsx("span",{className:"text-text-muted",children:"Pairing"}),s.jsx("span",{className:"rounded-full border border-border-subtle px-2 py-0.5 text-xs font-mono text-text-primary",children:ae?"loading":z})]}),s.jsxs("div",{className:"mt-3 grid gap-2 text-xs text-text-muted",children:[s.jsxs("div",{children:["Host address: ",s.jsx("code",{className:"text-text-primary",children:U.hostAddress||"not configured"})]}),s.jsxs("div",{children:["Token id: ",s.jsx("code",{className:"text-text-primary",children:((Z=U.pairing)==null?void 0:Z.tokenId)||"not configured"})]}),s.jsxs("div",{children:["Can own coordinator: ",s.jsx("code",{className:"text-text-primary",children:String(U.canOwnCoordinator??U.role!=="member")})]}),s.jsxs("div",{children:["Can own queue: ",s.jsx("code",{className:"text-text-primary",children:String(U.canOwnQueue??U.role!=="member")})]})]}),s.jsx("p",{className:"mt-3 text-xs leading-relaxed text-text-secondary",children:J}),(Y==null?void 0:Y.error)&&s.jsx("div",{className:"mt-3 rounded-lg border border-red-500/25 bg-red-500/10 px-3 py-2 text-xs text-red-300",children:Y.error})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-panel p-4",children:[s.jsx(ht,{label:"Mesh Host address",hint:"Example: http://127.0.0.1:3847 or a reachable HTTPS/WSS host endpoint.",children:s.jsx(Ss,{value:ue,onChange:E=>me(E.target.value),placeholder:"http://127.0.0.1:3847",disabled:we||V})}),s.jsx(ht,{label:"Pairing token",hint:"The raw token is used once to derive a local token id; it is not displayed after save.",children:s.jsx(Ss,{value:le,onChange:E=>je(E.target.value),placeholder:"paste Mesh Host pairing token",type:"password",disabled:we||V})}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:Fe,disabled:we||V||!ue.trim()||!le.trim(),children:we?"Saving...":"Save manual pairing"}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:st,disabled:V||we||!le.trim(),children:V?"Applying...":"Apply join"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>ze(m),disabled:ae||we||V,children:ae?"Checking...":"Check saved config"})]})]})]})}),s.jsxs(lt,{title:"Policy",description:"Coordinator safety defaults and node-removal session cleanup behavior for this local mesh.",children:[s.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[s.jsx(ht,{label:"Checkpoint before task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ke.requirePreTaskCheckpoint?"yes":"no",onChange:E=>Xe({requirePreTaskCheckpoint:E.target.value==="yes"}),disabled:x,children:[s.jsx("option",{value:"no",children:"No"}),s.jsx("option",{value:"yes",children:"Yes"})]})}),s.jsx(ht,{label:"Checkpoint after task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ke.requirePostTaskCheckpoint?"yes":"no",onChange:E=>Xe({requirePostTaskCheckpoint:E.target.value==="yes"}),disabled:x,children:[s.jsx("option",{value:"yes",children:"Yes"}),s.jsx("option",{value:"no",children:"No"})]})}),s.jsx(ht,{label:"Push approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ke.requireApprovalForPush?"required":"not_required",onChange:E=>Xe({requireApprovalForPush:E.target.value==="required"}),disabled:x,children:[s.jsx("option",{value:"required",children:"Require approval before push"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(ht,{label:"Submodule main auto-publish",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ke.allowAutoPublishSubmoduleMainCommits?"enabled":"disabled",onChange:E=>Xe({allowAutoPublishSubmoduleMainCommits:E.target.value==="enabled"}),disabled:x,children:[s.jsx("option",{value:"disabled",children:"Require explicit approval"}),s.jsx("option",{value:"enabled",children:"Allow Refinery non-force publish"})]})}),s.jsx(ht,{label:"Destructive git approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ke.requireApprovalForDestructiveGit?"required":"not_required",onChange:E=>Xe({requireApprovalForDestructiveGit:E.target.value==="required"}),disabled:x,children:[s.jsx("option",{value:"required",children:"Require approval"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(ht,{label:"Dirty workspace behavior",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ke.dirtyWorkspaceBehavior||"warn",onChange:E=>Xe({dirtyWorkspaceBehavior:E.target.value}),disabled:x,children:[s.jsx("option",{value:"warn",children:"Warn and continue"}),s.jsx("option",{value:"block",children:"Block task"}),s.jsx("option",{value:"checkpoint_then_continue",children:"Checkpoint then continue"})]})}),s.jsx(ht,{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(Ke.maxParallelTasks??2),onChange:E=>Xe({maxParallelTasks:Number(E.target.value)}),disabled:x,children:[1,2,3,4,5,6,7,8].map(E=>s.jsx("option",{value:E,children:E},E))})})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(ht,{label:"Node removal session cleanup",hint:"Separate transcript cleanup from runtime/process cleanup. Preserve is safest when completed work may need review.",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ke.sessionCleanupOnNodeRemove||"preserve",onChange:E=>Xe({sessionCleanupOnNodeRemove:E.target.value}),disabled:x,children:xn.map(E=>s.jsx("option",{value:E.value,children:E.label},E.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((ne=xn.find(E=>E.value===Ke.sessionCleanupOnNodeRemove))==null?void 0:ne.description)||xn[0].description})]}),x&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),s.jsxs(lt,{title:"Coordinator prompt",description:"Customize the system prompt for mesh coordinator sessions. Leave both fields empty to use the daemon's built-in prompt. Supports placeholders: {{meshName}}, {{repo}}, {{defaultBranch}}, {{cliType}}, {{nodes}}, {{policy}}, {{tools}}, {{workflow}}, {{rules}}, {{toolExposurePreflight}}.",children:[s.jsx(ht,{label:"Override (replaces default)",hint:"When set, REPLACES the daemon's default base prompt for this mesh. Use placeholders if you still want node/policy/tools to render. Leave empty to keep the default.",children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:v.override,onChange:E=>g(ie=>({...ie,override:E.target.value})),disabled:N,placeholder:"(empty — daemon default applies)"})}),s.jsx(ht,{label:"Append (added after the base)",hint:"Always added after whichever base prompt wins. Use this for mesh-specific rules that should layer on top of the default.",children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:4,value:v.append,onChange:E=>g(ie=>({...ie,append:E.target.value})),disabled:N,placeholder:"(empty — nothing appended at mesh layer)"})}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void pt(),disabled:N,children:N?"Saving…":"Save coordinator prompt"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>g({override:"",append:""}),disabled:N,title:"Clear both fields. Click Save to commit the reset.",children:"Clear"})]})]}),s.jsxs(lt,{title:"Visualization",description:"Live mesh topology: branches, worktrees, sessions, and orphan detection.",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500"}),"healthy"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-amber-500"}),"dirty"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-red-500"}),"error"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-gray-500"}),"offline"]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:Qe,disabled:W,children:W?"Loading...":"Refresh Graph"})]}),F&&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:F}),M?s.jsx(Vu,{status:M,emptyMessage:"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon.",daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:W?"Loading graph...":"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon."})]}),s.jsxs(lt,{title:"Nodes",description:"Workspaces participating in this mesh.",children:[s.jsx("div",{className:"flex justify-end mb-3",children:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>R(!0),children:"+ Add Node"})}),oe&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:"Add Node"}),s.jsx("button",{onClick:()=>R(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(xt,{size:16})})]}),s.jsx(ht,{label:"Workspace Path",children:s.jsx(Ss,{value:pe,onChange:E=>Se(E.target.value),placeholder:"/Users/dev/projects/myapp",autoFocus:!0})}),s.jsx(ht,{label:"Provider Priority",hint:"Order used when launching without an explicit provider. Empty means fail closed unless a provider is selected explicitly.",children:s.jsx(gl,{value:Me,availableProviders:i,onChange:ee})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:et,disabled:!pe.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>R(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),Ne.nodes.length===0?s.jsx(zn,{icon:s.jsx($s,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:Ne.nodes.map(E=>{const ie=Tn(E),xe=jk(E),ke=Sk(E,D),Ie=Ck(E,n),$e=O===E.id,Te=kk(E);return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary cursor-pointer transition-colors ${$e?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`,role:"button",tabIndex:0,onClick:()=>_($e?null:E.id),onKeyDown:Le=>{(Le.key==="Enter"||Le.key===" ")&&(Le.preventDefault(),_($e?null:E.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"text-sm font-medium",children:E.workspace.split("/").pop()}),ke.length>0&&s.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-orange-500/15 text-orange-300 border border-orange-500/25",children:[ke.length," active task",ke.length===1?"":"s"]}),Te&&s.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-cyan-500/15 text-cyan-300 border border-cyan-500/25",children:"worktree"})]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:E.workspace}),Te&&s.jsxs("div",{className:"mt-2 rounded-lg border border-cyan-500/20 bg-cyan-500/10 px-3 py-2 text-[11px] text-cyan-200",children:["Worktree node",E.worktreeBranch?` · ${E.worktreeBranch}`:"",". Provider priority saved here is node-local and disappears when this worktree node is removed."]}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:Le=>Le.stopPropagation(),children:[s.jsxs(ht,{label:"Provider priority",hint:Te?"Worktree-local launch defaults. Configure the source node for durable defaults.":"Used when launches omit an explicit provider. Empty keeps fail-closed behavior until a provider is selected manually.",children:[s.jsx(gl,{value:w[E.id]??ie,availableProviders:i,onChange:Le=>C(Ue=>({...Ue,[E.id]:Le})),disabled:j===E.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:Le=>{Le.stopPropagation(),qe(E)},disabled:j===E.id,children:j===E.id?"Saving...":"Save policy"})}),s.jsxs("div",{className:"mt-2 text-[12px]",children:[s.jsx("span",{className:"text-text-muted",children:"Effective provider priority: "}),s.jsx("span",{className:xe.configured?"text-text-primary font-mono":"text-amber-400",children:xe.label}),xe.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",xe.launchBlockedMessage,")"]})]})]}),s.jsxs(ht,{label:"Node instruction (optional)",hint:"Surfaced in the coordinator system prompt as 📌 Node instruction. The coordinator quotes it verbatim when delegating tasks to this node.",children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:S[E.id]??"",onChange:Le=>{const Ue=Le.target.value;T(dt=>({...dt,[E.id]:Ue}))},onClick:Le=>Le.stopPropagation(),disabled:P===E.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:Le=>{Le.stopPropagation(),Ae(E)},disabled:P===E.id,children:P===E.id?"Saving…":"Save instruction"})})]})]})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:Le=>{Le.stopPropagation(),ct(E.id)},children:s.jsx(xt,{size:14})})]}),$e&&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:E.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:xe.configured?"text-green-400":"text-amber-400",children:xe.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:E.repoRoot||E.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",Ie.length]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Branch / git:"})," not loaded in standalone list view"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Health:"})," ",ke.length>0||Ie.length>0?"active":"idle/unknown"]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),ke.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:ke.map(Le=>s.jsx("li",{className:"font-mono",children:Nk(Le)},Le.id))})]}),Ie.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active sessions"}),s.jsx("ul",{className:"m-0 pl-4",children:Ie.map(Le=>s.jsxs("li",{className:"font-mono",children:[Le.provider," / ",Le.status," / ",Le.id]},Le.id))})]})]})]},E.id)})})]}),s.jsx(Ik,{meshId:Ne.id,availableCliAgents:o})]})}function wi(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Tk(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=wi();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 Ft(e,t){return await fetch(Tk(e),{credentials:"same-origin",...t})}function Qu(){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 Ak{constructor(){We(this,"adapters",new Map);We(this,"states",new Map);We(this,"runtimeListeners",new Map);We(this,"screenshotCallbacks",new Map);We(this,"statusCallbacks",new Set);We(this,"stateChangeCallbacks",new Set);We(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 Ft(`${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 Ot=new Ak;function _k(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=wi();return r?`${t}?token=${encodeURIComponent(r)}`:t}const bn=_k(),uc=3e3,Lk=3e4;let Dt=null,Pk=0;const Qn=new Map;let is=null,vr=null;function mc(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function ir(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function Rk(e){return e==="connected"?"connected":e}async function wr(e,t,r){const n=Pd(e,r||{}),a=Dt;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++Pk}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{Qn.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);Qn.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 To(e,t){const r=Dt;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 Zu(e,t,r){const n=Dt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Pd(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}}Ot.registerPtyInputSender(Zu);class Dk{constructor(t){We(this,"daemonId");We(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Dt==null?void 0:Dt.readyState)===WebSocket.OPEN}get connectionState(){return(Dt==null?void 0:Dt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return wr(this.daemonId,t,r)}async sendInput(t,r){return wr(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,is&&(clearInterval(is),is=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await wr(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());Ot.emitScreenshot(this.daemonId,a)}}catch{}};r(),is=setInterval(r,2e3)}stopScreenshots(t){is&&(clearInterval(is),is=null)}}let Mt=null;function Ek(e){return(!Mt||Mt.daemonId!==e)&&(Mt=new Dk(e)),Mt}function $k({children:e}){const t=l.useRef(kr()),r=kr();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),vr==null||vr(x,k)},[]),m=l.useRef(null),u=l.useRef(),h=l.useRef(uc),f=l.useRef(!0),y=l.useRef(!1),b=l.useRef("initial_connect");return l.useEffect(()=>{f.current=!0,y.current=!1;function x(){var p,w;if(!f.current||((p=m.current)==null?void 0:p.readyState)===WebSocket.OPEN||((w=m.current)==null?void 0:w.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${bn}...`),ir("connect_attempt",{url:bn,reason:b.current,delayMs:h.current});let j;try{j=new WebSocket(bn)}catch(C){console.error("[Standalone WS] Failed to create WebSocket:",C),k();return}m.current=j,j.onopen=()=>{if(!f.current){j.close();return}d("connected"),h.current=uc,ir("open",{url:bn,reason:b.current}),Gt.resubscribeAll({sendData:To}),console.log("[Standalone WS] Connected")},Dt=j,j.onmessage=C=>{var v,g;try{const N=JSON.parse(C.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const I=Qn.get(N.requestId);I&&(Qn.delete(N.requestId),N.type==="error"?I.reject(new Error(((v=N.data)==null?void 0:v.message)||"Command failed")):I.resolve(N.data));return}if(N.type==="session_output"){const I=N.sessionId||N.cliId||N.cliType;I&&Ot.emitSessionOutput(I,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){Ot.emitRuntimeSnapshot(N.sessionId,typeof N.text=="string"?N.text:"",typeof N.seq=="number"?N.seq:0,!!N.truncated,typeof N.cols=="number"?N.cols:void 0,typeof N.rows=="number"?N.rows:void 0);return}if(N.type==="topic_update"){const I=N.update;I&&Gt.publish(I);return}if(N.type==="status"||N.type==="initial_state"){const I=N.data;if(!I)return;const{injectEntries:S,markLoaded:T,getIdes:P}=t.current,A=I.instanceId||"standalone",D=P().find(_=>_.id===A),L=Ek(A);Ot.register(A,L),Ot.setState(A,"connected"),d("connected",A),Ot.emitStatus(A,I);const O=$n(I,{daemonId:A,existingDaemon:D,existingEntries:P()});mc("ws_status",{type:N.type,daemonId:A,sessions:(I.sessions||[]).map(_=>({id:_.id,parentId:_.parentId,providerType:_.providerType,kind:_.kind,transport:_.transport,unread:_.unread,inboxBucket:_.inboxBucket,lastSeenAt:_.lastSeenAt,lastUpdated:_.lastUpdated,title:_.title})),recentLaunches:(I.recentLaunches||[]).map(_=>({id:_.id,providerType:_.providerType,kind:_.kind,workspace:_.workspace,lastLaunchedAt:_.lastLaunchedAt}))}),mc("entries",{daemonId:A,entries:O.filter(_=>_.type!=="adhdev-daemon").map(_=>({id:_.id,type:_.type,unread:_.unread,inboxBucket:_.inboxBucket,lastSeenAt:_.lastSeenAt,lastUpdated:_.lastUpdated,sessionId:_.sessionId}))}),O.length>0&&S(O,{authoritativeDaemonIds:[A]}),T(),i.current!==A&&((g=o.current)==null||g.call(o),i.current=A,o.current=Gt.subscribe({sendData:To},A,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${A}`,params:{includeSessions:!0}},_=>{if(_.topic!=="daemon.metadata")return;const M=t.current.getIdes(),$=M.find(B=>B.id===A),W=$n(_.status,{daemonId:A,existingDaemon:$,existingEntries:M,timestamp:_.timestamp});W.length>0&&t.current.injectEntries(W,{authoritativeDaemonIds:[A]}),_.userName&&a.current&&a.current(_.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},j.onclose=C=>{f.current&&(Mt==null||Mt.stopScreenshots(),Mt&&Ot.setState(Mt.daemonId,"disconnected"),d("disconnected"),m.current=null,b.current=`close:${C.code}${C.wasClean?":clean":":unclean"}`,ir("close",{code:C.code,reason:C.reason||"",wasClean:C.wasClean}),k())},j.onerror=C=>{y.current||!f.current||(b.current="error",ir("error",{message:C instanceof Event?"event":String(C),readyState:j.readyState}),console.warn("[Standalone WS] Error, will reconnect:",C))}}function k(){if(!f.current)return;clearTimeout(u.current);const j=h.current;console.log(`[Standalone WS] Reconnecting in ${j}ms...`),ir("schedule_reconnect",{reason:b.current,delayMs:j}),u.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,Lk),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,Dt=null),Mt&&(Mt.stopScreenshots(),Ot.unregister(Mt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function Bk({children:e}){const[t,r]=l.useState("disconnected"),[n,a]=l.useState(null);l.useEffect(()=>(vr=(i,c)=>{r(i),c&&a(c)},()=>{vr=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=Rk(t),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d}},[t,n]);return s.jsx(ch,{connectionOverrides:o,children:s.jsx($k,{children:e})})}const em="adhdev_standalone_font_preferences",bs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},da=[{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"}],Mr=[{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"}],Ok=new Set(da.map(e=>e.id)),Fk=new Set(Mr.map(e=>e.id));function Wt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:An("chat",t.chat),code:An("code",t.code),terminal:An("terminal",t.terminal)}}function An(e,t){const r=bs[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"?Ok:Fk).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function _n(e,t){var a;const r=An(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?da:Mr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function Hk(e){const t=Wt(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 cs(e,t=document.documentElement){const r=Wt(e),n=Hk(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function Ao(e){const t=Wt(e);try{localStorage.setItem(em,JSON.stringify(t))}catch{}return t}function Wk(){try{const e=localStorage.getItem(em);if(e)return Wt(JSON.parse(e))}catch{}return bs}function Kk(){return cs(Wk())}function lr(e,t){var n;const r=e==="chat"?da:Mr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const Uk=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Sc,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(ts,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(Os,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(ea,{}),label:"Settings"}];function zk({children:e}){const t=Tr(),r=Lo(),n=l.useMemo(()=>Uk.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(Cc,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Ic,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Hb,{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 Gk=[{icon:s.jsx(ts,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(ws,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Mc,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Bt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Os,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Cc,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Vk=[{icon:s.jsx(Th,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Sc,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Ar,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(kh,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Nc,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Nh,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],qk=[{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 Yk(){return s.jsxs(br,{icon:s.jsx(Ic,{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(lt,{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(lt,{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:Gk.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(lt,{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:Rd.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Ed.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Dd.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(lt,{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:Vk.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(lt,{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:qk.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(zn,{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(Bh,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function to(e,t,r){return{...e,[t]:r}}function so({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 Xk({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(so,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:da,onChange:u=>o(to(e,"chat",u))}),s.jsx(so,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Mr,onChange:u=>o(to(e,"code",u))}),s.jsx(so,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Mr,onChange:u=>o(to(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: ",lr("chat",e.chat.preset)," · Code: ",lr("code",e.code.preset)," · Terminal: ",lr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",lr("chat",bs.chat.preset)," / ",lr("code",bs.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 Jk(){const{ides:e}=qt(),t=e.find(V=>V.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),[h,f]=l.useState(bs),[y,b]=l.useState(!1),[x,k]=l.useState(""),[j,p]=l.useState(""),[w,C]=l.useState("127.0.0.1"),[v,g]=l.useState(""),[N,I]=l.useState(""),[S,T]=l.useState(""),[P,A]=l.useState(""),[D,L]=l.useState(""),[O,_]=l.useState(!1),M=async()=>{const q=await(await Ft("/auth/session")).json();d(q)},$=async()=>{const q=await(await Ft("/api/v1/standalone/preferences")).json();u(q),C(q.standaloneBindHost);const ue=Wt(q.standaloneFontPreferences);f(ue),cs(ue),Ao(ue)};l.useEffect(()=>{a!==void 0&&i(a)},[a]),l.useEffect(()=>{Promise.all([M(),$()]).catch(V=>{A(V instanceof Error?V.message:String(V))})},[]),l.useEffect(()=>{cs(h)},[h]);const W=V=>{const q=V.target.value.trim();t!=null&&t.id&&q!==a&&n(t.id,"set_user_name",{userName:q}).catch(console.error)},[B,F]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),K=V=>{F(V);try{localStorage.setItem("adhdev_sound",V?"1":"0")}catch{}},Y=async()=>{k(""),p(""),b(!0);try{const V=Wt(h),q=await Ft("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:V})}),ue=await q.json();if(!q.ok)throw new Error((ue==null?void 0:ue.error)||"Failed to save standalone font preferences");const me=Wt(ue.standaloneFontPreferences);u(ue),f(me),cs(me),Ao(me),p("Standalone chat fonts saved for this self-hosted dashboard.")}catch(V){k(V instanceof Error?V.message:String(V))}finally{b(!1)}},re=()=>{const V=Wt(m==null?void 0:m.standaloneFontPreferences);k(""),p(""),f(V),cs(V)},ae=()=>{k(""),p(""),f(bs),cs(bs)},he=async()=>{A(""),L(""),_(!0);try{const V=await Ft("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:w})}),q=await V.json();if(!V.ok)throw new Error((q==null?void 0:q.error)||"Failed to save standalone network preference");u(q),C(q.standaloneBindHost),L(q.standaloneBindHost==="0.0.0.0"?"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.":"Default standalone network mode set to localhost only. Restart standalone to apply it.")}catch(V){A(V instanceof Error?V.message:String(V))}finally{_(!1)}},we=async()=>{if(A(""),L(""),N.trim().length<4){A("Password must be at least 4 characters.");return}if(N!==S){A("New password and confirmation do not match.");return}_(!0);try{const V=await Ft("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:N})}),q=await V.json();if(!V.ok)throw new Error((q==null?void 0:q.error)||"Failed to save password");d(q),await $(),g(""),I(""),T(""),L(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Qu()}catch(V){A(V instanceof Error?V.message:String(V))}finally{_(!1)}},Ce=async()=>{A(""),L(""),_(!0);try{const V=await Ft("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),q=await V.json();if(!V.ok)throw new Error((q==null?void 0:q.error)||"Failed to clear password");d(q),await $(),g(""),I(""),T(""),L("Standalone password disabled.")}catch(V){A(V instanceof Error?V.message:String(V))}finally{_(!1)}};return s.jsxs(br,{icon:s.jsx(ea,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(_s,{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(_s,{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(lt,{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(lt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:w==="127.0.0.1",onChange:()=>C("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:w==="0.0.0.0",onChange:()=>C("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:()=>{he()},disabled:O,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:O?"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(lt,{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."}),P&&s.jsx(_s,{variant:"error",children:P}),D&&s.jsx(_s,{variant:"success",children:D}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:c!=null&&c.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:v,onChange:V=>g(V.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:N,onChange:V=>I(V.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:V=>T(V.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{we()},disabled:O,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:O?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{Ce()},disabled:O,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(lt,{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(V=>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 ${V.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:V.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:V.type})]},V.type))})}),s.jsx(lt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Xb,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(lt,{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(eg,{daemonId:t==null?void 0:t.id})}),s.jsx(lt,{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(sg,{})]}),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(dg,{})]}),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(Xk,{value:h,savedValue:Wt(m==null?void 0:m.standaloneFontPreferences),saving:y,error:x,notice:j,onChange:f,onSave:()=>{Y()},onResetToSaved:re,onResetToDefaults:ae})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),s.jsx(hg,{})]})]})}),s.jsx(lt,{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(Vb,{}),s.jsx(ls,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx($h,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:B,onChange:K})]})}),s.jsx(lt,{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(jh,{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:V=>i(V.target.value),onBlur:W,onKeyDown:V=>{V.key==="Enter"&&V.currentTarget.blur()}})]})})})]})}const Qk=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],mr="adhdev_onboarding_done",Zk=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],e1={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function t1({onDone:e}){const[t,r]=l.useState([]),[n,a]=l.useState(new Set(Qk)),[o,i]=l.useState(!0),[c,d]=l.useState(null),[m,u]=l.useState(!1),[h,f]=l.useState(null),[y,b]=l.useState("all");l.useEffect(()=>{let v=!1;const g=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${g}/providers?sort=popular&limit=100`).then(N=>{if(!N.ok)throw new Error(`HTTP ${N.status}`);return N.json()}).then(N=>{v||r(N.providers??[])}).catch(N=>{v||d(N instanceof Error?N.message:String(N))}).finally(()=>{v||i(!1)}),()=>{v=!0}},[]);const x=t.filter(v=>y==="all"||v.category===y),k=["cli","ide","extension","acp"].map(v=>({category:v,items:x.filter(g=>g.category===v)})).filter(v=>v.items.length>0),j=l.useCallback(v=>{a(g=>{const N=new Set(g);return N.has(v)?N.delete(v):N.add(v),N})},[]),p=l.useCallback(async()=>{if(n.size===0){localStorage.setItem(mr,"1"),e();return}u(!0);const v=[];for(const g of n)try{const I=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:g})})).json().catch(()=>({}));v.push({type:g,ok:!!I.success,error:I.error})}catch(N){v.push({type:g,ok:!1,error:N instanceof Error?N.message:String(N)})}f(v),u(!1),v.every(g=>g.ok)&&localStorage.setItem(mr,"1")},[n,e]),w=l.useCallback(()=>{localStorage.setItem(mr,"1"),e()},[e]),C=l.useCallback(()=>{h&&h.every(v=>v.ok)?e():m||w()},[h,m,e,w]);return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60",onClick:C,children:s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-2xl max-w-2xl w-full p-6 flex flex-col gap-5 max-h-[85vh] overflow-y-auto",onClick:v=>v.stopPropagation(),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Welcome to ADHDev"}),s.jsxs("div",{className:"text-[12px] text-text-muted mt-1",children:["Pick the providers you want to use. Defaults to the four officially supported CLI providers; you can install IDE, ACP, or extension providers from the tabs below or later from ",s.jsx("span",{className:"text-text-secondary",children:"Burrow → Providers → Add provider"}),"."]})]}),!o&&!c&&t.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:Zk.map(v=>{const g=v.key==="all"?t.length:t.filter(N=>N.category===v.key).length;return g===0&&v.key!=="all"?null:s.jsxs("button",{onClick:()=>b(v.key),className:`machine-btn text-[10px] px-2 py-0.5 ${y===v.key?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:[v.label," ",s.jsxs("span",{className:"opacity-60",children:["(",g,")"]})]},v.key)})}),o&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"Loading registry…"}),!o&&c&&s.jsxs("div",{className:"rounded-xl border border-red-500/30 bg-red-500/5 px-3 py-2 text-[12px] text-red-400",children:["Failed to load registry: ",c]}),!o&&!c&&x.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"No providers in this category."}),!o&&!c&&x.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:k.map(v=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:e1[v.category]??v.category}),s.jsx("div",{className:"grid gap-1.5",children:v.items.map(g=>{var P,A;const N=n.has(g.type),I=h==null?void 0:h.find(D=>D.type===g.type),S=((P=g.manifest)==null?void 0:P.icon)??"📦",T=((A=g.manifest)==null?void 0:A.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${N?"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:N,onChange:()=>j(g.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:g.displayName}),T&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:T})]}),I&&s.jsx("span",{className:`text-[10px] font-semibold ${I.ok?"text-green-400":"text-red-400"}`,children:I.ok?"✓ installed":`✗ ${I.error??"failed"}`})]},g.type)})})]},v.category))}),s.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-border-subtle",children:[s.jsxs("div",{className:"text-[11px] text-text-muted",children:[n.size," provider",n.size!==1?"s":""," selected"]}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx("button",{onClick:w,disabled:m,className:"machine-btn text-[11px] px-3 py-1",children:"Skip"}),s.jsx("button",{onClick:()=>{h?(localStorage.setItem(mr,"1"),e()):p()},disabled:m||!h&&n.size===0,className:"machine-btn text-[11px] px-3 py-1 bg-violet-500/15 border-violet-500/40 text-violet-400 hover:bg-violet-500/25",children:m?"Installing…":h?"Done":`Install ${n.size}`})]})]})]})})}function s1(){try{return localStorage.getItem(mr)==="1"}catch{return!1}}Ob();lg();Kk();const r1=vc({baseUrl:"",getToken:wi});function n1({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),h=async()=>{a(!0),d("");try{const b=await(await Ft("/auth/session")).json();r(b)}catch(y){d(y instanceof Error?y.message:String(y))}finally{a(!1)}};l.useEffect(()=>{h()},[]),l.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let y=!1;return(async()=>{try{const b=await Ft("/api/v1/standalone/preferences");if(!b.ok)return;const x=await b.json();if(y)return;const k=Wt(x.standaloneFontPreferences);cs(k),Ao(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 b=await Ft("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),x=await b.json();if(!b.ok)throw new Error((x==null?void 0:x.error)||"Login failed");r(x),i(""),Qu()}catch(b){d(b instanceof Error?b.message:String(b))}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 hc(){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(ao,{to:`/machines/${r.id}`,replace:!0}):s.jsx(ao,{to:"/dashboard",replace:!0})}function a1(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let r=!1;if(!s1())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(t1,{onDone:()=>t(!1)}):null}function o1(){const e=l.useMemo(()=>({sendCommand:wr,sendData:To,sendPtyInput:Zu}),[]);return s.jsx(Vm,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(mh,{client:r1,children:s.jsx(n1,{children:s.jsx(Bk,{children:s.jsx(ph,{value:e,children:s.jsx(gh,{sendDaemonCommand:wr,children:s.jsxs(zk,{children:[s.jsx(a1,{}),s.jsxs(qm,{children:[s.jsx(Jt,{path:"/dashboard",element:s.jsx(uj,{})}),s.jsx(Jt,{path:"/machine",element:s.jsx(hc,{})}),s.jsx(Jt,{path:"/machines/:id",element:s.jsx(vk,{})}),s.jsx(Jt,{path:"/machines",element:s.jsx(hc,{})}),s.jsx(Jt,{path:"/about",element:s.jsx(Yk,{})}),s.jsx(Jt,{path:"/settings",element:s.jsx(Jk,{})}),s.jsx(Jt,{path:"/mesh",element:s.jsx(Mk,{hideHostPairing:!0})}),s.jsx(Jt,{path:"*",element:s.jsx(ao,{to:"/dashboard",replace:!0})})]})]})})})})})})})}Vx({connectionManager:Ot});Ym(document.getElementById("root")).render(s.jsx(o1,{}));