@adhdev/daemon-standalone 0.9.82-rc.333 → 0.9.82-rc.334
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.
- package/dist/index.js +607 -528
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/index-UtQU55ZC.js +113 -0
- package/public/index.html +1 -1
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-DsCRNxW_.js","assets/vendor-BHUMCOj6.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
var Zm=Object.defineProperty;var eh=(e,t,r)=>t in e?Zm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ze=(e,t,r)=>eh(e,typeof t!="symbol"?t+"":t,r);import{r as l,j as s,M as ti,a as th,b as sh,c as rh,R as Ct,d as Er,t as nh,e as ah,u as Kr,D as oh,f as So,g as Co,E as ih,i as lh,C as ch,h as dh,B as uh,k as ph,l as mh,m as hh,H as dn,P as ds,n as fh,o as xh,p as bh,q as gh,s as yh,v as vh,w as si,x as wh,y as jh,z as kh,A as Nh,F as us,N as Io,G as Sh}from"./vendor-BHUMCOj6.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&n(i)}).observe(document,{childList:!0,subtree:!0});function r(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(a){if(a.ep)return;a.ep=!0;const o=r(a);fetch(a.href,o)}})();function Ch(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 Js=Ch();function ll(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 Ih(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function cl(e){return Array.isArray(e)?[...e]:[]}function pd(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?cl(e.messages):i?[]:t.messages,activeModal:n?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...r?{messages:cl(e.messages)}:{},...n?{activeModal:e.activeModal??null}:{}}}function Nr(e,t){const r=Ih(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:pd(e.activeChat,t==null?void 0:t.activeChat),activeInteractivePrompt:Object.prototype.hasOwnProperty.call(e,"activeInteractivePrompt")?e.activeInteractivePrompt??null:(t==null?void 0:t.activeInteractivePrompt)??null,controlValues:e.controlValues??(t==null?void 0:t.controlValues),providerControls:e.providerControls??(t==null?void 0:t.providerControls),summaryMetadata:e.summaryMetadata??(t==null?void 0:t.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(t==null?void 0:t.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(t==null?void 0:t.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(t==null?void 0:t.lastMessagePreview),lastMessageRole:e.lastMessageRole??(t==null?void 0:t.lastMessageRole),lastMessageAt:e.lastMessageAt??(t==null?void 0:t.lastMessageAt),lastMessageHash:e.lastMessageHash??(t==null?void 0:t.lastMessageHash),unread:e.unread??(t==null?void 0:t.unread),lastSeenAt:e.lastSeenAt??(t==null?void 0:t.lastSeenAt),inboxBucket:e.inboxBucket??(t==null?void 0:t.inboxBucket),completionMarker:e.completionMarker??(t==null?void 0:t.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(t==null?void 0:t.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(t==null?void 0:t.surfaceHidden),resume:e.resume??(t==null?void 0:t.resume),runtimeKey:e.runtimeKey??(t==null?void 0:t.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(t==null?void 0:t.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(t==null?void 0:t.runtimeWorkspaceLabel),settings:e.settings??(t==null?void 0:t.settings)}}function md(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?Nr(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 dl(e){return!!e&&typeof e=="object"&&"text"in e}function ri(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:dl(o)?String(o.text||""):"").join(r):dl(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Xs(e){return ri(e,{normalizeWhitespace:!0})}const hd=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}),fd=l.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function ul(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 xd(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 Mh(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 Ta(e){if(!e||typeof e!="object")return"";const t=e,r=Mh(Xs(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 Ah(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=Ta(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:Ta(e[0]),last:Ta(e[e.length-1])}}function Mo(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function Ao(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(Mo(e)&&Mo(t)){const i=e.messages;Array.isArray(i)&&i===t.messages&&r.add(i)}if(Array.isArray(e)&&Array.isArray(t)){const i=Math.min(e.length,t.length);for(let c=0;c<i;c+=1)Ao(e[c],t[c],r);return}const n=e,a=t,o=new Set([...Object.keys(n),...Object.keys(a)]);for(const i of o)i!=="messages"&&Ao(n[i],a[i],r)}function Mr(e,t){return Array.isArray(e)?e.map(r=>Mr(r,t)):!e||typeof e!="object"?e:Mo(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Ah(a,t):Mr(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,Mr(n,t)]))}function Th(e,t){try{const r=new WeakSet;return Ao(e,t,r),JSON.stringify(Mr(e,r))===JSON.stringify(Mr(t,r))}catch{return!1}}function To(e,t,r){return Th(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function bd(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function _h(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function pl(e,t,r,n){var d;const a=(d=t.chats)!=null&&d.length?t.chats:e.chats,o=md(e.childSessions,t.childSessions,{preserveMissing:n}),i=pd(t.activeChat,e.activeChat),c=t.workspace||e.workspace;return xd(e,t,{...e,...t,chats:a,childSessions:o,activeChat:i,workspace:c,_lastUpdate:r})}function Rh(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=md(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(n.chats=t.chats),t.workspace&&(n.workspace=t.workspace);for(const i of["title","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","activeInteractivePrompt","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])_h(n,t,i);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function Ph(e,t,r,n){const a=Rh(e,t,n),o=Object.keys(a).length>0?xd(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return To(e,o,r)}function Lh(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=bd(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 Dh(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 $h(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function Eh(e,t,r){var p,m;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(h=>({...h,_lastUpdate:n}));const o=new Map;for(const h of t)o.set(h.id,h);const{incomingIds:i,incomingDaemonIds:c,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:u}=Lh(e);for(const h of e){const b=o.get(h.id);if(!b){o.set(h.id,{...h,_lastUpdate:n});continue}const g=ul(h),f=ul(b),v=bd(h),j=!a.has(v);if(g>f){const N=pl(b,h,n,j);o.set(h.id,To(b,N,n));continue}if(g<f){o.set(h.id,Ph(b,h,n,j));continue}const y=h.timestamp||n,w=b._lastUpdate||b.timestamp||0;if(y>=w){const N=pl(b,h,n,j);o.set(h.id,To(b,N,n));continue}(p=h.chats)!=null&&p.length&&!((m=b.chats)!=null&&m.length)&&o.set(h.id,{...b,chats:h.chats})}for(const[h,b]of o){const g=b.daemonId||h.split(":")[0];if(!c.has(g))continue;if(a.has(g)&&u.has(g)&&!i.has(h)){o.delete(h);continue}const f=n-(b._lastUpdate||b.timestamp||0);Dh(b,g,f,i,a,d)&&o.delete(h)}for(const[h,b]of o){const g=b.daemonId||h.split(":")[0];if($h(b,g,c,d,o))continue;n-(b._lastUpdate||b.timestamp||0)>3e5&&b.status!=="online"&&o.delete(h)}return Array.from(o.values())}function Bh(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 Fh({children:e,connectionOverrides:t}){const[r,n]=l.useState([]),[a,o]=l.useState(!1),[i,c]=l.useState([]),[d,u]=l.useState(void 0),p=l.useRef(r);l.useEffect(()=>{p.current=r},[r]);const m=l.useCallback((j,y)=>{n(w=>{let N=!1;const k=w.map(x=>x.id!==j||x.chats===y?x:(N=!0,{...x,chats:y}));return N?k:w})},[]),h=l.useCallback((j,y)=>{n(w=>{const N=w.length===0?j:Eh(j,w,y),k=!Bh(w,N);return k&&Js.record({kind:"dashboard.entries_applied",payload:{incoming:ll(j),next:ll(N)}}),k?N:w})},[]),b=l.useCallback(()=>o(!0),[]),g=l.useMemo(()=>({injectEntries:h,markLoaded:b,getIdes:()=>p.current}),[h,b]),f=t,v=l.useMemo(()=>({ides:r,updateRouteChats:m,initialLoaded:a,toasts:i,setToasts:c,wsStatus:(f==null?void 0:f.wsStatus)??"connected",isConnected:(f==null?void 0:f.isConnected)??!0,connectionStates:(f==null?void 0:f.connectionStates)??{},connectionTransports:(f==null?void 0:f.connectionTransports)??{},showReconnected:(f==null?void 0:f.showReconnected)??!1,retryConnection:f==null?void 0:f.retryConnection,retryServerConnection:f==null?void 0:f.retryServerConnection,connectionLoginUrl:f==null?void 0:f.connectionLoginUrl,isP2PActive:(f==null?void 0:f.isP2PActive)??!1,p2pStates:(f==null?void 0:f.p2pStates)??{},userRole:f==null?void 0:f.userRole,connectionRetryStatuses:f==null?void 0:f.connectionRetryStatuses,userName:d,setUserName:u}),[r,m,a,i,f==null?void 0:f.wsStatus,f==null?void 0:f.isConnected,f==null?void 0:f.connectionStates,f==null?void 0:f.connectionTransports,f==null?void 0:f.showReconnected,f==null?void 0:f.retryConnection,f==null?void 0:f.retryServerConnection,f==null?void 0:f.connectionLoginUrl,f==null?void 0:f.isP2PActive,f==null?void 0:f.p2pStates,f==null?void 0:f.userRole,f==null?void 0:f.connectionRetryStatuses,d]);return s.jsx(fd.Provider,{value:g,children:s.jsx(hd.Provider,{value:v,children:e})})}function ss(){return l.useContext(hd)}function Br(){return l.useContext(fd)}function gd(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(),u=a(c),p=c.startsWith("http")?new URL(u):new URL(u,typeof window<"u"?window.location.origin:"http://localhost");return d&&p.searchParams.set("token",d),!c.startsWith("http")&&!t?`${p.pathname}${p.search}${p.hash}`:p.toString()}async function i(c,d={}){const u={"Content-Type":"application/json",...d.headers||{}},p=r==null?void 0:r();p&&(u.Authorization=`Bearer ${p}`);const m=a(c),h=new AbortController,b=setTimeout(()=>h.abort(),15e3);try{const g=await fetch(m,{...d,headers:u,signal:h.signal});if(g.status===401)throw n==null||n(),new Error("Unauthorized");if(!g.ok){const f=await g.json().catch(()=>({error:g.statusText}));throw new Error(f.error||`API Error: ${g.status}`)}return g.json()}finally{clearTimeout(b)}}return{getDaemons:()=>i("/api/v1/daemons"),getDaemonStatus:c=>i(`/api/v1/daemons/${c}/status`),sendCommand:(c,d,u={})=>i(`/api/v1/daemons/${c}/command`,{method:"POST",body:JSON.stringify({type:d,payload:u})}),execTerminal:(c,d,u)=>i(`/api/v1/daemons/${c}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:u})}),sendAgentMessage:(c,d,u)=>i(`/api/v1/shortcuts/${c}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:u})}),getAgentStatus:c=>i(`/api/v1/shortcuts/${c}/status`),approveAgent:(c,d,u)=>i(`/api/v1/shortcuts/${c}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:u?"approve":"reject"})}),getMuxState:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/state`),getMuxSocketInfo:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/socket-info`),controlMux:(c,d,u={})=>i(`/api/v1/mux/${encodeURIComponent(c)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:u})}),getMuxEventsUrl:c=>o(`/api/v1/mux/${encodeURIComponent(c)}/events`),getRuntimeEventsUrl:c=>o(`/api/v1/runtime/${encodeURIComponent(c)}/events`),request:i}}const Oh=gd({baseUrl:"http://localhost:3847"}),Hh=l.createContext(Oh);function zh({client:e,children:t}){return s.jsx(Hh.Provider,{value:e,children:t})}const Wh={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},yd=l.createContext(Wh);function Kh({value:e,children:t}){return s.jsx(yd.Provider,{value:e,children:t})}function mt(){return l.useContext(yd)}function vd(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function Uh(e){const t=vd(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 Gh(e){const[t,r]=l.useState(null),n=l.useCallback(async(i,c)=>{const d=m=>e(i,"launch_cli",{...c,...m}),u=await d({}),p=Uh(u);return p?new Promise(m=>{r({providerType:p.providerType||String(c.cliType??"?"),sourceName:p.sourceName,description:p.description,retry:()=>d({confirmExternalUntrusted:!0}),resolve:h=>{h.cancelled?m({success:!1,error:"user_cancelled_untrusted_launch"}):m(h.response)}})}):u},[e]),a=l.useCallback(async()=>{const i=t;if(i){r(null);try{const c=await i.retry(),d=vd(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 Vh({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 wd=l.createContext(null);function qh({sendDaemonCommand:e,children:t}){const r=Gh(e),n=l.useMemo(()=>({launchCli:r.launchCli}),[r.launchCli]);return s.jsxs(wd.Provider,{value:n,children:[t,r.pending&&s.jsx(Vh,{providerType:r.pending.providerType,sourceName:r.pending.sourceName,description:r.pending.description,onConfirm:r.confirm,onCancel:r.cancel})]})}function ma(){const e=l.useContext(wd);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 Jh(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function jd(e){return e?Yh([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Jh(e.content)]):""}const ze={size:18};function kd({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 ni({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function xs({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),s.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),s.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),s.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function Nd({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"9",cy:"7",r:"4"}),s.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),s.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Xh({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Qh({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function Sd({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),s.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),s.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),s.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function Zh({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),s.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),s.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),s.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),s.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function ha({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Cd({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),s.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function ef({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function tf({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function $s({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function qt({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function ai({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("polyline",{points:"14 2 14 8 20 8"}),s.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),s.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Qs({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function fa({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function Zs({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),s.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function er({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M12 22v-5"}),s.jsx("path",{d:"M9 8V2"}),s.jsx("path",{d:"M15 8V2"}),s.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function as({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"5",r:"2"}),s.jsx("circle",{cx:"5",cy:"19",r:"2"}),s.jsx("circle",{cx:"19",cy:"19",r:"2"}),s.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),s.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),s.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function sf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 Id({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function oi({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),s.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),s.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Md({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function rf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 ii({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"4 17 10 11 4 5"}),s.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function nf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Ad({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Td({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function vt({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function af({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 of({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),s.jsx("path",{d:"M12 2v6"}),s.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function lf({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("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 cf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"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 Ur({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function df({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 uf({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function pf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 _d({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 mf({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function hf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),s.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function ff({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 xf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),s.jsx("path",{d:"M13 2h9v9"}),s.jsx("path",{d:"M22 2L13 11"})]})}function bf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function gf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),s.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),s.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),s.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),s.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),s.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),s.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),s.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),s.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),s.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function yf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function vf({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const Rd="adhdev_chat_activity_visible",ml=new Set(["hidden","debug","internal"]),hl=new Set(["visible","user","chat"]),wf=new Set(["debug","trace","internal"]),jf=new Set(["tool_call","terminal_command","runtime_activity"]),kf=new Set(["runtime_status","provider_chrome","control"]),Nf=new Set(["thought","tool","terminal"]);function Pd(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function zs(e){return typeof e=="string"?e.trim().toLowerCase():""}function _a(e,t,r){return e[r]??(t==null?void 0:t[r])}function fl(e,t,r){const n=e;return r.some(a=>n[a]===!0||(t==null?void 0:t[a])===!0)}function Sf(e,t){const r=zs(e.kind);return r||(t==="tool"?"tool":"standard")}function Ra(e,t,r){const n=Pd(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 Cf(e){const t=e.content;return Array.isArray(t)&&t.some(r=>!!r&&typeof r=="object"&&r.type!=="text")}function li(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=Pd(e),r=zs(e.role),n=Sf(e,r),a=zs(_a(e,t,"visibility")),o=zs(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),i=zs(_a(e,t,"audience")),c=zs(_a(e,t,"source")),d=ml.has(a)||ml.has(o)||wf.has(i)||fl(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),u=hl.has(a)||hl.has(o)||i==="chat"||fl(e,t,["userFacing"]),p=Nf.has(n)||jf.has(c);if(d)return{surface:p?"activity":"internal",isUserFacing:!1,isActivityFacing:p,isInternal:!p,role:r,kind:n,label:Ra(e,n,c)};if(u)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:Ra(e,n,c)};if((r==="system"||n==="system")&&Cf(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:"Chat"};if(kf.has(c)||r==="system"||n==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:r,kind:n,label:"Internal"};if(p)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:r,kind:n,label:Ra(e,n,c)};const m=(r==="user"||r==="human"||r==="assistant")&&(n==="standard"||n==="");return{surface:m?"chat":"internal",isUserFacing:m,isActivityFacing:!1,isInternal:!m,role:r,kind:n,label:m?"Chat":"Internal"}}function If(e){return(Array.isArray(e)?e:[]).filter(t=>li(t).isUserFacing)}function Ld(e){return(Array.isArray(e)?e:[]).filter(t=>li(t).isActivityFacing)}function Mf(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 xl(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(Rd))==="1"}catch{return!1}}const Dd=[th,{singleTilde:!1}],$d=[Dd,sh,rh],Af=[Dd],ci=200,Tf=80,bl=650,dr=new Map;function Gn(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function _f(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}:${jd(n)}`}function Rf(e,t,r,n){return e||!t?!1:Gn(r,n)}function Pf({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=Tf,bottomThresholdPx:a=ci}){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 Lf(e){return Pf({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Sr(e,t=ci){return!!e&&e.fromBottom>=t}function Df(e,t){return Gn(e,t)?!Sr(e):!0}function $f({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function Ef({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 Ed(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Bf(e,t,r){return Number(e.receivedAt||r[Vn(e,t)]||0)||0}function Bd(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Ff(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function ur(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 La(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 un(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 gl(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Bd(e)?s.jsx(ti,{remarkPlugins:$d,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}const Of=l.memo(function({content:t,renderAsPreformatted:r,renderAsMarkdown:n}){return r?s.jsx("pre",{className:"chat-preformatted",children:t}):n?s.jsx(ti,{remarkPlugins:$d,children:t}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:t})});function pr({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:gl(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=La(r),o=r.alt||r.description||ur(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:un("Image",o,r.mimeType)},`image-fallback-${n}`)}if(r.type==="audio"){const a=La(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:un("Audio",ur(r.uri,"audio"),r.transcript||r.mimeType)},`audio-fallback-${n}`)}if(r.type==="video"){const a=La(r),o=r.title||r.name||r.alt||ur(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"}):un("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||ur(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}):un("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=ur(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}),gl(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 Vn(e,t){const r=e,n=ri(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 Hf=l.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(ti,{remarkPlugins:Af,children:t.text}),s.jsx("span",{className:"action-time",children:Ed(t.timestamp)})]})},(e,t)=>e.log===t.log);function yl(e){const t=e.meta;return[jd(e),e.kind||"",e.senderName||"",e.bubbleId||"",e.bubbleState||"",e.visibility||"",e.transcriptVisibility||"",e.audience||"",e.source||"",e.userFacing===void 0?"":String(e.userFacing),e.internal===void 0?"":String(e.internal),e.isInternal===void 0?"":String(e.isInternal),e.debug===void 0?"":String(e.debug),t?String(t.label??""):"",t?String(t.isRunning??""):"",t?String(t.renderMode??""):""].join("")}const zf=l.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:i,onToggleTextExpanded:c}){var C,I,R;const d=(t.role||"").toLowerCase(),u=d==="user"||d==="human",p=t.kind||(d==="tool"?"tool":"standard"),m=li(t),h=Ff(t.content)?t.content:null,b=!!(h!=null&&h.some(L=>L.type!=="text")),g=ri(t.content,{joiner:`
|
|
6
|
+
`});if(m.isActivityFacing&&p!=="thought"&&p!=="tool"&&p!=="terminal"){const L=m.label||"Activity";return s.jsxs("div",{className:"self-start chat-msg-activity","data-chat-activity-row":"true",children:[s.jsxs("div",{className:"chat-msg-activity-meta","aria-label":"Activity message",children:[s.jsx("span",{className:"activity-dot"}),s.jsx("span",{children:L})]}),b&&h?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(pr,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:g})]})}if(p==="thought"){const L=typeof((C=t.meta)==null?void 0:C.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(lf,{size:13}),s.jsx("span",{children:L})]}),s.jsx("div",{className:"chat-msg-body",children:g})]})}if(p==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-tool-meta","aria-label":"Tool message",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),s.jsx("span",{className:"tool-label",children:"Tool"})]}),b&&h?s.jsx("div",{className:"tool-text w-full",children:s.jsx(pr,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:g})]});if(p==="terminal"){const L=(I=t.meta)!=null&&I.isRunning?"⏳":"✅",T=typeof((R=t.meta)==null?void 0:R.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:L}),s.jsx("span",{children:T})]}),b&&h?s.jsx("div",{className:"chat-msg-body",children:s.jsx(pr,{parts:h,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:g})]})}if(p==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:b&&h?s.jsx(pr,{parts:h,renderAsPreformatted:!1}):g.slice(0,100)});const f=t.meta,j=(typeof(f==null?void 0:f.renderMode)=="string"?f.renderMode.trim():"")==="preformatted",y=g,w=!1,N=y,k=j,x=!u&&!k&&Bd(N),S=["chat-message-row",u?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:S,children:(y||b||u)&&s.jsxs("div",{className:`chat-bubble ${u?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${y||b?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:u?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:Ed(r)})]}),(y||b)&&s.jsx("div",{className:"chat-markdown",children:b&&h?s.jsx(pr,{parts:h,renderAsPreformatted:k}):s.jsx(Of,{content:N,renderAsPreformatted:k,renderAsMarkdown:x})}),w]})})},(e,t)=>(e.message===t.message||yl(e.message)===yl(t.message))&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),Wf=l.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:o=!1,isWorking:i=!1,contextKey:c="",receivedAtMap:d={},lastMessageHash:u,showActivityMessages:p=!1,emptyState:m,onLoadMore:h,isLoadingMore:b,hasMoreHistory:g,hiddenLiveCount:f=0,loadError:v,scrollToBottomRequestNonce:j,isVisible:y=!0},w){const N=l.useRef(null),k=l.useRef(null),x=l.useRef(null),S=l.useRef(0),C=l.useRef(""),I=l.useRef(""),R=l.useRef(!1),L=l.useRef(null),T=l.useRef(!1),_=l.useRef(null),$=l.useRef(!1),[X,M]=l.useState(new Set),[A,E]=l.useState({showTop:!1,showBottom:!1}),F=l.useRef(!1),z=l.useRef(!1),D=l.useRef(y),K=l.useRef(y),O=l.useRef(null);K.current=y;const q=()=>{const Z=N.current;return Z?Z.scrollHeight-Z.scrollTop-Z.clientHeight<ci:!0},ne=l.useCallback(()=>{const Z=N.current,P=Z?Lf(Z):{showTop:!1,showBottom:!1};E(ie=>ie.showTop===P.showTop&&ie.showBottom===P.showBottom?ie:P)},[]),J=l.useCallback((Z="auto")=>{var ie;const P=N.current;P&&(P.scrollTo({top:P.scrollHeight,behavior:Z}),(ie=P.ownerDocument.defaultView)==null||ie.requestAnimationFrame(()=>ne()))},[ne]),ye=l.useCallback((Z="auto")=>{var ie;const P=N.current;P&&(P.scrollTo({top:0,behavior:Z}),(ie=P.ownerDocument.defaultView)==null||ie.requestAnimationFrame(()=>ne()))},[ne]),oe=l.useCallback(()=>{var ue;const Z=N.current,P=(ue=window.getSelection)==null?void 0:ue.call(window);if(!Z||!P||P.rangeCount===0||P.isCollapsed){$.current=!1;return}const ie=P.anchorNode,be=P.focusNode;$.current=!!(ie&&be&&Z.contains(ie)&&Z.contains(be))},[]),B=l.useMemo(()=>{const Z=If(t),P=Ld(t);return Mf(Z,P,p)},[t,p]),W=B.length===t.length?u:void 0,ve=_f(B,W),we=l.useCallback(()=>{const Z=N.current;if(!Z||!c||!K.current)return;const P={top:Z.scrollTop,fromBottom:Math.max(0,Z.scrollHeight-Z.scrollTop-Z.clientHeight),messageFingerprint:ve};O.current={contextKey:c,snapshot:P},dr.set(c,P)},[c,ve]),fe=l.useCallback((Z="auto")=>{L.current!=null&&cancelAnimationFrame(L.current),L.current=requestAnimationFrame(()=>{L.current=null,J(Z)})},[J]),Ne=l.useCallback(()=>{F.current=!1,T.current=!0,z.current=!0,_.current!=null&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{T.current=!1,_.current=null},bl)},[]);l.useEffect(()=>{const Z=!R.current,P=I.current!==c;if(I.current=c,Z||P){R.current=!0;const be=c?dr.get(c):null,ue=!!be&&Gn(be,ve);F.current=ue?Sr(be):!1,T.current=Df(be,ve),$.current||(ue?requestAnimationFrame(()=>{const te=N.current;te&&(Pa(te,be),F.current=Sr(be),ne(),z.current=!0)}):fe("auto")),S.current=B.length,C.current=ve;return}B.length>S.current;const ie=ve!==C.current;$f({hasSelection:$.current,userScrolledUp:F.current,hasChatContentChanged:ie})&&fe("auto"),S.current=B.length,C.current=ve},[ve,c,B.length,fe,ne]),l.useEffect(()=>{j&&(Ne(),$.current||fe("auto"))},[Ne,fe,j]),l.useEffect(()=>{const Z=D.current;Z&&!y&&we(),K.current=y,D.current=y;const P=c?dr.get(c):null;if(Rf(Z,y,P,ve)){if(!P)return;F.current=Sr(P),T.current=!1,$.current||requestAnimationFrame(()=>{const ie=N.current;ie&&(Pa(ie,P),ne())});return}},[y,c,ve,Ne,we,fe,ne]),l.useEffect(()=>()=>{const Z=O.current;Z&&dr.set(Z.contextKey,Z.snapshot),L.current!=null&&cancelAnimationFrame(L.current),_.current!=null&&window.clearTimeout(_.current)},[]),l.useEffect(()=>{const Z=k.current,P=N.current;if(!Z||!P)return;const ie=()=>{_.current!=null&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{T.current=!1,_.current=null},bl)},be=new ResizeObserver(()=>{ne();const ue=T.current;Ef({hasSelection:$.current,userScrolledUp:F.current,contextAutoScrollActive:ue})&&(fe("auto"),ue&&ie())});return be.observe(Z),P!==Z&&be.observe(P),()=>{be.disconnect(),_.current!=null&&(window.clearTimeout(_.current),_.current=null)}},[fe,c,ne]),l.useImperativeHandle(w,()=>({scrollToBottom:(Z="smooth")=>{J(Z)}}),[J]),l.useEffect(()=>{const Z=N.current;if(!Z)return;let P;const ie=()=>{we(),clearTimeout(P),P=setTimeout(()=>{F.current=!q(),ne()},50)};return Z.addEventListener("scroll",ie,{passive:!0}),()=>{Z.removeEventListener("scroll",ie),clearTimeout(P)}},[we,ne]),l.useEffect(()=>(document.addEventListener("selectionchange",oe),()=>document.removeEventListener("selectionchange",oe)),[oe]);const re=l.useRef(0),je=l.useRef(!1);l.useEffect(()=>{const Z=N.current;if(!Z||!je.current||re.current===0)return;const P=Z.scrollHeight-re.current;P>0&&(Z.scrollTop=P),ne(),we(),re.current=0,je.current=!1},[B.length,we,ne]),l.useEffect(()=>{if(z.current||!c)return;const Z=dr.get(c),P=N.current;if(!(!Z||!P)){if(!Gn(Z,ve)){J("auto"),z.current=!0;return}Pa(P,Z),F.current=Sr(Z),ne(),z.current=!0}},[c,ve,B.length,J,ne]);const de=()=>{const Z=N.current;Z&&(re.current=Z.scrollHeight),je.current=!0,h==null||h()},U=()=>{F.current=!0,ye("smooth"),we()},H=()=>{Ne(),J("smooth"),we()},Y=l.useMemo(()=>{const Z=B.map((ue,te)=>({type:"message",data:ue,index:te,ts:Bf(ue,te,d)}));if(!r||r.length===0)return Z;const P=[...r].sort((ue,te)=>ue.timestamp-te.timestamp).map((ue,te)=>({type:"action",data:ue,index:te,ts:ue.timestamp})),ie=[];let be=0;for(const ue of Z){for(;be<P.length&&ue.ts>0&&P[be].ts<ue.ts;)ie.push(P[be++]);ie.push(ue)}for(;be<P.length;)ie.push(P[be++]);return ie},[B,r,d]),se=f>0||!!g,xe=f>0?`↑ Show ${Math.min(f,80)} earlier messages${f>80?` (${f} hidden)`:""}`:v?`↻ ${v}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:N,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:k,className:"chat-container-content",children:[b&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),se&&!b&&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 ${v&&f===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:xe})}),Y.length===0&&!se&&(m||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),Y.map(Z=>{if(Z.type==="action"){const Ae=Z.data;return s.jsx(Hf,{log:Ae},`action-${Z.index}`)}const P=Z.data,ie=Z.index,be=Vn(P,ie),ue=P.receivedAt||d[be],te=`${c}-${be}`,Me=X.has(te);return s.jsx(zf,{message:P,receivedAt:ue,agentName:n,userName:a,isCliMode:o,isTextExpanded:Me,onToggleTextExpanded:()=>M(Ae=>{const Ce=new Set(Ae);return Me?Ce.delete(te):Ce.add(te),Ce})},`msg-${be}`)}),i&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),s.jsx("div",{className:"min-h-10",ref:x})]})}),(A.showTop||A.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[A.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:U,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),A.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:H,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Kf=l.memo(Wf,(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),Uf="modulepreload",Gf=function(e){return"/"+e},vl={},Vf=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=Gf(d),d in vl)return;vl[d]=!0;const u=d.endsWith(".css"),p=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${p}`))return;const m=document.createElement("link");if(m.rel=u?"stylesheet":Uf,u||(m.as="script"),m.crossOrigin="",m.href=d,c&&m.setAttribute("nonce",c),document.head.appendChild(m),u)return new Promise((h,b)=>{m.addEventListener("load",h),m.addEventListener("error",()=>b(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return a.then(i=>{for(const c of i||[])c.status==="rejected"&&o(c.reason);return t().catch(o)})};let wl=!1;const Fd=l.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:o="measured"},i)=>{const c=l.useRef(null),[d,u]=l.useState(null),p=l.useRef([]),m=l.useRef(!1),h=l.useRef(!1),b=l.useRef(!1),g=l.useRef(!1),f=()=>{const v=c.current;if(v){m.current&&(v.clear(),m.current=!1);for(const j of p.current)v.write(j.data,j.onProcessed);p.current=[],h.current&&(v.fit(),h.current=!1),b.current&&(v.bumpResize(),b.current=!1),g.current&&(v.scrollToTop(),g.current=!1)}};return l.useImperativeHandle(i,()=>({write:(v,j)=>{c.current?c.current.write(v,j):p.current.push({data:v,onProcessed:j})},clear:()=>{c.current?c.current.clear():(p.current=[],m.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(p.current=[],m.current=!0)},resize:(v,j)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(v,j)},fit:()=>{c.current?c.current.fit():h.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():b.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():g.current=!0},getSelection:()=>{var v,j;return((j=(v=c.current)==null?void 0:v.getSelection)==null?void 0:j.call(v))||""},getVisibleText:()=>{var v,j;return((j=(v=c.current)==null?void 0:v.getVisibleText)==null?void 0:j.call(v))||""}}),[]),l.useEffect(()=>{d&&f()},[d]),l.useEffect(()=>{let v=!1;return Vf(()=>import("./terminal-DsCRNxW_.js"),__vite__mapDeps([0,1,2])).then(j=>{wl||(wl=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),v||u(()=>j.GhosttyTerminalView)}).catch(j=>{console.error("[CliTerminal] failed to load terminal renderer",j)}),()=>{v=!0}},[]),d?s.jsx(d,{ref:c,onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:o,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});Fd.displayName="CliTerminal";function pn({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 jl({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 qf({cursorPos:e,viewportRef:t,imgRef:r}){var y;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(y=t.current)==null?void 0:y.getBoundingClientRect();if(!o)return null;const i=n.naturalWidth||a.width,c=n.naturalHeight||a.height,d=i/c,u=a.width/a.height;let p,m,h,b;d>u?(p=a.width,m=a.width/d,h=0,b=(a.height-m)/2):(m=a.height,p=a.height*d,h=(a.width-p)/2,b=0);const g=a.left-o.left+h+p*e.nx,f=a.top-o.top+b+m*e.ny,v=Math.max(8,Math.min(o.width-8,g)),j=Math.max(8,Math.min(o.height-8,f));return s.jsxs("div",{style:{position:"absolute",left:v-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 Yf({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:i,setImeText:c,handleImeSubmit:d,isConnActive:u,zoom:p,isMobile:m,mobileFillZoom:h,onZoomOut:b,onZoomReset:g,onZoomIn:f,transportType:v,screenshotUsage:j,lastActionStatus:y}){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:u?"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:u?"#22c55e":"#eab308",boxShadow:u?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:u?"#22c55e":"#eab308"},children:u?"Connected":"WS"})]}),p>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(p*100),"%"]}),v==="direct"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),v==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),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`}),y&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:y})]})]}),a&&s.jsxs("div",{onTouchStart: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: ",p<=(m?h:1)+.01?m?"FILL":"FIT":`${Math.round(p*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},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:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:w=>{w.stopPropagation(),g()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:m?"FILL":"FIT"}),s.jsx("button",{onClick:w=>{w.stopPropagation(),f()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function Jf({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 Xf(){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 kl(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 Gr(e,t){const r=l.useRef(null),n=l.useRef(0);l.useEffect(()=>{if(!Xf())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,kl(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,kl(t[i])]))}),r.current=t})}function Qf({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:i,panXRef:c,panYRef:d,setPanX:u,setPanY:p,setZoom:m,lastWheelTimeRef:h,onAction:b,setLastActionStatus:g,spawnRippleFromNormalized:f,clampPan:v,isMobile:j,mobileFillZoom:y}){const[w,N]=l.useState(null),k=l.useRef(null),x=l.useRef(null),S=l.useRef(null),C=l.useRef(!1),I=l.useRef(null),R=l.useRef(0),L=l.useRef(null),T=l.useRef(1),_=l.useRef({x:0,y:0}),$=l.useRef(!1),X=l.useRef(n),M=l.useRef(b),A=30,E=550,F=18,z=60,D=400,K=12,O=()=>{if(k.current)return;const J={nx:.5,ny:.5};k.current=J,N(J)};return l.useEffect(()=>{X.current=n,n==="mouse"&&O()},[n]),l.useEffect(()=>{M.current=b},[b]),l.useEffect(()=>{const J=e.current;if(!J)return;const ye=fe=>{if(!r.current)return null;const Ne=r.current.getBoundingClientRect();return!Ne.width||!Ne.height?null:{nx:Math.max(0,Math.min(1,(fe.clientX-Ne.left)/Ne.width)),ny:Math.max(0,Math.min(1,(fe.clientY-Ne.top)/Ne.height))}},oe=(fe,Ne)=>{if(!r.current)return{dnx:0,dny:0};const re=r.current,je=re.getBoundingClientRect(),de=re.naturalWidth||je.width,U=re.naturalHeight||je.height,H=de/U,Y=je.width/je.height;let se,xe;return H>Y?(se=je.width,xe=je.width/H):(xe=je.height,se=je.height*H),{dnx:fe/se,dny:Ne/xe}},B=(fe,Ne,re)=>{if(re<=1.05)return;const je=-(fe-.5)*100,de=-(Ne-.5)*100,U=v(je,de,re);(Math.abs(U.x-c.current)>.1||Math.abs(U.y-d.current)>.1)&&(u(U.x),p(U.y),c.current=U.x,d.current=U.y)},W=fe=>{const Ne=t.current;if(Ne&&fe.target instanceof Node&&Ne.contains(fe.target))fe.preventDefault();else return;if(fe.touches.length===1){const re=fe.touches[0];x.current={x:re.clientX,y:re.clientY,time:Date.now()},S.current={x:re.clientX,y:re.clientY},$.current||(C.current=!1),I.current=setTimeout(()=>{if(!C.current&&!$.current)if(C.current=!0,X.current==="mouse"){const je=k.current||{nx:.5,ny:.5};g("Right Click"),f(je.nx,je.ny,"right"),M.current("input_click",{...je,button:"right"}).catch(()=>{})}else{const je=ye(re);je&&(g("Right Click"),f(je.nx,je.ny,"right"),M.current("input_click",{...je,button:"right"}).catch(()=>{}))}},500);return}if(fe.touches.length===2){I.current&&clearTimeout(I.current),C.current=!0,$.current=!0;const re=fe.touches[1].clientX-fe.touches[0].clientX,je=fe.touches[1].clientY-fe.touches[0].clientY;L.current=Math.sqrt(re*re+je*je),T.current=i.current,_.current={x:(fe.touches[0].clientX+fe.touches[1].clientX)/2,y:(fe.touches[0].clientY+fe.touches[1].clientY)/2}}},ve=fe=>{const Ne=t.current;if(Ne&&fe.target instanceof Node&&Ne.contains(fe.target)&&fe.preventDefault(),fe.touches.length===1&&S.current){const re=fe.touches[0],je=re.clientX-S.current.x,de=re.clientY-S.current.y;if(!C.current&&x.current){const U=re.clientX-x.current.x,H=re.clientY-x.current.y;Math.sqrt(U*U+H*H)>8&&(C.current=!0,I.current&&clearTimeout(I.current))}if(C.current)if(X.current==="mouse"){const U=oe(je,de),H=k.current||{nx:.5,ny:.5},Y=Math.max(0,Math.min(1,H.nx+U.dnx)),se=Math.max(0,Math.min(1,H.ny+U.dny));k.current={nx:Y,ny:se},N({nx:Y,ny:se}),g(`Cursor: ${Math.round(Y*100)}%, ${Math.round(se*100)}%`),B(Y,se,i.current);const xe=Date.now();xe-h.current>=30&&(h.current=xe,M.current("input_mouseMoved",{nx:Y,ny:se}).catch(()=>{}))}else if(i.current>1){const U=t.current;if(U){const H=U.clientWidth,Y=U.clientHeight,se=c.current+je/H*100,xe=d.current+de/Y*100,Z=v(se,xe,i.current);u(Z.x),p(Z.y),c.current=Z.x,d.current=Z.y}}else{const U=ye(re);if(U){const H=Date.now();H-h.current>=40&&(h.current=H,g("Scroll"),M.current("input_wheel",{nx:U.nx,ny:U.ny,deltaX:Math.round(-je*2.5),deltaY:Math.round(-de*2.5)}).catch(()=>{}))}}S.current={x:re.clientX,y:re.clientY};return}if(fe.touches.length===2&&L.current!==null){const re=fe.touches[1].clientX-fe.touches[0].clientX,je=fe.touches[1].clientY-fe.touches[0].clientY,U=Math.sqrt(re*re+je*je)/L.current,H=(fe.touches[0].clientX+fe.touches[1].clientX)/2,Y=(fe.touches[0].clientY+fe.touches[1].clientY)/2,se=H-_.current.x,xe=Y-_.current.y,Z=Math.abs(U-1)>.03;if(X.current==="mouse"){if(Z){const P=Math.max(o,Math.min(5,T.current*U));m(P),i.current=P}else if(Math.abs(se)>2||Math.abs(xe)>2){const P=k.current||{nx:.5,ny:.5},ie=Date.now();ie-h.current>=30&&(h.current=ie,g("Scroll"),M.current("input_wheel",{nx:P.nx,ny:P.ny,deltaX:Math.round(-se*3),deltaY:Math.round(-xe*3)}).catch(()=>{}))}}else{const P=Math.max(o,Math.min(5,T.current*U));m(P),i.current=P;const ie=t.current;if(ie&&P>1){const be=ie.clientWidth,ue=ie.clientHeight,te=c.current+se/be*100,Me=d.current+xe/ue*100,Ae=v(te,Me,P);u(Ae.x),p(Ae.y),c.current=Ae.x,d.current=Ae.y}}_.current={x:H,y:Y}}},we=fe=>{var Ne;if(I.current&&clearTimeout(I.current),L.current=null,fe.touches.length===1&&$.current){const re=fe.touches[0];x.current={x:re.clientX,y:re.clientY,time:Date.now()},S.current={x:re.clientX,y:re.clientY},C.current=!0;return}if(fe.touches.length===0){if($.current){$.current=!1,C.current=!1;return}if(fe.changedTouches.length===1){const re=fe.changedTouches[0],je=Date.now(),de=je-(((Ne=x.current)==null?void 0:Ne.time)||0),U=x.current?re.clientX-x.current.x:0,H=x.current?re.clientY-x.current.y:0,Y=Math.sqrt(U*U+H*H);if(X.current==="mouse"){if(de<A||de>E||Y>F){C.current=!1;return}const se=k.current||ye(re);se&&(g(`Click: ${Math.round(se.nx*100)}%, ${Math.round(se.ny*100)}%`),f(se.nx,se.ny,"left"),M.current("input_click",{...se}).catch(()=>{}))}else{if(C.current){C.current=!1;return}if(de<z||de>D||Y>K){C.current=!1;return}const se=ye(re);if(!se)return;je-R.current<300?(g("Double tap"),f(se.nx,se.ny,"double"),M.current("input_click",{...se,clickCount:2}).catch(()=>{}),R.current=0):(g(`Tap: ${Math.round(se.nx*100)}%, ${Math.round(se.ny*100)}%`),f(se.nx,se.ny,"left"),M.current("input_click",{...se}).catch(()=>{}),R.current=je)}}C.current=!1}};return J.addEventListener("touchstart",W,{passive:!1}),J.addEventListener("touchmove",ve,{passive:!1}),J.addEventListener("touchend",we,{passive:!1}),()=>{J.removeEventListener("touchstart",W),J.removeEventListener("touchmove",ve),J.removeEventListener("touchend",we),I.current&&clearTimeout(I.current)}},[e,t,r,o,i,c,d,u,p,m,h,g,f,v]),{cursorPos:w,cursorPosRef:k,handleToggleInputMode:()=>{a(J=>{const ye=J==="touch"?"mouse":"touch";return ye==="mouse"&&O(),ye})},handleZoomReset:()=>{const J=j?y:1;m(J),i.current=J,u(0),p(0),c.current=0,d.current=0}}}function Od({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),[u,p]=l.useState(null),[m,h]=l.useState(""),[,b]=l.useState(!1),[g,f]=l.useState([]),v=l.useRef(0),[j,y]=l.useState(!1),[w,N]=l.useState(!1),k=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[x,S]=l.useState(k?"mouse":"touch"),[C,I]=l.useState(1),R=l.useRef(!1),[L,T]=l.useState(1),[_,$]=l.useState(0),[X,M]=l.useState(0);Gr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:x,zoom:L,panX:_,panY:X,isMenuOpen:j,isImeOpen:w});const A=l.useRef(0),E=l.useRef(L),F=l.useRef(_),z=l.useRef(X);l.useEffect(()=>{E.current=L},[L]),l.useEffect(()=>{F.current=_},[_]),l.useEffect(()=>{z.current=X},[X]),l.useEffect(()=>{var de;(de=i.current)==null||de.focus()},[]);const D=r==="connected",K=n,O=D?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",q=D?"The remote stream is warming up":"Waiting for the remote stream to catch up";l.useEffect(()=>{if(!k||R.current||!K)return;const de=d.current,U=c.current;if(!de||!U)return;const H=()=>{const Y=U.clientWidth,se=U.clientHeight,xe=de.naturalWidth,Z=de.naturalHeight;if(!xe||!Z||!Y||!se)return;const P=Math.min(Y/xe,se/Z),be=Math.max(Y/xe,se/Z)/P;be>1.01&&(I(be),T(be),E.current=be),R.current=!0};de.complete&&de.naturalWidth?H():de.addEventListener("load",H,{once:!0})},[K,k]);const ne=.5;l.useEffect(()=>{L<=ne&&($(0),M(0))},[L,ne]);const J=(de,U,H)=>{if(H<=ne)return{x:0,y:0};const Y=(H-1)/(2*H)*100,se=(H-1)/(2*H)*100;return{x:Math.max(-Y,Math.min(Y,de)),y:Math.max(-se,Math.min(se,U))}},ye=(de,U)=>{if(!d.current)return null;const H=d.current.getBoundingClientRect();return!H.width||!H.height?null:{nx:Math.max(0,Math.min(1,(de-H.left)/H.width)),ny:Math.max(0,Math.min(1,(U-H.top)/H.height))}},oe=(de,U,H)=>{const Y=c.current;if(!Y)return;const se=Y.getBoundingClientRect(),xe=++v.current;f(Z=>[...Z,{id:xe,x:de-se.left,y:U-se.top,type:H}]),setTimeout(()=>f(Z=>Z.filter(P=>P.id!==xe)),600)},B=(de,U,H)=>{const Y=d.current,se=c.current;if(!Y||!se)return;const xe=Y.getBoundingClientRect(),Z=se.getBoundingClientRect(),P=Y.naturalWidth||xe.width,ie=Y.naturalHeight||xe.height,be=P/ie,ue=xe.width/xe.height;let te,Me,Ae,Ce;be>ue?(te=xe.width,Me=xe.width/be,Ae=0,Ce=(xe.height-Me)/2):(Me=xe.height,te=xe.height*be,Ae=(xe.width-te)/2,Ce=0);const Ue=xe.left-Z.left+Ae+te*de,Qe=xe.top-Z.top+Ce+Me*U,pe=++v.current;f(De=>[...De,{id:pe,x:Ue,y:Qe,type:H}]),setTimeout(()=>f(De=>De.filter($e=>$e.id!==pe)),600)},W=async de=>{var H;const U=ye(de.clientX,de.clientY);if(U){p(`Click: ${Math.round(U.nx*100)}%, ${Math.round(U.ny*100)}%`),oe(de.clientX,de.clientY,"left"),(H=i.current)==null||H.focus();try{const Y=await e("input_click",{nx:U.nx,ny:U.ny});Y!=null&&Y.success||t(`❌ Click failed: ${Y==null?void 0:Y.error}`)}catch(Y){t(`❌ Click error: ${Y.message||Y}`)}}},ve=async(de,U,H,Y=0)=>{try{await e("input_key",{type:H?"char":"keyDown",key:de,code:U,text:H?de:void 0,unmodifiedText:H?de:void 0,modifiers:Y})}catch(se){t(`❌ Key error: ${se.message||se}`)}},we=async de=>{if(de.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(de.key)&&de.preventDefault();let H=0;de.altKey&&(H|=1),de.ctrlKey&&(H|=2),de.metaKey&&(H|=4),de.shiftKey&&(H|=8),p(`Key: ${de.key}`),await ve(de.key,de.code,de.key.length===1,H)},fe=async de=>{if(de.key==="Enter"){if(de.nativeEvent.isComposing)return;if(m){const U=m;h(""),p(`IME Sent: ${U}`);try{const H=await e("input_type",{text:U});H!=null&&H.success||t(`❌ IME error: ${H==null?void 0:H.error}`)}catch(H){t(`❌ IME error: ${H.message}`)}}else p("Key: Enter"),await ve("Enter","Enter",!1)}};l.useEffect(()=>{const de=i.current;if(!de)return;const U=H=>{var Y;if((Y=d.current)!=null&&Y.contains(H.target)){H.preventDefault();const se=Date.now();if(se-A.current<40)return;A.current=se;const xe=ye(H.clientX,H.clientY);if(!xe)return;p(`Scroll: ${Math.round(H.deltaY)}`),e("input_wheel",{nx:xe.nx,ny:xe.ny,deltaX:Math.round(H.deltaX),deltaY:Math.round(H.deltaY)}).catch(()=>{})}};return de.addEventListener("wheel",U,{passive:!1}),()=>de.removeEventListener("wheel",U)},[e]);const{cursorPos:Ne,handleToggleInputMode:re,handleZoomReset:je}=Qf({containerRef:i,viewportRef:c,imgRef:d,inputMode:x,setInputMode:S,minZoom:ne,zoomRef:E,panXRef:F,panYRef:z,setPanX:$,setPanY:M,setZoom:T,lastWheelTimeRef:A,onAction:e,setLastActionStatus:p,spawnRippleFromNormalized:B,clampPan:J,isMobile:k,mobileFillZoom:C});return s.jsxs("div",{ref:i,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:we,onContextMenu:de=>de.preventDefault(),onFocus:()=>b(!0),onBlur:()=>b(!1),tabIndex:0,children:[s.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[K?s.jsx("img",{ref:d,src:K,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${L}) translate(${_}%, ${X}%)`,transformOrigin:"center center",cursor:x==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:W,onContextMenu:de=>de.preventDefault(),onDragStart:de=>de.preventDefault()}):s.jsx(Jf,{waitingLabel:O,waitingHint:q,transportType:o}),x==="mouse"&&K&&s.jsx(qf,{cursorPos:Ne,viewportRef:c,imgRef:d}),g.map(de=>{const H={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(${H}, 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(${H}, 0.9)`,boxShadow:`0 0 12px rgba(${H}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},de.id)})]}),s.jsx(Yf,{inputMode:x,onToggleInputMode:re,isImeOpen:w,setIsImeOpen:N,isMenuOpen:j,setIsMenuOpen:y,imeText:m,setImeText:h,handleImeSubmit:fe,isConnActive:D,zoom:L,isMobile:k,mobileFillZoom:C,onZoomOut:()=>T(de=>Math.max(.5,de-.25)),onZoomReset:je,onZoomIn:()=>T(de=>Math.min(5,de+.25)),transportType:o,screenshotUsage:a,lastActionStatus:u}),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 Nl(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 Zf(e){var t;return Nl(e.activeInteractivePrompt)||Nl((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function ex(e){return e.sessionId||e.instanceId||e.id}function tx(e,t){const r=typeof t=="string"?t.trim():"";for(const n of e){const a=Zf(n);if(!a)continue;const o=ex(n);if(r&&r!==o&&r!==n.id)continue;return{daemonId:n.daemonId||n.id.split(":")[0]||n.id,sessionId:o,routeId:n.id,providerType:n.type,title:n.title||n.cliName||n.type,prompt:a}}return null}function Hd(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 Sl(e){const t={};for(const r of(e==null?void 0:e.prompt.questions)||[])t[r.questionId]={selectedLabels:[],freeformText:""};return t}function Cl(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 sx({label:e,description:t,selected:r,multiSelect:n,disabled:a,onClick:o}){return s.jsx("button",{type:"button",disabled:a,role:n?"checkbox":"radio","aria-checked":r,onClick:o,className:`w-full text-left rounded-md border px-3 py-2 transition ${r?"border-accent-primary bg-accent-primary/15 text-text-primary":"border-border-primary bg-surface-secondary text-text-secondary hover:bg-surface-tertiary hover:text-text-primary"} ${a?"cursor-not-allowed opacity-60":""}`,children:s.jsxs("span",{className:"flex items-start gap-2",children:[s.jsx("span",{className:`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center border ${n?"rounded-sm":"rounded-full"} ${r?"border-accent-primary bg-accent-primary text-accent-on-primary":"border-border-secondary"}`,children:r?s.jsx(_d,{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 zd({promptSession:e,isSubmitting:t=!1,error:r,onSubmit:n,onCancel:a}){var S;const[o,i]=l.useState(()=>Sl(e)),[c,d]=l.useState(0);l.useEffect(()=>{i(Sl(e)),d(0)},[e==null?void 0:e.prompt.promptId]);const u=(e==null?void 0:e.prompt.questions)||[],p=u.length,m=c===p-1,h=p===1,b=u[c],g=b?o[b.questionId]:void 0,f=b?Cl(b,g):!1,v=l.useMemo(()=>e?e.prompt.questions.every(C=>Cl(C,o[C.questionId])):!1,[e,o]);if(!e)return null;const j=(C,I)=>{i(R=>{const L=R[C.questionId]||{selectedLabels:[]},T=L.selectedLabels||[],_=C.multiSelect?T.includes(I)?T.filter($=>$!==I):[...T,I]:[I];return{...R,[C.questionId]:{...L,selectedLabels:_}}})},y=(C,I)=>{i(R=>({...R,[C]:{...R[C]||{selectedLabels:[]},freeformText:I}}))},w=()=>{c<p-1&&d(C=>C+1)},N=()=>{c>0&&d(C=>C-1)},k=()=>{!v||t||n(o)},x=Hd(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(Zs,{size:15})," Action Required"]}),s.jsx("h2",{className:"mt-1 text-lg font-bold text-text-primary",children:e.title||e.providerType})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[!h&&s.jsxs("span",{className:"text-xs text-text-muted",children:[c+1," / ",p]}),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(vt,{size:16})})]})]}),!h&&s.jsx("div",{className:"flex gap-1.5 px-5 pt-3",children:u.map((C,I)=>s.jsx("div",{className:`h-1.5 flex-1 rounded-full transition-colors ${I<c?"bg-accent-primary":I===c?"bg-accent-primary/60":"bg-border-primary"}`},C.questionId))}),s.jsxs("div",{className:"space-y-4 px-5 py-4",children:[b&&s.jsxs("section",{className:"space-y-3",children:[s.jsxs("div",{children:[b.header&&s.jsx("div",{className:"mb-1 text-xs font-semibold uppercase tracking-normal text-text-muted",children:b.header}),s.jsxs("div",{className:"text-sm font-semibold text-text-primary",children:[h?"":`${c+1}. `,b.question]}),b.multiSelect&&b.options.length>0&&s.jsx("div",{className:"mt-0.5 text-xs text-text-muted",children:"Select all that apply"})]}),s.jsx("div",{className:"grid gap-2",role:b.multiSelect?"group":"radiogroup","aria-label":b.question,children:b.options.map(C=>{var I;return s.jsx(sx,{label:C.label,description:C.description||C.preview,selected:(((I=x.answers[b.questionId])==null?void 0:I.selectedLabels)||[]).includes(C.label),multiSelect:b.multiSelect,disabled:t,onClick:()=>j(b,C.label)},C.label)})}),b.allowFreeform&&s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-semibold text-text-muted",children:"Other"}),s.jsx("textarea",{value:((S=o[b.questionId])==null?void 0:S.freeformText)||"",disabled:t,onChange:C=>y(b.questionId,C.currentTarget.value),className:"w-full min-h-20 rounded-md border border-border-primary bg-surface-secondary px-3 py-2 text-sm text-text-primary outline-none focus:border-accent-primary"})]})]}),r&&s.jsx("div",{className:"rounded-md border border-status-error/30 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:r})]}),s.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-border-primary px-5 py-4",children:[s.jsx("div",{children:!h&&c>0&&s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:N,disabled:t,children:"Back"})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:a,disabled:t,children:"Cancel"}),h||m?s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:k,disabled:!v||t,children:t?"Submitting...":"Submit"}):s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:w,disabled:!f||t,children:"Next"})]})]})]})})}function xa(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 u=Math.floor(d/24);return u<7?`${u}d${r}`:new Date(e).toLocaleDateString()}const Wd=e=>xa(e);function rx(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 or(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating"||e.status==="no_progress"||e.status==="long_generating"||e.status==="streaming",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function nx(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...rx(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 qn(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 ba(e,t,r){const n=qn(e,t),a=or(e),o=a.isReconnecting,i=a.isConnecting,c=a.isGenerating,d=a.isWaiting,u=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d,p=n.inboxBucket==="working"||c,h=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:h,requiresAction:u,isWorking:p,isReconnecting:o,isConnecting:i,isGenerating:c,isWaiting:d,inboxBucket:u?"needs_attention":p?"working":h?"task_complete":"idle"}}function ax(e,t,r){return ba(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Kd({activeConv:e,onModalButton:t}){const[r,n]=l.useState(null);if(l.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!or(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(Zs,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((c,d)=>{const u=i(c).toLowerCase(),p=/^(run|approve|accept|yes|allow|always)/.test(u),m=/^(reject|deny|delete|remove|abort)/.test(u),h=r===c,b=r!==null;return s.jsx("button",{onClick:()=>o(c),disabled:b,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${p?"font-extrabold":m?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${b&&!h?"opacity-40":"opacity-100"} ${b?"cursor-not-allowed":"cursor-pointer"}`,style:p?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:m?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:h?"⏳ ...":i(c)},d)})})]})]})}const di="adhdev_controls_bar_visible",_o="adhdev:controlsbarvisibilitychange";function Da(e){if(!e)return!1;try{return e.getItem(di)==="1"}catch{return!1}}function ox(e,t){if(t)try{t.setItem(di,e?"1":"0")}catch{}}function ix(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(_o,{detail:{visible:e}}))}function ui(){const[e,t]=l.useState(()=>typeof window>"u"?!1:Da(window.localStorage)),r=l.useRef(e),n=l.useCallback((i,c=!0)=>{r.current=i,t(i),typeof window<"u"&&ox(i,window.localStorage),c&&ix(i)},[]);l.useEffect(()=>{const i=d=>{const u=d.detail,p=typeof(u==null?void 0:u.visible)=="boolean"?u.visible:Da(window.localStorage);r.current=p,t(p)},c=d=>{if(d.key!==di)return;const u=Da(window.localStorage);r.current=u,t(u)};return window.addEventListener(_o,i),window.addEventListener("storage",c),()=>{window.removeEventListener(_o,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{n(i)},[n]),o=l.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:o}}var lx=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function cx(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function Bt(e,t){if(cx(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":r==="waiting_choice"?"waiting_choice":lx.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 Ro(e){return Bt(e)==="generating"}function Il(e,t){return Bt(e,t)==="waiting_approval"}function Mt(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function dx(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 $a(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Ud(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 ux(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 px(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function mx(e){return ux(e.trim().replace(/\.local$/i,""))}function hx(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function Gd(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&&!px(i));if(r&&r!=="Unknown")return mx(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Ft(e,t={}){return hx(e)||Gd(e,t)}function Vd(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 qd(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 _s(e,t){return Vd(e).join(" · ")}function Fr(e){return e.transport==="pty"}function qs(e){return e.transport==="acp"}function fx(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:Mt(e)}function Ml(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),i=Mt(r||"").trim().toLowerCase();return n===a||n===o||n===i}function xx(e,t=[],r=[]){var d,u,p,m;const n=Bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(n==="waiting_approval")return"waiting_approval";if(n==="waiting_choice")return"waiting_choice";if(n==="generating")return"generating";const a=t.find(h=>Il(h.status,{activeModal:h.activeModal})||Ro(h.status));if(a)return Bt(a.status,{activeModal:a.activeModal});const o=r.find(h=>Il(h.status,{activeModal:h.activeModal})||Ro(h.status));if(o)return Bt(o.status,{activeModal:o.activeModal});if(n&&n!=="idle")return n;const i=Bt((d=t[0])==null?void 0:d.status,{activeModal:(u=t[0])==null?void 0:u.activeModal});if(i!=="idle")return i;const c=Bt((p=r[0])==null?void 0:p.status,{activeModal:(m=r[0])==null?void 0:m.activeModal});return c!=="idle"?c:"idle"}function bx(e){return Bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function gx(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,r=["generating","waiting_approval","waiting_choice","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),o=t.get(a),i=Bt(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 yx(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 vx(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&&yx(t.receivedAt)||0}function wx(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Po(e){return Math.max(wx(e),vx(e.activeChat))}function jx(e,t,r,n,a,o){const i=t-e;if(i!==0)return i;const c=r.localeCompare(n);return c!==0?c:a.localeCompare(o)}function pi(e,t){return jx(Po(e),Po(t),Ft(e,{fallbackId:e.id}),Ft(t,{fallbackId:t.id}),e.id,t.id)}const Yd="adhdev_notification_prefs",Al={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function kx(){try{const e=localStorage.getItem(Yd);if(e){const t=JSON.parse(e);return{...Al,...t}}}catch{}return{...Al}}function Nx(e){try{localStorage.setItem(Yd,JSON.stringify(e))}catch{}}let rs=kx(),_n=[];function Sx(){_n.forEach(e=>e())}function Cx(e){rs={...rs,...e},Nx(rs),Sx()}function Ix(){const[,e]=l.useState(0);l.useEffect(()=>{const r=()=>e(n=>n+1);return _n.push(r),()=>{_n=_n.filter(n=>n!==r)}},[]);const t=l.useCallback(r=>{Cx(r)},[]);return[{...rs},t]}function Ar(e){if(!rs.globalEnabled)return!1;switch(e){case"disconnect":return rs.disconnectAlert;case"completion":return rs.completionAlert;case"approval":return rs.approvalAlert;case"browser":return rs.browserNotifications;default:return!0}}function At(e){return(typeof e=="string"?e.trim():"")||void 0}function ns(e,t){const r=At(t);return r?`${e}:${r}`:void 0}function ms(e,t,r){const n=ns(t,r),a=At(r);n&&e.push(n),a&&e.push(a)}function Vs(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function Jd(e){return At(e.providerSessionId)||At(e.sessionId)||At(e.tabKey)||At(e.routeId)}function ga(e){return Vs([At(e.historySessionId),At(e.providerSessionId),At(e.sessionId)])}function os(e){const t=[];return ms(t,"provider",e.providerSessionId),ms(t,"session",e.sessionId),ms(t,"tab",e.tabKey),ms(t,"route",e.routeId),Vs(t)}function Mx(e){const t=[];return At(e.providerSessionId)?(ms(t,"provider",e.providerSessionId),Vs(t)):At(e.sessionId)?(ms(t,"session",e.sessionId),Vs(t)):At(e.tabKey)?(ms(t,"tab",e.tabKey),Vs(t)):At(e.routeId)?(ms(t,"route",e.routeId),Vs(t)):[]}function ir(e){return ns("provider",e.providerSessionId)||ns("session",e.sessionId)||ns("tab",e.tabKey)||ns("route",e.routeId)||"unknown:"}function Vr(e){return ga(e)[0]}function Ax(e){const t=At(e.providerSessionId),r=At(e.sessionId),n=At(e.tabKey),a=At(e.routeId),o=[ns("provider",t),ns("session",r),ns("tab",n),ns("route",a)].filter(d=>typeof d=="string"),i=os({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),c=ir({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:c,targetKey:c,targetValue:Jd({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:Vr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:i}}function Lo(e,t){const r=Ax(e);return Mx(t).some(n=>r.lookupKeys.includes(n))}const Xd="adhdev_hiddenTabs",Qd="adhdev_autoHiddenMeshTabs";function Tx(){try{const e=localStorage.getItem(Xd);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ys(e){try{localStorage.setItem(Xd,JSON.stringify([...e]))}catch{}}function _x(){try{const e=localStorage.getItem(Qd);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function Tl(e){try{localStorage.setItem(Qd,JSON.stringify([...e]))}catch{}}function Cr(e){return ir(e)}function ya(e,t){return os(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 Rx(e,t,r=new Set){return e.filter(n=>{if(!Zd(n))return!1;const a=Cr(n);return r.has(a)?!1:!ya(t,n)})}function Px(){const[e,t]=l.useState(Tx),[r,n]=l.useState(_x),a=l.useCallback(h=>{const b=Cr(h);t(g=>{const f=new Set(g);return f.has(b)?f.delete(b):f.add(b),ys(f),f})},[]),o=l.useCallback(h=>{const b=Cr(h);t(g=>{if(g.has(b))return g;const f=new Set(g);return f.add(b),ys(f),f})},[]),i=l.useCallback(h=>{const b=Cr(h);t(g=>{if(g.has(b))return g;const f=new Set(g);return f.add(b),ys(f),f}),n(g=>{if(g.has(b))return g;const f=new Set(g);return f.add(b),Tl(f),f})},[]),c=l.useCallback(h=>{const b=Cr(h);t(g=>{if(!g.has(b))return g;const f=new Set(g);return f.delete(b),ys(f),f}),n(g=>{if(g.has(b))return g;const f=new Set(g);return f.add(b),Tl(f),f})},[]),d=l.useCallback(()=>{t(h=>{if(h.size===0)return h;const b=new Set;return ys(b),b})},[]),u=l.useCallback((h,b)=>{t(g=>{const f=new Set(g);for(const v of b)f.add(v);return ys(f),f})},[]),p=l.useCallback((h,b)=>{t(g=>{const f=new Set(g);for(const v of b)f.delete(v);return ys(f),f})},[]),m=l.useCallback(h=>ya(e,h),[e]);return{hiddenTabs:e,autoHiddenTabs:r,toggleTarget:a,hideTarget:o,autoHideTarget:i,showTarget:c,showAllTabs:d,hideAllForDaemon:u,showAllForDaemon:p,isHidden:m}}const eu="adhdev_mutedConversations",tu="adhdev_autoMutedMeshConversations";function su(e){try{const t=localStorage.getItem(e);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function ru(e,t){try{localStorage.setItem(e,JSON.stringify([...t]))}catch{}}let is=su(eu),Rs=su(tu);const Do=new Set;function nu(){for(const e of Do)e()}function _l(e){return Do.add(e),()=>{Do.delete(e)}}function mi(e){is=e,ru(eu,e),nu()}function au(e){Rs=e,ru(tu,e),nu()}function ou(e,t){return os(t).some(r=>e.has(r))}function iu(e){return ou(is,e)}function Rl(e){const t=ir(e);if(is.has(t))return;const r=new Set(is);r.add(t),mi(r)}function Pl(e){const t=os(e);let r=!1;const n=new Set(is);for(const o of t)n.delete(o)&&(r=!0);r&&mi(n);const a=ir(e);if(!Rs.has(a)){const o=new Set(Rs);o.add(a),au(o)}}function Lx(e){if(!Zd(e))return;const t=ir(e);if(Rs.has(t))return;const r=new Set(Rs);if(r.add(t),au(r),!is.has(t)){const n=new Set(is);n.add(t),mi(n)}}function lu(){const e=l.useSyncExternalStore(_l,()=>is,()=>is),t=l.useSyncExternalStore(_l,()=>Rs,()=>Rs),r=l.useCallback(c=>Rl(c),[]),n=l.useCallback(c=>Pl(c),[]),a=l.useCallback(c=>{os(c).some(p=>e.has(p))?Pl(c):Rl(c)},[e]),o=l.useCallback(c=>Lx(c),[]),i=l.useCallback(c=>ou(e,c),[e]);return{mutedTargets:e,autoMutedTargets:t,muteTarget:r,unmuteTarget:n,toggleTarget:a,autoMuteIfCoordinator:o,isMuted:i}}const Dx={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function cu(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function du(){return"Notification"in window&&Notification.permission==="granted"}let vs=null;function $x(e){return e!==!1}async function Ex(){if(vs!==null)return vs;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return vs=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(vs=!!await e.pushManager.getSubscription(),vs):(vs=!1,!1)}catch{return vs=!1,!1}}function $o(e,t,r){if(du())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 Bx(e,t={}){const r={...Dx,...t},n=l.useRef(new Map),a=l.useRef(0),[o,i]=l.useState(null);l.useEffect(()=>{let d=!1;return Ex().then(u=>{d||i(u)}),()=>{d=!0}},[]);const c=l.useCallback((d,u,p)=>{const m=Date.now();m-a.current<r.throttleMs||(a.current=m,$o(d,u,p))},[r.throttleMs]);l.useEffect(()=>{var d;if(!(!r.enabled||!du())&&Ar("browser")&&!$x(o)){if(document.hasFocus()){for(const u of e)n.current.set(u.id,Bt(u.status,{activeModal:u.activeModal}));return}for(const u of e){const p=n.current.get(u.id),m=Bt(u.status,{activeModal:u.activeModal}),h=u.name||u.id;if(u.target&&iu(u.target)){n.current.set(u.id,m);continue}if(r.onApproval&&Ar("approval")&&m==="waiting_approval"&&p!=="waiting_approval"){const b=((d=u.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${h} — Approval needed`,b.slice(0,120),`approval-${u.id}`)}r.onComplete&&Ar("completion")&&Ro(p)&&m==="idle"&&c(`✅ ${h} — Task complete`,"Agent has finished generating",`complete-${u.id}`),r.onError&&m==="error"&&p!=="error"&&c(`⚠️ ${h} — Error`,"Agent encountered an error",`error-${u.id}`),n.current.set(u.id,m)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,c])}const Fx=/^(run|approve|accept|yes|allow|always)/,Ox=/^(run|approve|accept|yes|allow|always|proceed|save)/,Hx=/^(reject|deny|delete|remove|abort|cancel|no)/;function hi(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function zx(e){const t=hi(e).toLowerCase();return Fx.test(t)?"primary":Hx.test(t)?"danger":"default"}function Wx(e){return Ox.test(hi(e).toLowerCase())?"approve":"reject"}function Kx(e){return e.map((t,r)=>({label:hi(t),variant:zx(t),action:Wx(t),button:t,buttonIndex:r}))}function Ux(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Gx(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 Vx{constructor(){Ze(this,"dedupMap",new Map);Ze(this,"DEDUP_WINDOW_MS",5e3);Ze(this,"DEDUP_MAX_SIZE",50);Ze(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ze(this,"toastCallbacks",[]);Ze(this,"statusEventCallbacks",[]);Ze(this,"resolveActionFn",null);Ze(this,"viewRequestRespondFn",null);Ze(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,o]of this.dedupMap)r-o>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(o=>o.id===t.daemonId&&o.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const o=this.ides.find(i=>i.id===a&&i.type==="adhdev-daemon");if(o)return o}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}isConversationEventMuted(t){const r=t.providerSessionId,n=t.targetSessionId;return!r&&!n?!1:iu({providerSessionId:r,sessionId:n})}handleRawEvent(t,r){var f;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),o=n||t.daemonId||"",i=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),c=`${o}:${t.event}:${i}`;if(this.isDuplicate(c))return;for(const v of this.statusEventCallbacks)v(t);const d=this.isConversationEventMuted(t),u=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,p=(u==null?void 0:u.type)||"";let m=Mt(p);const h=this.resolveOwningDaemon(t);if(h){const v=Ft(h,{fallbackId:h.id});v&&(m=!p||p==="adhdev-daemon"?v:`${v}/${m}`)}let b="",g="info";if(t.event==="agent:generating_completed"){const v=t.duration?` (${t.duration}s)`:"";if(b=`✅ ${m} agent task completed${v}`,g="success",!d)try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started")if(t.event==="agent:waiting_approval"){if(b=`⚡ ${m} approval needed`,g="warning",d)b="";else if((f=t.modalButtons)!=null&&f.length&&this.resolveActionFn){const v=this.resolveActionRouteTarget(t);if(!v)return;const j=this.resolveActionFn,y=Kx(t.modalButtons).map(k=>({label:k.label,variant:k.variant,onClick:()=>{j(v,"resolve_action",{action:k.action,button:k.button,buttonIndex:k.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),w=Ux(m,t.modalMessage,b),N=Date.now();this.emitToast({id:N,message:w,type:g,timestamp:N,targetKey:n||v,actions:y,duration:15e3}),b=""}}else if(t.event==="monitor:no_progress"||t.event==="monitor:long_generating"){const v=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";b=`⚠️ ${m} agent shows no progress${v}`,g="warning",!d&&Ar("browser")&&!document.hasFocus()&&$o(`⚠️ ${m} — No Progress`,`Agent has shown no progress for over ${v.replace(/[()]/g,"")}`,`no-progress-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const v=t.requesterName||"A team member",j=t.requestId,y=t.orgId;if(b=`👁️ ${v} wants to view your session`,g="warning",j&&y&&this.viewRequestRespondFn){const w=Date.now(),N=Gx(y,j,this.viewRequestRespondFn,(k,x)=>console.error(`[EventManager] ${k} view request failed:`,x));this.emitToast({id:w,message:b,type:g,timestamp:w,actions:N,duration:3e4}),b=""}Ar("browser")&&!document.hasFocus()&&$o("👁️ View Request",`${v} wants to view your session`,`view-request-${j}`)}else t.event==="team:view_request_approved"?(b="✅ View request approved",g="success"):t.event==="team:view_request_rejected"&&(b=`❌ ${t.targetName||"Team member"} declined your view request`,g="warning");if(b&&!d){const v=Date.now();this.emitToast({id:v,message:b,type:g,timestamp:v,targetKey:n||t.daemonId,duration:5e3})}}}const ot=new Vx,Ll=new Map;function Yn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ys(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function va(e){return Yn(e)?Yn(e.result)?e.result:e:null}function qx(e){const t=va(e);return!t||!Yn(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function mn(e){const t=va(e);return!t||!Yn(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function mr(e){const t=va(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function hn(e){const t=va(e);return!!t&&t.success===!1}function Yx(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";ot.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";ot.showToast(n.notification.body,a)}}}function Jx(e,t){return e&&Ys(e.currentValue)?e.currentValue:t}function Xx(e,t){return Ys(t)?Ys(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Qx(e,t){var o,i;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if(Ys(c))return c}const n=(o=t.controlValues)==null?void 0:o[e];if(Ys(n))return n;const a=(i=t.defaultValues)==null?void 0:i[e];return Ys(a)?a:void 0}function Rn(e,t){return e.options||t[e.id]||[]}const Zx={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 eb(e,t,r){var n;return((n=Zx[t])==null?void 0:n.has(r.id))===!0}function fi(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!eb(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function Ea(e,t){return{value:t}}function tb(e,t,r){var a;return r?((a=Rn(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const sb={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function rb({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:i}){const{sendCommand:c}=mt(),d=`${e}:${t||n}`,u=sb[n]||"#94a3b8",[p,m]=l.useState({}),h=l.useRef({}),b=l.useRef(i);h.current=p,b.current=i;const g=l.useRef(0),f={};for(const A of o||[])A.defaultValue!==void 0&&(f[A.id]=A.defaultValue);const v={...f,...i||{},...Date.now()<g.current?p:{}};l.useEffect(()=>{i&&Date.now()>g.current&&m({})},[i]);const[j,y]=l.useState(Ll.get(d)||{}),[w,N]=l.useState(null),[k,x]=l.useState(null),S=l.useCallback(async(A,E={})=>{const F={...E,...t&&{targetSessionId:t}};return await c(e,A,F)},[e,t,c]),C=l.useCallback(async(A,E={})=>{const F=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await S("invoke_provider_script",{...F,scriptName:A,...E})},[S,n,r,t]),I=l.useCallback((A,E,F)=>{const z=Jx(F,E);m(D=>({...D,[A.id]:z})),Yx(F==null?void 0:F.effects)},[]),R=l.useCallback((A,E)=>{m(F=>{const z={...F};return E===void 0?delete z[A.id]:z[A.id]=E,z}),g.current=0},[]);if(!o||o.length===0)return null;const L=fi(o,{hostIdeType:r,providerType:n});if(L.length===0)return null;const T=async A=>{if(w===A.id){N(null);return}if(Rn(A,j).length>0){N(A.id);return}if(A.dynamic&&A.listScript){x(A.id);try{const F=await C(A.listScript,{}),z=qx(F);if(!z){const O=mr(F);O&&ot.showToast(O,"warning");return}const D=z.options;y(O=>{const q={...O,[A.id]:D};return Ll.set(d,q),q});const K=Qx(A.id,{localOverrideUntil:g.current,localValues:h.current,controlValues:b.current,defaultValues:f});if(Xx(K,z.currentValue)){const O=z.currentValue;m(q=>({...q,[A.id]:O}))}N(A.id)}catch(F){const z=F instanceof Error?F.message:`Could not load ${A.label}`;ot.showToast(z,"warning")}finally{x(null)}}},_=async(A,E)=>{N(null);const F=(i==null?void 0:i[A.id])??f[A.id];m(z=>({...z,[A.id]:E})),g.current=Date.now()+5e3;try{if(!A.setScript)return;const z=await C(A.setScript,Ea(A,E)),D=mn(z);if(D&&!D.ok||hn(z))throw new Error((D==null?void 0:D.error)||mr(z)||`Could not update ${A.label}`);I(A,E,D)}catch(z){R(A,F);const D=z instanceof Error?z.message:`Could not update ${A.label}`;ot.showToast(D,"warning")}},$=async A=>{const E=Rn(A,j).map(q=>q.value);if(E.length===0)return;const F=String(v[A.id]||""),D=(E.indexOf(F)+1)%E.length,K=E[D];if(typeof K!="string")return;const O=(i==null?void 0:i[A.id])??f[A.id];m(q=>({...q,[A.id]:K})),g.current=Date.now()+5e3;try{if(!A.setScript)return;const q=await C(A.setScript,Ea(A,K)),ne=mn(q);if(ne&&!ne.ok||hn(q))throw new Error((ne==null?void 0:ne.error)||mr(q)||`Could not update ${A.label}`);I(A,K,ne)}catch(q){R(A,O);const ne=q instanceof Error?q.message:`Could not update ${A.label}`;ot.showToast(ne,"warning")}},X=async A=>{const F=!v[A.id],z=(i==null?void 0:i[A.id])??f[A.id];m(D=>({...D,[A.id]:F})),g.current=Date.now()+5e3;try{if(!A.setScript)return;const D=await C(A.setScript,Ea(A,F)),K=mn(D);if(K&&!K.ok||hn(D))throw new Error((K==null?void 0:K.error)||mr(D)||`Could not update ${A.label}`);I(A,F,K)}catch(D){R(A,z);const K=D instanceof Error?D.message:`Could not update ${A.label}`;ot.showToast(K,"warning")}},M=async A=>{if(!A.invokeScript)return;if(A.confirmMessage){const F=[A.confirmTitle,A.confirmMessage,A.confirmLabel].filter(D=>typeof D=="string"&&D.trim().length>0);if(!window.confirm(F.join(`
|
|
30
|
+
|
|
31
|
+
`)))return}const E=(i==null?void 0:i[A.id])??f[A.id];try{const F=await C(A.invokeScript),z=mn(F);if(z&&!z.ok||hn(F))throw new Error((z==null?void 0:z.error)||mr(F)||`Could not run ${A.label}`);z&&I(A,E??!0,z)}catch(F){R(A,E);const z=F instanceof Error?F.message:`Could not run ${A.label}`;ot.showToast(z,"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:`${u}33`,background:`${u}12`,color:u},children:a}),L.map(A=>{const E=String(v[A.id]||""),F=tb(A,j,E),z=w===A.id,D=k===A.id,K=Rn(A,j),O="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium transition-colors whitespace-nowrap";switch(A.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${O} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:z?`${u}55`:"var(--border-default)",background:z?`${u}10`:"var(--surface-tertiary)",color:E?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void T(A),title:A.label,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:D?"Loading…":F||A.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),z&&K.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>N(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:A.label}),K.map(q=>s.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-[12px] transition-colors",style:{background:q.value===E?`${u}14`:"transparent",color:q.value===E?"var(--text-primary)":"var(--text-secondary)",borderLeft:q.value===E?`2px solid ${u}`:"2px solid transparent"},title:q.description||q.label,onMouseEnter:ne=>{ne.currentTarget.style.background=`${u}10`},onMouseLeave:ne=>{ne.currentTarget.style.background=q.value===E?`${u}14`:"transparent"},onClick:()=>void _(A,q.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:q.label}),q.value===E&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:u},children:"✓"})]},q.value))]})]})]},A.id);case"cycle":return s.jsxs("button",{type:"button",className:`${O} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:E?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void $(A),title:`Click to cycle: ${K.map(q=>q.label).join(" → ")}`,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:F||A.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},A.id);case"toggle":return s.jsxs("button",{type:"button",className:`${O} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:E?`${u}44`:"var(--border-default)",background:E?`${u}14`:"var(--surface-tertiary)",color:E?u:"var(--text-muted)"},onClick:()=>void X(A),"aria-pressed":!!E,children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),A.label]},A.id);case"action":return s.jsxs("button",{type:"button",className:`${O} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void M(A),children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:A.resultDisplay==="inline"&&E?`${A.label}: ${E}`:A.label})]},A.id);case"display":return s.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:E?"var(--text-primary)":"var(--text-muted)"},children:[A.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:E?`${A.label}: ${E}`:A.label})]},A.id);default:return null}})]})})}function nb({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:c,controlValues:d}){const{isVisible:u}=ui(),p=fi(c,{hostIdeType:a,providerType:o});return!e||t||p.length===0||!u?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(rb,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:p,controlValues:d})})}const hr=5,uu=10*1024*1024;function ab({hasDraft:e,isBusy:t=!1}){return!e||t}function ob(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 ib(e){if(e.size>uu)return null;const t=await ob(e),r=t.indexOf(",");if(r<0)return null;const n=t.slice(r+1);return{mimeType:e.type||"image/png",data:n,name:e.name,previewUrl:t}}function lb(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const pu=l.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,inlineStatusMessage:i=null,onSend:c,onForceSend:d,canForceSend:u=!1,isActive:p=!0,showControlsToggle:m=!1,animateVisibility:h=!0,onControlsToggle:b,messageInput:g}){const f=l.useRef(null),v=l.useRef(null),[j,y]=l.useState(""),[w,N]=l.useState([]),[k,x]=l.useState(null),[S,C]=l.useState(!1),I=l.useRef(!1),{isVisible:R,toggleVisibility:L}=ui(),T=lb(g),_=!!j.trim()||w.length>0;l.useEffect(()=>{y(""),N([]),x(null)},[t]),l.useEffect(()=>{var D;p&&((D=f.current)==null||D.focus({preventScroll:!0}))},[t,p]),l.useEffect(()=>{const D=f.current;D&&(D.style.height="auto",D.style.height=`${Math.min(D.scrollHeight,160)}px`)},[j]);const $=l.useCallback(async D=>{x(null);const K=Array.from(D).filter(oe=>oe.type.startsWith("image/"));if(K.length===0)return;const O=hr-w.length;if(O<=0){x(`Max ${hr} images`);return}const q=K.slice(0,O);if(q.filter(oe=>oe.size>uu).length>0){x("Image too large (max 10 MB)");return}const ye=(await Promise.all(q.map(ib))).filter(oe=>oe!==null);N(oe=>[...oe,...ye])},[w.length]),X=l.useCallback(D=>{N(K=>K.filter((O,q)=>q!==D))},[]),M=l.useCallback(async()=>{const D=j.trim();if(!D&&w.length===0||a||I.current)return;I.current=!0;const K=w.length>0?[...w]:void 0;try{await c(D,K)!==!1&&(y(""),N([]),x(null))}finally{I.current=!1}},[j,w,a,c]),A=l.useCallback(async()=>{if(!u||!d)return;const D=j.trim();if(!D&&w.length===0||I.current)return;I.current=!0;const K=w.length>0?[...w]:void 0;try{await d(D,K)!==!1&&(y(""),N([]),x(null))}finally{I.current=!1}},[w,u,j,d]),E=l.useCallback(D=>{T&&(D.preventDefault(),C(!0))},[T]),F=l.useCallback(()=>C(!1),[]),z=l.useCallback(D=>{T&&(D.preventDefault(),C(!1),D.dataTransfer.files.length>0&&$(D.dataTransfer.files))},[T,$]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",h?"transition-all duration-200 ease-out":"",S?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:p?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:p?200:0,opacity:p?1:0,transform:p?"translateY(0)":"translateY(10px)",padding:p?"10px 12px":"0 12px",pointerEvents:p?"auto":"none"},"aria-hidden":!p,onDragOver:E,onDragLeave:F,onDrop:z,children:[w.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:w.map((D,K)=>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:D.previewUrl,alt:D.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>X(K),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 ${D.name}`,children:"✕"})]},K))}),s.jsxs("div",{className:"flex gap-2 items-center",title:p?`Send message to ${r}`:void 0,children:[m&&s.jsx("button",{type:"button",onClick:()=>{L(),b==null||b()},"aria-label":R?"Hide controls":"Show controls","aria-pressed":R,title:R?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:s.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),T&&s.jsxs(s.Fragment,{children:[s.jsx("input",{ref:v,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:D=>{D.target.files&&$(D.target.files),D.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var D;return(D=v.current)==null?void 0:D.click()},disabled:w.length>=hr,title:w.length>=hr?`Max ${hr} images`:"Attach image",className:"h-10 w-8 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center disabled:opacity-40","aria-label":"Attach image",children:s.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"})})})]}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("textarea",{ref:f,rows:1,placeholder:o||(T&&w.length>0?"Add a message (optional)...":`Send message to ${r}... (Shift+Enter for newline)`),value:j,onChange:D=>y(D.target.value),onPaste:D=>{T&&D.clipboardData.files.length>0&&Array.from(D.clipboardData.files).some(O=>O.type.startsWith("image/"))&&(D.preventDefault(),$(D.clipboardData.files))},onKeyDown:D=>{D.key==="Enter"&&(D.nativeEvent.isComposing||D.shiftKey||(D.preventDefault(),M()))},className:"w-full rounded-[20px] px-4 py-2 bg-bg-secondary text-sm text-text-primary resize-none leading-[1.4] block",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))",minHeight:40,maxHeight:160,overflowY:"auto",whiteSpace:"pre-wrap"}})}),s.jsx("button",{onClick:()=>{M()},disabled:ab({hasDraft:_,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${_&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:_&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":"Send message",children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:_?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})}),u&&s.jsx("button",{type:"button",onClick:()=>{A()},disabled:!_,className:`h-10 px-3 rounded-full text-[11px] font-medium border border-border-subtle shrink-0 transition-colors ${_?"bg-bg-secondary text-text-primary hover:bg-[var(--surface-tertiary)]":"bg-bg-secondary text-text-muted cursor-default opacity-60"}`,"aria-label":"Force send message now",title:"Force send message now",children:"Force"})]}),(k||T&&S)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${k?"text-red-400":"text-[var(--accent-primary)]"}`,children:k||"Drop image here"}),i&&!k&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),cb=l.createContext(null);function xi(){return l.useContext(cb)}function ct(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Se(...e){for(const t of e){if(typeof t!="string")continue;const r=t.trim();if(r)return r}}function Dt(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function Rt(...e){for(const t of e)if(typeof t=="boolean")return t}function Ba(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function db(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 bi(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 ub(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=ct(n),o=Se(a.path),i=Se(a.commit),c=Se(a.repoPath,a.repo_root)??db(t,o);if(!o||!i)return null;const d={path:o,commit:i,dirty:Rt(a.dirty)??!1,outOfSync:Rt(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:Dt(a.lastCheckedAt,a.last_checked_at)??Date.now()};c&&(d.repoPath=c);const u=Se(a.error);return u&&(d.error=u),d}).filter(n=>n!==null);return r.length>0?r:void 0}function pb(e){return Rt(e.isGitRepo)!==void 0||!!Se(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||!!Se(e.repoRoot,e.repo_root,e.workspace)||Dt(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 Pn(e,t,r){const n=Rt(e.isGitRepo);if(!Object.keys(e).length||!pb(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(w=>typeof w=="string"):[],i=Dt(e.conflicts)??o.length,c=Rt(e.hasConflicts)??i>0,d=Se(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,u=ub(e.submodules,d),p=Se(e.upstreamStatus,e.upstream_status),m=Dt(e.upstreamFetchedAt,e.upstream_fetched_at),h=Se(e.upstreamFetchError,e.upstream_fetch_error),b=Se(e.error),g=Dt(e.staged)??0,f=Dt(e.modified)??0,v=Dt(e.untracked)??0,j=Dt(e.deleted)??0,y=Dt(e.renamed)??0;return{workspace:Se(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:a,branch:Se(e.branch)??null,headCommit:Se(e.headCommit)??null,headMessage:Se(e.headMessage)??null,upstream:Se(e.upstream)??null,upstreamStatus:p??"unchecked",...m!==void 0?{upstreamFetchedAt:m}:{},...h?{upstreamFetchError:h}:{},ahead:Dt(e.ahead)??0,behind:Dt(e.behind)??0,staged:g,modified:f,untracked:v,deleted:j,renamed:y,dirty:Rt(e.dirty,e.isDirty,e.is_dirty)??(g+f+v+j+y>0||c),hasConflicts:c,conflictFiles:o,stashCount:Dt(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??Dt(e.lastCheckedAt,e.last_checked_at)??Date.now(),...u?{submodules:u}:{},...b?{error:b}:{}}}function mb(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+=bi(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 hb(e,t){const r=ct(e.lastGit??e.last_git),n=ct(r.result),a=ct(r.status),o=ct(n.status),i=ct(e.lastProbe??e.last_probe),c=ct(i.git),d=ct(c.result),u=ct(c.status),p=ct(d.status),m=t==null?void 0:t.lastCheckedAt;let h=null;for(const b of[a,o,u,p]){const g=Pn(b,e,{lastCheckedAt:m??Date.now()});if(!g)continue;const f=mb(g);(!h||f>h.score)&&(h={git:g,score:f})}return h==null?void 0:h.git}function fb(e){const t=[Se(e.workspace),Se(e.providerType,e.provider),Se(e.role),Se(e.state,e.status),Se(e.title),Se(e.createdAt,e.created_at),Se(e.startedAt,e.started_at)].filter(r=>!!r);if(t.length!==0)return`synthetic:${t.join("|")}`}function Eo(e){const t=ct(e),r=Se(t.sessionId,t.session_id,t.id)??fb(t);return r?{sessionId:r,...Se(t.providerType,t.provider)?{providerType:Se(t.providerType,t.provider)}:{},...Se(t.state,t.status)?{state:Se(t.state,t.status)}:{},...Se(t.chatStatus,t.chat_status)?{chatStatus:Se(t.chatStatus,t.chat_status)}:{},...Se(t.lifecycle)?{lifecycle:Se(t.lifecycle)}:{},...Se(t.surfaceKind,t.surface_kind)?{surfaceKind:Se(t.surfaceKind,t.surface_kind)}:{},...Se(t.recoveryState,t.recovery_state)?{recoveryState:Se(t.recoveryState,t.recovery_state)}:{},...Se(t.workspace)?{workspace:Se(t.workspace)}:{},...Se(t.title)?{title:Se(t.title)}:{},...Se(t.role)?{role:Se(t.role)}:{},...Rt(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:Rt(t.isSelfCoordinator,t.is_self_coordinator)}:{},...Se(t.statusNote,t.status_note)?{statusNote:Se(t.statusNote,t.status_note)}:{},...Se(t.createdAt,t.created_at)?{createdAt:Se(t.createdAt,t.created_at)}:{},...Se(t.startedAt,t.started_at)?{startedAt:Se(t.startedAt,t.started_at)}:{},...Se(t.lastActivityAt,t.last_activity_at)?{lastActivityAt:Se(t.lastActivityAt,t.last_activity_at)}:{},...Rt(t.isCached,t.is_cached)!==void 0?{isCached:Rt(t.isCached,t.is_cached)}:{}}:null}function xb(e){const t=e&&typeof e=="object"?e:{};return Se(t.id,t.nodeId,t.node_id)}function bb(e,t){if(!t)return!1;const r=t.trim();return r?xb(e)===r:!1}function gb(e){return hb(e,{lastCheckedAt:Date.now()})}function yb(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 vb(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=yb(e);return t.outOfSync?"degraded":t.dirty||vb(e)?"dirty":"online"}function wb(e,t){const r=t?Jn(t):void 0;return!e||e==="unknown"?r:e}function jb(e){const t=Array.isArray(e.activeSessionDetails)?e.activeSessionDetails:Array.isArray(e.active_session_details)?e.active_session_details:Array.isArray(e.sessions)?e.sessions:null;if(t){const o=t.map(Eo).filter(i=>i!==null);if(o.length>0)return o}const r=ct(e.activeSession??e.active_session),n={...r,sessionId:Se(r.sessionId,r.id,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id)},a=Eo(n);return a?[a]:void 0}function kb(e){const t=ct(e.connection);return Object.keys(t).length>0?t:void 0}function Nb(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 gi(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 Dl(e){var n,a,o,i,c,d;let t=0;const r=e.git;return gi(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+=bi(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 Sb(e,t){var g,f,v,j;const r=Dl(e),a=Dl(t)>r?t:e,o=a===t?e:t,i=a.git??o.git,c=(((g=a.providers)==null?void 0:g.length)??0)>0?a.providers:o.providers,d=(((f=a.activeSessions)==null?void 0:f.length)??0)>0?a.activeSessions:o.activeSessions,u=(((v=a.activeSessionDetails)==null?void 0:v.length)??0)>0?a.activeSessionDetails:o.activeSessionDetails,p=(((j=a.providerPriority)==null?void 0:j.length)??0)>0?a.providerPriority:o.providerPriority,m=a.connection??o.connection,h={...o,...a,machineLabel:a.machineLabel||o.machineLabel,workspace:a.workspace||o.workspace,...a.repoRoot||o.repoRoot?{repoRoot:a.repoRoot||o.repoRoot}:{},...a.daemonId||o.daemonId?{daemonId:a.daemonId||o.daemonId}:{},...a.machineId||o.machineId?{machineId:a.machineId||o.machineId}:{},...a.machineStatus||o.machineStatus?{machineStatus:a.machineStatus||o.machineStatus}:{},health:i&&(!a.health||a.health==="unknown")?Jn(i):a.health,providers:c??[],activeSessions:d??[],...u&&u.length>0?{activeSessionDetails:u}:{},...p&&p.length>0?{providerPriority:p}:{},...m?{connection:m}:{},...i?{git:i}:{}},b=ct(a.branchConvergence);return Object.keys(b).length>0?Object.assign(h,{branchConvergence:b}):delete h.branchConvergence,i&&(delete h.gitProbePending,delete h.error),h}function mu(e){const t=ct(e),r=Se(t.nodeId,t.id);if(!r)return null;const n=ct(t.cachedStatus),a=gb(t),o=a?void 0:Pn(ct(t.git),t)??Pn(t,t),i=a??o,c=i?void 0:Pn(ct(n.git),t),d=i??c,u=Se(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),p=Se(t.health),m=a?Jn(d):wb(p,i)||(d?Jn(d):void 0)||Se(n.health)||u||Se(t.status)||"unknown",b=(a?void 0:Se(t.error))??(i?void 0:Se(n.error)),g=jb(t),f=Ba(t.activeSessions),v=(g==null?void 0:g.map(C=>C.sessionId))??[],j=Ba(t.providerPriority),y=Rt(t.gitProbePending,t.git_probe_pending),w=i?void 0:y,N=kb(t),k=ct(t.branchConvergence??t.branch_convergence),x=N==null?void 0:N.state,S=a&&(!(N!=null&&N.reported)||x==="unknown")?Nb(N):N;return{nodeId:r,machineLabel:Se(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:Se(t.workspace,d==null?void 0:d.workspace)||"",...Se(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:Se(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},...Se(t.daemonId,t.daemon_id)?{daemonId:Se(t.daemonId,t.daemon_id)}:{},...Se(t.machineId,t.machine_id)?{machineId:Se(t.machineId,t.machine_id)}:{},...u?{machineStatus:u}:{},...Rt(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Rt(t.isLocalWorktree,t.is_local_worktree)}:{},...Se(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:Se(t.worktreeBranch,t.worktree_branch)}:{},...Se(t.clonedFromNodeId,t.cloned_from_node_id)?{clonedFromNodeId:Se(t.clonedFromNodeId,t.cloned_from_node_id)}:{},health:m,...d?{git:d}:{},...w!==void 0?{gitProbePending:w}:{},providers:Ba(t.providers),activeSessions:f.length>0?f:v,...g&&g.length>0?{activeSessionDetails:g}:{},...j.length>0?{providerPriority:j}:{},...Rt(t.launchReady)!==void 0?{launchReady:Rt(t.launchReady)}:a?{launchReady:!0}:{},...Se(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:Se(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},...Se(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:Se(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...S?{connection:S}:{},...Object.keys(k).length>0?{branchConvergence:k}:{},...b?{error:b}:{}}}function $l(e){const t=new Map;for(const r of e){const n=t.get(r.sessionId);t.set(r.sessionId,n?{...n,...r}:r)}return[...t.values()]}function hu(e,t){const r=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],n=r.map(Eo).filter(a=>a!==null);return n.length===0?t:t.map(a=>{const o=n.filter(c=>{const d=ct(r.find(h=>{const b=ct(h);return Se(b.sessionId,b.session_id,b.id)===c.sessionId})),u=Se(d.nodeId,d.node_id),p=Se(d.daemonId,d.daemon_id),m=Se(d.workspace);return u&&u===a.nodeId?!0:p&&a.daemonId&&p===a.daemonId?!m||!a.workspace||m===a.workspace:!!(m&&a.workspace&&m===a.workspace)});if(o.length===0)return a;const i=$l([...a.activeSessionDetails??[],...o]);return{...a,activeSessionDetails:i,activeSessions:$l([...a.activeSessionDetails??[],...o,...(a.activeSessions??[]).map(c=>({sessionId:c}))]).map(c=>c.sessionId)}})}function Cb(e){const t=ct(e);return Array.isArray(t.sessions)||Array.isArray(t.active_session_details)||Se(t.daemon_id,t.machine_id,t.repo_root,t.worktree_branch,t.cloned_from_node_id)!==void 0||Rt(t.is_local_worktree)!==void 0}function fu(e){const t=new Map,r=[];for(const n of e){const a=Cb(n)?mu(n)??n:n;if(!(a!=null&&a.nodeId))continue;const o=t.get(a.nodeId);if(!o){t.set(a.nodeId,a),r.push(a);continue}const i=Sb(o,a);t.set(a.nodeId,i);const c=r.findIndex(d=>d.nodeId===a.nodeId);c>=0&&(r[c]=i)}return r}function yi(e){const t=fu(e.nodes??[]);return{...e,nodes:hu(e,t)}}function Ib(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:gi(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 Mb(e){const t=Se(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(d=>mu(d)).filter(d=>d!==null):null;if(!t||!n)return null;const a=hu(e,fu(n)),o=Se(e.meshName,e.mesh_name,e.name),i=Se(e.repoIdentity,e.repo_identity),c=Se(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!o||!i||!c?null:{...e,meshId:t,meshName:o,repoIdentity:i,refreshedAt:c,nodes:a}}function Ab(e){var o;let t=0;const r=ct(e.sourceOfTruth),n=ct(r.directPeerTruth);Se(r.currentStatus)==="live_git_and_session_probes"&&(t+=100),r.coordinatorOwnsLiveTruth===!0&&(t+=25),n.satisfied===!0&&(t+=15);for(const i of e.nodes){const c=i.git;if(!c){i.gitProbePending&&(t-=8);continue}t+=10,c.isGitRepo===!0&&(t+=5),c.isGitRepo===!1&&(t+=1),c.branch&&(t+=4),c.upstream&&(t+=3),c.headCommit&&(t+=3),t+=bi(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 Tb(e){const t=e.refreshedAt;if(typeof t!="string"||t.length===0)return 0;const r=Date.parse(t);return Number.isFinite(r)?r:0}const _b=20;function El(e){let t=null;for(const r of e){const n=Mb(ct(r));if(!n)continue;const a=Ab(n),o=Tb(n);if(!t){t={status:n,score:a,refreshedAt:o};continue}(Math.abs(a-t.score)<=_b?o>t.refreshedAt||o===t.refreshedAt&&a>t.score:a>t.score)&&(t={status:n,score:a,refreshedAt:o})}return(t==null?void 0:t.status)??null}function vi(e){const r=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,n=El([r==null?void 0:r.status,r]);return n||El([e==null?void 0:e.status,e])}function Rb(e){var n;if(!e)return null;const t=(n=e.coordinator)==null?void 0:n.meshId;if(typeof t=="string"&&t.trim())return t.trim();const r=e.settings||{};for(const a of["meshNodeFor","meshCoordinatorFor"]){const o=r[a];if(typeof o=="string"&&o.trim())return o.trim()}return null}function Pb(e){const t=(e==null?void 0:e.settings)||{};for(const r of["meshNodeId","nodeId"]){const n=t[r];if(typeof n=="string"&&n.trim())return n.trim()}return null}function Lb(e,t){var a;if(!t)return null;const r=vi(e),n=(a=r==null?void 0:r.nodes)==null?void 0:a.find(o=>bb(o,t));return n?{nodeId:n.nodeId,workspace:n.workspace,repoRoot:n.repoRoot,daemonId:n.daemonId,role:n.role,machineStatus:n.machineStatus,health:n.health,isLocalWorktree:n.isLocalWorktree,worktreeBranch:n.worktreeBranch,launchReady:n.launchReady,providers:n.providers,providerPriority:n.providerPriority,git:n.git?{branch:n.git.branch,headCommit:n.git.headCommit,ahead:n.git.ahead,behind:n.git.behind,dirty:n.git.dirty,upstream:n.git.upstream}:void 0,connection:n.connection?{transport:n.connection.transport,state:n.connection.state,rttMs:n.connection.rttMs}:void 0}:null}function Bl(e){if(!e||!Number.isFinite(e))return"—";try{return`${new Date(e).toLocaleString()} (${e})`}catch{return String(e)}}function Fl(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 Db({sessionId:e,daemonId:t,conv:r,onClose:n}){var N,k;const{sendCommand:a}=mt(),o=xi(),[i,c]=l.useState(!0),[d,u]=l.useState(null),[p,m]=l.useState(null),[h,b]=l.useState(null),[g,f]=l.useState(null),v=l.useMemo(()=>Rb(r),[r]),j=l.useMemo(()=>Pb(r),[r]),y=l.useCallback(async()=>{c(!0),m(null);try{const x=await a(t,"get_session_info",{targetSessionId:e}),S=x&&typeof x=="object"?x:{},C=S.result&&typeof S.result=="object"?S.result:S;C!=null&&C.success?u(C):(m((C==null?void 0:C.error)||"Failed to load session info"),u(null))}catch(x){m((x==null?void 0:x.message)||String(x)),u(null)}finally{c(!1)}},[a,t,e]);l.useEffect(()=>{y()},[y]);const w=l.useCallback(async()=>{if(b(null),f(null),!(!v||!j||!(o!=null&&o.loadMeshStatus)))try{const x=await o.loadMeshStatus(t,v,{refresh:!1}),S=Lb(x,j);if(!S){f("This session is stamped to a mesh node that the coordinator no longer reports.");return}b(S)}catch(x){f((x==null?void 0:x.message)||"Failed to load mesh node info")}},[o,t,v,j]);return l.useEffect(()=>{w()},[w]),l.useEffect(()=>{const x=S=>{S.key==="Escape"&&n()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[n]),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:n,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:x=>x.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:n,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:[i&&s.jsx("div",{className:"text-text-secondary",children:"Loading…"}),p&&s.jsx("div",{className:"text-red-500",children:p}),(d==null?void 0:d.session)&&s.jsxs(Ws,{title:"Session",children:[s.jsx(qe,{k:"Session ID",v:s.jsx(wt,{children:d.session.sessionId})}),s.jsx(qe,{k:"Provider",v:`${d.session.providerName||d.session.providerType} (${d.session.providerType})`}),d.session.transport&&s.jsx(qe,{k:"Transport",v:d.session.transport}),d.session.workspace&&s.jsx(qe,{k:"Workspace",v:s.jsx(wt,{children:d.session.workspace})}),s.jsx(qe,{k:"Spawned at",v:s.jsxs(s.Fragment,{children:[Bl(d.session.spawnedAtMs),d.session.spawnedAtMs?s.jsx("span",{className:"text-text-secondary ml-2",children:Fl(d.session.spawnedAtMs)}):null]})}),d.session.providerSessionId&&s.jsx(qe,{k:"Provider session ID",v:s.jsx(wt,{children:d.session.providerSessionId})}),!d.session.workspace&&(r==null?void 0:r.workspacePath)&&s.jsx(qe,{k:"Workspace",v:s.jsx(wt,{children:r.workspacePath})}),(r==null?void 0:r.machineName)&&s.jsx(qe,{k:"Machine",v:r.machineName}),(r==null?void 0:r.connectionState)&&s.jsx(qe,{k:"Connection",v:r.connectionState}),(r==null?void 0:r.git)&&s.jsx(qe,{k:"Workspace git",v:s.jsxs("span",{children:[r.git.branch||"(detached)",r.git.ahead?` ↑${r.git.ahead}`:"",r.git.behind?` ↓${r.git.behind}`:"",r.git.dirty?" · dirty":" · clean"]})})]}),((N=d==null?void 0:d.session)==null?void 0:N.launch)&&s.jsxs(Ws,{title:"Launch",children:[d.session.launch.command&&s.jsx(qe,{k:"Command",v:s.jsx(wt,{children:d.session.launch.command})}),d.session.launch.cwd&&s.jsx(qe,{k:"Working directory",v:s.jsx(wt,{children:d.session.launch.cwd})}),Array.isArray(d.session.launch.args)&&d.session.launch.args.length>0&&s.jsx(qe,{k:"Args",v:s.jsx(wt,{children:d.session.launch.args.join(" ")})}),Array.isArray(d.session.launch.extraArgs)&&d.session.launch.extraArgs.length>0&&s.jsx(qe,{k:"Extra args",v:s.jsx(wt,{children:d.session.launch.extraArgs.join(" ")})}),Array.isArray(d.session.launch.extraEnvKeys)&&d.session.launch.extraEnvKeys.length>0&&s.jsx(qe,{k:"Extra env",v:s.jsx(wt,{children:d.session.launch.extraEnvKeys.join(", ")})})]}),h&&s.jsxs(Ws,{title:"Mesh node",children:[h.nodeId&&s.jsx(qe,{k:"Node ID",v:s.jsx(wt,{children:h.nodeId})}),h.workspace&&s.jsx(qe,{k:"Workspace",v:s.jsx(wt,{children:h.workspace})}),h.repoRoot&&h.repoRoot!==h.workspace&&s.jsx(qe,{k:"Repo root",v:s.jsx(wt,{children:h.repoRoot})}),h.daemonId&&s.jsx(qe,{k:"Daemon ID",v:s.jsx(wt,{children:h.daemonId})}),h.role&&s.jsx(qe,{k:"Role",v:h.role}),h.machineStatus&&s.jsx(qe,{k:"Machine status",v:h.machineStatus}),h.health&&s.jsx(qe,{k:"Health",v:h.health}),h.isLocalWorktree&&s.jsx(qe,{k:"Worktree",v:h.worktreeBranch?s.jsx(wt,{children:h.worktreeBranch}):"yes"}),typeof h.launchReady=="boolean"&&s.jsx(qe,{k:"Launch ready",v:h.launchReady?"yes":"no"}),h.git&&s.jsx(qe,{k:"Git",v:s.jsxs("span",{children:[h.git.branch||"(detached)",h.git.headCommit?` @ ${String(h.git.headCommit).slice(0,10)}`:"",h.git.ahead?` ↑${h.git.ahead}`:"",h.git.behind?` ↓${h.git.behind}`:"",h.git.dirty?" · dirty":" · clean",h.git.upstream?` · ${h.git.upstream}`:""]})}),h.connection&&s.jsx(qe,{k:"Connection",v:s.jsxs("span",{children:[h.connection.transport||"—",h.connection.state?` · ${h.connection.state}`:"",typeof h.connection.rttMs=="number"?` · ${h.connection.rttMs}ms RTT`:""]})}),Array.isArray(h.providers)&&h.providers.length>0&&s.jsx(qe,{k:"Providers",v:s.jsx(wt,{children:h.providers.join(", ")})}),Array.isArray(h.providerPriority)&&h.providerPriority.length>0&&s.jsx(qe,{k:"Provider priority",v:s.jsx(wt,{children:h.providerPriority.join(" › ")})})]}),!h&&g&&(v||j)&&s.jsx(Ws,{title:"Mesh node",children:s.jsx("div",{className:"text-text-secondary italic",children:g})}),(d==null?void 0:d.coordinator)&&s.jsxs(Ws,{title:"Mesh coordinator",children:[s.jsx(qe,{k:"Mesh ID",v:s.jsx(wt,{children:d.coordinator.meshId})}),d.coordinator.cliType&&s.jsx(qe,{k:"Coordinator CLI",v:d.coordinator.cliType}),s.jsx(qe,{k:"Started at",v:s.jsxs(s.Fragment,{children:[Bl(d.coordinator.startedAt),d.coordinator.startedAt?s.jsx("span",{className:"text-text-secondary ml-2",children:Fl(d.coordinator.startedAt)}):null]})}),d.coordinator.injection&&s.jsx(qe,{k:"Prompt injection",v:`${d.coordinator.injection.mode}${d.coordinator.injection.target?` → ${d.coordinator.injection.target}`:""}`}),d.coordinator.mcpConfigPath&&s.jsx(qe,{k:"MCP config",v:s.jsx(wt,{children:d.coordinator.mcpConfigPath})}),d.coordinator.extraSystemPrompt&&s.jsx(Bo,{title:"Per-launch extra prompt",body:d.coordinator.extraSystemPrompt,defaultOpen:!0}),d.coordinator.systemPrompt&&s.jsx(Bo,{title:"Final system prompt (click to expand)",body:d.coordinator.systemPrompt})]}),((k=d==null?void 0:d.session)==null?void 0:k.runtimeMetadata)!=null&&s.jsx($b,{meta:d.session.runtimeMetadata}),d&&!d.coordinator&&s.jsx("div",{className:"text-text-secondary italic",children:"This isn't a mesh coordinator session, so no coordinator-specific prompt was injected. The agent runs with whatever defaults its CLI ships with."})]}),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 y(),className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:"Refresh"}),s.jsx("button",{type:"button",onClick:n,className:"px-3 py-1 text-sm rounded bg-accent text-white hover:opacity-90",children:"Close"})]})]})})}function Ws({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 qe({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 wt({children:e}){return s.jsx("code",{className:"font-mono text-xs",children:e})}function $b({meta:e}){if(!e||typeof e!="object")return null;const t=e,r=d=>typeof d=="string"&&d.trim()?d:null,n=r(t.runtimeId),a=r(t.lifecycle),o=r(t.surfaceKind),i=r(t.recoveryState),c=Array.isArray(t.attachedClients)?t.attachedClients.length:null;return s.jsxs(Ws,{title:"Runtime",children:[n&&s.jsx(qe,{k:"Runtime ID",v:s.jsx(wt,{children:n})}),a&&s.jsx(qe,{k:"Lifecycle",v:a}),o&&s.jsx(qe,{k:"Surface",v:o}),i&&s.jsx(qe,{k:"Recovery state",v:i}),typeof t.restoredFromStorage=="boolean"&&s.jsx(qe,{k:"Restored from storage",v:t.restoredFromStorage?"yes":"no"}),c!=null&&s.jsx(qe,{k:"Attached clients",v:String(c)}),s.jsx(Bo,{title:"Raw runtime metadata (click to expand)",body:Eb(e)})]})}function Eb(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Bo({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 Bb({sessionId:e,daemonId:t,conv:r}){const[n,a]=l.useState(!1);return!e||!t?null:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:()=>a(!0),title:"Session info — launch args, mesh node, system prompt, …","aria-label":"Session info",className:"inline-flex items-center justify-center w-6 h-6 rounded-full text-text-secondary hover:text-text-primary hover:bg-surface-secondary text-sm leading-none",style:{pointerEvents:"auto"},children:"ⓘ"}),n&&s.jsx(Db,{sessionId:e,daemonId:t,conv:r,onClose:()=>a(!1)})]})}const nt=e=>e.transport==="pty",lr=(e,t)=>nt(e)?e.mode||"terminal":"chat",xu=(e,t)=>nt(e)&&lr(e)==="terminal",rt=e=>e.transport==="acp",Fb=180;function bs(e){return e.streamSource!=="agent-stream"}function Es(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function bu(e){return e.machineName||""}function qr(e){return Es(e)}function es(e){return e.agentType||""}function Xn(e){return e.hostIdeType||""}function wi(e){return e.displayPrimary||e.agentName||"Agent"}function gu(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Ob(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function yu(e){const t=Ob(e),r=Xs(t==null?void 0:t.content),n=Xs(e.lastMessagePreview);return r||n||""}function Hb(e,t=Fb){const r=Xs(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 zb(e){return Hb(yu(e)||e.displaySecondary||"")}function vu(e){return[e.displaySecondary,bu(e)].filter(Boolean)}function tr(e){return e.agentName||Mt(es(e))}function Wb(e){var t,r;if(!bs(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return Mt(Xn(e)||es(e))}function wu(e){return bs(e)?e.sessionId:e.nativeSessionId}function Ol(e){return bs(e)?"native":e.tabKey}function Kb(e){return e.sessionId}function Ub(e,t){if(t)return bs(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function Gb(e,t){const r=es(e),n=bs(e),a=nt(e)||rt(e),o=n?a?tr(e)||(t==null?void 0:t.cliName)||Mt(Xn(e)||r):t!=null&&t.type?Mt(t.type):Mt(Xn(e)||r):tr(e);return{isNativeConversation:n,isCli:nt(e),isAcp:rt(e),isCliTerminal:xu(e),providerType:r,displayLabel:o,targetEntry:Ub(e,t)}}function Ns(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:nt(e)||rt(e)?{agentType:es(e)}:e.streamSource==="agent-stream"?{agentType:es(e)}:t}function Ss(e){return e?qr(e):""}function fr(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function ji(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Hl(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 ju(){return"select_session"}function Vb(){return"open_panel"}function qb({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function zl(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function fn(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Tr(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function ki(e){return e instanceof Error?e.message:String(e||"")}function Wl(e){const t=ki(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Kl(e,t){const r=ki(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function Ul(e,t,r,n={}){const a=Ns(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 wa({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,o]=l.useState(!1),[i,c]=l.useState(!1),[d,u]=l.useState(null),p=l.useRef(!1),m=l.useRef(null);l.useEffect(()=>{u(null)},[t==null?void 0:t.tabKey]);const h=l.useCallback(async(j,y)=>{if(!t||p.current)return!1;const w=j.trim(),N=ji(t);if(qb({hasMessage:!!w,blockedMessage:N,sendInFlight:p.current}))return N&&u(N),!1;const k=Date.now(),x={tabKey:t.tabKey,message:w,timestamp:k};if(zl(m.current,x))return u(null),!0;p.current=!0,c(!0),u(null),m.current=x;try{const S=Ss(t);if(!S)return m.current=fn(m.current,x),u("Unable to send message right now."),!1;const C=await e(S,"send_chat",Ul(w,y,t)),I=Tr(C);if(I!=null&&I.deduplicated)return u(null),!0;if((I==null?void 0:I.sent)===!1)throw new Error((I==null?void 0:I.error)||"Send failed");if((I==null?void 0:I.success)===!1)throw new Error((I==null?void 0:I.error)||"Send failed");return u(null),!0}catch(S){const C=ki(S);return C.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",C):console.warn("Send blocked/failed",S),m.current=fn(m.current,x),u(Hl(S)),!1}finally{p.current=!1,c(!1)}},[t,e]),b=l.useCallback(async(j,y)=>{if(!t||p.current)return!1;const w=j.trim();if(!w&&(!y||y.length===0))return!1;const N=Date.now(),k={tabKey:t.tabKey,message:`force:${w}`,timestamp:N};if(zl(m.current,k))return u(null),!0;p.current=!0,c(!0),u(null),m.current=k;try{const x=Ss(t);if(!x)return m.current=fn(m.current,k),u("Unable to send message right now."),!1;const S=await e(x,"send_chat",Ul(w,y,t,{force:!0})),C=Tr(S);if((C==null?void 0:C.success)===!1||(C==null?void 0:C.sent)===!1)throw new Error((C==null?void 0:C.error)||"Send failed");return u(null),!0}catch(x){return console.warn("Force send blocked/failed",x),m.current=fn(m.current,k),u(Hl(x)),!1}finally{p.current=!1,c(!1)}},[t,e]),g=l.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(j){console.error("Relaunch failed",j)}},[t,e]),f=l.useCallback(async j=>{if(t)try{const w=(t.modalButtons||[]).indexOf(j),N=j.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(N),x=Ss(t);if(!x)return;const S=await e(x,"resolve_action",{button:j,action:k?"approve":"reject",...w>=0&&{buttonIndex:w},...Ns(t)}),C=Tr(S);C.success||r(I=>[...I,{routeId:t.tabKey,text:Kl(j,C==null?void 0:C.error),timestamp:Date.now()}])}catch(y){Wl(y)||console.error("[ModalButton] Error:",y),r(w=>[...w,{routeId:t.tabKey,text:Wl(y)?Kl(j,y):`❌ **${j}** error`,timestamp:Date.now()}])}},[t,e,r]),v=l.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,Vb(),{...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:h,handleForceSendChat:b,handleRelaunch:g,handleModalButton:f,handleFocusAgent:v}}const Yb=10,Jb=8e3,Xb=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function Qb(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 Fo(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(Xb.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=Qb(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=>Fo(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,Fo(a,n,r+1)]))}function xr(e,t){return Array.isArray(e)?e.slice(-t):[]}function Zb(e,t=Date.now()){const r=e&&t-e.firstAt<=Jb,n=r?e.count+1:1;return n>=Yb?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function ku(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:xr(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:xr(t.messages,10),visibleMessagesTail:xr(e.visibleMessages,5),historyMessagesTail:xr(e.chatTailState.historyMessages,5),actionLogsTail:xr(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 Fo(r)}function Nu(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 Su(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 Cu(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 Fa(e,t){return`${e}:${t}`}function eg(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function tg(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Os(e,t){tg()&&console.debug(`[subscription-manager] ${e}`,t)}class sg{constructor(){Ze(this,"active",new Map);Ze(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var p,m;const i=Fa(n.topic,n.key),c=this.active.get(i);let d=!0;if(c)c.handlers.add(a),(!eg(c.request,n)||c.daemonId!==r)&&(c.daemonId=r,c.request=n,d=((p=t.sendData)==null?void 0:p.call(t,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)?this.scheduleRetry(i,t,o.retryIntervalMs):d&&this.clearRetry(i),Os("subscribe_update",{daemonId:r,topic:n.topic,key:n.key,accepted:d})),c.lastUpdate&&a(c.lastUpdate);else{const h={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,h),Os("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((m=t.sendData)==null?void 0:m.call(t,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(i,t,o.retryIntervalMs)}const u=()=>{var g;this.clearRetry(i);const h=this.active.get(i);if(!h||(h.handlers.delete(a),h.handlers.size>0))return;this.active.delete(i);const b={type:"unsubscribe",topic:n.topic,key:n.key};Os("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(g=t.sendData)==null||g.call(t,r,b)};return u.initialSendAccepted=d,u}publish(t){const r=Fa(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Js.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),Js.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=Fa(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;Os("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);Os("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;Os("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 ts=new sg;function rg(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 ng(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 Oa(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function ag(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function og(e){ag()&&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 Qn(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:i}=t,c=i||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:u,childrenByParent:p}=ng(d),m=rg(o,n),h=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,b=u.filter(v=>v.kind==="workspace"&&v.transport==="cdp-page"),g=u.filter(v=>v.kind==="agent"&&v.transport==="pty"),f=u.filter(v=>v.kind==="agent"&&v.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:c,...e.version&&{version:e.version},...h&&{machine:h,platform:h.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:b.some(v=>!!v.cdpConnected)});for(const v of b){const j=m.get(v.id),y=Nr(v,j),w=(p.get(v.id)||[]).map(N=>Nr(N,m.get(N.id)));r.push({id:`${n}:ide:${v.id}`,sessionId:v.id,providerSessionId:v.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:y.parentId,sessionKind:y.kind,transport:y.transport,sessionCapabilities:y.capabilities,type:y.providerType,status:y.cdpConnected?"online":"detected",daemonId:n,instanceId:Oa(n,v.id),workspace:y.workspace,terminals:0,childSessions:w,agents:w.map(N=>({id:N.id,name:N.providerName||N.providerType,type:N.providerType,status:N.status})),activeChat:y.activeChat,...y.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:y.activeInteractivePrompt},chats:[],cdpConnected:y.cdpConnected,...y.lastMessagePreview!==void 0&&{lastMessagePreview:y.lastMessagePreview},...y.lastMessageRole!==void 0&&{lastMessageRole:y.lastMessageRole},...y.lastMessageAt!==void 0&&{lastMessageAt:y.lastMessageAt},...y.lastMessageHash!==void 0&&{lastMessageHash:y.lastMessageHash},lastUpdated:y.lastUpdated,unread:y.unread,lastSeenAt:y.lastSeenAt,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,seenCompletionMarker:y.seenCompletionMarker,surfaceHidden:y.surfaceHidden,...y.controlValues!==void 0&&{controlValues:y.controlValues},...y.providerControls!==void 0&&{providerControls:y.providerControls},...y.summaryMetadata!==void 0&&{summaryMetadata:y.summaryMetadata},...y.settings!==void 0&&{settings:y.settings},...y.messageInput!==void 0&&{messageInput:y.messageInput},timestamp:c})}for(const v of g){const j=m.get(v.id),y=Nr(v,j);r.push({id:`${n}:cli:${v.id}`,sessionId:v.id,providerSessionId:v.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:y.parentId,sessionKind:y.kind,transport:y.transport,sessionCapabilities:y.capabilities,type:y.providerType,agentType:y.providerType,status:y.status||"running",daemonId:n,instanceId:Oa(n,v.id),cliName:y.providerName||y.providerType,mode:y.mode||(j==null?void 0:j.mode)||"terminal",workspace:y.workspace||"",...v.ownerDaemonId&&{ownerDaemonId:v.ownerDaemonId},...v.ownerMachineName&&{ownerMachineName:v.ownerMachineName},activeChat:y.activeChat,...y.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:y.activeInteractivePrompt},...y.resume!==void 0&&{resume:y.resume},...y.runtimeKey!==void 0&&{runtimeKey:y.runtimeKey},...y.runtimeDisplayName!==void 0&&{runtimeDisplayName:y.runtimeDisplayName},...y.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:y.runtimeWorkspaceLabel},...y.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:y.runtimeWriteOwner},...y.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:y.runtimeAttachedClients},...y.lastMessagePreview!==void 0&&{lastMessagePreview:y.lastMessagePreview},...y.lastMessageRole!==void 0&&{lastMessageRole:y.lastMessageRole},...y.lastMessageAt!==void 0&&{lastMessageAt:y.lastMessageAt},...y.lastMessageHash!==void 0&&{lastMessageHash:y.lastMessageHash},lastUpdated:y.lastUpdated,unread:y.unread,lastSeenAt:y.lastSeenAt,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,seenCompletionMarker:y.seenCompletionMarker,surfaceHidden:y.surfaceHidden,...y.controlValues!==void 0&&{controlValues:y.controlValues},...y.providerControls!==void 0&&{providerControls:y.providerControls},...y.summaryMetadata!==void 0&&{summaryMetadata:y.summaryMetadata},...y.settings!==void 0&&{settings:y.settings},...y.messageInput!==void 0&&{messageInput:y.messageInput},timestamp:c,_isCli:!0})}for(const v of f){const j=m.get(v.id),y=Nr(v,j);r.push({id:`${n}:acp:${v.id}`,sessionId:v.id,providerSessionId:v.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:y.parentId,sessionKind:y.kind,transport:y.transport,sessionCapabilities:y.capabilities,type:y.providerType,agentType:y.providerType,status:y.status||"running",daemonId:n,instanceId:Oa(n,v.id),cliName:y.providerName||y.providerType,mode:"chat",workspace:y.workspace||"",...v.ownerDaemonId&&{ownerDaemonId:v.ownerDaemonId},...v.ownerMachineName&&{ownerMachineName:v.ownerMachineName},activeChat:y.activeChat,...y.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:y.activeInteractivePrompt},...y.runtimeKey!==void 0&&{runtimeKey:y.runtimeKey},...y.runtimeDisplayName!==void 0&&{runtimeDisplayName:y.runtimeDisplayName},...y.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:y.runtimeWorkspaceLabel},...y.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:y.runtimeWriteOwner},...y.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:y.runtimeAttachedClients},...y.lastMessagePreview!==void 0&&{lastMessagePreview:y.lastMessagePreview},...y.lastMessageRole!==void 0&&{lastMessageRole:y.lastMessageRole},...y.lastMessageAt!==void 0&&{lastMessageAt:y.lastMessageAt},...y.lastMessageHash!==void 0&&{lastMessageHash:y.lastMessageHash},lastUpdated:y.lastUpdated,unread:y.unread,lastSeenAt:y.lastSeenAt,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,seenCompletionMarker:y.seenCompletionMarker,surfaceHidden:y.surfaceHidden,...y.controlValues!==void 0&&{controlValues:y.controlValues},...y.providerControls!==void 0&&{providerControls:y.providerControls},...y.summaryMetadata!==void 0&&{summaryMetadata:y.summaryMetadata},...y.settings!==void 0&&{settings:y.settings},...y.messageInput!==void 0&&{messageInput:y.messageInput},timestamp:c,_isAcp:!0})}return og(r),r}const ig=15e3,lg=15e3,cg=6e4,dg=1200,Gl=12,ug=8e3,pg=4e3,Ha=new Map,za=new Map,xn=new Set,_r=new Map;function mg(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 Vl(e,t){const r=_r.get(e);!r||r.size===0||(_r.delete(e),r.forEach(n=>n(t)))}function hg(e,t){return new Promise(r=>{const n=_r.get(e)||new Set;_r.set(e,n);const a=i=>{clearTimeout(o),n.delete(a),n.size===0&&_r.delete(e),r(i)},o=setTimeout(()=>a(!1),t);n.add(a)})}function Yr(){const{sendCommand:e,sendData:t}=mt(),{injectEntries:r,getIdes:n}=Br();return l.useCallback(async(a,o)=>{if(!a)return;const i=(o==null?void 0:o.minFreshMs)??cg,c=za.get(a)||0;if(!(o!=null&&o.force)&&xn.has(a)&&c>0||!(o!=null&&o.force)&&c>0&&Date.now()-c<i)return;const d=Ha.get(a);if(d)return d;const u=(async()=>{if(t&&!xn.has(a)){const f=ts.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},v=>{const j=n(),y=j.find(N=>N.id===a),w=Qn(v.status,{daemonId:a,existingDaemon:y,existingEntries:j,timestamp:v.timestamp});w.length>0&&r(w),za.set(a,Date.now()),Vl(a,!0)});if(f.initialSendAccepted?xn.add(a):xn.delete(a),!(o!=null&&o.force)&&f.initialSendAccepted&&await hg(a,dg))return}const p=await e(a,"get_status_metadata"),m=mg(p);if(!m)return;const h=n(),b=h.find(f=>f.id===a),g=Qn(m,{daemonId:a,existingDaemon:b,existingEntries:h,timestamp:m.timestamp||Date.now()});g.length>0&&r(g,{authoritativeDaemonIds:[a]}),za.set(a,Date.now()),Vl(a,!0)})().finally(()=>{Ha.delete(a)});return Ha.set(a,u),u},[n,r,e,t])}function fg(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const xg=60,bg=50;function Iu(e={}){return e.isCliLike?bg:xg}function gg(e={}){return Iu(e)}const Jr=60,yg=1e3,ql=500,Ni=12e4,vg=new Set(["generating","waiting_approval","starting","streaming","working"]),Oo=new Map;function Si(e,t,r){return`${e}::${t}::${r||t}`}function Zn(e=Jr){return{liveMessages:[],hasLiveSnapshot:!1,cursor:wg([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function wg(e,t=Jr){return{tailLimit:t}}function Yl(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 Ho(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(Ho).join(`
|
|
41
|
+
`);if(typeof e=="object"){const t=e;return Ho(t.text??t.content??t.value??"")}return String(e)}function jg(e){return Ho(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function kg(e){return e.length===0||e.every(jg)}function Ng(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="generating"||t==="no_progress"||t==="long_generating"||t==="streaming"||t==="working"||t==="starting"}function Mu(e,t){return Math.max(Math.max(0,t),Array.isArray(e.liveMessages)?e.liveMessages.length:0)}function Sg(e,t,r,n,a){if(!Ng(n))return!1;const o=Mu(e,t);if(o<=0)return!1;if(kg(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 Cg(e,t,r,n){if(r.length!==0||Mu(e,t)<=0||e.hasLiveSnapshot&&e.liveMessages.length===0||!n||typeof n!="object")return!1;const o=n.selected,i=n.fallbackReason,c=n.nativeSource;return o==="native-history"?!1:c==="native-unavailable"?!0:typeof i=="string"&&i.startsWith("native_history_")}function Ig(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}function Jl(e,t){const r=e[t];return typeof r=="string"?r:""}class Mg{constructor(t){Ze(this,"manager");Ze(this,"sendData");Ze(this,"daemonId");Ze(this,"sessionId");Ze(this,"historySessionId");Ze(this,"subscriptionKey");Ze(this,"fallbackRecentCount");Ze(this,"snapshot");Ze(this,"transportSubscription",null);Ze(this,"listeners",new Set);Ze(this,"retainCount",0);Ze(this,"loadHistoryPromise",null);Ze(this,"pendingDisconnectTimer",null);this.manager=t.manager||ts,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=Zn(Math.max(0,t.tailLimit??Jr))}updateOptions(t){const r=this.sendData,n=this.daemonId,a=this.sessionId;if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount)),t.tailLimit!==void 0){const o=Math.max(0,t.tailLimit);o!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:o}},this.transportSubscription&&(this.disconnect(),this.connect()))}this.retainCount>0&&(r!==this.sendData||n!==this.daemonId||a!==this.sessionId)&&(this.disconnect(),this.connect())}getSnapshot(){return this.snapshot}clearLiveSnapshot(){this.snapshot={...Zn(this.snapshot.cursor.tailLimit),hasLiveSnapshot:!0},this.emit()}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=this.snapshot.hasLiveSnapshot,a=n?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),o=await t({offset:this.snapshot.historyOffset,excludeRecentCount:a}),i=Array.isArray(o.messages)?o.messages:[],c=!n&&i.length===0&&o.hasMore!==!0&&this.fallbackRecentCount>0,d=[...i,...this.snapshot.historyMessages],u=d.length>ql?d.slice(d.length-ql):d;this.snapshot={...this.snapshot,historyMessages:u,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:yg}))}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=Jl(t,"sessionId");if(r&&r!==this.sessionId)return;const n=Jl(t,"historySessionId");if(n&&this.historySessionId&&n!==this.historySessionId)return;const a=Ig(t),o=t.messageSource;if(Sg(this.snapshot,this.fallbackRecentCount,a,t.status,o)||Cg(this.snapshot,this.fallbackRecentCount,a,o))return;const i={tailLimit:this.snapshot.cursor.tailLimit};Yl(this.snapshot.liveMessages)===Yl(a)&&this.snapshot.cursor.tailLimit===i.tailLimit||(this.snapshot={...this.snapshot,liveMessages:a,hasLiveSnapshot:!0,cursor:i,messageSource:o},this.emit())}}function Au(e){const t=Si(e.daemonId,e.sessionId,e.historySessionId),r=Oo.get(t);if(r)return r.updateOptions(e),r;const n=new Mg(e);return Oo.set(t,n),n}function Ag(e,t,r){if(!e||!t)return;const n=`${e}::${t}::`,a=Si(e,t,r);for(const[o,i]of Oo.entries())(o===a||o.startsWith(n))&&i.clearLiveSnapshot()}function Tg(e,t){return{...e,loadHistoryPage:t}}function _g(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Rg(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(vg.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??Ni)),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 Pg(e=Ni){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Lg(e,t={}){const r=new Set,n=[];for(const a of e){if(!Rg(a,t))continue;const o=qr(a),i=a.sessionId||"";if(!o||!i)continue;const c=Vr(a),d=Si(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(_g),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Dg(e,t){const{sendData:r,sendCommand:n}=mt(),a=(t==null?void 0:t.enabled)!==!1,o=qr(e),i=e.sessionId||"",c=Vr(e)||i,d=`daemon:${o}:session:${i}`,u=Math.max(0,(t==null?void 0:t.tailLimit)??Jr),p=e.messages.length,m=l.useMemo(()=>!a||!o||!i?null:Au({daemonId:o,sessionId:i,historySessionId:c,subscriptionKey:d,sendData:r,tailLimit:u,fallbackRecentCount:p}),[o,a,c,r,i,d,u]);l.useEffect(()=>{m==null||m.updateOptions({fallbackRecentCount:p})},[m,p]);const[h,b]=l.useState(()=>(m==null?void 0:m.getSnapshot())||Zn(u));l.useEffect(()=>{if(!m){b(Zn(u));return}m.retain(),b(m.getSnapshot());const f=m.subscribe(v=>{b(v)});return()=>{f(),m.release()}},[m,u]);const g=l.useCallback(async()=>{!m||!o||!i||await m.loadHistoryPage(async({offset:f,excludeRecentCount:v})=>{const j=e.agentType,y=await n(o,"chat_history",{agentType:j,offset:f,limit:30,targetSessionId:i,historySessionId:c,excludeRecentCount:v}),w=y&&typeof y=="object"&&"result"in y?y.result||{}:y||{};return{messages:Array.isArray(w.messages)?w.messages:[],hasMore:w.hasMore===!0}})},[e.agentType,m,o,c,n,i]);return l.useMemo(()=>Tg(h,g),[g,h])}function $g(e,t){const{sendData:r}=mt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??Jr),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Ni)),i=Pg(o),[c,d]=l.useState(0);l.useEffect(()=>{if(!n||e.length===0)return;const p=setInterval(()=>{d(m=>m+1)},i);return()=>{clearInterval(p)}},[e.length,n,i]);const u=l.useMemo(()=>Lg(e,{recentActivityMs:o}),[e,o,c]);l.useEffect(()=>{if(!n||!r||u.descriptors.length===0)return;const p=u.descriptors.map(m=>Au({...m,sendData:r,tailLimit:a}));return p.forEach(m=>{m.retain()}),()=>{p.forEach(m=>m.release())}},[u.signature,n,r,a])}function Eg(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function Xl(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 Bg(e,t){if(e.length===0)return[];if(t.some(Xl))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||!Xl(o))continue;const i=String(o.role||"").toLowerCase();n.has(i)||(n.add(i),r.unshift(o))}return r}function Fg(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=Bg(o,i),d=c.length>0?[...c,...i]:i;return t.length===0?d:[...t,...d]}function Og(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Hg(e){return Og(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Ln=new Map,zo=new Set;function Ql(e,t){!e||Ln.get(e)===t||(t?Ln.set(e,!0):Ln.delete(e),zo.forEach(n=>n(e,t)))}function zg(e){return e?Ln.get(e)===!0:!1}function Wg(e){return zo.add(e),()=>{zo.delete(e)}}function Kg(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function Ug(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function Gg(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Tu(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function _u(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 Vg(e){return Tu(e)?!1:e.inboxBucket==="task_complete"&&_u(e).length>0}function Zl(e){return e.branch||"detached HEAD"}function qg(e){if(e.error)return`${Zl(e)} · Git error: ${e.error}`;const t=[Zl(e)];return e.changedFiles>0?t.push(Kg(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 Yg(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${qg(t)}`}function Jg(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function Xg(e,t={}){if(t.enabled===!1)return[];if(!Gg(e))return[];const r=Tu(e)?"working":Vg(e)?"complete":null;if(!r)return[];const n=r==="complete"?_u(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${Ug(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:Yg(r,e.git),timestamp:Jg(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 Qg=60;function Zg(e){return e.status==="no_progress"||e.status==="long_generating"?"Agent shows no progress.":e.status==="generating"||e.status==="streaming"?"Agent is generating.":e.status==="waiting_approval"&&(!e.modalButtons||e.modalButtons.length===0)?"Agent is waiting for approval. Approval controls will appear when available.":null}function Wo({activeConv:e,ideEntry:t,handleSendChat:r,handleForceSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:d,userName:u,scrollToBottomRequestNonce:p,isInputActive:m=!0,isVisible:h=!0}){var je,de,U,H,Y,se,xe;const b=l.useRef(new Map),g=l.useRef(void 0),f=Yr(),{sendCommand:v}=mt(),{isVisible:j}=ui();Gr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:d.length,isSendingChat:a});const y=Ct.useMemo(()=>or(e),[e.status,e.connectionState]);Ct.useEffect(()=>{const Z=e.sessionId;if(Z)return Ql(Z,y.isGenerating),()=>{Ql(Z,!1)}},[e.sessionId,y.isGenerating]);const w=l.useMemo(()=>Gb(e,t),[e,t]),N=l.useMemo(()=>{var Z;return fi((Z=w.targetEntry)==null?void 0:Z.providerControls,{hostIdeType:e.hostIdeType,providerType:w.providerType})},[e.hostIdeType,w.providerType,(je=w.targetEntry)==null?void 0:je.providerControls]),k=Iu({isCliLike:w.isCli||w.isAcp}),x=gg({isCliLike:w.isCli||w.isAcp}),S=Dg(e,{enabled:h&&!!e.sessionId,tailLimit:x}),[C,I]=l.useState(k),[R,L]=l.useState(()=>xl()),T=e.tabKey,_=S.historyMessages,$=S.hasMoreHistory,X=S.historyError,M=Eg(e,S),A=Ld(M).length;l.useEffect(()=>{I(k)},[k,T]);const E=Math.max(0,M.length-C),F=wi(e),z=qr(e),D=Hg(e),K=ji(e),O=Zg(e),q=o||K,ne=q||O,J=!!K,[ye,oe]=l.useState(!1);l.useEffect(()=>{const Z=w.targetEntry;z&&(!Z||Z.providerControls===void 0||Z.controlValues===void 0)&&f(z,{minFreshMs:3e4}).catch(()=>{})},[z,w.isAcp,(de=w.targetEntry)==null?void 0:de.providerControls,(U=w.targetEntry)==null?void 0:U.controlValues,f]);const B=l.useCallback(async()=>{if(!ye){if(M.length>C){I(Z=>Math.min(M.length,Z+Qg));return}oe(!0);try{await S.loadHistoryPage()}finally{oe(!1)}}},[S,ye,M.length,C]),{allMessages:W,receivedAtMap:ve}=l.useMemo(()=>{const Z=Fg({historyMessages:_,liveMessages:M,visibleLiveCount:C}),P=Xg(e),ie=P.length>0?[...Z,...P]:Z,be={};return ie.forEach((ue,te)=>{const Me=`${e.tabKey}:${Vn(ue,te)}`;let Ae=fg(ue)||b.current.get(Me)||0;Ae||(Ae=Date.now(),b.current.set(Me,Ae)),be[Vn(ue,te)]=Ae}),{allMessages:ie,receivedAtMap:be}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,E,_,M,C]),we=l.useMemo(()=>d.filter(Z=>Z.routeId===e.tabKey).sort((Z,P)=>Z.timestamp-P.timestamp),[d,e.tabKey]),fe=l.useCallback(async()=>{var te,Me;if(!z)return;const Z=ku({activeConv:e,visibleMessages:W,actionLogs:d,controls:(te=w.targetEntry)==null?void 0:te.providerControls,controlValues:(Me=w.targetEntry)==null?void 0:Me.controlValues,visibleBarControlCount:N.length,chatTailState:{liveMessages:S.liveMessages,hasLiveSnapshot:S.hasLiveSnapshot,hasMoreHistory:$,historyError:X,historyMessages:_},ui:{controlsVisible:j,visibleLiveCount:C,activityVisible:R,activityCount:A,hiddenLiveCount:E,isInputActive:m,isVisible:h}}),P=await v(z,"get_chat_debug_bundle",{agentType:w.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:Z}),ie=Tr(P),be=Cu(ie),ue=await Su(be);ue==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),ot.showToast(Nu(ie,{locatorCopyStatus:ue}),ue==="failed"?"warning":"success")},[e,d,A,W,j,S.hasLiveSnapshot,S.liveMessages,w.providerType,(H=w.targetEntry)==null?void 0:H.controlValues,(Y=w.targetEntry)==null?void 0:Y.providerControls,z,$,E,_,m,h,X,v,R,N.length,C]);l.useEffect(()=>{const Z=P=>{P.key===Rd&&L(xl())};return window.addEventListener("storage",Z),()=>window.removeEventListener("storage",Z)},[]);const Ne=l.useCallback(()=>{const Z=Zb(g.current);g.current=Z.state,Z.shouldCollect&&fe().catch(P=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",P),ot.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[fe]),re=l.useMemo(()=>{if(M.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((y.isGenerating||e.status==="streaming")&&oe(!1),e.status==="not_monitored"&&D)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(er,{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(Qs,{size:14})," Open ",F," 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"&&D)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(Id,{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(Qs,{size:14})," Open ",F," 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"&&!ye)return!$&&_.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,D,i,$,_.length,c,ye,M.length,F,y.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col relative",children:[s.jsx("div",{className:"chat-activity-toggle-bar",children:s.jsx("div",{className:"ml-auto flex items-center gap-1",children:s.jsx(Bb,{sessionId:e.sessionId,daemonId:e.daemonId,conv:e})})}),s.jsx(Kf,{messages:W,actionLogs:we,agentName:tr(e)||F||"Agent",userName:u,isCliMode:w.isCli||w.isAcp,isWorking:y.isGenerating,contextKey:e.tabKey,receivedAtMap:ve,lastMessageHash:e.lastMessageHash,showActivityMessages:R,onLoadMore:B,isLoadingMore:ye,hasMoreHistory:$,hiddenLiveCount:E,loadError:X??void 0,emptyState:re,scrollToBottomRequestNonce:p,isVisible:h}),s.jsx(nb,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:w.providerType,displayLabel:w.displayLabel,controls:(se=w.targetEntry)==null?void 0:se.providerControls,controlValues:(xe=w.targetEntry)==null?void 0:xe.controlValues,isActive:m,isCliTerminal:w.isCliTerminal}),!w.isCliTerminal&&s.jsx(pu,{contextKey:e.tabKey,panelLabel:F,isSending:a,isBusy:J,statusMessage:ne,inlineStatusMessage:q,onSend:r,onForceSend:n,canForceSend:!!n&&y.isGenerating&&!J,isActive:m,showControlsToggle:N.length>0,onControlsToggle:Ne,messageInput:e.messageInput})]})}let Ru=ss;function Pu(){return Ru()}class e0{constructor(){Ze(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 Lu=new e0;class t0{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 ft=new t0;function s0(e){e.dashboardWS&&(Lu=e.dashboardWS),e.connectionManager&&(ft=e.connectionManager),e.useDaemonsHook&&(Ru=e.useDaemonsHook)}const r0=.5,n0=1.25;function pt(e){return wi(e)}function Ps(e){return vu(e).join(" · ")}function a0(e){var a,o,i;const t=[],r=typeof((a=e.settings)==null?void 0:a.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0,n=!!((o=e.coordinator)!=null&&o.meshId)||typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0;return r&&t.push("Mesh node"),n&&t.push("Coordinator"),t}function o0(e){var i,c,d;const t=[],r=typeof((i=e.settings)==null?void 0:i.meshNodeFor)=="string"?e.settings.meshNodeFor.trim():"",n=typeof((c=e.coordinator)==null?void 0:c.meshId)=="string"?e.coordinator.meshId.trim():"",a=typeof((d=e.settings)==null?void 0:d.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor.trim():"",o=n||a;if(r&&t.push(`Mesh node: ${r}`),o&&t.push(`Coordinator: ${o}`),e.meshQueueStats){const{pending:u,assigned:p,completed:m,failed:h}=e.meshQueueStats;t.push(`Queue: ${u} pending, ${p} assigned, ${m} completed, ${h} failed`)}return t.join(" · ")}function Du(e){const t=yu(e);return t||(e.title?e.title:Ps(e)||"No messages yet")}function $u(e,t){const{isReconnecting:r,isConnecting:n}=or(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function i0(e,t){const r=["Chat",...vu(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function Cs(e){return $u(e)||Ps(e)}function l0(e){return`${pt(e)} · ${Du(e)}`}function c0(e){const t=Xn(e),r=t?Mt(t):tr(e);return`${pt(e)} — ${r||"Agent"}`}function d0(e){return tr(e)||"CLI"}function Eu(e){return gu(e)}function Bu(e){return e?`Remote · ${pt(e)||e.workspaceName||"Session"}`:"Remote"}const ec=[{kind:"regex",label:"section matches",hint:"regex against a screen section",make:e=>({section:e[0],matches:""})},{kind:"elapsed",label:"elapsed_ms",hint:"N ms since state entered",make:()=>({elapsed_ms:1e3})},{kind:"stable",label:"stable_ms",hint:"region unchanged for N ms",make:()=>({stable_ms:1e3,cursor_above:5})},{kind:"changed",label:"changed",hint:"region changed vs prev frame",make:()=>({cursor_above:3,changed:!0})},{kind:"all",label:"all (AND)",hint:"every child must match",make:()=>({all:[]})},{kind:"any",label:"any (OR)",hint:"some child must match",make:()=>({any:[]})},{kind:"not",label:"not",hint:"invert a condition",make:()=>({not:{matches:""}})}],u0=[{label:"active spinner (busy)",cond:{section:"body",matches:"(?:^|\\n)\\s*[·✢✳✶✽✷✸✹]\\s+\\w.*?(?:…|\\.\\.\\.)"}},{label:"completion marker (done)",cond:{section:"body",matches:"✻\\s+\\w+ed\\s+for\\s+(?:\\d+h\\s+)?(?:\\d+m\\s+)?\\d+s"}},{label:"approval prompt (❯ 1.)",cond:{section:"footer",matches:"(?:^|\\n)\\s*[❯›>]\\s*1\\.\\s*.+"}},{label:"picker (Select a …)",cond:{section:"modal",matches:"Select (?:a |an )?(?:model|mode|option)\\b"}},{label:"stable 1.2s (settled)",cond:{stable_ms:1200,cursor_above:5}}];function p0(e){return"all"in e?"all":"any"in e?"any":"not"in e?"not":"elapsed_ms"in e?"elapsed":"stable_ms"in e&&!("changed"in e)?"stable":"changed"in e?"changed":"regex"}function Ci({cond:e,path:t,sections:r,onChange:n,onRemove:a,onPreview:o,preview:i}){const c=p0(e),d=i[t],u=p=>{const m=ec.find(h=>h.kind===p);m&&n(m.make(r))};return s.jsxs("div",{className:"border border-zinc-700/60 rounded bg-zinc-800/30 p-1.5 space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("select",{value:c,onChange:p=>u(p.target.value),className:"bg-zinc-900 text-zinc-200 text-[10px] font-mono rounded border border-zinc-700 px-1 py-0.5",children:ec.map(p=>s.jsx("option",{value:p.kind,children:p.label},p.kind))}),(c==="regex"||c==="stable"||c==="changed"||c==="elapsed")&&s.jsx("button",{type:"button",className:"text-[10px] text-sky-300 hover:text-sky-100 px-1.5 py-0.5 rounded border border-sky-700/40 hover:bg-sky-600/20",onClick:()=>o(t,e),children:"test"}),d&&d!=="loading"&&s.jsx("span",{className:`text-[10px] font-mono px-1.5 py-0.5 rounded ${d.result?"text-green-200 bg-green-600/25":"text-zinc-400 bg-zinc-700/40"}`,children:d.result?"match ✓":"no match"}),d==="loading"&&s.jsx("span",{className:"text-[10px] text-zinc-500",children:"testing…"}),a&&s.jsx("button",{type:"button",className:"ml-auto text-zinc-500 hover:text-red-300 text-xs px-1",onClick:a,children:"×"})]}),c==="regex"&&s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs("select",{value:e.section??"",onChange:p=>n({...e,section:p.target.value||void 0}),className:"bg-zinc-900 text-sky-300 text-[10px] font-mono rounded border border-zinc-700 px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(whole screen)"}),r.map(p=>s.jsx("option",{value:p,children:p},p))]}),s.jsx("input",{value:e.matches??"",onChange:p=>n({...e,matches:p.target.value}),placeholder:"regex",spellCheck:!1,className:"flex-1 bg-black/40 text-zinc-200 text-[10px] font-mono rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"})]}),c==="elapsed"&&s.jsx(hs,{label:"elapsed_ms",value:e.elapsed_ms,onChange:p=>n({elapsed_ms:p})}),c==="stable"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(hs,{label:"stable_ms",value:e.stable_ms,onChange:p=>n({...e,stable_ms:p})}),s.jsx(hs,{label:"cursor_above",value:e.cursor_above??0,onChange:p=>n({...e,cursor_above:p||void 0})})]}),c==="changed"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(hs,{label:"cursor_above",value:e.cursor_above,onChange:p=>n({...e,cursor_above:p})}),s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-zinc-400",children:[s.jsx("input",{type:"checkbox",checked:!!e.changed,onChange:p=>n({...e,changed:p.target.checked}),className:"accent-sky-500"}),"changed"]})]}),(c==="all"||c==="any")&&s.jsx(m0,{kind:c,cond:e,path:t,sections:r,onChange:n,onPreview:o,preview:i}),c==="not"&&s.jsx("div",{className:"pl-2 border-l border-zinc-700",children:s.jsx(Ci,{cond:e.not,path:`${t}.not`,sections:r,onChange:p=>n({not:p}),onPreview:o,preview:i})})]})}function m0({kind:e,cond:t,path:r,sections:n,onChange:a,onPreview:o,preview:i}){const c=(e==="all"?t.all:t.any)??[],d=u=>a(e==="all"?{all:u}:{any:u});return s.jsxs("div",{className:"pl-2 border-l border-zinc-700 space-y-1",children:[c.map((u,p)=>s.jsx(Ci,{cond:u,path:`${r}.${e}[${p}]`,sections:n,onChange:m=>d(c.map((h,b)=>b===p?m:h)),onRemove:()=>d(c.filter((m,h)=>h!==p)),onPreview:o,preview:i},p)),s.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[s.jsx("button",{type:"button",className:"text-[10px] text-zinc-300 hover:text-white px-1.5 py-0.5 rounded border border-zinc-700 hover:bg-zinc-700/40",onClick:()=>d([...c,{section:n[0],matches:""}]),children:"+ condition"}),u0.map(u=>s.jsxs("button",{type:"button",className:"text-[10px] text-sky-300/80 hover:text-sky-100 px-1.5 py-0.5 rounded border border-sky-700/30 hover:bg-sky-600/15",onClick:()=>d([...c,JSON.parse(JSON.stringify(u.cond))]),title:"insert verified pattern",children:["+ ",u.label]},u.label))]})]})}function hs({label:e,value:t,onChange:r}){return s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-zinc-400 font-mono",children:[e,s.jsx("input",{type:"number",value:Number.isFinite(t)?t:0,onChange:n=>r(Number(n.target.value)),className:"w-20 bg-black/40 text-zinc-200 rounded border border-zinc-700 px-1 py-0.5 outline-none focus:border-sky-500/50"})]})}function h0({sections:e,otherSectionIds:t,onChange:r,onTest:n,testResult:a}){const o=Object.keys(e),i=a&&a!=="loading"&&!("error"in a)?Object.fromEntries(a.sections.map(m=>[m.id,m])):{},c=(m,h)=>{if(!h||h===m||e[h])return;const b={};for(const[g,f]of Object.entries(e))b[g===m?h:g]=f;r(b)},d=(m,h)=>r({...e,[m]:h}),u=m=>{const h={...e};delete h[m],r(h)},p=()=>{let m="section",h=1;for(;e[m];)m=`section${h++}`;r({...e,[m]:{from_top:0}})};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-zinc-400 text-[10px] uppercase tracking-widest font-semibold",children:"Sections"}),s.jsx("span",{className:"text-zinc-600 text-[10px]",children:"— how the screen is split; conditions match against these"}),s.jsx("button",{type:"button",className:"ml-auto text-[10px] text-sky-300 hover:text-sky-100 px-1.5 py-0.5 rounded border border-sky-700/40 hover:bg-sky-600/20",onClick:n,title:"Resolve all sections against the live session screen",children:a==="loading"?"testing…":"test on live screen"}),s.jsx("button",{type:"button",className:"text-[10px] text-zinc-300 hover:text-white px-1.5 py-0.5 rounded border border-zinc-700 hover:bg-zinc-700/40",onClick:p,children:"+ section"})]}),a&&a!=="loading"&&"error"in a&&s.jsx("div",{className:"text-red-300 bg-red-900/30 border border-red-700/40 rounded p-1.5 text-[10px] mb-1",children:a.error}),s.jsx("div",{className:"space-y-1.5",children:o.map(m=>{var f;const h=e[m],b=h.anchor!=null?"anchor":"positional",g=v=>{v==="anchor"?d(m,{anchor:h.anchor??"^",anchor_last:h.anchor_last,until:h.until}):d(m,{from_top:h.from_top??0,until:h.until})};return s.jsxs("div",{className:"border border-zinc-700/60 rounded bg-zinc-800/30 p-2 space-y-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{value:m,onChange:v=>c(m,v.target.value.trim()),className:"w-28 bg-black/40 text-sky-300 font-mono text-[11px] rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"}),s.jsxs("div",{className:"inline-flex rounded border border-zinc-700 overflow-hidden text-[10px]",children:[s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${b==="positional"?"bg-sky-600/30 text-sky-100":"text-zinc-400 hover:bg-zinc-700/40"}`,onClick:()=>g("positional"),children:"positional"}),s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${b==="anchor"?"bg-sky-600/30 text-sky-100":"text-zinc-400 hover:bg-zinc-700/40"}`,onClick:()=>g("anchor"),children:"anchor"})]}),s.jsx("button",{type:"button",className:"ml-auto text-zinc-500 hover:text-red-300 text-sm px-1",onClick:()=>u(m),children:"×"})]}),b==="positional"?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx(hs,{label:"from_top",value:typeof h.from_top=="number"?h.from_top:0,onChange:v=>d(m,{...h,from_top:v,from_bottom:void 0})}),s.jsx(hs,{label:"from_bottom",value:typeof h.from_bottom=="number"?h.from_bottom:0,onChange:v=>d(m,{...h,from_bottom:v||void 0})}),s.jsx(tc,{def:h,otherIds:t(m),onChange:v=>d(m,v)})]}):s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-[10px] text-zinc-500 w-16",children:"anchor"}),s.jsx("input",{value:h.anchor??"",onChange:v=>d(m,{...h,anchor:v.target.value}),placeholder:"^regex locating section start",spellCheck:!1,className:"flex-1 bg-black/40 text-zinc-200 text-[10px] font-mono rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"}),s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-zinc-400",children:[s.jsx("input",{type:"checkbox",checked:!!h.anchor_last,onChange:v=>d(m,{...h,anchor_last:v.target.checked||void 0}),className:"accent-sky-500"}),"last"]})]}),s.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s.jsx(tc,{def:h,otherIds:t(m),onChange:v=>d(m,v)})}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-[10px] text-zinc-500 w-16",children:"ctx next"}),s.jsx("input",{value:((f=h.anchor_context)==null?void 0:f.next)??"",onChange:v=>d(m,{...h,anchor_context:{...h.anchor_context,next:v.target.value||void 0}}),placeholder:"optional: line after anchor must match",spellCheck:!1,className:"flex-1 bg-black/40 text-zinc-300 text-[10px] font-mono rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"})]})]}),i[m]&&s.jsxs("div",{className:"border-t border-zinc-700/50 pt-1",children:[s.jsxs("div",{className:"text-[9px] text-zinc-500 mb-0.5",children:["captured lines ",i[m].fromLine,"–",i[m].toLine,i[m].text.trim()===""&&s.jsx("span",{className:"text-amber-400 ml-1",children:"(empty — check bounds)"})]}),s.jsx("pre",{className:"font-mono text-[10px] text-zinc-300 whitespace-pre-wrap break-all bg-black/40 rounded border border-zinc-700/50 px-2 py-1 max-h-28 overflow-y-auto",children:i[m].text||"(empty)"})]})]},m)})})]})}function tc({def:e,otherIds:t,onChange:r}){const n=e.until??"",a=n.startsWith("^");return s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-zinc-400",children:["until",s.jsxs("select",{value:a?"__regex__":n,onChange:o=>{const i=o.target.value;r(i===""?{...e,until:void 0}:i==="__regex__"?{...e,until:n.startsWith("^")?n:"^"}:{...e,until:i})},className:"bg-zinc-900 text-sky-300 rounded border border-zinc-700 px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(none)"}),t.map(o=>s.jsx("option",{value:o,children:o},o)),s.jsx("option",{value:"__regex__",children:"regex…"})]}),a&&s.jsx("input",{value:n,onChange:o=>r({...e,until:o.target.value}),spellCheck:!1,className:"w-40 bg-black/40 text-zinc-200 font-mono rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"})]})}function f0({model:e,onChange:t,onPreview:r,preview:n,onTestSections:a,sectionPreview:o}){const i=e.states.map(m=>m.id),c=Object.keys(e.sections??{}),d=l.useCallback(m=>t({...e,...m}),[e,t]),u=(m,h)=>d({states:e.states.map((b,g)=>g===m?{...b,...h}:b)}),p=(m,h)=>d({transitions:e.transitions.map((b,g)=>g===m?{...b,...h}:b)});return s.jsxs("div",{className:"space-y-3",children:[s.jsx(h0,{sections:e.sections??{},otherSectionIds:m=>c.filter(h=>h!==m),onChange:m=>d({sections:m}),onTest:()=>a(e.sections??{}),testResult:o}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-zinc-400 text-[10px] uppercase tracking-widest font-semibold",children:"States"}),s.jsx("button",{type:"button",className:"text-[10px] text-zinc-300 hover:text-white px-1.5 py-0.5 rounded border border-zinc-700 hover:bg-zinc-700/40",onClick:()=>d({states:[...e.states,{id:`state${e.states.length}`,label:"New"}]}),children:"+ state"})]}),s.jsx("div",{className:"space-y-1.5",children:e.states.map((m,h)=>s.jsxs("div",{className:"border border-zinc-700/60 rounded bg-zinc-800/30 p-2 space-y-1",children:[s.jsxs("div",{className:"flex items-end gap-2 flex-wrap",children:[s.jsxs("label",{className:"flex flex-col gap-0.5",children:[s.jsx("span",{className:"text-[9px] text-zinc-500 uppercase tracking-wide",children:"id (used by transitions)"}),s.jsx("input",{value:m.id,onChange:b=>u(h,{id:b.target.value}),placeholder:"idle",className:"w-32 bg-black/40 text-sky-300 font-mono text-[11px] rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"})]}),s.jsxs("label",{className:"flex flex-col gap-0.5 flex-1",children:[s.jsx("span",{className:"text-[9px] text-zinc-500 uppercase tracking-wide",children:"label (shown in dashboard)"}),s.jsx("input",{value:m.label,onChange:b=>u(h,{label:b.target.value}),placeholder:"Ready",className:"w-full bg-black/40 text-zinc-200 text-[11px] rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"})]}),s.jsx("button",{type:"button",className:"text-zinc-500 hover:text-red-300 text-sm px-1 pb-0.5",onClick:()=>d({states:e.states.filter((b,g)=>g!==h)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-zinc-400 flex-wrap",children:[s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"radio",name:"initial",checked:!!m.initial,onChange:()=>d({states:e.states.map((b,g)=>({...b,initial:g===h}))}),className:"accent-sky-500"}),"initial"]}),s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"checkbox",checked:!!m.modal,onChange:b=>u(h,{modal:b.target.checked||void 0}),className:"accent-sky-500"}),"modal"]}),s.jsxs("label",{className:"flex items-center gap-1",children:["status",s.jsxs("select",{value:m.status??"",onChange:b=>u(h,{status:b.target.value||void 0}),className:"bg-zinc-900 text-zinc-200 rounded border border-zinc-700 px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(auto)"}),s.jsx("option",{value:"idle",children:"idle"}),s.jsx("option",{value:"generating",children:"generating"}),s.jsx("option",{value:"approval",children:"approval"})]})]})]})]},h))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-zinc-400 text-[10px] uppercase tracking-widest font-semibold",children:"Transitions"}),s.jsx("button",{type:"button",className:"text-[10px] text-zinc-300 hover:text-white px-1.5 py-0.5 rounded border border-zinc-700 hover:bg-zinc-700/40",onClick:()=>d({transitions:[...e.transitions,{from:i[0]??"",to:i[0]??""}]}),children:"+ transition"})]}),s.jsx("div",{className:"space-y-1.5",children:e.transitions.map((m,h)=>s.jsxs("div",{className:"border border-zinc-700/60 rounded bg-zinc-800/30 p-2 space-y-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"text-[10px] text-zinc-500",children:"from"}),s.jsx(x0,{value:m.from,states:i,onChange:b=>p(h,{from:b})}),s.jsx("span",{className:"text-[10px] text-zinc-500",children:"→"}),s.jsx("select",{value:m.to,onChange:b=>p(h,{to:b.target.value}),className:"bg-zinc-900 text-green-200 font-mono text-[10px] rounded border border-zinc-700 px-1 py-0.5",children:i.map(b=>s.jsx("option",{value:b,children:b},b))}),s.jsx("span",{className:"text-[10px] text-zinc-500 ml-1",children:"label"}),s.jsx("input",{value:m.label??"",onChange:b=>p(h,{label:b.target.value||void 0}),placeholder:"debug name only (optional)",title:"Display name shown in the debug history/transition table. Does not affect behaviour.",className:"flex-1 min-w-[120px] bg-black/40 text-zinc-300 text-[10px] rounded border border-zinc-700 px-1.5 py-0.5 outline-none focus:border-sky-500/50"}),s.jsx("button",{type:"button",className:"text-zinc-500 hover:text-red-300 text-sm px-1",onClick:()=>d({transitions:e.transitions.filter((b,g)=>g!==h)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(hs,{label:"min_hold_ms",value:m.min_hold_ms??0,onChange:b=>p(h,{min_hold_ms:b||void 0})}),s.jsx(hs,{label:"priority",value:m.priority??0,onChange:b=>p(h,{priority:b||void 0})})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-[10px] text-zinc-500",children:"when"}),!m.when&&s.jsx("button",{type:"button",className:"text-[10px] text-zinc-300 hover:text-white px-1.5 py-0.5 rounded border border-zinc-700 hover:bg-zinc-700/40",onClick:()=>p(h,{when:{section:c[0],matches:""}}),children:"+ guard condition"}),m.when&&s.jsx("button",{type:"button",className:"text-[10px] text-zinc-500 hover:text-red-300",onClick:()=>p(h,{when:void 0}),children:"remove guard"})]}),m.when&&s.jsx(Ci,{cond:m.when,path:`t${h}`,sections:c,onChange:b=>p(h,{when:b}),onPreview:r,preview:n})]})]},h))})]})]})}function x0({value:e,states:t,onChange:r}){const n=new Set(Array.isArray(e)?e:e==="*"?t:[e]),a=e==="*",o=i=>{const c=new Set(n);c.has(i)?c.delete(i):c.add(i);const d=t.filter(u=>c.has(u));r(d.length===1?d[0]:d)};return s.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.map(i=>s.jsx("button",{type:"button",onClick:()=>o(i),className:`font-mono text-[10px] px-1 py-0.5 rounded border ${a||n.has(i)?"text-sky-200 bg-sky-600/25 border-sky-500/40":"text-zinc-500 border-zinc-700 hover:border-zinc-500"}`,children:i},i))})}function br(e){const t=Date.now()-e;if(t<0)return"just now";if(t<2e3)return`${t}ms ago`;if(t<6e4)return`${(t/1e3).toFixed(1)}s ago`;const r=Math.floor(t/6e4);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}function sc(e){return e<=0?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}const b0={busy_hold_expired:"text-amber-200 bg-amber-500/20 border border-amber-500/30",idle_hold_committed:"text-green-200 bg-green-500/20 border border-green-500/30",completion_idle_after:"text-sky-200 bg-sky-500/20 border border-sky-500/30",forced_completion:"text-orange-200 bg-orange-500/20 border border-orange-500/30",forceEmit:"text-purple-200 bg-purple-500/20 border border-purple-500/30",spec_reload:"text-purple-200 bg-purple-500/20 border border-purple-500/30",eval_match:"text-zinc-300 bg-zinc-500/15 border border-zinc-500/20"},g0={idle:"text-green-100 bg-green-600/30 border border-green-500/40",busy:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",generating:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",waiting_approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",picker:"text-sky-100 bg-sky-600/30 border border-sky-500/40",signing_in:"text-sky-100 bg-sky-600/30 border border-sky-500/40"};function Wa(e){return g0[e]??"text-zinc-200 bg-zinc-600/20 border border-zinc-500/30"}function bn({children:e}){return s.jsx("div",{className:"text-zinc-400 text-[10px] uppercase tracking-widest font-semibold mb-1.5 mt-0.5",children:e})}function gn(){return s.jsx("div",{className:"border-t border-white/8 my-2"})}function Fu({node:e,depth:t=0}){var a;const r=e.result?"text-green-300":"text-zinc-500",n=e.result?"●":"○";return s.jsxs("div",{style:{marginLeft:t*10},className:"font-mono text-[10px] leading-relaxed",children:[s.jsxs("span",{className:r,children:[n," "]}),s.jsx("span",{className:"text-zinc-400",children:e.kind}),s.jsxs("span",{className:"text-zinc-500",children:[" ",e.detail]}),e.remainingMs!=null&&e.remainingMs>0&&s.jsxs("span",{className:"text-amber-300",children:[" (",e.remainingMs,"ms left)"]}),(a=e.children)==null?void 0:a.map((o,i)=>s.jsx(Fu,{node:o,depth:t+1},i))]})}function y0({t:e}){const[t,r]=l.useState(!1),n=e.fires?"text-green-200 bg-green-600/25 border-green-500/40":e.holdSatisfied?"text-zinc-400 bg-zinc-700/30 border-zinc-600/30":"text-amber-200 bg-amber-600/20 border-amber-500/30";return s.jsxs("div",{className:"border border-zinc-700/50 rounded bg-zinc-800/30 overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-1 hover:bg-zinc-700/30 text-left",onClick:()=>r(a=>!a),children:[s.jsx("span",{className:"text-[10px] text-zinc-500 w-3",children:e.cond?t?"▾":"▸":" "}),s.jsxs("span",{className:`font-mono text-[11px] px-1.5 py-0.5 rounded border ${n}`,children:["→ ",e.to]}),s.jsx("span",{className:"text-zinc-400 font-mono text-[10px] truncate",children:e.label}),s.jsxs("span",{className:"ml-auto flex items-center gap-1.5 shrink-0",children:[e.fires&&s.jsx("span",{className:"text-green-300 text-[10px] font-mono",children:"FIRES"}),!e.holdSatisfied&&s.jsxs("span",{className:"text-amber-300 text-[10px] font-mono",children:["hold ",e.holdRemainingMs,"ms"]}),s.jsx("span",{className:`text-[10px] font-mono ${e.condResult?"text-green-400":"text-zinc-600"}`,children:e.condResult?"cond✓":"cond✗"})]})]}),t&&e.cond&&s.jsx("div",{className:"px-3 pb-1.5 pt-0.5 bg-black/30 border-t border-zinc-700/50",children:s.jsx(Fu,{node:e.cond})})]})}function v0({activeConv:e,onClose:t}){var fe,Ne,re,je,de;const{sendCommand:r}=mt(),[n,a]=l.useState(!0),[o,i]=l.useState(null),[c,d]=l.useState(null),[u,p]=l.useState(!1),[m,h]=l.useState(new Set(["footer"])),[b,g]=l.useState("Snapshot"),[f,v]=l.useState(!1),[j,y]=l.useState(null),[w,N]=l.useState(!1),[k,x]=l.useState(""),[S,C]=l.useState(!1),[I,R]=l.useState("idle"),[L,T]=l.useState(null),[_,$]=l.useState([]),[X,M]=l.useState({}),[A,E]=l.useState(null),[F,z]=l.useState(!1),D=e.daemonId||((fe=e.routeId)==null?void 0:fe.split(":")[0])||e.routeId||"",K=e.sessionId||"",O=l.useCallback(async()=>{a(!0),d(null);try{const U=await r(D,"get_spec_debug",{targetSessionId:K}),H=U&&typeof U=="object"?U:{},Y=H.result&&typeof H.result=="object"?H.result:H;Y!=null&&Y.success?i(Y):(d((Y==null?void 0:Y.error)||"Failed to load spec debug"),i(null))}catch(U){d((U==null?void 0:U.message)||String(U)),i(null)}finally{a(!1)}},[r,D,K]);l.useEffect(()=>{O()},[O]),l.useEffect(()=>{if(!F)return;const U=setInterval(()=>{O()},1e3);return()=>clearInterval(U)},[F,O]),l.useEffect(()=>{const U=H=>{H.key==="Escape"&&!f&&t()};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[t,f]);const q=l.useCallback(async U=>{try{const H=await r(D,"validate_spec",{content:JSON.stringify(U)}),Y=H&&typeof H=="object"?H:{},se=Y.result&&typeof Y.result=="object"?Y.result:Y;$(se!=null&&se.valid?[]:(se==null?void 0:se.errors)??["validation failed"])}catch(H){$([(H==null?void 0:H.message)||String(H)])}},[r,D]),ne=l.useCallback(async()=>{T(null),R("idle"),M({});try{const U=await r(D,"get_spec_source",{targetSessionId:K}),H=U&&typeof U=="object"?U:{},Y=H.result&&typeof H.result=="object"?H.result:H;if(!(Y!=null&&Y.success)||typeof Y.content!="string"){T((Y==null?void 0:Y.error)||"Failed to load spec source");return}x(Y.content);let se=null;try{se=JSON.parse(Y.content)}catch{}se&&se.$schema==="adhdev:cli/spec@4"?(y(se),N(!1),q(se)):(y(null),N(!0)),C(!1),v(!0)}catch(U){T((U==null?void 0:U.message)||String(U))}},[r,D,K,q]),J=l.useCallback(U=>{y(U),x(JSON.stringify(U,null,2)),C(!0),R("idle"),q(U)},[q]),ye=l.useCallback(async(U,H)=>{M(Y=>({...Y,[U]:"loading"}));try{const Y=await r(D,"eval_condition_preview",{targetSessionId:K,condition:H}),se=Y&&typeof Y=="object"?Y:{},xe=se.result&&typeof se.result=="object"?se.result:se;!(xe!=null&&xe.success)||!xe.result?M(Z=>({...Z,[U]:{result:!1,detail:xe==null?void 0:xe.error}})):M(Z=>({...Z,[U]:{result:xe.result.result,detail:xe.result.detail}}))}catch(Y){M(se=>({...se,[U]:{result:!1,detail:Y==null?void 0:Y.message}}))}},[r,D,K]),oe=l.useCallback(async U=>{E("loading");try{const H=await r(D,"resolve_section_preview",{targetSessionId:K,sections:U}),Y=H&&typeof H=="object"?H:{},se=Y.result&&typeof Y.result=="object"?Y.result:Y;!(se!=null&&se.success)||!Array.isArray(se.sections)?E({error:(se==null?void 0:se.error)||"resolve failed"}):E({sections:se.sections,screenLineCount:se.screenLineCount??0})}catch(H){E({error:(H==null?void 0:H.message)||String(H)})}},[r,D,K]),B=l.useCallback(async()=>{var Y,se;const U=(Y=o==null?void 0:o.snapshot)==null?void 0:Y.specPath;if(!U){T("No spec path on this session");return}if(!w&&_.length>0){T("Fix validation errors before saving");return}const H=!w&&j?JSON.stringify(j,null,2):k;R("saving"),T(null);try{const xe=await r(D,"write_spec_source",{specPath:U,content:H}),Z=xe&&typeof xe=="object"?xe:{},P=Z.result&&typeof Z.result=="object"?Z.result:Z;if(!(P!=null&&P.success)){R("error"),T(((se=P==null?void 0:P.validationErrors)==null?void 0:se.join(`
|
|
42
|
+
`))||(P==null?void 0:P.error)||"Save failed");return}R("saved"),C(!1),setTimeout(()=>{O()},400),setTimeout(()=>R("idle"),1500)}catch(xe){R("error"),T((xe==null?void 0:xe.message)||String(xe))}},[r,D,(Ne=o==null?void 0:o.snapshot)==null?void 0:Ne.specPath,k,j,w,_,O]),W=o==null?void 0:o.snapshot,ve=async()=>{var P,ie,be;let U=o;U||(await O(),U=o);const H=U==null?void 0:U.snapshot,Y=[];if(Y.push("# Spec Debug Snapshot"),Y.push(`Generated: ${new Date().toISOString()}`),Y.push(`Session: ${(U==null?void 0:U.sessionId)??""} (${(U==null?void 0:U.providerType)??""})`),Y.push(`Spec: ${(H==null?void 0:H.spec_id)??""} (${(H==null?void 0:H.specPath)??""})`),Y.push(`Provider: ${(H==null?void 0:H.name)??""} (${(H==null?void 0:H.cliType)??""})`),Y.push(`Working dir: ${(H==null?void 0:H.workingDir)??""}`),Y.push(`Spawned: ${H!=null&&H.spawnedAtMs?new Date(H.spawnedAtMs).toISOString():""}`),Y.push(""),Y.push("## Current State"),Y.push(`State: ${((P=H==null?void 0:H.current_state)==null?void 0:P.id)??"none"} (${((ie=H==null?void 0:H.current_state)==null?void 0:ie.label)??""})`),Y.push(`Status: ${(H==null?void 0:H.status)??""}`),Y.push(`Idle hold pending: ${(H==null?void 0:H.idleHoldPending)??!1}`),Y.push(`Exited: ${(H==null?void 0:H.exited)??!1}`),Y.push(`Last busy: ${H!=null&&H.lastBusyAt?br(H.lastBusyAt):""}`),Y.push(`Cursor: ${(H==null?void 0:H.cursorPosition)!=null?`(${H.cursorPosition.row},${H.cursorPosition.col})`:"n/a"}`),(be=H==null?void 0:H.completionIdleDebounce)!=null&&be.active){const ue=H.completionIdleDebounce;Y.push(`completion_idle_after: age=${ue.ageMs}ms hold=${ue.holdMs}ms force=${ue.forceAfterMs}ms remaining=${Math.max(0,ue.holdMs-ue.ageMs)}ms`)}if(Y.push(""),Y.push("## Modal"),H!=null&&H.current_modal){const ue=H.current_modal.buttons.map(te=>te.label).join(" / ");Y.push(`${H.current_modal.title??""} [${ue}]`)}else Y.push("none");Y.push(""),Y.push("## State History (last 20)");const se=H!=null&&H.stateHistory?[...H.stateHistory].reverse().slice(0,20):[];for(const ue of se){const te=ue.reason!=null?typeof ue.reason=="string"?ue.reason:JSON.stringify(ue.reason):"",Me=ue.debounceKind!=null?typeof ue.debounceKind=="string"?ue.debounceKind:JSON.stringify(ue.debounceKind):"",Ae=ue.matchedStateId!=null?String(ue.matchedStateId):"",Ce=(ue.matchedRules??[]).map(Ue=>typeof Ue=="string"?Ue:JSON.stringify(Ue)).join(", ");Y.push(`- ${ue.stateId} @ ${new Date(ue.at).toISOString()} held ${ue.durationMs}ms | reason: ${te} | debounce: ${Me} | eval→${Ae} | rules: ${Ce}`)}if(Y.push(""),Y.push("## Sections"),H!=null&&H.sections)for(const[ue,te]of Object.entries(H.sections)){const Me=te.split(`
|
|
43
|
+
`).slice(0,3).join(`
|
|
44
|
+
`);Y.push(`${ue}: ${Me}`)}Y.push(""),Y.push("## Last Assistant Message");const Z=[...(H==null?void 0:H.messages)??(H==null?void 0:H.committedMessages)??[]].reverse().find(ue=>ue.role==="assistant");Y.push(Z?Z.content.slice(0,400):""),Y.push(""),Y.push("## Screen (first 50 lines)"),Y.push(H!=null&&H.screen?H.screen.split(`
|
|
45
|
+
`).slice(0,50).join(`
|
|
46
|
+
`):"");try{await navigator.clipboard.writeText(Y.join(`
|
|
47
|
+
`)),g("Copied!"),setTimeout(()=>g("Snapshot"),1500)}catch(ue){console.error("[SpecDebugPanel] clipboard write failed",ue)}},we=U=>{h(H=>{const Y=new Set(H);return Y.has(U)?Y.delete(U):Y.add(U),Y})};return s.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Spec debug",className:"fixed inset-0 z-50 flex items-end justify-center bg-black/60 p-0 sm:items-center sm:p-4",onClick:t,style:{pointerEvents:"auto"},children:s.jsxs("div",{className:"bg-zinc-900 text-zinc-100 border border-zinc-700 rounded-t-xl sm:rounded-lg shadow-2xl max-w-2xl w-full max-h-[92vh] sm:max-h-[88vh] flex flex-col",onClick:U=>U.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-zinc-700 px-4 py-2.5 shrink-0 gap-2 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 overflow-hidden",children:[s.jsx("span",{className:"text-sm font-semibold text-zinc-100 shrink-0",children:"Spec Debug"}),W&&s.jsx("span",{className:"text-[11px] text-zinc-400 font-mono bg-zinc-800 px-1.5 py-0.5 rounded truncate",children:W.spec_id})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(W==null?void 0:W.specPath)&&s.jsx("button",{type:"button",className:`text-[11px] transition-colors px-2 py-1 rounded border ${f?"text-sky-200 bg-sky-600/25 border-sky-500/40":"text-zinc-300 hover:text-white hover:bg-zinc-700 border-transparent hover:border-zinc-600"}`,onClick:()=>{f?v(!1):ne()},disabled:n,children:f?"Close Editor":"Edit Spec"}),s.jsx("button",{type:"button",className:"text-[11px] text-zinc-300 hover:text-white transition-colors px-2 py-1 rounded hover:bg-zinc-700 border border-transparent hover:border-zinc-600",onClick:()=>{ve()},disabled:n,children:b}),s.jsx("button",{type:"button",className:"text-[11px] text-zinc-300 hover:text-white transition-colors px-2 py-1 rounded hover:bg-zinc-700 border border-transparent hover:border-zinc-600",onClick:()=>{O()},disabled:n,children:n?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"text-zinc-400 hover:text-zinc-100 transition-colors text-xl leading-none w-7 h-7 flex items-center justify-center rounded hover:bg-zinc-700",onClick:t,"aria-label":"Close",children:"×"})]})]}),f&&s.jsxs("div",{className:"flex-1 flex flex-col min-h-0 px-4 py-3 gap-2",children:[s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsxs("div",{className:"inline-flex rounded border border-zinc-700 overflow-hidden text-[10px]",children:[s.jsx("button",{type:"button",className:`px-2 py-0.5 ${w?"text-zinc-400 hover:bg-zinc-700/40":"bg-sky-600/30 text-sky-100"}`,onClick:()=>{if(w)try{const U=JSON.parse(k);y(U),q(U)}catch{return}N(!1)},disabled:!j&&w,children:"Form"}),s.jsx("button",{type:"button",className:`px-2 py-0.5 ${w?"bg-sky-600/30 text-sky-100":"text-zinc-400 hover:bg-zinc-700/40"}`,onClick:()=>{j&&x(JSON.stringify(j,null,2)),N(!0)},children:"JSON"})]}),s.jsx("span",{className:"text-[10px] text-zinc-500 font-mono truncate flex-1",title:W==null?void 0:W.specPath,children:((W==null?void 0:W.specPath)??"").split("/").slice(-3).join("/")}),S&&s.jsx("span",{className:"text-amber-300 text-[10px]",children:"unsaved"}),!w&&_.length>0&&s.jsxs("span",{className:"text-red-300 text-[10px]",children:[_.length," error",_.length>1?"s":""]}),s.jsx("button",{type:"button",className:`text-[11px] px-2.5 py-1 rounded border transition-colors ${I==="saving"||!w&&_.length>0?"text-zinc-600 border-zinc-700 cursor-not-allowed":"text-green-200 bg-green-600/25 border-green-500/40 hover:bg-green-600/40"}`,onClick:()=>{B()},disabled:I==="saving"||!w&&_.length>0,children:I==="saving"?"Saving…":I==="saved"?"Saved ✓ (reloading)":"Save & Apply"})]}),L&&s.jsx("pre",{className:"text-red-300 bg-red-900/40 border border-red-700/50 rounded p-2 text-[10px] whitespace-pre-wrap shrink-0 max-h-28 overflow-y-auto",children:L}),!w&&_.length>0&&s.jsx("div",{className:"text-red-300 bg-red-900/30 border border-red-700/40 rounded p-1.5 text-[10px] shrink-0 max-h-24 overflow-y-auto space-y-0.5",children:_.map((U,H)=>s.jsx("div",{className:"font-mono",children:U},H))}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:w||!j?s.jsx("textarea",{value:k,onChange:U=>{x(U.target.value),C(!0),R("idle")},spellCheck:!1,className:"w-full h-full min-h-[300px] font-mono text-[11px] leading-relaxed bg-black/40 text-zinc-200 border border-zinc-700 rounded p-3 resize-none outline-none focus:border-sky-500/50"}):s.jsx(f0,{model:j,onChange:J,onPreview:ye,preview:X,onTestSections:oe,sectionPreview:A})}),s.jsx("div",{className:"text-[10px] text-zinc-500 shrink-0",children:w?"Raw JSON — validated on save.":'Build the FSM; from/to are constrained to existing states. "test" evaluates a condition against the live screen. Save hot-reloads the session.'})]}),!f&&s.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3 space-y-3 text-[12px]",children:[c&&s.jsx("div",{className:"text-red-300 bg-red-900/40 border border-red-700/50 rounded p-2",children:c}),n&&!o&&s.jsx("div",{className:"text-zinc-500 text-center py-6",children:"Loading…"}),o&&!o.isSpecProvider&&s.jsxs("div",{className:"text-zinc-500 text-center py-6",children:["Not a spec-driven provider (",o.providerType||"unknown",")."]}),W&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-[11px] bg-zinc-800/60 rounded-md px-3 py-2 border border-zinc-700/50",children:[W.name&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Provider"}),s.jsxs("span",{className:"font-mono text-zinc-200",children:[W.name," ",s.jsxs("span",{className:"text-zinc-500",children:["(",W.cliType,")"]})]})]}),W.workingDir&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Dir"}),s.jsx("span",{className:"font-mono text-zinc-300 truncate",title:W.workingDir,children:W.workingDir})]}),W.spawnedAtMs?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Spawned"}),s.jsx("span",{className:"text-zinc-400",children:br(W.spawnedAtMs)})]}):null,W.providerSessionId&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Session"}),s.jsx("span",{className:"font-mono text-zinc-500 text-[10px] truncate",title:W.providerSessionId,children:W.providerSessionId})]})]}),s.jsxs("div",{className:"flex items-center gap-2 flex-wrap bg-zinc-800/40 rounded-md px-3 py-2 border border-zinc-700/50",children:[s.jsx("span",{className:`font-semibold font-mono text-[12px] px-2 py-0.5 rounded ${W.current_state?Wa(W.current_state.id):"text-zinc-500"}`,children:W.current_state?W.current_state.id:"none"}),((re=W.current_state)==null?void 0:re.label)&&W.current_state.label!==W.current_state.id&&s.jsx("span",{className:"text-zinc-400 text-[11px]",children:W.current_state.label}),W.status&&W.status!==((je=W.current_state)==null?void 0:je.id)&&s.jsxs("span",{className:"text-zinc-500 text-[11px]",children:["engine: ",s.jsx("span",{className:`font-mono ${Wa(W.status)} px-1 py-0.5 rounded text-[10px]`,children:W.status})]}),W.idleHoldPending&&s.jsx("span",{className:"text-yellow-200 text-[10px] bg-yellow-600/25 border border-yellow-500/35 px-1.5 py-0.5 rounded font-mono",children:"idle hold pending"}),W.exited&&s.jsx("span",{className:"text-red-200 text-[10px] bg-red-600/25 border border-red-500/35 px-1.5 py-0.5 rounded font-mono",children:"exited"}),W.cursorPosition!=null&&s.jsxs("span",{className:"text-zinc-500 text-[11px] font-mono",children:["cursor: ",s.jsxs("span",{className:"text-zinc-300",children:[W.cursorPosition.row,",",W.cursorPosition.col]})]}),W.lastBusyAt>0&&s.jsxs("span",{className:"text-zinc-500 text-[11px] ml-auto",children:["last busy: ",s.jsx("span",{className:"text-zinc-400",children:br(W.lastBusyAt)})]})]}),((de=W.completionIdleDebounce)==null?void 0:de.active)&&s.jsxs("div",{className:"flex items-center gap-2 text-[11px] bg-sky-900/20 border border-sky-700/30 rounded-md px-3 py-1.5 font-mono",children:[s.jsx("span",{className:"text-sky-400",children:"completion_idle_after"}),s.jsxs("span",{className:"text-zinc-400",children:["age: ",s.jsxs("span",{className:"text-sky-200",children:[W.completionIdleDebounce.ageMs,"ms"]})]}),s.jsx("span",{className:"text-zinc-500",children:"/"}),s.jsxs("span",{className:"text-zinc-400",children:["hold: ",s.jsxs("span",{className:"text-zinc-300",children:[W.completionIdleDebounce.holdMs,"ms"]})]}),s.jsxs("span",{className:"text-zinc-400",children:["force: ",s.jsxs("span",{className:"text-zinc-300",children:[W.completionIdleDebounce.forceAfterMs,"ms"]})]}),s.jsx("span",{className:"text-zinc-500 ml-auto",children:W.completionIdleDebounce.ageMs<W.completionIdleDebounce.holdMs?s.jsxs("span",{className:"text-amber-300",children:["hold remaining: ",W.completionIdleDebounce.holdMs-W.completionIdleDebounce.ageMs,"ms"]}):W.completionIdleDebounce.ageMs<W.completionIdleDebounce.forceAfterMs?s.jsxs("span",{className:"text-orange-300",children:["force in: ",W.completionIdleDebounce.forceAfterMs-W.completionIdleDebounce.ageMs,"ms"]}):s.jsx("span",{className:"text-red-300",children:"overdue"})})]}),W.current_modal&&s.jsxs("div",{className:"bg-orange-900/30 border border-orange-600/40 rounded-md p-2.5",children:[s.jsx("span",{className:"text-orange-200 font-semibold",children:"Modal: "}),s.jsx("span",{className:"text-zinc-300",children:W.current_modal.title||""}),W.current_modal.buttons.length>0&&s.jsxs("span",{className:"text-zinc-400 ml-2",children:["[",W.current_modal.buttons.map(U=>U.label).join(" / "),"]"]})]}),W.fsm&&s.jsxs(s.Fragment,{children:[s.jsx(gn,{}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsxs(bn,{children:["FSM — outgoing from ",s.jsx("span",{className:"text-sky-300 font-mono normal-case",children:W.fsm.currentState})," (held ",sc(W.fsm.stateAgeMs),")"]}),s.jsxs("label",{className:"ml-auto flex items-center gap-1 text-[10px] text-zinc-500 cursor-pointer select-none mb-1.5",children:[s.jsx("input",{type:"checkbox",checked:F,onChange:U=>z(U.target.checked),className:"accent-sky-500"}),"live"]})]}),s.jsxs("div",{className:"space-y-1",children:[W.fsm.transitions.length===0&&s.jsx("div",{className:"text-zinc-600 text-[11px] italic px-1",children:"no outgoing transitions (terminal state)"}),W.fsm.transitions.map((U,H)=>s.jsx(y0,{t:U},H))]})]})]}),s.jsx(gn,{}),W.sections&&Object.keys(W.sections).length>0&&s.jsxs("div",{children:[s.jsx(bn,{children:"Sections"}),s.jsx("div",{className:"space-y-1",children:Object.entries(W.sections).map(([U,H])=>{var Z;const Y=m.has(U),se=H.split(`
|
|
48
|
+
`),xe=((Z=se[0])==null?void 0:Z.slice(0,80))||"(empty)";return s.jsxs("div",{className:"border border-zinc-700 rounded overflow-hidden bg-zinc-800/30",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2.5 py-1.5 hover:bg-zinc-700/40 transition-colors text-left",onClick:()=>we(U),children:[s.jsx("span",{className:"text-[10px] text-zinc-500 w-3",children:Y?"▾":"▸"}),s.jsx("span",{className:"font-mono text-sky-300 w-20 shrink-0 text-[11px]",children:U}),!Y&&s.jsx("span",{className:"text-zinc-400 truncate font-mono text-[11px]",children:xe}),s.jsxs("span",{className:"ml-auto text-zinc-600 text-[10px] shrink-0",children:[se.length,"L"]})]}),Y&&s.jsx("pre",{className:"px-3 pb-2.5 pt-1 font-mono text-[11px] text-zinc-300 whitespace-pre-wrap break-all bg-black/30 max-h-40 overflow-y-auto border-t border-zinc-700/50",children:H||"(empty)"})]},U)})})]}),s.jsx(gn,{}),W.stateHistory&&W.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs(bn,{children:["State History (",W.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...W.stateHistory].reverse().slice(0,20).map((U,H)=>s.jsxs("div",{className:"rounded px-2 py-1 hover:bg-zinc-800/60 transition-colors",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:`font-mono text-[11px] font-semibold px-1.5 py-0.5 rounded shrink-0 ${Wa(U.stateId)}`,children:U.stateId}),s.jsx("span",{className:"text-zinc-400 text-[11px] shrink-0 tabular-nums",children:br(U.at)}),U.durationMs>0&&s.jsxs("span",{className:"text-zinc-500 text-[11px]",children:["held ",s.jsx("span",{className:"text-zinc-400",children:sc(U.durationMs)})]}),U.reason&&s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${b0[String(U.reason)]??"text-zinc-400 bg-zinc-700/50 border border-zinc-600/30"}`,children:String(U.reason)}),U.debounceKind&&String(U.debounceKind)!=="none"&&s.jsxs("span",{className:"text-zinc-500 text-[10px] font-mono",children:["debounce:",String(U.debounceKind)]}),U.matchedStateId&&String(U.matchedStateId)!==U.stateId&&s.jsxs("span",{className:"text-zinc-500 text-[10px] font-mono",children:["eval→",s.jsx("span",{className:"text-zinc-300",children:String(U.matchedStateId)})]})]}),U.matchedRules&&U.matchedRules.length>0&&s.jsxs("div",{className:"flex items-start gap-1 flex-wrap mt-0.5 ml-1 pl-1 border-l border-zinc-700",children:[U.matchedRules.slice(0,3).map((Y,se)=>s.jsx("span",{className:"font-mono text-[10px] text-sky-200 bg-sky-900/40 border border-sky-700/40 px-1.5 py-0.5 rounded break-all",children:typeof Y=="string"?Y:JSON.stringify(Y)},se)),U.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-zinc-500",children:["+",U.matchedRules.length-3," more"]})]})]},H))})]}),s.jsx(gn,{}),(()=>{const U=W.messages??W.committedMessages??[];if(U.length===0)return null;const H=U.filter(xe=>xe.role==="user").length,Y=U.filter(xe=>xe.role==="assistant").length,se=[...U].reverse().find(xe=>xe.role==="assistant");return s.jsxs("div",{children:[s.jsxs(bn,{children:["Transcript (",U.length," — ",H,"u / ",Y,"a)"]}),se&&s.jsxs("div",{className:"bg-zinc-800/50 border border-zinc-700 rounded-md p-2.5 text-[11px]",children:[s.jsxs("div",{className:"text-zinc-500 mb-1 text-[10px]",children:["Last assistant ",se.receivedAt?br(se.receivedAt):""]}),s.jsxs("div",{className:"text-zinc-300 font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[se.content.slice(0,400),se.content.length>400?"…":""]})]})]})})(),W.specPath&&s.jsx("div",{className:"text-[10px] text-zinc-600 font-mono truncate border-t border-zinc-800 pt-2 mt-1",title:W.specPath,children:W.specPath}),s.jsxs("div",{children:[s.jsxs("button",{type:"button",className:"text-[11px] text-zinc-400 hover:text-zinc-200 transition-colors flex items-center gap-1.5",onClick:()=>p(U=>!U),children:[s.jsx("span",{className:"text-zinc-600",children:u?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",W.screen?W.screen.split(`
|
|
49
|
+
`).length:0," lines)"]})]}),u&&s.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-[11px] text-zinc-300 whitespace-pre bg-black/40 rounded-md border border-zinc-700 max-h-64 overflow-auto",children:W.screen||"(empty)"})]})]})]})]})})}function w0({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var ke;ss();const{sendPtyInput:d}=mt(),[u,p]=l.useState(!1),m=l.useRef(!1);m.current=u;const[h,b]=l.useState("Runtime terminal unavailable"),[g,f]=l.useState(!1),[v,j]=l.useState(null),[y,w]=l.useState(!1),[N,k]=l.useState(!1),[x,S]=l.useState(1),[C,I]=l.useState(!1),[R,L]=l.useState(!1),[T,_]=l.useState({width:0,height:0}),[$,X]=l.useState({width:0,height:0}),[M,A]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[E,F]=l.useState(null),z=l.useRef(null),D=l.useRef(null),K=l.useRef(!1),O=l.useRef(!1),q=l.useRef(i),ne=l.useRef(0),J=l.useRef(!1),ye=l.useRef(""),oe=l.useRef(null),B=l.useRef(!1),W=l.useRef(!1),ve=l.useRef(null),we=l.useRef(null),fe=l.useRef(null),Ne=32*1024,re=()=>{var Q,ee,he,Ie;return((ee=(Q=z.current)==null?void 0:Q.ownerDocument)==null?void 0:ee.defaultView)||((Ie=(he=D.current)==null?void 0:he.ownerDocument)==null?void 0:Ie.defaultView)||window},je=Q=>{const ee=re();return{ownerWindow:ee,frameId:ee.requestAnimationFrame(Q)}},de=()=>{const Q=ve.current;if(Q){try{Q.ownerWindow.cancelAnimationFrame(Q.frameId)}catch{}ve.current=null}},U=()=>{const Q=we.current;if(Q){try{Q.ownerWindow.clearTimeout(Q.timeoutId)}catch{}we.current=null}},H=()=>{const Q=fe.current;if(Q){try{Q.ownerWindow.clearTimeout(Q.timeoutId)}catch{}fe.current=null}},Y=()=>{i&&ve.current===null&&(ve.current=je(()=>{Ke()}))},se=e.tabKey,xe=e.sessionId||"",Z=e.daemonId||((ke=e.routeId)==null?void 0:ke.split(":")[0])||e.routeId||"",P=ji(e),ie=u?o||P:h,be=r0,ue=n0,te=.05,Me=()=>{const Q=$.width,ee=$.height;if(!Number.isFinite(T.width)||T.width<=0||!Number.isFinite(T.height)||T.height<=0||!Number.isFinite(Q)||Q<=0||!Number.isFinite(ee)||ee<=0)return 1;const he=T.width/Q,Ie=T.height/ee;return Number(Math.min(ue,Math.max(be,Math.min(he,Ie))).toFixed(2))},Ae=Me(),Ce=K.current&&x>Ae,Ue=Number.isFinite($.width)&&$.width>0?Math.max(T.width,Math.round($.width*x)):T.width,Qe=Number.isFinite($.height)&&$.height>0?Math.max(T.height,Math.round($.height*x)):T.height,pe=()=>{je(()=>{const Q=D.current;Q&&(Q.scrollLeft=0,Q.scrollTop=Q.scrollHeight-Q.clientHeight)})},De=()=>{var Q,ee;ne.current=0,J.current=!1,ye.current="",oe.current=null,B.current=!1,W.current=!1,K.current||(O.current=!1,S(1)),ve.current!==null&&de(),p(!1),b("Runtime terminal unavailable"),H(),U(),j(null),F(null),I(!1),f(!1),w(!1),k(!1),(ee=(Q=r.current)==null?void 0:Q.reset)==null||ee.call(Q)},$e=()=>{var Q,ee;ne.current=0,J.current=!1,ye.current="",oe.current=null,B.current=!1,W.current=!1,ve.current!==null&&de(),p(!0),b(""),H(),U(),j(null),F(null),I(!1),f(!1),w(!1),k(!1),(ee=(Q=r.current)==null?void 0:Q.reset)==null||ee.call(Q)},tt=()=>{W.current&&(W.current=!1,je(()=>{var Q,ee;(ee=(Q=r.current)==null?void 0:Q.scrollToTop)==null||ee.call(Q)}))},Ke=()=>{if(ve.current=null,!i)return;const Q=ye.current;if(!Q)return;const ee=Q.slice(0,Ne);ye.current=Q.slice(ee.length);const he=r.current;if(!he){ye.current=ee+ye.current,Y();return}he.write(ee,()=>{if(ye.current.length>0){Y();return}tt()})},Ve=Q=>{Q&&(ye.current+=Q,Y())},_e=(Q,ee=0,he,Ie,Le={})=>{var Ee,We,Re,Ye;const Te=!!Le.force;!Te&&ee>0&&ne.current>=ee||!Te&&ee===0&&J.current||(ne.current=ee,ee>0&&w(!0),p(!0),b(""),typeof he=="number"&&typeof Ie=="number"&&he>0&&Ie>0&&((We=(Ee=r.current)==null?void 0:Ee.resize)==null||We.call(Ee,he,Ie)),ye.current="",(Ye=(Re=r.current)==null?void 0:Re.reset)==null||Ye.call(Re),Q?Ve(Q):tt())};l.useEffect(()=>{De()},[xe]),l.useEffect(()=>{var ee;if(!xe)return;const Q=((ee=ft.onRuntimeEvent)==null?void 0:ee.call(ft,xe,he=>{if(!(!he||he.sessionId!==xe)){if(he.type==="runtime_snapshot"){if(!i){oe.current={text:he.text||"",seq:he.seq||0,cols:he.cols,rows:he.rows,force:!!he.force};return}_e(he.text||"",he.seq||0,he.cols,he.rows,{force:!!he.force});return}if(he.type==="session_output"){J.current=!0,typeof he.seq=="number"&&(ne.current=Math.max(ne.current,he.seq),he.seq>0&&w(!0)),m.current||p(!0),m.current||b(""),typeof he.data=="string"&&Ve(he.data);return}if(he.type==="session_cleared"){if(!i){B.current=!0,ye.current="",oe.current=null;return}$e();return}if(he.type==="session_io_error"){const Ie=typeof he.error=="string"&&he.error?he.error:typeof he.reason=="string"&&he.reason?he.reason:"unknown error";p(!1),b(`Runtime input failed: ${Ie}`);return}}},Z))||(()=>{});return()=>{Q()}},[Z,xe,r,i]);const He=async(Q={})=>{var ee;if(!Z||!xe)return{success:!1,error:"daemonId and sessionId are required"};Q.preserveStatus||b(Q.loadingMessage||"Loading runtime terminal...");try{const he=await((ee=ft.requestRuntimeSnapshot)==null?void 0:ee.call(ft,Z,xe,{sinceSeq:Q.sinceSeq,force:Q.force}));return he&&he.success===!1?(Q.preserveStatus||(p(!1),b(`Runtime terminal unavailable: ${he.error}`)),he):he||{success:!0}}catch(he){const Ie=(he==null?void 0:he.message)||String(he);return Q.preserveStatus||(p(!1),b(`Runtime terminal unavailable: ${Ie}`)),{success:!1,error:Ie}}},it=async Q=>{var Te,Ee;const ee=((Te=z.current)==null?void 0:Te.ownerDocument)||document,he=ee.defaultView||window,Ie=(Ee=he.navigator)==null?void 0:Ee.clipboard;if(Ie!=null&&Ie.writeText&&he.isSecureContext)try{return await Ie.writeText(Q),!0}catch{}let Le=null;try{return Le=ee.createElement("textarea"),Le.value=Q,Le.setAttribute("readonly","true"),Le.style.position="fixed",Le.style.left="-9999px",Le.style.top="0",ee.body.appendChild(Le),Le.focus(),Le.select(),ee.execCommand("copy")}catch{return!1}finally{Le==null||Le.remove()}},Xe=Q=>{U(),F(Q);const ee=re();we.current={ownerWindow:ee,timeoutId:ee.setTimeout(()=>{we.current=null,F(he=>he===Q?null:he)},2200)}},Pe=Q=>{H(),j(Q);const ee=re();fe.current={ownerWindow:ee,timeoutId:ee.setTimeout(()=>{fe.current=null,j(he=>he===Q?null:he)},2200)}},G=async()=>{var Le,Te,Ee,We;const Q=((Te=(Le=r.current)==null?void 0:Le.getSelection)==null?void 0:Te.call(Le))||"",ee=((We=(Ee=r.current)==null?void 0:Ee.getVisibleText)==null?void 0:We.call(Ee))||"",he=Q.trimEnd()||ee.trimEnd();if(!he){Xe("Nothing to copy");return}if(!await it(he)){Xe("Copy failed");return}Xe(Q.trimEnd()?"Copied selection":"Copied visible terminal")},V=Q=>{if(!u||!i)return;((d==null?void 0:d(Z,xe,Q))??!1)||Xe("Terminal input failed")},ae=async()=>{if(g)return;f(!0),j("Loading older terminal output..."),W.current=!0;const Q=await He({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:u});if(f(!1),(Q==null?void 0:Q.success)===!1){W.current=!1,j(`Older terminal output unavailable: ${Q.error}`);return}k(!0),Pe("Older terminal output loaded"),je(()=>{var ee;(ee=r.current)==null||ee.bumpResize()})};l.useEffect(()=>{var ee,he;if(!xe)return;Z&&((ee=ft.getState)==null?void 0:ee.call(ft,Z))==="connected"&&He();const Q=(he=ft.onStateChange)==null?void 0:he.call(ft,(Ie,Le)=>{Ie!==Z||Le!=="connected"||He()});return()=>{Q==null||Q()}},[Z,xe,r]),l.useEffect(()=>{t&&De()},[t,se,r]),l.useEffect(()=>{var Ie,Le;const Q=z.current,ee=(Le=(Ie=Q==null?void 0:Q.ownerDocument)==null?void 0:Ie.defaultView)==null?void 0:Le.ResizeObserver;if(!Q||!ee)return;const he=new ee(Te=>{const Ee=Te[0];if(!Ee)return;const{width:We,height:Re}=Ee.contentRect;_(Ye=>{const st=Math.round(We),ht=Math.round(Re);return Ye.width===st&&Ye.height===ht?Ye:{width:st,height:ht}})});return he.observe(Q),()=>he.disconnect()},[]),l.useEffect(()=>{if(K.current)return;const Q=Me();!Number.isFinite(Q)||Q<=0||S(ee=>O.current?Q<ee-te?Q:ee:(O.current=!0,Q))},[$.height,$.width,T.height,T.width]),l.useEffect(()=>{Ce&&pe()},[Ce,Qe,Ue]),l.useEffect(()=>{var he;const Q=q.current;if(q.current=i,!i)return;Q||k(!1),B.current&&(B.current=!1,$e());const ee=oe.current;ee&&(oe.current=null,_e(ee.text,ee.seq,ee.cols,ee.rows,{force:!!ee.force})),Z&&xe&&((he=ft.getState)==null?void 0:he.call(ft,Z))==="connected"&&He(),ye.current&&ve.current===null&&Y(),je(()=>{var Ie;(Ie=r.current)==null||Ie.bumpResize()})},[Z,i,xe]),l.useEffect(()=>()=>{ve.current!==null&&de(),U(),H()},[]),l.useEffect(()=>{const Q=Ie=>{var Te;const Le=Ie.detail;Le!=null&&Le.sessionId&&Le.sessionId!==xe||u&&((Te=r.current)==null||Te.bumpResize())},ee=re(),he=ee===window?[window]:[window,ee];for(const Ie of he)Ie.addEventListener("adhdev:fit-cli-terminal",Q);return()=>{for(const Ie of he)Ie.removeEventListener("adhdev:fit-cli-terminal",Q)}},[u,xe,r]);const ge=u&&y&&!N&&(M.atTop||!M.canScroll)||g||!!v;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:z,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[ge&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{ae()},disabled:!xe||g,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:g?"Loading older...":"Load older terminal output"}),v&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:v})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[E&&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:E}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>L(Q=>!Q),title:"Spec debug — inspect current state, sections, and transition history",children:"Debug"}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{G()},disabled:!u,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>I(Q=>!Q),disabled:!u,"aria-label":"Open terminal control keys","aria-expanded":C,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),C&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":"Terminal control keys",className:"absolute right-0 top-10 w-56 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>I(!1),"aria-label":"Close terminal control keys",children:"×"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>V("\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:()=>V(" "),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:()=>V("\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:()=>V("\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:()=>V("\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:()=>V("\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:()=>V("\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:()=>V(""),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:()=>V(""),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:()=>V(""),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:()=>{K.current=!0,S(Q=>{const ee=Math.max(Ae,Number((Q-.1).toFixed(2)));return ee>Ae&&pe(),ee})},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:()=>{K.current=!0,S(Q=>{const ee=Math.min(ue,Number((Q+.1).toFixed(2)));return ee>Ae&&pe(),ee})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:D,className:Ce?"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:Ue>0?`${Ue}px`:"100%",height:Qe>0?`${Qe}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:$.width>0?`${$.width}px`:"100%",height:$.height>0?`${$.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:x},children:s.jsx(Fd,{ref:r,readOnly:!u||!i,sizingMode:"measured",onViewportMetrics:X,onScrollMetrics:A,onInput:Q=>{!u||(d==null||d(Z,xe,Q))}})})})}),!u&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:h})]}),s.jsx(pu,{contextKey:e.tabKey,panelLabel:pt(e),isSending:a,isBusy:!!P,statusMessage:ie,inlineStatusMessage:ie,onSend:async Q=>P?!1:n(Q),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),R&&s.jsx(v0,{activeConv:e,onClose:()=>L(!1)})]})}const j0=5e3,k0=12e3;function N0(e){return e==="disconnected"||e==="reconnecting"}function S0({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=j0,reconnectActionDelayMs:o=k0}){const i=N0(e),[c,d]=l.useState(()=>!i||a<=0),[u,p]=l.useState(()=>!i||o<=0),m=l.useRef(!1);l.useEffect(()=>{if(!i){d(!1);return}if(m.current=!1,a<=0){m.current=!0,d(!0);return}d(!1);const k=setTimeout(()=>{m.current=!0,d(!0)},a);return()=>clearTimeout(k)},[a,i]),l.useEffect(()=>{if(!i){p(!1);return}if(o<=0){p(!0);return}p(!1);const k=setTimeout(()=>{p(!0)},o);return()=>clearTimeout(k)},[o,i]);const h=i?c:e==="offline"||e==="auth_failed",b=!!(n&&e!=="auth_failed"&&(!i||u)),g=l.useMemo(()=>!t||e!=="connected"?!1:a<=0||m.current,[a,t,e]),f=e==="auth_failed"?"red":e==="offline"?"orange":"accent",v={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},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)"},y={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",N={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[h&&s.jsx("div",{className:w,style:N,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:v[f],border:j[f],color:y[f]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&"Network offline",e==="disconnected"&&"Reconnecting",e==="reconnecting"&&"Reconnecting",e==="auth_failed"&&(r?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),b&&s.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>n==null?void 0:n(),disabled:e==="offline",children:"Reconnect now"})]})}),g&&s.jsx("div",{className:w,style:N,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 Ou({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(ii,{size:n}):s.jsx($s,{size:n})})}const Qt="New session",Hu="A connected machine is ready. Start a new session with any installed provider — CLI, ACP, or IDE.";function C0(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 I0(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 M0(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 ea({git:e,className:t="",compact:r=!1}){const n=C0(e),a=I0(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 ${M0(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 A0({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 rc({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function nc({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const i=xa(e.updatedAt),c=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${c?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",i].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[c?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),o()},children:"Delete"})]})]})}function T0({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:u,hiddenConversations:p=[],onShowConversation:m,onShowAllHidden:h,onResetPanelsToMain:b,inboxOpen:g,onInboxOpenChange:f,hiddenOpen:v,onHiddenOpenChange:j,onOpenNewSession:y,onOpenDashboardGuide:w,guideNudgeVisible:N=!1,actionShortcuts:k,notifications:x,notificationUnreadCount:S,onOpenNotification:C,onMarkNotificationRead:I,onMarkNotificationUnread:R,onDeleteNotification:L,onOpenGitDialog:T,onOpenMeshGraph:_}){var Ne;const{ides:$,p2pStates:X={}}=ss(),M=!!e&&nt(e)&&!rt(e),A=!!e&&rt(e),E=!!(e!=null&&e.daemonId)&&!!((Ne=e==null?void 0:e.coordinator)!=null&&Ne.meshId),F=c||(e?xu(e)?"terminal":"chat":null),[z,D]=l.useState(!1),K=l.useRef(null),O=l.useRef(null),q=$.filter(re=>re.type==="adhdev-daemon"),ne=A0({wsStatus:t,isConnected:r,daemonCount:q.length,p2pStates:X}),J=ne.subtitle,ye=ne.tone==="connected"?"#22c55e":ne.tone==="limited"?"#eab308":"#ef4444",oe=ne.tone==="connected"?"0 0 4px #22c55e80":ne.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",B=l.useMemo(()=>x.filter(re=>!re.readAt),[x]),W=l.useMemo(()=>x.filter(re=>!!re.readAt),[x]),ve=l.useMemo(()=>B.slice(0,9),[B]),we=S;l.useEffect(()=>{if(!g)return;const re=je=>{var de;(de=K.current)!=null&&de.contains(je.target)||f(!1)};return document.addEventListener("mousedown",re),()=>document.removeEventListener("mousedown",re)},[g,f]),l.useEffect(()=>{if(!v)return;const re=je=>{var de;(de=O.current)!=null&&de.contains(je.target)||j(!1)};return document.addEventListener("mousedown",re),()=>document.removeEventListener("mousedown",re)},[v,j]),l.useEffect(()=>{if(!v&&!g)return;const re=je=>{if(!je.altKey)return;const de=je.code.match(/^Digit([1-9])$/);if(!de)return;const U=Number(de[1])-1,H=v?p[U]:void 0,Y=g?ve[U]:void 0;if(!(!H&&!Y)){if(je.preventDefault(),je.stopPropagation(),H){m==null||m(H),j(!1);return}Y&&(C(Y),f(!1))}};return window.addEventListener("keydown",re,!0),()=>window.removeEventListener("keydown",re,!0)},[p,v,g,ve,j,f,C,m]);const fe=re=>{if(!re)return;const je=n.find(de=>de.tabKey===re);je&&(u==null||u(je))};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($s,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?pt(e):"Dashboard"}),s.jsx("span",{title:ne.title,"aria-label":ne.title,className:"header-title-status-dot",style:{background:ye,boxShadow:oe}}),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:ye,boxShadow:oe}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[J&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",J]}),y&&s.jsx("button",{type:"button",onClick:y,className:"btn btn-secondary btn-sm ml-2",title:`${Qt}${k!=null&&k.openNewSession?` (${k.openNewSession})`:""}`,"aria-label":Qt,children:s.jsx(Td,{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:"?"}),N&&s.jsx("span",{children:"Guide"})]}),e&&(M||A||!rt(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:Ps(e)||pt(e),children:pt(e)}),T&&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:()=>T(e.daemonId,e.workspacePath),children:s.jsx(ea,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(ea,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),E&&_&&s.jsxs("button",{type:"button",onClick:()=>_(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:"Open live repo mesh graph",children:[s.jsx(as,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:"Mesh graph"})]}),(M||A)&&i&&s.jsxs(s.Fragment,{children:[M&&d&&F&&s.jsx(Ou,{mode:F,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:A?"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(vt,{size:14})})]}),!rt(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(ai,{size:14})}),!M&&!rt(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(qt,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:K,children:[s.jsxs("div",{className:`dashboard-header-hidden${z?" is-drop-target":""}`,ref:O,onDragEnter:re=>{re.dataTransfer.types.includes("text/tab-key")&&(re.preventDefault(),D(!0))},onDragOver:re=>{re.dataTransfer.types.includes("text/tab-key")&&(re.preventDefault(),re.dataTransfer.dropEffect="move",D(!0))},onDragLeave:re=>{re.currentTarget.contains(re.relatedTarget)||D(!1)},onDrop:re=>{const je=re.dataTransfer.getData("text/tab-key");re.preventDefault(),D(!1),fe(je)},children:[s.jsxs("button",{type:"button",onClick:()=>j(!v),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${k!=null&&k.toggleHiddenTabs?` (${k.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(oi,{size:16}),p.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:p.length})]}),v&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),s.jsx(rc,{value:k==null?void 0:k.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[b&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:b,children:"Reset panels"}),p.length>0&&h&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{h(),j(!1)},children:"Restore all"})]})]}),e&&u&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>u(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(rc,{value:k==null?void 0:k.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:pt(e)})]}),p.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:p.map(re=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(re),j(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:pt(re)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[p.indexOf(re)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",p.indexOf(re)+1]}):null,Ps(re)]})]},re.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>f(!g),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Ur,{size:16}),we>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:we})]}),g&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[B.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),B.map(re=>s.jsx(nc,{notification:re,shortcutIndex:ve.indexOf(re)>=0?ve.indexOf(re)+1:void 0,onOpen:()=>C(re),onMarkRead:()=>I(re.id),onMarkUnread:()=>R(re.id),onDelete:()=>L(re.id)},re.id))]}),W.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),W.map(re=>s.jsx(nc,{notification:re,onOpen:()=>C(re),onMarkRead:()=>I(re.id),onMarkUnread:()=>R(re.id),onDelete:()=>L(re.id)},re.id))]}),x.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function _t(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function _0(e,t){return String(e||"")!==String(t||"")}function R0(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.resumableOnly;return!r&&!n&&!a&&!o?e:e.filter(i=>!(o&&!i.canResume||r&&![i.title,i.preview].map(d=>String(d||"").toLowerCase()).join(`
|
|
50
|
+
`).includes(r)||n&&!String(i.workspace||"").toLowerCase().includes(n)||a&&!Vd(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
51
|
+
`).includes(a)))}function P0(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 zu(e,t={}){return P0(R0(e,t),t.sortMode||"recent")}function ta(e){return e?"Resume saved history":"Start fresh"}function Ii(e){return e?"Resuming saved history…":"Starting fresh…"}function L0(){return"Start fresh"}function D0(e,t=!1){return e==="cli"?ta(t):e==="ide"?"Start IDE":"Start ACP session"}function $0(e,t=!1){return e==="cli"?Ii(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function E0(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function B0(){return"Open saved history"}function F0(){return"Saved History"}function Mi(){return"Use saved history when you want continuity in the same provider conversation."}function O0(){return"No saved history found yet."}function H0(){return"Refresh saved history"}function z0(){return"Refreshing saved history…"}function sa(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function ra(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 na(e){return e==="start-fresh"?"Start fresh":"Restart"}function aa(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Wu(e){return`Resume saved history with ${e}?`}function Ku(){return"Review or change the target workspace before resuming saved history."}function W0(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 Uu({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:u,onClose:p,onNewChat:m,onSwitchSession:h,onRefreshHistory:b,onResumeSavedSession:g}){var L;const f=t.find(T=>T.id===e.routeId),v=(f==null?void 0:f.chats)||[],j=(L=f==null?void 0:f.activeChat)==null?void 0:L.id,y=nt(e)&&!rt(e),[w,N]=l.useState(()=>_t()),k=c||w,x=String(d||"").trim(),S=T=>{if(u){u(T);return}N(T)},C=l.useMemo(()=>a.map(T=>{const _=String(T.workspace||"").trim();return T.canResume||_||!x?T:{...T,workspace:x,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[x,a]),I=l.useMemo(()=>zu(C,{textQuery:k.textQuery,workspaceQuery:k.workspaceQuery,modelQuery:k.modelQuery,resumableOnly:k.resumableOnly,sortMode:k.sortMode}),[C,k.modelQuery,k.resumableOnly,k.sortMode,k.textQuery,k.workspaceQuery]),R=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:p,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:y?F0():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:c0(e)}),y&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Mi()})]}),s.jsx("button",{onClick:p,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(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!y&&s.jsx("button",{onClick:m,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),y?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:k.textQuery,onChange:T=>S({...k,textQuery:T.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:k.workspaceQuery,onChange:T=>S({...k,workspaceQuery:T.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:k.modelQuery,onChange:T=>S({...k,modelQuery:T.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:k.sortMode,onChange:T=>S({...k,sortMode:T.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:k.resumableOnly,onChange:T=>S({...k,resumableOnly:T.target.checked})}),"Resume-ready only"]})]}),I.map(T=>{const _=e.providerSessionId===T.providerSessionId,$=_||!T.canResume||!!i,X=T.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{$||!g||g(T)},disabled:$,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${_?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${$?"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 ${_?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:T.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:W0(T.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:T.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:[T.workspace||"Workspace unknown",X?" · selected workspace":"",_s(T.summaryMetadata)?` · ${_s(T.summaryMetadata)}`:"",T.messageCount>0?` · ${T.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:_?"ACTIVE":T.canResume?X?"RESUME IN SELECTED WORKSPACE":i===T.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},T.id)})]}):v.map(T=>s.jsxs("div",{onClick:()=>{h(e.routeId,T.id),p()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${j===T.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===T.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.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:[T.id.substring(0,12),"..."]}),j===T.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},T.id)),(y&&!o&&I.length===0||!y&&v.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(cf,{size:32})}),s.jsx("div",{className:"text-[13px]",children:y?a.length>0?"No saved history matches these filters.":O0():"No recent chat sessions found."})]}),y&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:z0()})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:b,disabled:n||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||o?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(fa,{size:13})," ",y?H0():"Refresh History"]})})})]})]});return typeof document>"u"?R:Er.createPortal(R,document.body)}const ac={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 Gu({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=ac[n.type]||ac.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(vt,{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 K0=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function U0(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function G0(e){return e.sessionId||e.instanceId||e.agentType}function Ka(e,t){return t||e||"unknown"}function Vu(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Ft(r,{fallbackId:r.id}));return t}function qu(e,t={}){var a,o,i;const r=e.daemonId||((a=e.id)==null?void 0:a.split(":")[0])||e.id;return{machineName:e.ownerDaemonId&&((o=t.machineNames)==null?void 0:o[e.ownerDaemonId])||e.ownerMachineName||void 0||e.daemonId&&((i=t.machineNames)==null?void 0:i[e.daemonId])||void 0,connectionState:t.connectionStates?t.connectionStates[r]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Ai(e,t={}){return V0(e,qu(e,t))}function V0(e,t={}){var m,h,b,g,f,v,j,y,w;const r=[],n=t.machineName,a=t.connectionState,o=U0(e),i=e.workspace||"",c=fx(e.type,{agentName:e.cliName}),d=nt(e)||rt(e)?c:Mt(e.type),u=Array.isArray(e.childSessions)?e.childSessions.map(N=>{var k,x,S;return{sessionId:N.id,instanceId:N.id,providerSessionId:N.providerSessionId,activeChatId:(k=N.activeChat)==null?void 0:k.id,transport:N.transport,sessionCapabilities:N.capabilities,agentType:N.providerType,agentName:N.providerName||Mt(N.providerType),status:N.status,title:N.title,lastMessagePreview:N.lastMessagePreview,lastMessageRole:N.lastMessageRole,lastMessageAt:N.lastMessageAt,lastMessageHash:N.lastMessageHash,messages:((x=N.activeChat)==null?void 0:x.messages)||[],activeModal:((S=N.activeChat)==null?void 0:S.activeModal)||void 0,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,inboxBucket:N.inboxBucket,completionMarker:N.completionMarker,surfaceHidden:N.surfaceHidden,git:N.git,settings:N.settings,coordinator:N.coordinator,messageInput:N.messageInput}}):[],p=K0(e);if(p){const N=e.sessionId||e.instanceId,k=(m=e.settings)==null?void 0:m.meshCoordinatorFor,x=((h=e.settings)==null?void 0:h.meshNodeFor)||!((b=e.settings)!=null&&b.meshCoordinatorFor)&&((g=e.settings)==null?void 0:g.launchedByCoordinator),S=k?" (Coordinator)":x?" (Mesh Node)":"",C=c+S,I=(f=e.activeChat)==null?void 0:f.activeModal,R=I&&Array.isArray(I.buttons)&&I.buttons.length>0,L=xx(e.activeChat,[{status:e.status,activeModal:(v=e.activeChat)==null?void 0:v.activeModal}],e.agents||[]),T=e.activeChat||{title:"",messages:[]};let _=T.title&&String(T.title).trim()?String(T.title).trim():"";const $=(j=e.activeChat)==null?void 0:j.id,X=e.chats;if($&&Array.isArray(X)&&X.length>0){const O=X.find(q=>q.id===$||q.id&&String(q.id)===String($));O!=null&&O.title&&String(O.title).trim()&&(_=String(O.title).trim())}const M=(nt(e)||rt(e),e.type),A=(nt(e)||rt(e))&&Ml(_,C,M)?"":_,E=T.messages||[],F=typeof $=="string"?$.trim():"",z=(nt(e)||rt(e))&&F===String(e.type||"").trim(),D=F&&!z?F:e.providerSessionId,K=e.coordinator||(typeof((y=e.settings)==null?void 0:y.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:N,providerSessionId:e.providerSessionId,historySessionId:D,nativeSessionId:N,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:nt(e)?e.mode||"terminal":"chat",agentName:C,agentType:M,status:L,title:A,messages:E,resume:e.resume,hostIdeType:!nt(e)&&!rt(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:A||o||(nt(e)?e.mode==="chat"?C:`Terminal${S}`:C),displaySecondary:nt(e)&&o?C: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:R?I.buttons:void 0,modalMessage:R?I.message:void 0,streamSource:"native",tabKey:Ka(N,e.id),machineName:n,connectionState:a,settings:e.settings,coordinator:K,messageInput:e.messageInput})}if(p&&(nt(e)||rt(e)))return r;for(const N of u){const k=N.activeModal&&Array.isArray(N.activeModal.buttons)&&N.activeModal.buttons.length>0,x=bx(N),S=G0(N),C=`${e.id}:${S}`,I=N.title&&String(N.title).trim()||"",R=Ml(I,N.agentName,N.agentType)?"":I,L=N.messages||[];if(!(N.transport==="cdp-webview"||!!N.sessionId||!!N.providerSessionId||L.length>0||k||!!R||!["idle","panel_hidden","disconnected","not_monitored"].includes(x)))continue;const _=N.coordinator||(typeof((w=N.settings)==null?void 0:w.meshCoordinatorFor)=="string"&&N.settings.meshCoordinatorFor?{meshId:N.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:N.sessionId||N.instanceId,providerSessionId:N.providerSessionId,historySessionId:N.activeChatId||N.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:N.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:N.sessionCapabilities,mode:"chat",agentName:N.agentName,agentType:N.agentType,status:x,title:R,messages:L,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:N.git||e.git,displayPrimary:R||o||N.agentName||d,displaySecondary:`${d} · ${N.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:N.lastMessagePreview,lastMessageRole:N.lastMessageRole,lastMessageAt:N.lastMessageAt,lastMessageHash:N.lastMessageHash,lastUpdated:N.lastUpdated||e.lastUpdated,inboxBucket:N.inboxBucket,completionMarker:N.completionMarker,modalButtons:k?N.activeModal.buttons:void 0,modalMessage:k?N.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Ka(N.sessionId||N.instanceId,C),machineName:n,connectionState:a,settings:N.settings,coordinator:_,messageInput:N.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 Yu(e){return String(e.type||e.id||"").trim()}function q0(e){var t;return e.category!=="cli"||!Yu(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 sr(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!q0(a))continue;const o=Yu(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 Xr(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 Dn(e,t){const r=new Set(t.map(n=>n.type));return Xr(e).filter(n=>r.has(n))}function Or(e){return e.map(t=>t.type)}function Y0(e,t){const r=Xr(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function J0(e,t){return Xr(e).filter(r=>r!==t)}function oc(e,t,r){const n=Xr(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 ic({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 lc({value:e,availableProviders:t,onChange:r,disabled:n=!1,saveButton:a}){const[o,i]=l.useState(""),c=l.useMemo(()=>new Map(t.map(h=>[h.type,h])),[t]),d=l.useMemo(()=>Dn(e,t),[e,t]),u=e.length-d.length,p=t.filter(h=>!d.includes(h.type)),m=()=>{o&&(r(Y0(d,o)),i(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:d.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):d.map((h,b)=>{const g=c.get(h);return s.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border-subtle bg-bg-primary px-3 py-2 sm:flex-row sm:items-center sm:justify-between",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",b+1]}),(g==null?void 0:g.icon)&&s.jsx("span",{"aria-hidden":"true",children:g.icon}),s.jsx("span",{className:"font-mono text-[12px] text-text-primary",children:h}),s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:"available"})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:g?`${g.label} · ${g.statusLabel}`:h})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:n||b===0,title:"Move up",onClick:()=>r(oc(d,h,"up")),children:s.jsx(ic,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:n||b===d.length-1,title:"Move down",onClick:()=>r(oc(d,h,"down")),children:s.jsx(ic,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(J0(d,h)),children:"Remove"})]})]},h)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:"Add available CLI provider"}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:o,onChange:h=>i(h.target.value),disabled:n||p.length===0,children:[s.jsx("option",{value:"",children:p.length?"Select provider…":"No additional detected CLI providers"}),p.map(h=>s.jsxs("option",{value:h.type,children:[h.label," (",h.type,")"]},h.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!o,onClick:m,children:"Add provider"}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Inventory is filtered to CLI providers detected on this machine. New launches use this order; existing running sessions may need restart.",u>0?` ${u} provider${u===1?"":"s"} from the saved policy are not detected now and will be omitted when saved.`:""]})]})}function X0(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 Ju(e,t){const r=X0(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Xu=[{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:"🏄"}],Qu=[{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:"🧩"}],Zu=[{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:"🟠"}],Q0=Xu,Z0=Qu,ey=Zu;function Ut(...e){return nh(ah(e))}function ty({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:Ut("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 Qr({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(ty,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Ut("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const Ko="adhdev:themechange";function sy(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Ks(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Us(e){return e==="system"?sy():e}function ep(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function $n(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Ko,{detail:{preference:e,theme:t}}))}function ry(){const e=Ks(),t=Us(e);ep(t),$n(e,t)}function Bs(){const[e,t]=l.useState(Ks),[r,n]=l.useState(()=>Us(Ks()));l.useEffect(()=>{ep(r)},[r]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const u=d.matches?"light":"dark";n(u),$n("system",u)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=d=>{const u=d.detail||{},p=u.preference,m=u.theme;t(p==="dark"||p==="light"||p==="system"?p:Ks()),n(m==="dark"||m==="light"?m:Us(Ks()))},c=d=>{if(d.key!=="theme")return;const u=Ks(),p=Us(u);t(u),n(p)};return window.addEventListener(Ko,i),window.addEventListener("storage",c),()=>{window.removeEventListener(Ko,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=Us(i);t(i),n(c);try{localStorage.setItem("theme",i)}catch{}$n(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=Us(c);n(d);try{localStorage.setItem("theme",c)}catch{}return $n(c,d),c})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const cc={dark:"Dark",light:"Light",system:"System"};function ny({collapsed:e}){const{preference:t,cycleTheme:r}=Bs(),n=t==="dark"?s.jsx(uf,{size:16}):t==="light"?s.jsx(df,{size:16}):s.jsx(pf,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${cc[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:cc[t]})]})}function Ua(e,t){return e?typeof e=="function"?e(t):e:null}function ay({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const[u,p]=l.useState(!1),[m,h]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),b=()=>p(!0),g=()=>p(!1),f=()=>{h(w=>{const N=!w;try{localStorage.setItem(d,N?"1":"0")}catch{}return N})},v=l.useMemo(()=>({collapsed:m,mobileMenuOpen:u,openMobileMenu:b,closeMobileMenu:g,toggleCollapsed:f}),[m,u]),j=w=>`nav-item${w.active?" active":""} cursor-pointer ${m?"justify-center py-2.5 px-0":""}${w.className?` ${w.className}`:""}`,y=w=>s.jsxs("div",{className:j(w),id:`nav-${w.id}`,onClick:()=>{w.onSelect(),g()},title:m?w.title??(typeof w.label=="string"?w.label:void 0):w.title,children:[s.jsx("span",{className:"nav-icon",children:w.icon}),!m&&w.label]},w.id);return s.jsxs("div",{className:`app-layout${u?" mobile-menu-open":""}${m?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:b,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),u&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:g,onKeyDown:w=>w.key==="Escape"&&g()}),s.jsxs("aside",{className:`sidebar ${u?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${m?"justify-center gap-0":""}`,children:Ua(t,v)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:g,children:s.jsx(vt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(y)}),n.map(w=>s.jsxs("div",{className:w.className??"border-t border-border-subtle pt-2 mt-2",children:[!m&&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(y)]},w.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(y),Ua(o,v),s.jsx(ny,{collapsed:m}),Ua(i,v)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function dt({title:e,icon:t,description:r,accentColor:n,className:a,collapsible:o,defaultOpen:i=!0,badge:c,children:d}){const[u,p]=l.useState(i),m=o?u:!0,h=(e||r)&&s.jsxs("div",{className:Ut("flex items-start justify-between gap-3",m&&"mb-4"),children:[s.jsxs("div",{className:"min-w-0",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary flex items-center gap-1.5",children:[t&&s.jsx("span",{children:t}),s.jsx("span",{children:e}),c]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),o&&s.jsx("span",{className:Ut("mt-0.5 shrink-0 text-text-muted transition-transform select-none",m?"rotate-90":"rotate-0"),"aria-hidden":!0,children:"▸"})]});return s.jsxs("div",{className:Ut("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[o&&h?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>p(b=>!b),"aria-expanded":m,children:h}):h,m&&d]})}function ja({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:Ut("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 oy={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"},iy={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function fs({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:Ut("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",oy[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:iy[e]}),s.jsx("span",{children:t})]}),r&&s.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function jt({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:Ut("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 Rr(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:Ut("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 ly={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"},cy={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function dy({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:Ut("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",ly[e],r),children:[s.jsx("span",{className:Ut("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",cy[e])}),n]})}function js({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 uy({onPrefChange:e}){const[t,r]=Ix(),[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(js,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ur,{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(js,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(qt,{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:()=>{cu().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(js,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_d,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:i=>o("completionAlert",i)}),s.jsx(js,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(mf,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:i=>o("approvalAlert",i)}),s.jsx(js,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(er,{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 oa(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function py(e,t){const r=oa(e),n=oa(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 Ti(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function Pr(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||py(r,t)>=0)return!1;const n=oa(r),a=oa(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function my(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Ga(e,t){return e instanceof Error?e.message:t}function hy({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(ja,{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(xy,{ide:i,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},i.id))})}function dc({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 Er.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 fy(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Q0,...Z0,...ey].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 xy({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var $,X;const[o,i]=l.useState("idle"),[c,d]=l.useState(""),[u,p]=l.useState(null),[m,h]=l.useState("idle"),[b,g]=l.useState(""),f=e.version||null,v=(($=e.machine)==null?void 0:$.platform)||((X=e.system)==null?void 0:X.platform)||"",j=Ft(e,{fallbackId:e.id}),y=v==="win32"?"🪟":v==="darwin"?"🍎":"🐧",w=t.filter(M=>M.daemonId===e.id&&M.transport==="cdp-page"),N=t.filter(M=>M.daemonId===e.id&&M.transport==="pty"),k=t.filter(M=>M.daemonId===e.id&&M.transport==="acp"),x=e.p2p,S=async()=>{if(r){i("upgrading"),d("Starting upgrade...");try{const M=my(await r(e.id,"daemon_upgrade",{}));M.alreadyLatest?(i("done"),d(`Already on v${M.version||"latest"}.`)):M.upgraded||M.success?(i("done"),d(`Upgrade to v${M.version||"latest"} started. Daemon is restarting...`)):(i("error"),d(M.error||"Upgrade failed"))}catch(M){i("error"),d(Ga(M,"Connection lost during upgrade"))}}},C=async()=>{if(p(null),!!n){h("loading");try{await n(e.id),h("done"),g("Machine disconnected.")}catch(M){h("error"),g(Ga(M,"Failed to disconnect"))}}},I=async()=>{if(p(null),!!a){h("loading");try{await a(e.id),h("done"),g("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(M){h("error"),g(Ga(M,"Failed to revoke token"))}}},R="0.9.82",L=Ti(e,R),T=Pr(e,R),_=w.length+N.length+k.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:y}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children: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),"…"]}),f&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${L?"":"bg-bg-secondary"}`,style:L?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",f,!L&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&L&&s.jsx("button",{onClick:S,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${R}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${T?"↑ Update now":`↑ Update${` to v${R}`}`}`}),n&&s.jsx("button",{onClick:()=>p("disconnect"),disabled:m==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>p("revoke"),disabled:m==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(dy,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[x&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${x.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${x.state==="connecting"||x.state==="new"?"animate-pulse":""}`,style:x.state==="connecting"||x.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",x.state==="connected"?"connected":x.state==="connecting"||x.state==="new"?"connecting...":x.state||"off"]}),x.peers!==void 0&&x.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",x.peers," peer",x.peers!==1?"s":"",")"]})]}),x&&_>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),_>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[w.map(M=>{const A=fy(M.type),E=M.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:A.icon}),s.jsx("span",{children:A.name}),E!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${E?"bg-green-400":"animate-pulse"}`,style:E?void 0:{background:"var(--status-warning)"},title:E?"CDP connected":"CDP connecting..."})]},M.id)}),N.map(M=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:M.cliName||"CLI"})]},M.id)),k.map(M=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:M.cliName||"ACP"})]},M.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(c||b)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||m==="error"?"text-red-400":o==="done"||m==="done"?"text-green-400":"text-text-muted"}`,children:b||c})]}),u==="disconnect"&&s.jsx(dc,{title:"🔌 Disconnect Machine",message:`Disconnect "${j}" from ADHDev?
|
|
52
|
+
|
|
53
|
+
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
54
|
+
|
|
55
|
+
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:C,onCancel:()=>p(null)}),u==="revoke"&&s.jsx(dc,{title:"⚠️ Remove Machine",message:`Remove "${j}" from your dashboard?
|
|
56
|
+
|
|
57
|
+
This will:
|
|
58
|
+
• Immediately disconnect the machine
|
|
59
|
+
• Delete the machine registration
|
|
60
|
+
• Require restarting ADHDev on that machine
|
|
61
|
+
|
|
62
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:I,onCancel:()=>p(null)})]})}const by=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function gy({daemonId:e,knownCliTypes:t=by}){const{sendCommand:r}=mt(),[n,a]=l.useState({}),[o,i]=l.useState({}),[c,d]=l.useState(!0),[u,p]=l.useState(null),[m,h]=l.useState(null),[b,g]=l.useState(""),f=l.useCallback(async()=>{if(e){d(!0),h(null);try{const y=await r(e,"list_coordinator_prompts",{}),w=y!=null&&y.result&&typeof y.result=="object"?y.result:y;if(!(w!=null&&w.success)){h((w==null?void 0:w.error)||"Failed to load");return}const N=w.entries||{};g(w.dir||"");const k={};for(const x of t)k[x]=N[x]||{override:"",append:""};for(const x of Object.keys(N))k[x]||(k[x]=N[x]);a(k),i(JSON.parse(JSON.stringify(k)))}catch(y){h((y==null?void 0:y.message)||String(y))}finally{d(!1)}}},[r,e,t]);l.useEffect(()=>{f()},[f]);const v=l.useCallback(async(y,w)=>{var N;if(e){p(`${y}:${w}`),h(null);try{const k=((N=n[y])==null?void 0:N[w])||"",x=await r(e,"write_coordinator_prompt",{key:y,kind:w,content:k}),S=x!=null&&x.result&&typeof x.result=="object"?x.result:x;if(!(S!=null&&S.success)){h((S==null?void 0:S.error)||"Save failed");return}i(C=>({...C,[y]:{...C[y]||{override:"",append:""},[w]:k}}))}catch(k){h((k==null?void 0:k.message)||String(k))}finally{p(null)}}},[r,e,n]),j=l.useMemo(()=>(y,w)=>{var N,k;return(((N=n[y])==null?void 0:N[w])||"")!==(((k=o[y])==null?void 0:k[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:b||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx("strong",{children:"Override"})," replaces the daemon's built-in base prompt for that CLI."," ",s.jsx("strong",{children:"Append"})," stacks after whichever base wins. Leave a field empty + Save to remove it (reset to default). Supports placeholders: ","{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}",", etc."]})]}),m&&s.jsx("div",{className:"text-[12px] text-red-400 bg-red-500/10 border border-red-500/20 rounded px-3 py-2",children:m}),c&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(n).map(([y,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:y}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Override"}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:4,value:w.override,onChange:N=>a(k=>({...k,[y]:{...k[y],override:N.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:u===`${y}:override`}),s.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void v(y,"override"),disabled:u===`${y}:override`||!j(y,"override"),children:u===`${y}:override`?"Saving…":j(y,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Append"}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:3,value:w.append,onChange:N=>a(k=>({...k,[y]:{...k[y],append:N.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:u===`${y}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void v(y,"append"),disabled:u===`${y}:append`||!j(y,"append"),children:u===`${y}:append`?"Saving…":j(y,"append")?"Save append":"Saved"})})]},y))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const yy=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function vy(){const{preference:e,setPreference:t}=Bs();return s.jsx("div",{className:"flex gap-2",children:yy.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 wy(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 jy(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Va(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function uc(e){const{r:t,g:r,b:n}=jy(e);return .2126*Va(t)+.7152*Va(r)+.0722*Va(n)}function pc(e,t){const r=uc(e),n=uc(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function tp(e){const t=wy(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return pc(t,r)>=pc(t,n)?r:n}const Uo={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},Go={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},ky=[{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"}}}],sp="adhdev-chat-theme",rp="adhdev-chat-theme-custom";function En(){if(typeof window>"u")return"ember";try{return localStorage.getItem(sp)||"ember"}catch{return"ember"}}function Kt(e){try{const t=localStorage.getItem(rp);if(t){const r=JSON.parse(t);return{...e==="dark"?Uo:Go,...r[e]}}}catch{}return e==="dark"?Uo:Go}function yn(e,t){try{localStorage.setItem(rp,JSON.stringify({dark:e,light:t}))}catch{}}function $t(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 ia(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 Ny={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Lr(e,t){var a;const r=(a=Ny[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",ia(r,24)),n.style.setProperty("--accent-on-primary",tp(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${ia(r,18)})`),n.style.setProperty("--border-accent",$t(r,.35)),n.style.setProperty("--nav-active-bg",$t(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${$t(r,.06)}`)}function Is(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",$t(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",$t(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",$t(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",$t(e.borderSubtle,.5)),t.style.setProperty("--border-default",$t(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",ia(e.accentColor,30)),t.style.setProperty("--accent-on-primary",tp(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${ia(e.accentColor,40)})`),t.style.setProperty("--border-accent",$t(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",$t(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${$t(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 ${$t(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 _i(){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 Sy(e){try{localStorage.setItem(sp,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Ms()?"dark":"light";Is(Kt(t))}else _i(),Lr(e,Ms()?"dark":"light")}function Cy(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=En();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Ms()?"dark":"light";Is(Kt(t))}else _i(),Lr(e,Ms()?"dark":"light")}function Ms(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Tt({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 gr({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 Iy({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=l.useState(()=>Kt(r));l.useEffect(()=>{a(Kt(r))},[r]);const o=l.useCallback((i,c)=>{a(d=>{const u={...d,[i]:c},m=Kt(r==="dark"?"light":"dark");return r==="dark"?yn(u,m):yn(m,u),Is(u),t(u),u})},[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(gr,{title:"App Background",children:[s.jsx(Tt,{label:"Background",value:n.bgPrimary,onChange:i=>o("bgPrimary",i)}),s.jsx(Tt,{label:"Surface",value:n.bgSecondary,onChange:i=>o("bgSecondary",i)}),s.jsx(Tt,{label:"Card",value:n.surfacePrimary,onChange:i=>o("surfacePrimary",i)})]}),s.jsxs(gr,{title:"App Text",children:[s.jsx(Tt,{label:"Primary",value:n.textPrimary,onChange:i=>o("textPrimary",i)}),s.jsx(Tt,{label:"Secondary",value:n.textSecondary,onChange:i=>o("textSecondary",i)}),s.jsx(Tt,{label:"Muted",value:n.textMuted,onChange:i=>o("textMuted",i)})]}),s.jsxs(gr,{title:"Borders & Accent",children:[s.jsx(Tt,{label:"Border subtle",value:n.borderSubtle,onChange:i=>o("borderSubtle",i)}),s.jsx(Tt,{label:"Border default",value:n.borderDefault,onChange:i=>o("borderDefault",i)}),s.jsx(Tt,{label:"Accent",value:n.accentColor,onChange:i=>o("accentColor",i)})]})]}),s.jsxs("div",{children:[s.jsxs(gr,{title:"Chat Bubbles",children:[s.jsx(Tt,{label:"User bubble",value:n.userBubble,onChange:i=>o("userBubble",i)}),s.jsx(Tt,{label:"User text",value:n.userText,onChange:i=>o("userText",i)}),s.jsx(Tt,{label:"Agent bubble",value:n.assistantBubble,onChange:i=>o("assistantBubble",i)}),s.jsx(Tt,{label:"Agent text",value:n.assistantText,onChange:i=>o("assistantText",i)})]}),s.jsxs(gr,{title:"Chat Layout",children:[s.jsx(Tt,{label:"Chat BG",value:n.containerBg,onChange:i=>o("containerBg",i)}),s.jsx(Tt,{label:"Send button",value:n.sendButton,onChange:i=>o("sendButton",i)}),s.jsx(Tt,{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?Uo:Go,d=Kt(e?"light":"dark");e?yn(i,d):yn(d,i),a(i),Is(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 My(){const[e,t]=l.useState(En),[r,n]=l.useState(!0),[a,o]=l.useState(()=>Kt("dark"));l.useEffect(()=>{n(Ms());const d=new MutationObserver(()=>{const m=Ms();n(m);const h=En();h==="custom"?Is(Kt(m?"dark":"light")):Lr(h,m?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const u=window.matchMedia("(prefers-color-scheme: dark)"),p=()=>{const m=Ms();n(m);const h=En();h==="custom"?Is(Kt(m?"dark":"light")):Lr(h,m?"dark":"light")};return u.addEventListener("change",p),()=>{d.disconnect(),u.removeEventListener("change",p)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?Is(Kt(r?"dark":"light")):(_i(),Lr(e,r?"dark":"light"))},[e,r]),l.useEffect(()=>{o(Kt(r?"dark":"light"))},[r]);const i=d=>{t(d),Sy(d)},c=[...ky,{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 u=e===d.id,p=r?d.preview.dark:d.preview.light,m=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>i(d.id),className:"text-left rounded-xl p-3 transition-all",style:{background:u?"var(--bg-glass-hover)":"var(--bg-glass)",border:u?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:u?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:p.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:p.assistantBubble,border:p.assistantBorder,color:p.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:p.userBubble,color:m},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:p.assistantBubble,border:p.assistantBorder,color:p.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[u&&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(Iy,{dark:r,onColorsChange:d=>o(d)})]})}const Ri="adhdev_mobileDashboardMode_v1",Vo="adhdev:mobile-dashboard-mode-change";function Pi(){try{return localStorage.getItem(Ri)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Ay(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Pi())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==Ri||t()};return window.addEventListener(Vo,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Vo,r),window.removeEventListener("storage",n)}}function Ty(e){try{localStorage.setItem(Ri,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Vo,{detail:e}))}function _y(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(Pi()==="chat")},[]),s.jsx(js,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx($s,{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),Ty(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const qa=new Map,mc=new Map;function Ry(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 Py(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 np(){const{sendCommand:e}=mt(),{injectEntries:t,getIdes:r}=Br();return l.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??lg,i=mc.get(n)||0;if(!(a!=null&&a.force)&&i>0&&Date.now()-i<o)return;const c=qa.get(n);if(c)return c;const d=(async()=>{const u=await e(n,"get_machine_runtime_stats"),p=Ry(u);if(!p)return;const m=r().find(b=>b.id===n),h=Py(m,n,p.machine,p.timestamp||Date.now());t([h]),mc.set(n,Date.now())})().finally(()=>{qa.delete(n)});return qa.set(n,d),d},[r,t,e])}function Ly(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 Dy(e,t){const{sendData:r}=mt(),{injectEntries:n,getIdes:a}=Br(),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=>ts.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},p=>{const m=a().find(b=>b.id===d),h=Ly(m,d,p);n([h])}));return()=>{c.forEach(d=>d())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function $y(e,t){const{sendData:r}=mt(),[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=ts.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}:{}}},u=>{c&&(clearTimeout(c),c=null),a(u.diagnostics),i(!1)});return d.initialSendAccepted?c=setTimeout(()=>{i(!1)},pg):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 Ey(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function ap(e){const{sendData:t}=mt(),[r,n]=l.useState({});return l.useEffect(()=>{const a=Ey(e);if(!a||!e.sessionId||!t){n({});return}const o=ts.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}),Js.record({interactionId:i.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:i.status,modalButtonCount:Array.isArray(i.modalButtons)?i.modalButtons.length:0}})});return o.initialSendAccepted||n({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),r}function By(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function Fy(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 Oy(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 Hy({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(!By(o))throw new Error(Fy(o));return}await Oy(e.sessionId,t,a)}function op(e){const{ides:t,isP2PActive:r,p2pStates:n}=ss(),{sendCommand:a}=mt(),[o,i]=l.useState(null),[c,d]=l.useState(!1),[u,p]=l.useState(null),m=l.useMemo(()=>tx(t,e),[t,e]),h=!!m,b=l.useMemo(()=>m?m.prompt.promptId===o?null:m:null,[o,m]),g=l.useCallback(async j=>{if(!b)return;const y=Hd(b.prompt,j);d(!0),p(null);try{const w=(n==null?void 0:n[b.daemonId])==="connected"||r===!0;await Hy({promptSession:b,response:y,useP2PCommand:w,sendCommand:a}),i(b.prompt.promptId)}catch(w){throw p(w instanceof Error?w.message:String(w)),w}finally{d(!1)}},[r,n,b,a]),f=l.useCallback(()=>{b&&i(b.prompt.promptId)},[b]),v=l.useCallback(()=>{i(null),p(null)},[]);return{promptSession:b,hasActivePrompt:h,responseError:u,isSubmitting:c,submit:g,cancel:f,reopen:v}}function ip(e){return e instanceof Error?e.message:String(e||"")}function zy(e){const t=ip(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 Wy(e){const t=ip(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function lp({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!nt(e)||rt(e))return;const o=lr(e);if(o===t)return;const i=e.sessionId;i&&a(c=>({...c,[i]:t}));try{await n(Es(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:es(e),mode:t})}catch(c){const d=Wy(c);i&&!d&&a(u=>{const p={...u};return o===cp(r,i)?delete p[i]:p[i]=o,p}),zy(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 hc(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 Ky(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=hc(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(d=>hc(d,t)):a.childSessions,c=i!==a.childSessions;return o!==a||c?(r=!0,{...o,...c?{childSessions:i}:{}}):a});return r?n:e}function cp(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 Uy(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))cp(t,a)===o&&(delete n[a],r=!0);return r?n:e}function Gy({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){l.useEffect(()=>{cu()},[]);const a=l.useMemo(()=>e.map(o=>({id:o.tabKey,name:Eu(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null,target:{providerSessionId:o.providerSessionId,sessionId:o.sessionId,tabKey:o.tabKey,routeId:o.routeId}})),[e]);return Bx(a),l.useEffect(()=>{if(Object.keys(t).length===0)return;const i=setTimeout(()=>{r(c=>{const d=Date.now(),u={};for(const[p,m]of Object.entries(c))d-m<5e3&&(u[p]=m);return Object.keys(u).length===Object.keys(c).length?c:u})},5500);return()=>clearTimeout(i)},[t,r]),l.useEffect(()=>{const o=setInterval(()=>{const i=Date.now()-3e5;n(c=>{const d=c.filter(u=>u.timestamp>i).slice(-100);return d.length===c.length?c:d})},6e4);return()=>clearInterval(o)},[n]),null}function fc(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 As(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=fc(t==null?void 0:t.receivedAt)||fc(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function qo(e,t=0){return As(e)||e.lastUpdated||t||0}function dp(e){return As(e)||e.lastUpdated||0}function up(e,t,r=dp){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 Yo(e){var r;const t=Bt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function Vy(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Yo(e)&&!e.title.trim()}function qy(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(Yo(r))-Number(Yo(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:up(t,r)})[0]||null}function Gt(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=qy(a);return n?o&&Vy(n)?o:n:o||r[0]||null}function Yy(e){const t=String(e.daemonId||"").trim(),r=String(e.id||"").trim(),n=String(e.ownerDaemonId||"").trim()||t,a=t&&r.startsWith(`${t}:`)?r.slice(t.length+1):r;return n?a?`${n}:${a}`:n:r}function Jy(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=Yy(n),o=r.get(a);if(!o){r.set(a,n);continue}const i=(o.workspace?1:0)+(o.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(o.timestamp||0))&&r.set(a,n)}return Array.from(r.values())}function Ya(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 Xy(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 xc(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Xy(Xs(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 Qy(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||""),xc(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||""),xc(r.activeChat)].join(":"))].join("|")}function Zy(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 ev(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of os({routeId:n.routeId}))r.set(o,a);for(const o of os({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of os({tabKey:n.tabKey}))r.set(o,n)}return r}function tv(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function sv(e){const t=tv(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=Xs(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function rv({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=l.useMemo(()=>Jy(e),[e]),o=l.useMemo(()=>Vu(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),u=l.useRef(new Map),p=l.useRef(new Map),m=l.useMemo(()=>{const N=new Map,k=[];for(const I of a){const{connectionState:R="new",machineName:L}=qu(I,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),T=Qy(I),_=u.current.get(I.id);if(_&&_.ide===I&&_.sourceSignature===T&&_.connectionState===R&&_.machineName===L){N.set(I.id,_),k.push(..._.conversations);continue}const $=Ai(I,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),X={ide:I,sourceSignature:T,connectionState:R,machineName:L,conversations:$};N.set(I.id,X),k.push(...$)}u.current=N;const x=new Map,S=I=>{const R=sv(I),L=p.current.get(I.tabKey);if(L&&L.signature===R)return x.set(I.tabKey,L),L.timestamp;const T={signature:R,timestamp:dp(I)||(L==null?void 0:L.timestamp)||0};return x.set(I.tabKey,T),T.timestamp},C=[...k].sort((I,R)=>up(I,R,S));return p.current=x,C},[a,t,o]),h=l.useMemo(()=>{const N=Zy(m,r);return Ya(i.current,N)?i.current:(i.current=N,N)},[m,r]),b=l.useMemo(()=>{const N=new Map,k=Array.from(new Set(h.map(x=>x.routeId)));for(const x of k){const S=Gt(h,x);S&&N.set(x,S)}return N},[h]),g=l.useMemo(()=>{const N=new Map;for(const k of h){const x=b.get(k.routeId),S=k.streamSource==="native"&&x?x:k;for(const C of os({providerSessionId:k.providerSessionId,sessionId:k.sessionId,tabKey:k.tabKey}))N.set(C,S)}return N},[h,b]),f=l.useMemo(()=>ev(h,b),[h,b]),v=l.useCallback(N=>{if(N)return g.get(N)},[g]),j=l.useCallback(N=>{if(N)return f.get(N)},[f]),y=l.useMemo(()=>{const N=h.filter(k=>!ya(n,k));return Ya(c.current,N)?c.current:(c.current=N,N)},[h,n]),w=l.useMemo(()=>{const N=y.map(k=>k.tabKey);return Ya(d.current,N)?d.current:(d.current=N,N)},[y]);return{chatIdes:a,conversations:h,visibleConversations:y,visibleTabKeys:w,resolveConversationBySessionId:v,resolveConversationByTarget:j}}function nv({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 av({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){l.useEffect(()=>{ot.setIdes(e)},[e]),l.useEffect(()=>{ot.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=ot.onToast(o=>{r(c=>c.some(u=>u.message===o.message&&o.timestamp-u.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=Lu.on("status_event",o=>{ot.handleRawEvent(o,"ws")});return()=>{a()}},[]),l.useEffect(()=>{var o;const a=i=>{var f;const c=i.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,u=n(d),p=(u==null?void 0:u.routeId)||c.daemonId;if(!p)return;const m=Number(c.buttonIndex),h=c.button||((f=u==null?void 0:u.modalButtons)==null?void 0:f[m])||"Approve",b=String(h).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),g=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(b);t(p,"resolve_action",{action:g?"approve":"reject",button:h,...Number.isFinite(m)&&{buttonIndex:m},...(u==null?void 0:u.sessionId)&&{targetSessionId:u.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(v=>console.error("[SW Action] approval failed:",v))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",a)}},[n,t])}const ov="adhdev_dashboardLayout_v1",iv="adhdev_dashboardDockview_v1",lv="adhdev_dashboardDockviewHiddenRestore_v1",yr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Li(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function cv(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function pp(e){return`${ov}:${e}`}function dv(e){const t=pp(e);return Li(t,null)}function uv(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=pp(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function mp(e){return`${iv}:${e}`}function pv(e){const t=mp(e);return Li(t,null)}function mv(e,t){try{const r=mp(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function hp(e){return`${lv}:${e}`}function hv(e){const t=hp(e);return Li(t,{})}function fv(e,t){try{const r=hp(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function xv(){return{groupAssignments:[...yr.groupAssignments],focusedGroup:yr.focusedGroup,groupActiveTabIds:{...yr.groupActiveTabIds},groupTabOrders:{...yr.groupTabOrders},groupSizes:[...yr.groupSizes]}}function bv(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function gv(){const[e]=l.useState(()=>cv(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({}),[u,p]=l.useState([]),[m,h]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[b,g]=l.useState(!1),f=l.useCallback(()=>{if(b)return;const I=dv(e)??xv();r(new Map(I.groupAssignments)),a(I.focusedGroup),i(I.groupActiveTabIds),d(I.groupTabOrders),p(I.groupSizes),g(!0)},[b,e]);l.useEffect(()=>{b&&uv(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:c,groupSizes:u})},[b,e,t,n,o,c,u]),l.useEffect(()=>{const I=window.matchMedia("(max-width: 767px)"),R=L=>h(L.matches);return I.addEventListener("change",R),()=>I.removeEventListener("change",R)},[]);const v=l.useCallback(I=>{r(I)},[]),j=l.useCallback(I=>{a(I)},[]),y=l.useCallback(I=>{i(I)},[]),w=l.useCallback(I=>{d(I)},[]),N=l.useCallback(I=>{p(I)},[]),k=l.useCallback(I=>{j(I)},[j]),x=l.useCallback((I,R)=>{i(L=>(L[I]??null)===(R??null)?L:{...L,[I]:R})},[]),S=l.useCallback((I,R)=>{d(L=>{const T=L[I];return bv(T,R)?L:{...L,[I]:R}})},[]),C=l.useCallback((I,R)=>{const L=R.get(I)??0;return x(L,I),k(L),L},[k,x]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:v,focusedGroup:n,updateFocusedGroup:j,focusGroup:k,groupActiveTabIds:o,updateGroupActiveTabIds:y,setGroupActiveTab:x,groupTabOrders:c,updateGroupTabOrders:w,setGroupTabOrder:S,groupSizes:u,updateGroupSizes:N,isMobile:m,hasHydratedStoredLayout:b,hydrateStoredLayout:f,focusConversationTab:C}}function yv(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=ga(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function vv({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:u,isRefreshingHistory:p,ides:m,handleRefreshHistory:h}){const b=l.useRef(!1),g=l.useRef(!1),f=l.useRef(null),v=l.useRef(!1);l.useEffect(()=>{if(!e||b.current||t.length===0)return;if(!a){o();return}const j=r(e);j&&(i(j.tabKey,n),b.current=!0,g.current=!0,f.current!=null&&(window.clearTimeout(f.current),f.current=null),c(y=>{const w=new URLSearchParams(y);return w.delete("activeTab"),w},{replace:!0}))},[e,t,r,n,a,o,i,c]),l.useEffect(()=>{if(!(g.current||a)&&t.length!==0){if(!e){o(),g.current=!0;return}if(b.current){g.current=!0;return}if(f.current==null)return f.current=window.setTimeout(()=>{f.current=null,!(g.current||a)&&(o(),g.current=!0)},1500),()=>{f.current!=null&&(window.clearTimeout(f.current),f.current=null)}}},[e,t.length,a,o]),l.useEffect(()=>{if(!d){v.current=!1;return}if(!u||v.current||p)return;const j=m.find(y=>y.id===u.routeId);j&&(!j.chats||j.chats.length===0||yv(j.chats,u))&&(v.current=!0,h())},[d,u,p,m,h])}function Ja(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=ga(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function fp({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[i,c]=l.useState(!1),[d,u]=l.useState(!1),p=l.useCallback(async g=>{try{await e("standalone","launch_ide",{ideType:g,enableCdp:!0})}catch(f){console.error("Launch failed",f)}},[e]),m=l.useCallback(async(g,f)=>{try{const v=g||(t==null?void 0:t.daemonId)||"",j=await e(v,"switch_chat",{id:f,sessionId:f,...Ns(t)}),y=j==null?void 0:j.result;if((j==null?void 0:j.success)===!0||y==="switched"||y==="switched-by-title")return;y===!1||y==="not_found"?fr(a,"⚠️ Session tab not found — try refreshing history"):typeof y=="string"&&y.startsWith("error:")?fr(a,`⚠️ Switch error: ${y}`):fr(a,"⚠️ Session switch failed")}catch(v){console.error("Switch failed",v),fr(a,`❌ Switch failed: ${v.message||"connection error"}`)}},[t,e,a]),h=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const g=Ss(t);await e(g,"new_chat",{...Ns(t)}),Ag(g,t.sessionId,ga(t)[0]),o(f=>({...f,[t.tabKey]:Date.now()}))}catch(g){console.error("New chat failed",g)}finally{c(!1)}}},[t,i,e,o]),b=l.useCallback(async()=>{var g,f;if(!(!t||d)){u(!0);try{const v=Ss(t),j=async()=>e(v,"list_chats",{forceExpand:!0,...Ns(t)});let y=await j(),w=(y==null?void 0:y.chats)||((g=y==null?void 0:y.result)==null?void 0:g.chats);Ja(w,t)&&(await new Promise(N=>setTimeout(N,450)),y=await j(),w=(y==null?void 0:y.chats)||((f=y==null?void 0:y.result)==null?void 0:f.chats)),y!=null&&y.success&&Array.isArray(w)&&(n(t.routeId,w),Ja(w,t)&&!Ja(r,t)&&fr(a,"⚠️ History dialog did not fully open — try once more"))}catch(v){console.error("Refresh history failed",v)}finally{u(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:p,handleSwitchSession:m,handleNewChat:h,handleRefreshHistory:b}}function wv(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 jv(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function bc(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 vn(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 gc(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 kv(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 Nv(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 yc(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 vc(e){return Array(e).fill(100/e)}function Sv({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:u}){const p=l.useRef(null),m=l.useMemo(()=>vn(e,u),[e,u]),h=m.assignments,b=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),g=b>1,f=l.useCallback((k,x)=>{t(S=>{const C=new Map(vn(S,u).assignments);return x===0?C.delete(k):C.set(k,x),C}),n(S=>({...S,[x]:k})),r(x)},[t,u,n,r]),v=l.useCallback(k=>{t(x=>{const S=vn(x,u).assignments,C=new Map;for(const[I,R]of S)R!==k&&(R>k?C.set(I,R-1):C.set(I,R));return C}),i(x=>{if(x.length<=1)return[];const S=[...x];S.splice(k,1);const C=S.reduce((I,R)=>I+R,0);return C>0?S.map(I=>I/C*100):[]}),r(0)},[t,u,i,r]),j=l.useCallback((k,x)=>{x.preventDefault();const S=p.current;if(!S)return;const C=x.clientX,I=S.offsetWidth,R=o.length===b?[...o]:vc(b),L=_=>{const X=(_.clientX-C)/I*100,M=[...R];M[k]=Math.max(15,R[k]+X),M[k+1]=Math.max(15,R[k+1]-X),i(M)},T=()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",T),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",L),document.addEventListener("mouseup",T)},[o,b,i]),y=l.useCallback((k,x,S)=>{if(b>=4)return;const C=S==="left"?x:x+1;t(I=>{const R=vn(I,u).assignments,L=new Map;for(const T of d){const _=R.get(T.tabKey)??0,$=_>=C?_+1:_;$>0&&L.set(T.tabKey,$)}return C>0&&L.set(k,C),L}),i(I=>{const R=I.length===b?[...I]:vc(b),L=R[x]??100/b,T=Math.max(15,L/2),_=Math.max(15,L/2),$=[...R];$[x]=T,$.splice(C,0,_);const X=$.reduce((M,A)=>M+A,0);return $.map(M=>M/X*100)}),n(I=>{const R=yc(I,C);return R[C]=k,R}),a(I=>{const R=yc(I,C);return R[C]=[k],R}),r(C)},[b,t,u,d,i,n,a,r]);l.useEffect(()=>{wv(e,h)||t(h)},[e,h,t]),l.useEffect(()=>{const{mapping:k,usedGroups:x}=m;n(S=>{const C=gc(S,k);return bc(S,C)?S:C}),a(S=>{const C=gc(S,k);return bc(S,C)?S:C}),r(S=>{const C=c?0:kv(S,x,k);return S===C?S:C}),i(S=>{const C=c?[]:Nv(S,x,m.groupCount);return jv(S,C)?S:C})},[m,c,n,a,r,i]);const w=l.useMemo(()=>{const k=Array.from({length:b},()=>[]);for(const x of d){const S=h.get(x.tabKey)??0,C=Math.min(S,b-1);k[C].push(x)}return k},[d,h,b]),N=l.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:p,normalizedGroupAssignments:h,numGroups:b,isSplitMode:g,groupedConvs:w,moveTabToGroup:f,closeGroup:v,handleResizeStart:j,splitTabRelative:y,clearAllSplits:N}}function Xa(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 Cv(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 wn(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Di(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=Xa(t.channel)||Xa(e.updateChannel)||Xa(e.releaseChannel)||void 0,n=Cv(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=wn(t.targetVersion)||wn(e.serverVersion)||void 0,o=wn(t.minVersion)||void 0,i=wn(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 Gs(e,t=null){return Di(e).targetVersion||t}function xp(e){return Di(e).channel||null}function bp(e){const t=Di(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 Iv({ides:e,sendDaemonCommand:t}){const r="0.9.82",n=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:Ti(m,Gs(m,r))).sort((m,h)=>Number(Pr(h,Gs(h,r)))-Number(Pr(m,Gs(m,r)))),[r,e]),a=l.useMemo(()=>n.some(m=>Pr(m,Gs(m,r))),[r,n]),o=l.useMemo(()=>n.map(m=>Gs(m,r)).find(m=>typeof m=="string"&&m.trim().length>0)||r,[r,n]),[i,c]=l.useState(!1),[d,u]=l.useState({}),p=l.useCallback(async m=>{var b,g;const h=e.find(f=>f.id===m);if(h){u(f=>({...f,[m]:"upgrading"}));try{const f=await t(m,"daemon_upgrade",bp(h));(b=f==null?void 0:f.result)!=null&&b.upgraded||(g=f==null?void 0:f.result)!=null&&g.success?u(v=>({...v,[m]:"done"})):u(v=>({...v,[m]:"error"}))}catch{u(f=>({...f,[m]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:p}}const gp=80;function Bn(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function Mv(e){return{...e,createdAt:Bn(e.createdAt),updatedAt:Bn(e.updatedAt,e.createdAt),lastEventAt:Bn(e.lastEventAt,e.updatedAt||e.createdAt)}}function Av(e){const t=ir(e);return t==="unknown:"?e.id:t}function Tv(e){return[e.type,Jd(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function _v(e,t=gp){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Av(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 Rv(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=ba(a,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=Bn(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),u=Tv({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(Mv({id:u,dedupKey:u,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:gu(a),preview:zb(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return _v(n)}function Pv(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function Lv(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=gp}=e,a=l.useMemo(()=>Rv(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=l.useMemo(()=>Pv(a),[a]);return{notifications:a,unreadCount:o}}function Dv({notifications:e,sendDaemonCommand:t}){const r=l.useCallback(o=>{const i=e.find(d=>d.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),n=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}function $i(...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 $v(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 Ei(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=$v(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 Ev(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 Bv(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Bi(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=Bv(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=(u,p)=>/^[A-Za-z]:\\?$/.test(u)?`${u.replace(/\\?$/,"\\")}${p}`:u==="/"||u==="\\"?`${i}${p}`:`${u.replace(/[\\/]+$/,"")}${i}${p}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(u=>(u==null?void 0:u.type)==="directory"&&typeof(u==null?void 0:u.name)=="string").map(u=>({name:u.name,path:typeof(u==null?void 0:u.path)=="string"&&u.path.trim()?u.path:c(o,u.name)})).sort((u,p)=>u.name.localeCompare(p.name)):[];return{path:o,directories:d}}function Fv(e,t){const r=t.meshId||"",n={meshId:r,workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp",adhdevMcpArgs:t.adhdevMcpArgs||`mcp --mode ipc --repo-mesh ${r}`};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(a,o)=>n[o]||"")}function yp(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:Fv(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function Ov(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 Hr(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function vp(e){return Vr(e)||e.tabKey||e.routeId||null}function wp(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=Gt(e.conversations,n)||e.conversations.find(i=>i.routeId===n);if(o!=null&&o.tabKey)return o.tabKey}return t||r||n||null}function ps(e){return String(e||"").trim()}function jp(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function la(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Hv(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function zv(e,t){const r=ps(e.providerSessionId),n=ps(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(ps).filter(Boolean);return!!(r&&i.includes(r)||n&&i.includes(n))});return a?a.tabKey:n||r||null}function Wv(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=jp(t.daemonId);if(n&&n!==e.machineId)return null;const a=ps(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=ps(e.resumeSessionId),i=ps(e.launchedSessionId),c=ps(t.providerSessionId),d=ps(t.targetSessionId);if(o&&o!==c&&o!==d||i&&i!==c&&i!==d)return null;const u=la(e.workspacePath);if(u){const p=la(t.workspaceName);if(p&&!Hv(p,u))return null}return zv(t,r)}function wc(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Kv({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=la(n.workspacePath),u=e.find(m=>{var v,j,y,w;if(!m||m.type==="adhdev-daemon"||jp(m.daemonId||m.id)!==n.machineId||(Fr(m)?"cli":qs(m)?"acp":"ide")!==n.kind)return!1;const g=String(m.agentType||m.type||"");if(n.providerType&&g!==n.providerType)return!1;if(n.resumeSessionId)return String(m.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const N=String(n.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(x=>String(x||"")).filter(Boolean).includes(N)}if(d){const N=la(m.workspace||m.runtimeWorkspaceLabel);return N?N===d:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((w=(y=(j=(v=m.activeChat)==null?void 0:v.messages)==null?void 0:j.at)==null?void 0:y.call(j,-1))==null?void 0:w.timestamp)||0)>=n.startedAt-5e3});if(!u)return;const p=wp({entrySessionId:u.sessionId,entryInstanceId:u.instanceId,entryRouteId:u.id,conversations:t});p&&(i(),r(p))},[i,t,e,r,n]),l.useEffect(()=>ot.onStatusEvent(d=>{const u=o.current;if(!u)return;const p=Wv(u,d,t);p&&(i(),r(p))}),[i,t,r]),l.useEffect(()=>{if(!n)return;const d=window.setTimeout(()=>{a(u=>!u||u.startedAt!==n.startedAt?u:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[n]),{trackPendingLaunch:c}}function Uv({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const i=xi(),{launchCli:c}=ma(),d=l.useCallback(async(v,j)=>Bi(e,v,j),[e]),u=l.useCallback(async(v,j)=>{if(!j.trim())return{ok:!1,error:"Choose a workspace path first."};try{const y=await e(v,"workspace_add",{path:j.trim()});return y!=null&&y.success?{ok:!0}:{ok:!1,error:(y==null?void 0:y.error)||"Could not save workspace"}}catch(y){return{ok:!1,error:y instanceof Error?y.message:"Could not save workspace"}}},[e]),p=l.useCallback(async(v,j,y)=>{var w;try{const N={ideType:j,enableCdp:!0};(w=y==null?void 0:y.workspacePath)!=null&&w.trim()&&(N.workspace=y.workspacePath.trim());const k=await e(v,"launch_ide",N);return!(k!=null&&k.success)&&(k==null?void 0:k.success)!==void 0?{ok:!1,error:(k==null?void 0:k.error)||"Could not launch IDE"}:(t({machineId:v,kind:"ide",providerType:j,workspacePath:(y==null?void 0:y.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(N){return{ok:!1,error:N instanceof Error?N.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(v,j,y,w)=>{var k,x,S;const N=Date.now();try{const C={cliType:y};(k=w==null?void 0:w.workspacePath)!=null&&k.trim()?C.dir=w.workspacePath.trim():w!=null&&w.workspaceId&&(C.workspaceId=w.workspaceId),(x=w==null?void 0:w.resumeSessionId)!=null&&x.trim()&&(C.resumeSessionId=w.resumeSessionId.trim()),Array.isArray(w==null?void 0:w.cliArgs)&&w.cliArgs.length>0&&(C.cliArgs=w.cliArgs),(S=w==null?void 0:w.initialModel)!=null&&S.trim()&&(C.initialModel=w.initialModel.trim());const I=await c(v,C),R=(I==null?void 0:I.result)||I,L=(R==null?void 0:R.sessionId)||(R==null?void 0:R.id);return I!=null&&I.success&&L?(t({machineId:v,kind:j,providerType:y,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,launchedSessionId:L,startedAt:N}),{ok:!0}):I!=null&&I.success?(t({machineId:v,kind:j,providerType:y,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:N}),{ok:!0}):{ok:!1,error:(I==null?void 0:I.error)||(R==null?void 0:R.error)||`Could not launch ${j.toUpperCase()} session`}}catch(C){return wc(C)?(t({machineId:v,kind:j,providerType:y,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:N}),{ok:!0}):{ok:!1,error:C instanceof Error?C.message:`Could not launch ${j.toUpperCase()} session`}}},[c,e,t]),h=l.useCallback(async v=>{var j;if(i!=null&&i.listMeshes)return i.listMeshes(v);if(!v)return[];try{const y=await e(v,"list_meshes",{}),w=(y==null?void 0:y.result)??y;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(k=>{var x;return{id:String((k==null?void 0:k.id)||""),name:String((k==null?void 0:k.name)||(k==null?void 0:k.id)||"Untitled mesh"),repoIdentity:(k==null?void 0:k.repoIdentity)||(k==null?void 0:k.repo_identity)||null,workspace:Array.isArray(k==null?void 0:k.nodes)&&k.nodes.length>0?String(((x=k.nodes[0])==null?void 0:x.workspace)||""):null,nodesCount:Array.isArray(k==null?void 0:k.nodes)?k.nodes.length:void 0,status:(k==null?void 0:k.status)||null}}).filter(k=>k.id)}catch(y){throw console.error("List meshes failed",y),y}},[i,e]),b=l.useCallback(async(v,j,y)=>{if(!j.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(v,j,y);const w=Date.now();try{const N={meshId:j.trim()};y.trim()&&(N.cliType=y.trim());const k=await e(v,"launch_mesh_coordinator",N),x=(k==null?void 0:k.result)??k;if((x==null?void 0:x.success)===!1||(k==null?void 0:k.success)===!1){const C=String((x==null?void 0:x.code)||(k==null?void 0:k.code)||""),I=Ov((x==null?void 0:x.meshCoordinatorSetup)||(x==null?void 0:x.manualSetup)||(k==null?void 0:k.meshCoordinatorSetup)||(k==null?void 0:k.manualSetup));return{ok:!1,error:(x==null?void 0:x.error)||(k==null?void 0:k.error)||"Could not launch mesh coordinator",code:C||void 0,manualSetup:I}}const S=(x==null?void 0:x.sessionId)||(x==null?void 0:x.id);return S?r(S):t({machineId:v,kind:"cli",providerType:(x==null?void 0:x.cliType)||y.trim()||void 0,workspacePath:(x==null?void 0:x.workspace)||null,startedAt:w}),{ok:!0}}catch(N){return wc(N)?(t({machineId:v,kind:"cli",providerType:y.trim()||void 0,startedAt:w}),{ok:!0}):{ok:!1,error:N instanceof Error?N.message:"Could not launch mesh coordinator"}}},[i,r,e,t]),g=l.useCallback(async(v,j)=>{if(!v||!j)return[];try{const y=await e(v,"list_saved_sessions",{providerType:j,kind:"cli",limit:30}),w=(y==null?void 0:y.result)??y;return Array.isArray(w==null?void 0:w.sessions)?w.sessions:[]}catch(y){return console.error("List saved sessions failed",y),[]}},[e]),f=l.useCallback(async v=>{await lp({conversation:n,mode:v,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:u,handleLaunchMachineIde:p,handleLaunchMachineProvider:m,handleListMachineMeshes:h,handleLaunchMeshCoordinator:b,handleListMachineSavedSessions:g,setActiveCliViewMode:f}}function Gv(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 Vv(e,t,r=Date.now()){return!e||!Gv(t)?null:{tabKey:e,nonce:r}}function qv({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:i}){const[c,d]=l.useState(null),[u,p]=l.useState(null),m=l.useMemo(()=>{var v,j;if(!e){if(c){const y=t.find(w=>w.tabKey===c);if(y)return y}return r[0]}const f=n[a];if(f){const y=t.find(w=>w.tabKey===f);if(y)return y}return((v=o[a])==null?void 0:v[0])||((j=o[0])==null?void 0:j[0])},[t,c,a,n,o,e,r]),h=l.useCallback(f=>{d(f)},[]),b=l.useCallback(f=>{d(f.tabKey),i(v=>{const j=new URLSearchParams(v),y=Kb(f);return y?j.set("activeTab",y):j.delete("activeTab"),j},{replace:!0})},[i]),g=l.useCallback((f,v)=>{const j=Vv(f,v);j&&p(j)},[]);return{activeConv:m,openDesktopConversation:b,requestScrollToBottom:g,scrollToBottomRequest:u,setDesktopActiveTab:h}}function Yv(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 Jv(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 Xv({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 u=()=>{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){u(),a.current=null;return}if(!(e!=null&&e.sessionId)){u(),a.current=null;return}const p=qn(e,r),m=Jv({tabKey:e.tabKey,historySessionId:Vr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:As(e),liveState:p}),h=m.autoReadKey,b=Yv({autoReadKey:h,shouldMarkSeen:m.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!m.shouldMarkSeen){b.shouldCancelPending&&u(),a.current=h;return}if(!b.shouldSchedule)return;b.shouldCancelPending&&u();const g=()=>{if(document.visibilityState!=="visible"||a.current===h)return;a.current=h,o.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const v=m.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:v,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=b.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(g,1500);const v=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=v,document.addEventListener("visibilitychange",v);return}const f=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(g,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=f,document.addEventListener("visibilitychange",f)},[e,t,r,n]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function Qa(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 Qv({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var E;const{launchCli:u}=ma(),[p,m]=l.useState(!1),[h,b]=l.useState([]),[g,f]=l.useState(()=>_t()),[v,j]=l.useState(!1),[y,w]=l.useState(null),N=l.useRef(null),k=l.useMemo(()=>r||t||e,[e,r,t]),x=!!k&&nt(k)&&!rt(k),S=l.useMemo(()=>{if(!k||!x)return null;const F=k.daemonId||k.routeId||"",z=es(k),D=Qa(k);return`${F}:${z}:${k.providerSessionId||""}:${D}`},[k,x]),C=l.useMemo(()=>!k||!x?"":Qa(k),[k,x]),{isCreatingChat:I,isRefreshingHistory:R,handleSwitchSession:L,handleNewChat:T,handleRefreshHistory:_}=fp({sendDaemonCommand:a,activeConv:k,chats:(E=n.find(F=>F.id===(k==null?void 0:k.routeId)))==null?void 0:E.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),$=l.useCallback(()=>{m(!0)},[]),X=l.useCallback(()=>{m(!1)},[]),M=l.useCallback(async()=>{if(!(!k||!x||v)){j(!0);try{const F=k.daemonId||k.routeId,z=es(k),D=Qa(k),K=await a(F,"list_saved_sessions",{agentType:z,providerType:z,kind:"cli",limit:50,...k.providerSessionId?{providerSessionId:k.providerSessionId}:{},...D?{workspace:D}:{}}),O=(K==null?void 0:K.result)??K;b(Array.isArray(O==null?void 0:O.sessions)?O.sessions:[])}catch(F){console.error("Refresh saved sessions failed",F),b([])}finally{j(!1)}}},[k,v,x,a]);l.useEffect(()=>{if(!p){N.current=null;return}if(!x){N.current=null,b([]),j(!1);return}!S||v||N.current!==S&&(N.current=S,M())},[M,p,v,x,S]);const A=l.useCallback(async F=>{if(!k||!x||!F.providerSessionId||!F.workspace)return;const z=k.daemonId||k.routeId,D=es(k);try{w(F.providerSessionId);const K=await u(z,{cliType:D,dir:F.workspace,resumeSessionId:F.providerSessionId,initialModel:qd(F.summaryMetadata,"model",{preferShortValue:!0})||void 0}),O=(K==null?void 0:K.result)??K,q=typeof(O==null?void 0:O.sessionId)=="string"?O.sessionId:typeof(O==null?void 0:O.id)=="string"?O.id:"";q&&d(ne=>{const J=new URLSearchParams(ne);return J.set("activeTab",q),J},{replace:!0}),X()}catch(K){console.error("Resume saved session failed",K)}finally{w(null)}},[X,k,x,a,d]);return{historyModalOpen:p,openHistoryModal:$,closeHistoryModal:X,historyTargetConv:k,isSavedSessionHistoryTarget:x,isHistoryCreatingChat:I,isHistoryRefreshingHistory:R,handleHistorySwitchSession:L,handleHistoryNewChat:T,handleHistoryRefresh:_,savedHistorySessions:h,savedHistoryFilters:g,setSavedHistoryFilters:f,missingWorkspaceResumePath:C,isSavedHistoryLoading:v,resumingSavedHistorySessionId:y,handleRefreshSavedHistory:M,handleResumeSavedHistorySession:A}}function Zv({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}){const[d,u]=l.useState(null),[p,m]=l.useState(null),h=l.useMemo(()=>{if(e||!n)return null;const j=c(n);return j&&!nt(j)&&!rt(j)?j:null},[e,n,c]),b=l.useMemo(()=>{const j=d==null?void 0:d.routeId;if(!j)return null;const y=d!=null&&d.tabKey?o.find(w=>w.tabKey===d.tabKey):a?o.find(w=>w.tabKey===a):null;return(y==null?void 0:y.routeId)===j?y:Gt(o,j)},[o,d,a]),g=l.useMemo(()=>{if(b)return i.find(j=>j.id===b.routeId)},[i,b]);l.useEffect(()=>{h&&(u({routeId:h.routeId,tabKey:Ol(h)}),m(h),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,h]);const f=l.useCallback(j=>{j&&(u({routeId:j.routeId,tabKey:Ol(j)}),m(j))},[]),v=l.useCallback(()=>{u(null),m(null)},[]);return{remoteDialogConv:b,remoteDialogIdeEntry:g,remoteDialogActiveConv:p,setRemoteDialogActiveConv:m,openRemoteDialog:f,closeRemoteDialog:v}}function ew({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:u}){const{remoteDialogConv:p,remoteDialogIdeEntry:m,remoteDialogActiveConv:h,setRemoteDialogActiveConv:b,openRemoteDialog:g,closeRemoteDialog:f}=Zv({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}),[v,j]=l.useState(!1),[y,w]=l.useState(null),N=l.useCallback(async S=>{const C=S||d;!C||!nt(C)&&!rt(C)||(w(C),j(!0))},[d]),k=l.useCallback(()=>{j(!1),w(null)},[]),x=l.useCallback(async S=>{const C=y||d;if(!C||!nt(C)&&!rt(C)){k();return}j(!1);try{const I=es(C),R=C.routeId||C.daemonId||"";await u(R,"stop_cli",{cliType:I,targetSessionId:C.sessionId,mode:S})}catch(I){console.error("Stop CLI failed:",I)}finally{w(null)}},[d,k,y,u]);return{remoteDialogConv:p,remoteDialogIdeEntry:m,remoteDialogActiveConv:h,setRemoteDialogActiveConv:b,openRemoteDialog:g,closeRemoteDialog:f,cliStopDialogOpen:v,cliStopTargetConv:y,requestCliStop:N,cancelCliStop:k,confirmCliStop:x}}function Za(e,t=!0){return(e??!0)&&t}const Fi=l.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:d,handleForceSendChat:u,isSendingChat:p,sendFeedbackMessage:m=null,handleFocusAgent:h,isFocusingAgent:b,actionLogs:g,userName:f,scrollToBottomRequestNonce:v,isInputActive:j=!0,isVisible:y=!0}){const w=n,N=!n,k=Za(y,w),x=Za(y,N),S=Za(y),C=ap(t),I=C.status||C.modalMessage||C.modalButtons?{...t,...C.status?{status:C.status}:{},...C.modalMessage!==void 0?{modalMessage:C.modalMessage}:{},...C.modalButtons!==void 0?{modalButtons:C.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Kd,{activeConv:I,onModalButton:i}),I.transport!=="pty"&&I.transport!=="acp"&&I.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(Zs,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:c,children:"Relaunch with CDP"})]})}):null,I.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:w?"visible":"hidden",pointerEvents:w?"auto":"none"},children:s.jsx(w0,{activeConv:I,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:p,sendFeedbackMessage:m,isVisible:k,isInputActive:j&&k})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:N?"visible":"hidden",pointerEvents:N?"auto":"none"},children:s.jsx(Wo,{activeConv:I,ideEntry:a,handleSendChat:d,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:b,actionLogs:g,userName:f,scrollToBottomRequestNonce:v,isInputActive:j&&x,isVisible:x})})]}):s.jsx(Wo,{activeConv:I,ideEntry:a,handleSendChat:d,handleForceSendChat:u,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:b,actionLogs:g,userName:f,scrollToBottomRequestNonce:v,isInputActive:j&&S,isVisible:S})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.handleForceSendChat===t.handleForceSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function tw({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var w,N,k;const i=Kr(),c=Es(e),d=o?null:bu(e),u=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),p=!o&&e.streamSource==="agent-stream"&&!!e.agentName,m=!o&&!p&&(e.transport==="pty"||e.transport==="acp"),h=tr(e),b=Wb(e),g=(w=e.settings)==null?void 0:w.meshNodeFor,f=e.meshQueueStats,v=((N=e.coordinator)==null?void 0:N.meshId)||((k=e.settings)==null?void 0:k.meshCoordinatorFor),j=l.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),y=l.useCallback(()=>{if(r){r();return}const x=vp(e);x&&i(Hr(x))},[e,i,r]);return!u&&!p&&!m&&!d&&!g&&!f?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:y,title:b,children:[s.jsx(qt,{size:12}),s.jsx("span",{children:b})]}):s.jsxs("span",{className:"conversation-meta-chip",title:b,children:[s.jsx(qt,{size:12}),s.jsx("span",{children:b})]})),p&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(er,{size:12}),s.jsx("span",{children:h})]}),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(er,{size:12}),s.jsx("span",{children:h})]}),d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:j,title:d,children:[s.jsx(xs,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(xs,{size:12}),s.jsx("span",{children:d})]})),g&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(xs,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),v&&f&&s.jsxs("span",{className:`conversation-meta-chip ${f.pending>0?"is-active":""}`,style:f.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${f.pending} pending, ${f.assigned} assigned, ${f.completed} completed, ${f.failed} failed`,children:[s.jsx(sf,{size:12}),s.jsxs("span",{children:[f.pending," Pending"]})]})]})}function sw({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:u,onOpenNativeConversation:p,onOpenMachine:m,onOpenHistory:h,onOpenRemote:b,onOpenMeshGraph:g,onStopCli:f,cliViewMode:v,onSetCliViewMode:j,handleSendChat:y,handleForceSendChat:w,handleFocusAgent:N,handleModalButton:k,handleRelaunch:x}){var T,_;const S=l.useRef(null),C=nt(e)&&!t,I=C&&v==="terminal",R=!!e.daemonId&&!!((T=e.coordinator)!=null&&T.meshId||(_=e.settings)!=null&&_.meshCoordinatorFor),L=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${L} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:u,type:"button","aria-label":"Back",children:s.jsx(ni,{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:pt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(tw,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>p(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[C&&v&&s.jsx(Ou,{mode:v,onChange:j,compact:!0}),C&&f&&s.jsx("button",{onClick:()=>{f(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(vt,{size:14})}),R&&g&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(as,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(e),type:"button",children:s.jsx(ai,{size:14})}),!t&&!C&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>b(e),type:"button",children:s.jsx(qt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(Fi,{activeConv:e,clearToken:0,isCliTerminal:I,ideEntry:n,terminalRef:S,handleModalButton:k,handleRelaunch:x,handleSendChat:y,handleForceSendChat:w,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:N,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const eo={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 rw(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function kp(){const[e,t]=l.useState("unix"),[r,n]=l.useState("powershell"),[a,o]=l.useState(!1),i=e==="unix"?"unix":r;l.useEffect(()=>{t(rw())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(eo[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:eo[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:eo[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 Np({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:qt},{key:"chats",label:"Chats",icon:$s}];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 jn({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 Hs({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 vr({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 nw({conversation:e,onCancel:t,onConfirm:r}){const n=pt(e),a=Ps(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(vt,{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 kn({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onOpenMeshGraph:o,onCollectChatDebugBundle:i,isMuted:c,onToggleMute:d}){var T,_;const u=t==="needs_attention"||t==="task_complete",p=t==="working",m=t==="earlier",h=t==="task_complete",{isReconnecting:b,isConnecting:g}=or(e.conversation),f=pt(e.conversation),v=Ps(e.conversation),j=$u(e.conversation,{requiresAction:t==="needs_attention"}),y=u?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":p?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",w=u?"bg-accent-primary shadow-glow":p?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":m?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",N=m?"text-text-secondary":"text-text-primary",k=m?"text-text-muted":"text-text-secondary",x=m?"text-text-secondary opacity-80":"text-text-muted",S=m?"text-text-muted opacity-80":"text-text-muted",C=!p&&!h,I=!!e.conversation.daemonId&&!!((T=e.conversation.coordinator)!=null&&T.meshId||(_=e.conversation.settings)!=null&&_.meshCoordinatorFor),R="text-[color:var(--status-warning)]",L=$=>{if(!i)return;$.preventDefault(),$.stopPropagation();const X=i==null?void 0:i(e.conversation);Promise.resolve(X).catch(M=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",M)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${y}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[u||p?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:u?{color:"var(--accent-on-primary)"}:void 0,children:r(f)}),a&&s.jsxs("button",{type:"button",className:"mobile-inbox-hide-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-border-subtle bg-bg-primary/70 px-2 text-[10px] font-semibold text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:$=>{$.preventDefault(),$.stopPropagation(),a()},"aria-label":`Hide ${f}`,title:"Hide conversation",children:[s.jsx(oi,{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:$=>{$.preventDefault(),$.stopPropagation(),d()},"aria-label":c?`Unmute ${f}`:`Mute ${f}`,title:c?"Unmute (resume notifications)":"Mute notifications",children:[s.jsx(Ur,{size:11}),s.jsx("span",{children:c?"Muted":"Mute"})]}),I&&o&&s.jsxs("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-border-subtle bg-bg-primary/70 px-2 text-[10px] font-semibold text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:$=>{$.preventDefault(),$.stopPropagation(),o(e.conversation)},"aria-label":`Open mesh graph for ${f}`,title:"Open live repo mesh graph",children:[s.jsx(as,{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:L,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 ${N}`,children:f}),C&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${S}`,children:Wd(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${k}`,children:[s.jsx("span",{className:"truncate",children:v}),s.jsx(ea,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),b?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${R} animate-pulse`,children:"Reconnecting…"})]}):g?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):j==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:R,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${x}`,children:e.preview})]}),u&&!h&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),h&&s.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),p&&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 jc({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 aw({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:u,onOpenConversation:p,onShowAllHidden:m,onHideConversation:h,onOpenMeshGraph:b,onOpenNewSession:g,onOpenMachine:f,onOpenSettings:v,onSectionChange:j,wsStatus:y="connected",isStandalone:w=!1,onCollectChatDebugBundle:N,isConversationMuted:k,onToggleMuteConversation:x}){const[S,C]=l.useState(null),I=y==="disconnected"||y==="reconnecting"||y==="offline"||y==="auth_failed",R=i.length>0,L=t.length>0||r.length>0||n.length>0||a.length>0,T=e==="machines"?"Machines":"Chats",_=w?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",$=w?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",X=l.useCallback(async E=>{const F=Ss(E);if(!F)return;const z=Array.isArray(E.messages)?E.messages:[],D=ku({activeConv:E,visibleMessages:z,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:z.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),K=await u(F,"get_chat_debug_bundle",{...Ns(E),delivery:"daemon_file",frontendSnapshot:D}),O=Tr(K),q=Cu(O),ne=await Su(q);ne==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ot.showToast(Nu(O,{locatorCopyStatus:ne}),ne==="failed"?"warning":"success")},[d,u]),M=N||X,A=l.useCallback(()=>{S&&(h==null||h(S),C(null))},[S,h]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${_}`,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:T}),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(Ur,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:v,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(ha,{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] ${$}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:I?s.jsx(vr,{icon:s.jsx(jc,{}),title:y==="offline"?"Network offline":y==="auth_failed"?"Session expired":"Reconnecting",subtitle:y==="offline"?"Waiting for network…":y==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):i.length===0?s.jsx(vr,{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(kp,{})})}):s.jsx(Hs,{children:i.map((E,F)=>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] ${F>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(E.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(E.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:E.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:E.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[E.unread," new"]}):E.total>0?`${E.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:E.subtitle}),E.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[E.total," chat",E.total!==1?"s":"",E.unread>0?` · ${E.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},E.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(jn,{title:"Needs attention",className:"mb-0"}),s.jsx(Hs,{children:t.map((E,F)=>s.jsx("div",{className:F>0?"border-t border-border-subtle/70":"",children:s.jsx(kn,{item:E,type:"needs_attention",getAvatarText:c,onOpenConversation:p,onRequestHideConversation:h?()=>C(E.conversation):void 0,onOpenMeshGraph:b,onCollectChatDebugBundle:M,isMuted:k==null?void 0:k(E.conversation),onToggleMute:x?()=>x(E.conversation):void 0})},E.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(jn,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(Hs,{children:r.map((E,F)=>s.jsx("div",{className:F>0?"border-t border-border-subtle/70":"",children:s.jsx(kn,{item:E,type:"task_complete",getAvatarText:c,onOpenConversation:p,onRequestHideConversation:h?()=>C(E.conversation):void 0,onOpenMeshGraph:b,onCollectChatDebugBundle:M,isMuted:k==null?void 0:k(E.conversation),onToggleMute:x?()=>x(E.conversation):void 0})},E.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(jn,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(Hs,{children:n.map((E,F)=>s.jsx("div",{className:F>0?"border-t border-border-subtle/70":"",children:s.jsx(kn,{item:E,type:"working",getAvatarText:c,onOpenConversation:p,onRequestHideConversation:h?()=>C(E.conversation):void 0,onOpenMeshGraph:b,onCollectChatDebugBundle:M,isMuted:k==null?void 0:k(E.conversation),onToggleMute:x?()=>x(E.conversation):void 0})},E.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(jn,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(Hs,{children:a.map((E,F)=>s.jsx("div",{className:F>0?"border-t border-border-subtle/70":"",children:s.jsx(kn,{item:E,type:"earlier",getAvatarText:c,onOpenConversation:p,onRequestHideConversation:h?()=>C(E.conversation):void 0,onOpenMeshGraph:b,onCollectChatDebugBundle:M,isMuted:k==null?void 0:k(E.conversation),onToggleMute:x?()=>x(E.conversation):void 0})},E.conversation.tabKey))}):L?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):I?s.jsx(vr,{icon:s.jsx(jc,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):R?s.jsx(vr,{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($s,{size:20})}),title:"No conversations yet",subtitle:Hu,children:g&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:g,"aria-label":Qt,title:Qt,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:Qt})]})}):s.jsx(vr,{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(Hs,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[o.length," collapsed ",o.length===1?"conversation":"conversations"]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:m,children:"Restore all"})]})})})]}),e==="chats"&&g&&L&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:g,"aria-label":Qt,title:Qt,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"})]})}),S&&s.jsx(nw,{conversation:S,onCancel:()=>C(null),onConfirm:A}),s.jsx(Np,{section:e,onSectionChange:j})]})}function ow(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 Sp(e){const t=[e.workspace||"Workspace unknown"],r=_s(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=ow(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Oi({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:d,onConfirm:u}){const[p,m]=l.useState(r);l.useEffect(()=>{m(r)},[r]);const h=Ev(r),b=p.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(vt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!h||a||d(h)},disabled:!h||a,children:[s.jsx(ni,{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:p,onChange:g=>m(g.target.value),onKeyDown:g=>{g.key!=="Enter"||!b||a||(g.preventDefault(),d(b))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!b||a||d(b)},disabled:!b||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):n.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:n.map(g=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(g.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Qs,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:g.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:g.path})]})]},g.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>u(b||r),disabled:!b&&!r||a,children:i})]})]})})}function Cp({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:i="Launch",busyLabel:c="Launching…",busy:d=!1,showArgsInput:u,argsValue:p,onArgsChange:m,showModelInput:h,modelValue:b,onModelChange:g,historyProviderNode:f,onConfirm:v,onCancel:j}){const y=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(vt,{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))}),(y==null?void 0:y.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:y.description})]}),f,r.map(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}`)),h&&g&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:b||"",onChange:w=>g(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})]}),u&&m&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:p||"",onChange:w=>m(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:v,disabled:d,children:[s.jsx(Ad,{size:14}),d?c:i]})]})]})})}function kc(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Ip(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?"⭐ ":""}${kc(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:kc(i),description:i,workspaceId:null,workspacePath:i}),n){const d=`saved:${n}`;if(o.some(u=>u.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 iw(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function lw(e){return[iw(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function cw(e){return e.lastLaunchedAt?xa(e.lastLaunchedAt):""}function Mp(e){return{metaText:lw(e),updatedLabel:cw(e)}}function to(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function dw({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var $e,tt,Ke,Ve;const i=Yr(),[c,d]=l.useState(!1),u=((($e=e.detectedIdes)==null?void 0:$e.length)||0)>0,p=l.useMemo(()=>(e.workspaces||[]).map(_e=>({id:_e.id,path:_e.path,label:_e.label})),[e]),m=e.defaultWorkspaceId||null,[h,b]=l.useState(m||((tt=p[0])==null?void 0:tt.id)||""),[g,f]=l.useState(""),[v,j]=l.useState(""),[y,w]=l.useState([]),[N,k]=l.useState(!1),[x,S]=l.useState(""),[C,I]=l.useState(!1),[R,L]=l.useState(to(u,t.length,r.length)),T=l.useRef(null),[_,$]=l.useState(null),X=l.useRef("__home__"),[M,A]=l.useState("__home__"),[E,F]=l.useState(""),[z,D]=l.useState(""),[K,O]=l.useState(""),[q,ne]=l.useState([]),[J,ye]=l.useState(()=>_t().textQuery),[oe,B]=l.useState(()=>_t().workspaceQuery),[W,ve]=l.useState(()=>_t().modelQuery),[we,fe]=l.useState(()=>_t().resumableOnly),[Ne,re]=l.useState(()=>_t().sortMode),[je,de]=l.useState(!1),[U,H]=l.useState(!1),Y=l.useRef(null),se=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const xe=h==="__custom__"?g.trim():((Ke=p.find(_e=>_e.id===h))==null?void 0:Ke.path)||"",Z=h==="__custom__"&&!!xe&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),P=h!=="__custom__"&&((Ve=p.find(_e=>_e.id===h))==null?void 0:Ve.path)||"",ie=l.useMemo(()=>(e.recentLaunches||[]).map(_e=>_e.workspace),[e]),be=l.useCallback(async _e=>{k(!0),S("");try{const He=await a(_e);j(He.path),f(He.path),w(He.directories)}catch(He){S(He instanceof Error?He.message:"Could not load folder")}finally{k(!1)}},[a]),ue=l.useCallback(()=>{var He;b("__custom__"),I(!0);const _e=Ei(e.platform,$i(g.trim(),P,ie,e.defaultWorkspacePath,(He=p.find(it=>it.id===m))==null?void 0:He.path,p.map(it=>it.path)));be(_e)},[g,m,be,ie,P,e.platform,p]),te=l.useCallback(_e=>{if(_e!=null&&_e.workspaceId){b(_e.workspaceId),f("");return}if(_e!=null&&_e.workspacePath){b("__custom__"),f(_e.workspacePath);return}b(""),f("")},[]),Me=l.useCallback(_e=>{if(b(_e),_e==="__custom__"){ue();return}f("")},[ue]),Ae=l.useCallback(_e=>{b("__custom__"),f(_e)},[]),Ce=l.useCallback((_e,He)=>{T.current=He,X.current=_e.selectedWorkspaceKey||"__home__",A(_e.selectedWorkspaceKey||"__home__"),F(_e.initialArgs||""),D(_e.initialModel||""),O(""),ne([]);const it=_e.providerType?`${e.id}:${_e.providerType}`:null;if(_0(se.current,it)){const Xe=_t();ye(Xe.textQuery),B(Xe.workspaceQuery),ve(Xe.modelQuery),fe(Xe.resumableOnly),re(Xe.sortMode)}se.current=it,$(_e),_e.providerType&&o&&(de(!0),o(_e.providerType).then(Xe=>ne(Xe||[])).catch(Xe=>console.warn("Failed to load saved sessions",Xe)).finally(()=>de(!1)))},[o,e.id]),Ue=l.useMemo(()=>zu(q,{textQuery:J,workspaceQuery:oe,modelQuery:W,resumableOnly:we,sortMode:Ne}),[W,we,q,Ne,J,oe]);l.useEffect(()=>{K&&(Ue.some(_e=>_e.providerSessionId===K)||O(""))},[Ue,K]);const Qe=l.useCallback(()=>{T.current&&(H(!0),T.current().finally(()=>{T.current=null,H(!1),$(null)}))},[]),pe=l.useCallback(()=>{T.current=null,$(null)},[]),De=l.useCallback(_e=>{X.current=_e,A(_e)},[]);return l.useEffect(()=>{var _e;Y.current!==e.id&&(Y.current=e.id,b(m||((_e=p[0])==null?void 0:_e.id)||"__custom__"),f(""),j(""),w([]),S(""),I(!1),ye(_t().textQuery),B(_t().workspaceQuery),ve(_t().modelQuery),fe(_t().resumableOnly),re(_t().sortMode),se.current=null,L(to(u,t.length,r.length)))},[r.length,t.length,m,u,e.id,p]),l.useEffect(()=>{var _e;h!=="__custom__"&&(h&&p.some(He=>He.id===h)||b(m||((_e=p[0])==null?void 0:_e.id)||"__custom__"))},[m,h,p]),l.useEffect(()=>{R==="ide"&&u||R==="cli"&&t.length>0||R==="acp"&&r.length>0||L(to(u,t.length,r.length))},[R,r.length,t.length,u]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:u,workspaceRows:p,defaultWorkspaceId:m,workspaceChoice:h,customWorkspacePath:g,browseCurrentPath:v,browseDirectories:y,browseBusy:N,browseError:x,browseDialogOpen:C,activeLauncherKind:R,launchConfirm:_,launchConfirmWorkspaceKeyRef:X,launchConfirmWorkspaceKey:M,launchConfirmArgs:E,launchConfirmModel:z,launchConfirmResumeId:K,launchConfirmSavedSessions:q,launchConfirmTextFilter:J,launchConfirmWorkspaceFilter:oe,launchConfirmModelFilter:W,launchConfirmResumableOnly:we,launchConfirmSortMode:Ne,filteredLaunchConfirmSavedSessions:Ue,launchConfirmSessionsLoading:je,launchConfirmBusy:U,resolvedWorkspacePath:xe,canCreateMissingWorkspace:Z,openBrowseDialog:ue,loadBrowsePath:be,handleWorkspaceChoiceChange:Me,chooseCustomWorkspacePath:Ae,setCustomWorkspacePath:f,setBrowseDialogOpen:I,setActiveLauncherKind:L,openLaunchConfirm:Ce,handleConfirmLaunch:Qe,closeLaunchConfirm:pe,setWorkspaceSelectionFromOption:te,setLaunchConfirmWorkspaceKeyAndSync:De,setLaunchConfirmArgs:F,setLaunchConfirmModel:D,setLaunchConfirmResumeId:O,setLaunchConfirmTextFilter:ye,setLaunchConfirmWorkspaceFilter:B,setLaunchConfirmModelFilter:ve,setLaunchConfirmResumableOnly:fe,setLaunchConfirmSortMode:re}}function uw({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:d,section:u,showBottomNav:p,onBack:m,onSectionChange:h,onOpenConversation:b,onOpenRecent:g,onOpenMachineDetails:f,onMachineUpgrade:v,onLaunchDetectedIde:j,onAddWorkspace:y,onBrowseDirectory:w,onLaunchWorkspaceProvider:N,onListSavedSessions:k}){const x=M=>M==="ide"?"Workspace":M==="cli"?"CLI":"ACP",S=r.slice(0,4),C=t.slice(0,3),I=dw({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:c,onBrowseDirectory:w,onListSavedSessions:k}),R=l.useMemo(()=>S.map(M=>{const{metaText:A,updatedLabel:E}=Mp(M);return{key:`recent-launch:${M.id}`,primary:M.label,secondary:A,updatedLabel:E,onClick:()=>{const{options:F,selectedKey:z}=Ip({machine:{workspaces:I.workspaceRows,defaultWorkspaceId:I.defaultWorkspaceId},currentWorkspacePath:M.workspace});I.openLaunchConfirm({title:M.kind==="ide"?sa("restart-ide",M.label):M.providerSessionId?Wu(M.label):sa("start-fresh",M.label),description:M.kind==="ide"?ra("restart-ide"):M.providerSessionId?Ku():ra("start-fresh"),confirmLabel:M.kind==="ide"?na("restart-ide"):M.providerSessionId?ta(!0):na("start-fresh"),busyLabel:M.kind==="ide"?aa("restart-ide"):M.providerSessionId?Ii(!0):aa("start-fresh"),workspaceOptions:F,selectedWorkspaceKey:z,details:[{label:"Mode",value:x(M.kind)},...M.providerType?[{label:"Provider",value:M.providerType}]:[]]},async()=>{const D=F.find(K=>K.key===I.launchConfirmWorkspaceKeyRef.current);I.setWorkspaceSelectionFromOption(D),await g({...M,workspace:(D==null?void 0:D.workspacePath)??null})})}}}),[I,g,S]),L=l.useMemo(()=>C.map(M=>({key:`recent-chat:${M.conversation.tabKey}`,primary:pt(M.conversation),secondary:i0(M.conversation,{timestampLabel:M.timestamp?Wd(M.timestamp):null}),unread:M.unread,onClick:()=>b(M.conversation)})),[b,C]),T=I.showAllRecent?R:R.slice(0,4),_=R.length>0,$=L.length>0,X=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 ${X} 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(ni,{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:Ft(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:[$&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:L.map(M=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${M.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:M.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:M.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:M.secondary})]},M.key))})]}),_&&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:T.map(M=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:M.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:M.primary}),M.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:M.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:M.secondary})]},M.key))}),R.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>I.setShowAllRecent(M=>!M),children:I.showAllRecent?"Show fewer":`Show ${R.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:v,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:f,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),I.browseDialogOpen&&s.jsx(Oi,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:I.browseCurrentPath,directories:I.browseDirectories,busy:I.browseBusy,error:I.browseError,confirmLabel:"Use this folder",onClose:()=>I.setBrowseDialogOpen(!1),onNavigate:M=>{I.loadBrowsePath(M)},onConfirm:M=>{I.chooseCustomWorkspacePath(M),I.setBrowseDialogOpen(!1)}}),I.launchConfirm&&s.jsx(Cp,{title:I.launchConfirm.title,description:I.launchConfirm.description,details:I.launchConfirm.details,workspaceOptions:I.launchConfirm.workspaceOptions,selectedWorkspaceKey:I.launchConfirmWorkspaceKey,onWorkspaceChange:I.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:I.launchConfirm.providerType?ta(!!I.launchConfirmResumeId):I.launchConfirm.confirmLabel,busyLabel:I.launchConfirm.providerType?void 0:I.launchConfirm.busyLabel,busy:I.launchConfirmBusy,showArgsInput:I.launchConfirm.showArgsInput,argsValue:I.launchConfirmArgs,onArgsChange:I.setLaunchConfirmArgs,showModelInput:I.launchConfirm.showModelInput,modelValue:I.launchConfirmModel,onModelChange:I.setLaunchConfirmModel,historyProviderNode:I.launchConfirm.providerType&&(I.launchConfirmSessionsLoading||I.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),I.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:Mi()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:I.launchConfirmTextFilter,onChange:M=>I.setLaunchConfirmTextFilter(M.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:I.launchConfirmWorkspaceFilter,onChange:M=>I.setLaunchConfirmWorkspaceFilter(M.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:I.launchConfirmModelFilter,onChange:M=>I.setLaunchConfirmModelFilter(M.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),s.jsxs("select",{value:I.launchConfirmSortMode,onChange:M=>I.setLaunchConfirmSortMode(M.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:I.launchConfirmResumableOnly,onChange:M=>I.setLaunchConfirmResumableOnly(M.target.checked),disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:I.launchConfirmResumeId,onChange:M=>I.setLaunchConfirmResumeId(M.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:L0()}),I.filteredLaunchConfirmSavedSessions.map(M=>s.jsxs("option",{value:M.providerSessionId,disabled:!M.canResume,children:[M.title||M.providerSessionId," ",M.canResume?"":"(workspace missing)"]},M.providerSessionId))]}),!I.launchConfirmSessionsLoading&&I.launchConfirmSavedSessions.length>0&&I.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),I.launchConfirmResumeId&&(()=>{const M=I.filteredLaunchConfirmSavedSessions.find(E=>E.providerSessionId===I.launchConfirmResumeId);if(!M)return null;const A=Sp(M);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:A.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:A.providerSessionId}),s.jsx("div",{className:"mt-1",children:A.metaLine}),A.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:A.updatedLabel}),A.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:A.preview})]})})()]}),onConfirm:I.handleConfirmLaunch,onCancel:I.closeLaunchConfirm}),p&&s.jsx(Np,{section:u,onSectionChange:h})]})}function Fn(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function pw(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:Fn(e)}function mw(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 hw(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:_s(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=Fr(n)?"cli":qs(n)?"acp":"ide",o=_s(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||(Fr(n)?n.cliName||n.type:qs(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:qs(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 fw(e,t){const r=new Map;for(const n of t){const a=Es(n.conversation),o=r.get(a);o?o.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],o=[...a].sort((m,h)=>h.timestamp-m.timestamp)[0]||null,i=(o==null?void 0:o.conversation)||null,c=Po(n),d=a.filter(m=>m.unread||m.requiresAction).length,u=mw(n),p=[n.platform||"machine",u].filter(Boolean);return{id:n.id,label:Ft(n,{fallbackId:n.id}),subtitle:p.join(" · "),unread:d,total:a.length,latestConversation:i,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:c,preview:i?l0(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 xw(e){return e==="chat"}function Nn(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 bw({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:u,requestedMachineId:p,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:b,setSelectedTabKey:g,setScreen:f,setSelectedMachineId:v,setSection:j,setMachineBackTarget:y,resetMachineAction:w}){const N=l.useRef(null),k=l.useCallback(x=>{if(!(x!=null&&x.sessionId))return;const S=qn(x,i),C=Math.max(Date.now(),As(x),S.lastUpdated||0);Nn("mark_read:start",{tabKey:x.tabKey,sessionId:x.sessionId,displayPrimary:pt(x),inboxBucket:S.inboxBucket,unread:S.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:As(x),readAt:C}),c(Es(x)||x.routeId,"mark_session_seen",{sessionId:x.sessionId,providerSessionId:x.providerSessionId,seenAt:C,completionMarker:S.completionMarker}).then(I=>{Nn("mark_read:result",{tabKey:x.tabKey,sessionId:x.sessionId,result:I})}).catch(I=>{Nn("mark_read:error",{tabKey:x.tabKey,sessionId:x.sessionId,error:I instanceof Error?I.message:String(I)})})},[i,c]);return l.useEffect(()=>{var S;if(!n){xw(o)&&f("inbox"),g(((S=e[0])==null?void 0:S.tabKey)||null),N.current=null;return}if(o!=="chat"){N.current=null;return}const x=`${n.tabKey}:${n.sessionId||""}`;N.current!==x&&(N.current=x,k(n))},[e,k,o,n,f,g]),l.useEffect(()=>{if(!d)return;const x=e.find(S=>S.tabKey===d);x&&(g(x.tabKey),f("chat"),u==null||u())},[e,u,d,f,g]),l.useEffect(()=>{if(!p)return;const x=t.find(S=>S.id===p);x&&(v(x.id),w(),j("machines"),y("inbox"),f("machine"),m==null||m())},[t,m,p,w,y,f,j,v]),l.useEffect(()=>{h&&(j(h),f("inbox"),b==null||b())},[b,h,f,j]),l.useEffect(()=>{const x=r.filter(S=>S.inboxBucket==="task_complete"||S.unread);x.length!==0&&Nn("inbox_state",{screen:o,selectedTabKey:a,items:x.map(S=>{const C=qn(S.conversation,i);return{liveState:C,tabKey:S.conversation.tabKey,sessionId:S.conversation.sessionId,displayPrimary:pt(S.conversation),serverBucket:C.inboxBucket,computedBucket:S.inboxBucket,serverUnread:C.unread,computedUnread:S.unread,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,activityAt:As(S.conversation)}})})},[r,i,o,a]),{markConversationRead:k}}function gw(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Nc(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function yw(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function vw({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const{launchCli:a}=ma(),[o,i]=l.useState("idle"),[c,d]=l.useState(""),[u,p]=l.useState(null),m=l.useCallback(()=>{i("idle"),d(""),p(null)},[]),h=l.useCallback(async(w,N,k)=>{var x;try{i("loading"),d(`Launching ${N}…`);const S={ideType:N,enableCdp:!0};(x=k==null?void 0:k.workspacePath)!=null&&x.trim()&&(S.workspace=k.workspacePath.trim()),await e(w,"launch_ide",S),i("done"),d(`${N} launch requested`)}catch(S){i("error"),d(S instanceof Error?S.message:"Launch IDE failed"),console.error("Launch IDE failed",S)}},[e]),b=l.useCallback(async(w,N,k)=>{if(N.trim())try{i("loading"),d(k!=null&&k.createIfMissing?"Creating folder…":"Saving workspace…");const x=await e(w,"workspace_add",{path:N.trim(),createIfMissing:(k==null?void 0:k.createIfMissing)===!0});if(x!=null&&x.success){i("done"),d(k!=null&&k.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((x==null?void 0:x.error)||"Could not save workspace")}catch(x){i("error"),d(x instanceof Error?x.message:"Could not save workspace")}},[e]),g=l.useCallback(async w=>{var N,k,x,S,C,I;try{i("loading"),d("Starting daemon upgrade…");const R=await e(w,"daemon_upgrade",{});if((N=R==null?void 0:R.result)!=null&&N.alreadyLatest){i("done"),d(`Already on v${((k=R==null?void 0:R.result)==null?void 0:k.version)||"latest"}.`);return}if((x=R==null?void 0:R.result)!=null&&x.upgraded||(S=R==null?void 0:R.result)!=null&&S.success){i("done"),d(`Upgrade to v${((C=R==null?void 0:R.result)==null?void 0:C.version)||"latest"} started. Daemon is restarting…`);return}i("error"),d(((I=R==null?void 0:R.result)==null?void 0:I.error)||"Upgrade failed")}catch(R){i("error"),d(R instanceof Error?R.message:"Upgrade failed")}},[e]),f=l.useCallback(async(w,N,k,x)=>{var I,R,L;const S=Date.now(),C={machineId:w,kind:N,providerType:k,workspaceId:(x==null?void 0:x.workspaceId)||null,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,startedAt:S};try{i("loading"),d(`Launching ${k}…`),p(C);const T={cliType:k};(I=x==null?void 0:x.workspacePath)!=null&&I.trim()?T.dir=x.workspacePath.trim():x!=null&&x.workspaceId&&(T.workspaceId=x.workspaceId),x!=null&&x.resumeSessionId&&(T.resumeSessionId=x.resumeSessionId),(R=x==null?void 0:x.args)!=null&&R.trim()&&(T.cliArgs=x.args.trim().split(/\s+/).filter(Boolean)),(L=x==null?void 0:x.model)!=null&&L.trim()&&(T.initialModel=x.model.trim());const _=await a(w,T),$=(_==null?void 0:_.result)||_,X=($==null?void 0:$.sessionId)||($==null?void 0:$.id);if(_!=null&&_.success&&X){p(null),i("done"),d(`${k} launched`),t(Hr(X));return}if(_!=null&&_.success){i("loading"),d(`${k} launch requested — waiting for session…`);return}p(null),i("error"),d((_==null?void 0:_.error)||($==null?void 0:$.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(T){if(yw(T)){i("loading"),d(`${k} launch requested — waiting for session…`);return}p(null),i("error"),d(T instanceof Error?T.message:`Could not launch ${N.toUpperCase()} workspace`)}},[t,e]),v=l.useCallback(async(w,N)=>{try{const k=await e(w,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),x=(k==null?void 0:k.result)??k;return Array.isArray(x==null?void 0:x.sessions)?x.sessions:[]}catch(k){return console.error("Failed to list saved sessions on mobile:",k),[]}},[e]),j=l.useCallback(async(w,N)=>Bi(e,w,N),[e]);l.useEffect(()=>{if(!u)return;const w=Nc(u.workspacePath),N=r.find(x=>{var T,_,$,X;if(!x||x.type==="adhdev-daemon"||gw(x.daemonId||x.id)!==u.machineId||(x.transport==="acp"?"acp":x.transport==="pty"?"cli":null)!==u.kind||String(x.agentType||x.type||"")!==u.providerType)return!1;const R=String(x.providerSessionId||"");if(u.resumeSessionId&&R)return R===u.resumeSessionId;if(w){const M=Nc(x.workspace||x.runtimeWorkspaceLabel);return M?M===w:!1}return Number(x.lastUpdated||x._lastUpdate||x.timestamp||((X=($=(_=(T=x.activeChat)==null?void 0:T.messages)==null?void 0:_.at)==null?void 0:$.call(_,-1))==null?void 0:X.timestamp)||0)>=u.startedAt-5e3});if(!N)return;const k=wp({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:n});k&&(p(null),i("done"),d(`${u.providerType} launched`),t(Hr(k)))},[n,r,t,u]),l.useEffect(()=>{if(!u)return;const w=window.setTimeout(()=>{p(N=>!N||N.startedAt!==u.startedAt?N:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(w)},[u]);const y=l.useCallback(async(w,N)=>{if(N.kind==="ide"&&N.providerType){await h(w,N.providerType,{workspacePath:N.workspace||null});return}(N.kind==="cli"||N.kind==="acp")&&N.providerType&&await f(w,N.kind,N.providerType,{workspacePath:N.workspace||null,resumeSessionId:N.providerSessionId||null})},[h,f]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:h,handleAddWorkspace:b,handleMachineUpgrade:g,handleLaunchWorkspaceProvider:f,handleListSavedSessions:v,handleBrowseDirectory:j,handleOpenRecent:y}}function ww({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:u}){const p=l.useCallback(j=>{o(j.tabKey),i("chat"),n(j)},[n,i,o]),m=l.useCallback(j=>{const y=e.find(w=>w.routeId===j.routeId&&w.streamSource==="native");y&&(o(y.tabKey),i("chat"),n(y))},[e,n,i,o]),h=l.useCallback(()=>{n(t),i("inbox")},[n,t,i]),b=l.useCallback((j,y="inbox")=>{c(j),a(),d("machines"),u(y),i("machine")},[a,u,i,d,c]),g=l.useCallback(j=>{const y=Es(j);y&&b(y,"chat")},[b]),f=l.useCallback(()=>{a(),i(r)},[r,a,i]),v=l.useCallback(j=>{d(j),i("inbox")},[i,d]);return{openConversation:p,openNativeConversation:m,backFromConversation:h,openMachine:b,openConversationMachine:g,backFromMachine:f,changeMachineSection:v}}function rr(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function jw(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function kw({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:u,requestedMachineId:p,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:b,onOpenHistory:g,onOpenRemote:f,onStopCli:v,wsStatus:j,isConnected:y,onShowAllHiddenConversations:w,onHideConversation:N,onOpenMeshGraph:k,onOpenNewSession:x,liveSessionInboxState:S,setCliViewModeOverrides:C}){const[I,R]=l.useState(()=>{var te;return((te=e[0])==null?void 0:te.tabKey)||null}),[L,T]=l.useState(()=>e[0]?"chat":"inbox"),[_,$]=l.useState("chats"),[X,M]=l.useState(null),[A,E]=l.useState("inbox"),F=l.useRef([]),z=Kr(),D="0.9.82",K=l.useMemo(()=>e.find(te=>te.tabKey===I)||e[0]||null,[e,I]),O=l.useMemo(()=>K?r.find(te=>te.id===K.routeId):void 0,[r,K]),q=l.useMemo(()=>!K||rt(K)||!nt(K)?null:lr(K),[K]),ne=l.useMemo(()=>r.filter(te=>te.type==="adhdev-daemon").sort(pi),[r]),J=l.useMemo(()=>ne.find(te=>te.id===X)||null,[ne,X]),ye=wa({sendDaemonCommand:a,activeConv:K||void 0,setActionLogs:o,isStandalone:i}),oe=vw({sendDaemonCommand:a,navigate:z,ides:r,conversations:e}),B=l.useMemo(()=>e.map(te=>{const Me=L==="chat"&&(K==null?void 0:K.tabKey)===te.tabKey,Ae=ba(te,S,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Me}),Ce=As(te),Ue=Du(te);return{conversation:te,timestamp:Ce,preview:Ue,unread:Ae.unread,requiresAction:Ae.requiresAction,isWorking:Ae.isWorking,inboxBucket:Ae.inboxBucket}}),[e,S,L,K]),{markConversationRead:W}=bw({conversations:e,machineEntries:ne,items:B,selectedConversation:K,selectedTabKey:I,screen:L,liveSessionInboxState:S,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:u,requestedMachineId:p,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:b,setSelectedTabKey:R,setScreen:T,setSelectedMachineId:M,setSection:$,setMachineBackTarget:E,resetMachineAction:oe.resetMachineAction}),ve=ww({conversations:e,selectedConversation:K,machineBackTarget:A,markConversationRead:W,resetMachineAction:oe.resetMachineAction,setSelectedTabKey:R,setScreen:T,setSelectedMachineId:M,setSection:$,setMachineBackTarget:E}),{isMuted:we,autoMuteIfCoordinator:fe,toggleTarget:Ne}=lu();l.useEffect(()=>{for(const te of B)fe(te.conversation)},[B,fe]);const re=l.useMemo(()=>Fn(B.filter(te=>te.requiresAction&&!we(te.conversation))),[B,we]),je=l.useMemo(()=>Fn(B.filter(te=>te.unread&&!te.requiresAction&&!we(te.conversation))),[B,we]),de=l.useMemo(()=>pw(B.filter(te=>!te.unread&&!te.requiresAction&&te.isWorking),F.current),[B]);l.useEffect(()=>{F.current=de.map(te=>te.conversation.tabKey)},[de]);const U=l.useMemo(()=>Fn(B.filter(te=>!te.unread&&!te.requiresAction&&!te.isWorking)),[B]),H=l.useMemo(()=>J?B.filter(te=>Es(te.conversation)===J.id):[],[B,J]),Y=l.useMemo(()=>hw(J,r),[r,J]),se=(J==null?void 0:J.version)||null,xe=!!J&&!!se&&!0&&se!==D,Z=l.useMemo(()=>(J==null?void 0:J.availableProviders)||[],[J]),P=l.useMemo(()=>Z.filter(te=>rr(te,"cli")).map(te=>({type:te.type,displayName:te.displayName||te.type,icon:te.icon})),[Z]),ie=l.useMemo(()=>Z.filter(te=>rr(te,"acp")).map(te=>({type:te.type,displayName:te.displayName||te.type,icon:te.icon})),[Z]),be=l.useMemo(()=>fw(ne,B),[B,ne]),ue=l.useCallback(async te=>{J&&await oe.handleOpenRecent(J.id,te)},[oe,J]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:L==="chat"&&K?s.jsx(sw,{selectedConversation:K,isAcp:rt(K),isStandalone:i,selectedIdeEntry:O,actionLogs:n,userName:c,isSendingChat:ye.isSendingChat,sendFeedbackMessage:ye.sendFeedbackMessage,isFocusingAgent:ye.isFocusingAgent,handleModalButton:ye.handleModalButton,handleRelaunch:ye.handleRelaunch,onBack:ve.backFromConversation,onOpenNativeConversation:ve.openNativeConversation,onOpenMachine:ve.openConversationMachine,onOpenHistory:g,onOpenRemote:f,onOpenMeshGraph:k,onStopCli:v,cliViewMode:q,onSetCliViewMode:async te=>{await lp({conversation:K,mode:te,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:C})},handleSendChat:ye.handleSendChat,handleForceSendChat:ye.handleForceSendChat,handleFocusAgent:ye.handleFocusAgent}):L==="machine"&&J?s.jsx(uw,{selectedMachineEntry:J,selectedMachineConversations:H,selectedMachineRecentLaunches:Y,cliProviders:P,acpProviders:ie,selectedMachineNeedsUpgrade:xe,appVersion:D,machineAction:oe.machineAction,isStandalone:i,section:_,showBottomNav:A==="inbox",onBack:ve.backFromMachine,onSectionChange:ve.changeMachineSection,onOpenConversation:ve.openConversation,onOpenRecent:ue,onOpenMachineDetails:()=>z(`/machines/${J.id}`),onMachineUpgrade:()=>oe.handleMachineUpgrade(J.id),onLaunchDetectedIde:(te,Me)=>oe.handleLaunchDetectedIde(J.id,te,Me),onAddWorkspace:(te,Me)=>oe.handleAddWorkspace(J.id,te,Me),onBrowseDirectory:te=>oe.handleBrowseDirectory(J.id,te),onLaunchWorkspaceProvider:(te,Me,Ae)=>oe.handleLaunchWorkspaceProvider(J.id,te,Me,Ae),onListSavedSessions:te=>oe.handleListSavedSessions(J.id,te)}):s.jsx(aw,{section:_,attentionItems:re,unreadItems:je,workingItems:de,completedItems:U,hiddenConversations:t,machineCards:be,getAvatarText:jw,actionLogs:n,sendDaemonCommand:a,onOpenConversation:ve.openConversation,onShowAllHidden:w,onHideConversation:N,onOpenMeshGraph:k,onOpenNewSession:x,onOpenMachine:ve.openMachine,onOpenSettings:()=>z("/settings"),onSectionChange:$,wsStatus:j,isConnected:y,isStandalone:i,isConversationMuted:we,onToggleMuteConversation:Ne})})}function so(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Nw({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const i=l.useRef(0),[c,d]=l.useState(!1),[u,p]=l.useState(null),m=l.useCallback(()=>{i.current=0,d(!1),p(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const h=l.useCallback(v=>{v.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),b=l.useCallback(v=>{if(!v.dataTransfer.types.includes("text/tab-key"))return;if(v.preventDefault(),!so(t,r)){p("merge");return}const j=v.currentTarget.getBoundingClientRect(),y=v.clientX-j.left,w=j.width/3;y<w?p("split-left"):y>w*2?p("split-right"):p("merge")},[t,r]),g=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),p(null))},[]),f=l.useCallback(v=>{i.current=0,d(!1);const j=v.dataTransfer.getData("text/tab-key"),y=j?e.some(N=>N.tabKey===j):!1,w=u;if(p(null),o(),!!j){if(v.preventDefault(),w==="split-left"&&so(t,r)){r==null||r(j,"split-left");return}if(w==="split-right"&&so(t,r)){r==null||r(j,"split-right");return}if(y){a(j);return}n==null||n(j)}},[e,u,t,r,n,a,o]);return{dragOver:c,dropAction:u,resetDragState:m,handleDragEnter:h,handleDragOver:b,handleDragLeave:g,handleDrop:f}}function Sw(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 Cw({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,i]=l.useState(t??null),[c,d]=l.useState(r??[]),[u,p]=l.useState(null),m=l.useRef(null),h=l.useRef(null),b=l.useRef(n),g=l.useRef(a);l.useEffect(()=>{b.current=n},[n]),l.useEffect(()=>{g.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(S=>{const C=Sw(S,e);return C.length===S.length&&C.every((I,R)=>I===S[R])?S:C})},[e]);const f=l.useMemo(()=>{const S=u??c;if(S.length===0)return e;const C=new Map(S.map((I,R)=>[I,R]));return[...e].sort((I,R)=>{const L=C.get(I.tabKey)??999,T=C.get(R.tabKey)??999;return L-T})},[e,u,c]);l.useEffect(()=>{var C,I;if(f.length===0){o!==null&&(i(null),(C=b.current)==null||C.call(b,null));return}if(o&&f.some(R=>R.tabKey===o))return;const S=f[0].tabKey;S!==o&&(i(S),(I=b.current)==null||I.call(b,S))},[f,o]);const v=l.useMemo(()=>f.find(S=>S.tabKey===o),[f,o]),j=l.useCallback(S=>{var C;i(S),(C=b.current)==null||C.call(b,S)},[]),y=l.useCallback((S,C,I)=>{d(R=>{var $;const L=R.filter(X=>X!==S),T=L.indexOf(C);if(T<0)return R;const _=I==="left"?T:T+1;return L.splice(_,0,S),($=g.current)==null||$.call(g,L),L}),p(null)},[]),w=l.useCallback((S,C,I)=>{const L=(c.length>0?c:e.map($=>$.tabKey)).filter($=>$!==S),T=L.indexOf(C);if(T<0)return;const _=I==="left"?T:T+1;L.splice(_,0,S),m.current=L,p(L)},[c,e]),N=l.useCallback(()=>{var C;const S=m.current;S&&(d(S),(C=g.current)==null||C.call(g,S))},[]),k=l.useCallback(()=>{m.current=null,p(null)},[]),x=l.useCallback(S=>{d(C=>{var R;const I=C.filter(L=>L!==S);return I.push(S),(R=g.current)==null||R.call(g,I),I})},[]);return{activeTabId:o,activeConv:v,sortedConversations:f,previewOrderRef:m,draggingTabRef:h,selectTab:j,handleTabReorder:y,updatePreviewOrder:w,commitPreviewOrder:N,clearPreviewOrder:k,moveTabToEnd:x,setDraggingTabKey:S=>{h.current=S}}}function Iw({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 Hi({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",u=n?Hu: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:u}),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:Qt,"aria-label":Qt,children:[s.jsx(Td,{size:14}),s.jsx("span",{children:Qt})]})}),i&&s.jsx(kp,{}),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 Ap="adhdev-tab-shortcuts";function Tp(){try{return JSON.parse(localStorage.getItem(Ap)||"{}")}catch{return{}}}function _p({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>Tp()),[c,d]=l.useState(null),u=l.useCallback(m=>{const h=[];return m.metaKey&&h.push(a?"⌘":"Meta"),m.ctrlKey&&h.push("Ctrl"),m.altKey&&h.push(a?"⌥":"Alt"),m.shiftKey&&h.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(h.push(m.key.length===1?m.key.toUpperCase():m.key),h.join("+"))},[a]),p=l.useCallback(m=>{i(m);try{localStorage.setItem(Ap,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=h=>{if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){d(null);return}const b=u(h);if(!b)return;const g={...o};for(const[f,v]of Object.entries(g))v===b&&delete g[f];g[c]=b,p(g),d(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,p,u]),l.useEffect(()=>{if(!e)return;const m=h=>{if(!(!h.ctrlKey&&!h.metaKey&&!h.altKey)){for(const[b,g]of Object.entries(o))if(t.includes(b)&&u(h)===g){h.preventDefault(),r(),n(b);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,r,n,u]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:p}}const ro=e=>{e.preventDefault()},Mw=l.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:u,onConversationActivated:p,onPreviewReorder:m,onReorderTab:h,onCommitPreviewOrder:b,onClearPreviewOrder:g,onDragStateReset:f,onDragTabKeyChange:v,onReceiveTab:j,onOpenContextMenu:y,longPressTimer:w,isGroupActive:N}){const k=or(t),x=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",S=k.isReconnecting,C=a0(t),I=o0(t),R=l.useCallback(F=>{c.current=t.tabKey,v(t.tabKey),F.dataTransfer.setData("text/tab-key",t.tabKey),F.dataTransfer.effectAllowed="move"},[t.tabKey,c,v]),L=l.useCallback(()=>{c.current=null,v(null),b(),g(),f()},[c,v,b,g,f]),T=l.useCallback(F=>{const z=c.current;if(!(!z||z===t.tabKey)&&F.dataTransfer.types.includes("text/tab-key")){F.preventDefault(),F.stopPropagation();const D=F.currentTarget.getBoundingClientRect(),K=F.clientX<D.left+D.width/2?"left":"right";m(z,t.tabKey,K)}},[t.tabKey,c,m]),_=l.useCallback(F=>{F.preventDefault(),F.stopPropagation();const z=F.dataTransfer.getData("text/tab-key");if(z&&z!==t.tabKey){const D=F.currentTarget.getBoundingClientRect(),K=F.clientX<D.left+D.width/2?"left":"right";i.includes(z)?h(z,t.tabKey,K):j&&j(z)}g()},[t.tabKey,i,h,j,g]),$=l.useCallback(F=>{F.stopPropagation(),d(),u(t.tabKey),p(t)},[t,p,d,u]),X=l.useCallback(F=>{F.preventDefault(),y(F.clientX,F.clientY,t.tabKey)},[t.tabKey,y]),M=l.useCallback(F=>{const z=F.touches[0];w.current=setTimeout(()=>{y(z.clientX,z.clientY,t.tabKey)},600)},[t.tabKey,w,y]),A=l.useCallback(()=>{w.current&&clearTimeout(w.current)},[w]),E=["adhdev-dockview-tab",x,r&&"is-active",N&&"is-group-active",S&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:E,draggable:!0,onDragStart:R,onDragEnd:L,onDragOver:T,onDrop:_,onClick:$,onContextMenu:X,onTouchStart:M,onTouchEnd:A,onTouchMove:A,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:k.isGenerating?s.jsx("div",{className:"tab-spinner"}):k.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):S?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.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:"○"})}),C.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:I,"aria-label":I||C.join(" · "),children:C.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:pt(t),children:pt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[S?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Cs(t)}):k.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Cs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:Cs(t)}),s.jsx(ea,{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 Aw({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:u,onCommitPreviewOrder:p,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:b,onReceiveTab:g,onHideTab:f,isGroupActive:v,allowTabShortcuts:j=!0}){const[y,w]=l.useState(null),N=l.useRef(null),k=l.useRef(null),x=l.useMemo(()=>e.map(_=>_.tabKey),[e]);Gr("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(y==null?void 0:y.tabKey)||null});const{isMac:S,tabShortcuts:C,shortcutListening:I,setShortcutListening:R,saveShortcuts:L}=_p({enabled:j,sortedTabKeys:e.map(_=>_.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!y)return;const _=$=>{const X=document.querySelector("[data-pane-context-menu]");X&&X.contains($.target)||w(null)};return window.addEventListener("mousedown",_,!0),()=>window.removeEventListener("mousedown",_,!0)},[y]),l.useEffect(()=>{const _=k.current;if(!_)return;const $=X=>{Math.abs(X.deltaY)<=Math.abs(X.deltaX)||(X.preventDefault(),_.scrollLeft+=X.deltaY)};return _.addEventListener("wheel",$,{passive:!1}),()=>_.removeEventListener("wheel",$)},[]);const T=l.useCallback((_,$,X)=>{w({x:_,y:$,tabKey:X})},[]);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:k,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(_=>s.jsx(Mw,{conv:_,isActive:t===_.tabKey,isDraggedTab:a.current===_.tabKey,isTaskCompleteUnread:n.has(_.tabKey),shortcut:j?C[_.tabKey]:void 0,conversationKeys:x,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:u,onCommitPreviewOrder:p,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:b,onReceiveTab:g,onOpenContextMenu:T,longPressTimer:N,isGroupActive:v},_.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),y&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:y.x,top:y.y},children:[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:ro,onClick:_=>{_.stopPropagation(),R(y.tabKey),w(null)},children:["⌨ ",C[y.tabKey]?`Change shortcut (${C[y.tabKey]})`:"Set shortcut"]}),C[y.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:ro,onClick:()=>{const _={...C};delete _[y.tabKey],L(_),w(null)},children:"✕ Remove shortcut"})]}),f&&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:ro,onClick:()=>{f(y.tabKey),w(null)},children:"🚫 Hide from Dashboard"})]})]}),j&&I&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>R(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:_=>_.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",S?"⌘+1":"Ctrl+1",", ",S?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Tw({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,userName:d,groupIndex:u,onFocus:p,isSplitMode:m,numGroups:h,onMoveTab:b,onReceiveTab:g,style:f,onActiveTabChange:v,initialActiveTabId:j,initialTabOrder:y,onTabOrderChange:w,onHideTab:N,isFocused:k,allowTabShortcuts:x=!0,onOpenNewSession:S,liveSessionInboxState:C}){const{sendCommand:I}=mt(),R=l.useRef(null),{activeTabId:L,activeConv:T,sortedConversations:_,draggingTabRef:$,selectTab:X,handleTabReorder:M,updatePreviewOrder:A,commitPreviewOrder:E,clearPreviewOrder:F,moveTabToEnd:z,setDraggingTabKey:D}=Cw({conversations:e,initialActiveTabId:j,initialTabOrder:y,onActiveTabChange:v,onTabOrderChange:w}),K=wa({sendDaemonCommand:a,activeConv:T,setActionLogs:o,isStandalone:i}),{dragOver:O,dropAction:q,resetDragState:ne,handleDragEnter:J,handleDragOver:ye,handleDragLeave:oe,handleDrop:B}=Nw({conversations:e,numGroups:h,onMoveTab:b,onReceiveTab:g,onOwnTabDrop:z,onClearPreviewOrder:F}),W=T&&!rt(T)&&lr(T)==="terminal",ve=l.useMemo(()=>T?t.find(re=>re.id===T.routeId):void 0,[t,T]),we=l.useMemo(()=>T?n.filter(re=>re.routeId===T.tabKey):[],[n,T]),fe=l.useMemo(()=>new Set(_.filter(re=>ax(re,C,{isOpenConversation:re.tabKey===L})).map(re=>re.tabKey)),[L,C,_]);Gr("PaneGroup",{groupIndex:u,conversationCount:e.length,activeTabId:L,dragOver:O});const Ne=l.useCallback(re=>{re.streamSource==="agent-stream"&&re.agentType&&I(re.routeId,ju(),{agentType:re.agentType,...re.sessionId&&{targetSessionId:re.sessionId}}).catch(()=>{})},[I]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:p,style:{...f,outline:O?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(Aw,{conversations:_,activeTabId:L,groupIndex:u,numGroups:h,unreadTabKeys:fe,draggingTabRef:$,onFocus:p,onSelectTab:X,onConversationActivated:Ne,onPreviewReorder:A,onReorderTab:M,onCommitPreviewOrder:E,onClearPreviewOrder:F,onDragStateReset:ne,onDragTabKeyChange:D,onMoveTab:b,onReceiveTab:g,onHideTab:N,isGroupActive:k??!1,allowTabShortcuts:x}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:J,onDragOver:ye,onDragLeave:oe,onDrop:B,children:[O&&s.jsx(Iw,{dropAction:q,canSplit:!!(h<4&&b)}),T?s.jsx(Fi,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!W,ideEntry:ve,terminalRef:R,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:we,userName:d,isInputActive:!m||!!k}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Hi,{conversationsCount:e.length,isSplitMode:m,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:S})})]})]})}function _w({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:u,isStandalone:p,hasRegisteredMachines:m,userName:h,focusedGroup:b,focusGroup:g,moveTabToGroup:f,splitTabRelative:v,closeGroup:j,handleResizeStart:y,groupActiveTabIds:w,setGroupActiveTab:N,groupTabOrders:k,setGroupTabOrder:x,toggleHiddenTab:S,onOpenNewSession:C,allowTabShortcuts:I=!0,liveSessionInboxState:R}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((L,T)=>{const _=t&&n.length===r?`${n[T]}%`:void 0;return s.jsxs(Ct.Fragment,{children:[t&&T>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:$=>y(T-1,$),onDoubleClick:()=>j(T),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(Tw,{style:t?{flexBasis:_??`${100/r}%`,flexGrow:_?0:1,flexShrink:_?0:1}:void 0,conversations:L,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:u,isStandalone:p,hasRegisteredMachines:m,userName:h,groupIndex:T,isFocused:t&&b===T,onFocus:()=>g(T),isSplitMode:t,numGroups:r,onMoveTab:($,X)=>{X==="left"&&T>0?f($,T-1):X==="right"&&T<r-1?f($,T+1):X==="split-left"&&r<4?v($,T,"left"):X==="split-right"&&r<4&&v($,T,"right")},onReceiveTab:$=>f($,T),onActiveTabChange:$=>N(T,$),initialActiveTabId:w[T],initialTabOrder:k[T],onTabOrderChange:$=>x(T,$),onHideTab:S,onOpenNewSession:C,allowTabShortcuts:I,liveSessionInboxState:R})]},T)})})}function Rp({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?ft.onScreenshot("ide-page",(p,m)=>{if(p!==e)return;const h=new FileReader;h.onload=()=>o(h.result),h.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{r!=="connected"&&o(null)},[r]),l.useEffect(()=>{var p;return e?((p=ft.onStatus)==null?void 0:p.call(ft,(m,h)=>{m===e&&h!=null&&h.screenshotUsage&&c(h.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const u=e?ft.get(e):null;if(!(!u||r!=="connected"))return n!=="chat"&&t?u.startScreenshots(t):u.stopScreenshots(t),()=>{u.stopScreenshots(t)}},[n,r,t,e]);const d=l.useCallback(async(u,p)=>{const m=e?ft.get(e):null;return!m||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(u,p,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:i,handleRemoteAction:d}}const Pp="adhdev-dashboard-action-shortcuts",Rw=1200,Pw=[["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 Lw(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function lt(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 Lp(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:lt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:lt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:lt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:lt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:lt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:lt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:lt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:lt("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:lt("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:lt("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:lt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:lt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:lt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:lt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:lt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:lt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:lt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:lt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:lt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:lt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:lt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:lt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:lt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:lt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:lt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:lt("toggleCliView",e)}]}function Jo(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function ca(e){const t=Object.fromEntries(Lp(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Pp)||"{}"),n={...t,...r};for(const[a,o]of Pw)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function Dp(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Dw({enabled:e=!0,onTrigger:t}){const r=Lw(),[n,a]=l.useState(()=>ca(r)),[o,i]=l.useState(null),[c,d]=l.useState([]),u=l.useRef({parts:[],timer:null}),p=l.useCallback(f=>{const v=[];return f.metaKey&&v.push(r?"⌘":"Meta"),f.ctrlKey&&v.push("Ctrl"),f.altKey&&v.push(r?"⌥":"Alt"),f.shiftKey&&f.key.length!==1&&v.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(v.push(Dp(f.key)),v.join("+"))},[r]),m=l.useCallback(f=>{a(f);try{localStorage.setItem(Pp,JSON.stringify(f))}catch{}},[]);l.useEffect(()=>{const f=ca(r),v=Object.entries(n),j=Object.entries(f);v.length===j.length&&v.every(([y,w])=>f[y]===w)||m(f)},[n,r,m]);const h=l.useCallback(()=>{typeof window<"u"&&u.current.timer!=null&&window.clearTimeout(u.current.timer),u.current={parts:[],timer:null}},[]),b=l.useCallback(()=>{typeof window>"u"||(u.current.timer!=null&&window.clearTimeout(u.current.timer),u.current.timer=window.setTimeout(()=>{u.current={parts:[],timer:null}},Rw))},[]);l.useEffect(()=>{if(!o)return;const f=v=>{if(v.preventDefault(),v.stopPropagation(),v.key==="Escape"){i(null),d([]);return}const j=p(v);if(!j)return;const w=!(v.metaKey||v.ctrlKey||v.altKey)&&/^[A-Z0-9]$/.test(j);if(c.length===0&&w){d([j]);return}const k=[...c,j].slice(0,2).join(" "),x={...n};for(const[S,C]of Object.entries(x))C===k&&delete x[S];x[o]=k,m(x),i(null),d([])};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[n,p,m,o,c]),l.useEffect(()=>{if(!e||o)return;const f=v=>{if(v.defaultPrevented)return;const j=p(v);if(!j)return;const y=v.metaKey||v.ctrlKey||v.altKey;if(Jo(v.target))return;const w=u.current.parts,N=y?[j]:[...w.slice(-1),j].slice(-2),k=N.join(" "),x=N[N.length-1],S=Object.entries(n).filter(([,T])=>!!T),C=S.find(([,T])=>T===k);if(C){v.preventDefault(),h(),t(C[0]);return}if(S.some(([,T])=>T.startsWith(`${k} `))){v.preventDefault(),u.current.parts=N,b();return}const R=S.find(([,T])=>T===x);if(R){v.preventDefault(),h(),t(R[0]);return}if(S.some(([,T])=>T.startsWith(`${x} `))){v.preventDefault(),u.current.parts=[x],b();return}h()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[n,b,e,p,t,h,o]),l.useEffect(()=>()=>h(),[h]);const g=l.useMemo(()=>Lp(r),[r]);return{isMac:r,actionDefinitions:g,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:m}}function $w({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 $p(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Sc({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!$p(n):!0}function Ew({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:$p(r)}const Ep=1e3,Bw=4;function Cc(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Ic(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function Fw({detachDelayMs:e=Ep,stillnessThresholdPx:t=Bw,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,d=null,u=null,p=!1;const m=()=>{u!=null&&(a(u),u=null)},h=()=>{m(),c=null},b=()=>{m(),o=null,i=null,c=null,d=null,p=!1},g=()=>{!o||!c||!d||p||u!=null||(u=n(()=>{u=null,!(!o||!c||!d||p)&&Cc(d,i)&&(Ic(c,d,t)||(p=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},f=j=>{if(!(!o||p)){if(!Cc(j,i)){d={clientX:j.clientX,clientY:j.clientY},h();return}(!c||Ic(c,j,t))&&(m(),c={clientX:j.clientX,clientY:j.clientY}),d={clientX:j.clientX,clientY:j.clientY},g()}},v=j=>{!o||p||(j&&(d={clientX:j.clientX,clientY:j.clientY}),h())};return{startDrag:j=>{m(),o=j.panelId,i=j.selfPanelBounds??null,c=null,d={clientX:j.clientX,clientY:j.clientY},p=!1},markSelfPanel:f,markNonSelfPanel:v,markNoDropTarget:v,markDockTarget:v,endDrag:b,isDragging:()=>o!=null,hasDetached:()=>p,dispose:b}}function Ow(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Sn(e){return e.isActive}function Mc(e){return e.isVisible}const Bp=l.createContext(null);function ka(){const e=l.useContext(Bp);if(!e)throw new Error("DashboardDockviewContext missing");return e}function On(e){return pt(e)||e.tabKey}function Hw(e){return`remote:${e}`}function zt(e){return e.startsWith("remote:")}function Ac(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function zw(e){e.preventDefault()}function no(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 ao(e,t){e.classList.remove(So.className,Co.className),e.classList.add(t==="light"?So.className:Co.className)}function Tc(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 Ww(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 Kw(e,t,r){var i;const n=[t];let a;for(const c of n){let d;for(const u of c){const p=e.addPanel({id:u.tabKey,component:"conversation",title:On(u),params:{kind:"conversation",tabKey:u.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=p.id)}a=d??a}return r??((i=t[0])==null?void 0:i.tabKey)??null}function _c(e,t){const r=new Set(t.map(a=>a.tabKey)),n=new Map;for(const a of t)n.set(a.tabKey,(n.get(a.tabKey)||0)+1);for(const a of[...e.panels])zt(a.id)||r.has(a.id)||e.removePanel(a);for(const a of t){const o=e.getPanel(a.tabKey);if(o){(n.get(a.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:a.tabKey,daemonId:a.daemonId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,panelId:o.id}),o.update({params:{tabKey:a.tabKey}}),o.title!==On(a)&&o.api.setTitle(On(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:On(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 Rc(e,t,r){var d,u;const n=r?Hw(r):null;for(const p of[...e.panels])zt(p.id)&&(!n||p.id!==n)&&e.removePanel(p);if(!r||!n)return;const a=Gt(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),i=Bu(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)??((u=e.panels.find(p=>!zt(p.id)))==null?void 0:u.id);e.addPanel({id:n,component:"remote",title:i,params:{kind:"remote",routeId:r},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function Uw({params:e,api:t}){var b;const r=ka(),n=l.useRef(null),[a,o]=l.useState(()=>Sn(t)),[i,c]=l.useState(()=>Mc(t)),d=r.conversationsByTabKey.get(e.tabKey),u=wa({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});l.useEffect(()=>{o(Sn(t)),c(Mc(t));const g=[t.onDidActiveChange(f=>o(f.isActive)),t.onDidActiveGroupChange(f=>{if(!Sn(t)&&!f.isActive){o(!1);return}o(Sn(t))}),t.onDidVisibilityChange(f=>c(f.isVisible))];return()=>{for(const f of g)f.dispose()}},[t]);const p=l.useMemo(()=>d?r.ides.find(g=>g.id===d.routeId):void 0,[r.ides,d]),m=l.useMemo(()=>d?r.actionLogs.filter(g=>g.routeId===d.tabKey):[],[r.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(Hi,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const h=!rt(d)&&lr(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(Fi,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:h,ideEntry:p,terminalRef:n,handleModalButton:u.handleModalButton,handleRelaunch:u.handleRelaunch,handleSendChat:u.handleSendChat,handleForceSendChat:u.handleForceSendChat,isSendingChat:u.isSendingChat,handleFocusAgent:u.handleFocusAgent,isFocusingAgent:u.isFocusingAgent,actionLogs:m,userName:r.userName,scrollToBottomRequestNonce:((b=r.scrollToBottomRequest)==null?void 0:b.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:i})})}function Gw({params:e}){var d;const t=ka(),r=l.useMemo(()=>Gt([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=l.useMemo(()=>t.ides.find(u=>u.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}=Rp({doId:a,targetSessionId:r?wu(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(Od,{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 Vw(){const e=ka();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Hi,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function qw(e){var y,w;Ww(e);const t=ka(),r=l.useCallback(N=>{"button"in N&&N.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(N=>Wg(N),[]),i=l.useCallback(()=>zg(a),[a]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const N=Gt([...t.conversationsByTabKey.values()],e.params.routeId),k=((y=e.api.group.activePanel)==null?void 0:y.id)===e.api.id,x=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${k?" is-active":""}${x?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(N==null?void 0:N.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:N!=null&&N.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:N.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 u=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,p=e.api.isGroupActive,m=ba(d,t.liveSessionInboxState,{isOpenConversation:u}),h=m.isReconnecting,b=m.isConnecting,g=m.isGenerating||c,f=m.isWaiting,v=m.unread,j=t.tabShortcuts[d.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${u?" is-active":""}${p?" is-group-active":""}${h?" is-reconnecting":""}`,title:pt(d),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:N=>{var k;N.preventDefault(),r(N),t.openTabContextMenu({x:N.clientX,y:N.clientY,tabKey:d.tabKey,sourceDocument:((k=N.target)==null?void 0:k.ownerDocument)??document})},children:[v&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:g?s.jsx("div",{className:"tab-spinner"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):b?s.jsx("div",{className:"tab-connecting-spinner"}):d.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:pt(d)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:h?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Cs(d)}):b?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Cs(d)}):s.jsx("span",{children:Cs(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 Yw({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:u,toggleHiddenTab:p,actionShortcuts:m,registerActionHandlers:h,onActiveTabChange:b,onOpenNewSession:g,onRequestScrollToBottom:f,requestedActiveTabKey:v,requestedRemoteIdeId:j,onRequestedActiveTabConsumed:y,scrollToBottomRequest:w,liveSessionInboxState:N,layoutProfile:k}){var it,Xe,Pe;const{theme:x}=Bs(),{sendCommand:S}=mt(),C=l.useRef(null),I=l.useRef(null),R=l.useRef(null),L=l.useRef(!1),T=l.useRef(!1),_=l.useRef(!1),$=l.useRef(null),X=l.useRef([]),[M,A]=l.useState(null),[E,F]=l.useState(0),z=l.useRef(typeof window>"u"?{}:hv(k)),D=l.useMemo(()=>new Map(e.map(G=>[G.tabKey,G])),[e]),K=l.useMemo(()=>{const G=C.current;return G?G.groups.some(V=>{try{const ae=V.model.location.type;return ae!=="floating"&&ae!=="popout"?!1:V.panels.some(le=>D.has(le.id))}catch{return!1}}):!1},[D,E,e]),O=l.useCallback(()=>{var G;(G=C.current)==null||G.focus()},[]),q=l.useCallback((G,V)=>{f==null||f(G,V)},[f]),ne=l.useCallback(G=>{const V=document,ae=G.document;for(const ee of V.querySelectorAll('link[rel="stylesheet"]')){const he=ae.createElement("link");he.rel="stylesheet",he.href=ee.href,ee.crossOrigin&&(he.crossOrigin=ee.crossOrigin),ae.head.appendChild(he)}for(const ee of V.querySelectorAll("style")){const he=ae.createElement("style");he.textContent=ee.textContent,ae.head.appendChild(he)}const le=[];for(const ee of V.styleSheets)try{for(const he of ee.cssRules)he instanceof CSSStyleRule&&(he.selectorText===":root"||he.selectorText==="html")&&le.push(he.cssText)}catch{}if(le.length>0){const ee=ae.createElement("style");ee.textContent=le.join(`
|
|
63
|
+
`),ae.head.appendChild(ee)}const ge=V.documentElement.getAttribute("data-theme");ge&&ae.documentElement.setAttribute("data-theme",ge),ae.documentElement.style.colorScheme=ge==="light"?"light":"dark",ae.body.className=V.body.className;const ke=V.documentElement.getAttribute("style");ke&&ae.documentElement.setAttribute("style",ke);const Q=ae.getElementById("dv-popout-window");Q instanceof HTMLElement&&(Q.classList.add("adhdev-dockview"),ao(Q,x))},[x]),J=l.useCallback(()=>{var V;const G=C.current;if(G)for(const ae of G.groups)try{const le=(V=ae.element)==null?void 0:V.ownerDocument;if(!le||le===document)continue;const ge=le.getElementById("dv-popout-window");ge instanceof HTMLElement&&(ge.classList.add("adhdev-dockview"),ao(ge,x));const ke=document.documentElement.getAttribute("data-theme");ke&&le.documentElement.setAttribute("data-theme",ke),le.documentElement.style.colorScheme=ke==="light"?"light":"dark",le.body.className=document.body.className;const Q=document.documentElement.getAttribute("style");Q?le.documentElement.setAttribute("style",Q):le.documentElement.removeAttribute("style")}catch{}},[x]),ye=l.useCallback(G=>{const V=C.current;if(!V)return;const ae=V.getPanel(G);ae&&V.addPopoutGroup(ae,{popoutUrl:"/popout.html",onDidOpen:({window:le})=>{ne(le),je();const ge=D.get(G);le.document.title=ge?`${pt(ge)} — ADHDev`:"ADHDev — Popout"}})},[D,ne]),oe=l.useCallback(G=>{const V=C.current,ae=V==null?void 0:V.getPanel(G);if(!V||!ae)return;const le=V.groups.filter(ge=>{var ke;try{return((ke=ge.element)==null?void 0:ke.ownerDocument)===document}catch{return!0}});le.length>0?ae.api.moveTo({group:le[0],position:"center"}):ae.api.moveTo({position:"center"}),ae.api.setActive()},[]),B=l.useCallback(G=>{var le;const V=C.current;if(!V)return!1;const ae=V.getPanel(G);if(!ae)return!1;try{return((le=ae.group.element)==null?void 0:le.ownerDocument)!==document}catch{return!1}},[]),W=l.useCallback(G=>{B(G)&&oe(G),p(G)},[B,oe,p]),ve=l.useCallback(G=>{const V=C.current,ae=V==null?void 0:V.getPanel(G);!V||!ae||V.addFloatingGroup(ae,{width:600,height:500})},[]),we=l.useCallback(G=>{var ae;const V=(ae=C.current)==null?void 0:ae.getPanel(G);if(!V)return!1;try{return V.group.model.location.type==="floating"}catch{return!1}},[]),fe=l.useCallback(()=>{var V,ae;const G=(ae=(V=C.current)==null?void 0:V.activePanel)==null?void 0:ae.id;return!G||zt(G)?null:D.has(G)?G:null},[D]),Ne=l.useCallback(G=>{const V=C.current,ae=V==null?void 0:V.getPanel(G);if(!V||!ae)return;const le=V.groups.filter(ge=>{try{return ge.model.location.type==="grid"}catch{return!0}});le.length>0?ae.api.moveTo({group:le[0],position:"center"}):ae.api.moveTo({position:"center"}),ae.api.setActive()},[]),re=l.useCallback(()=>{var ke;const G=C.current;if(!G)return;const ae=G.groups.filter(Q=>{var ee;try{return((ee=Q.element)==null?void 0:ee.ownerDocument)===document&&Q.model.location.type==="grid"}catch{return!1}})[0]||null,le=[...G.panels];for(const Q of le){const ee=(ke=Q.group.element)==null?void 0:ke.ownerDocument,he=Q.group.model.location.type;ee===document&&he==="grid"||(ae&&ae.id!==Q.group.id?Q.api.moveTo({group:ae,position:"center"}):Q.api.moveTo({position:"center"}))}const ge=G.activePanel;ge&&(ge.group.model.openPanel(ge),ge.api.setActive()),no(document)},[]),je=l.useCallback(()=>{var V,ae;const G=C.current;if(G)for(const le of G.groups){const ge=(V=le.element)==null?void 0:V.ownerDocument;if(!ge||ge===document)continue;const ke=ge.getElementById("dv-popout-window");if(!(ke instanceof HTMLElement))continue;let Q=null,ee=ge.title||"ADHDev",he="Popout workspace";const Ie=le.activePanel;if(Ie)if(Q=Ie.id,zt(Ie.id)){const Re=((ae=Ie.params)==null?void 0:ae.routeId)||Ie.id.slice(7),Ye=Gt([...D.values()],Re);ee=Bu(Ye),he=Ye!=null&&Ye.machineName?`Remote view · ${Ye.machineName}`:"Remote view"}else{const Re=D.get(Ie.id);ee=Re?pt(Re):Ie.title||Ie.id,he=Re?Cs(Re):"Dockview panel"}ge.title=`${ee} — ADHDev`;const Le=Array.from(ge.querySelectorAll("#adhdev-popout-header"));for(const Re of Le)Re.remove();const Te=ge.createElement("div");Te.id="adhdev-popout-header",ge.body.appendChild(Te),Te.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(";")),Te.innerHTML=`
|
|
64
|
+
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
65
|
+
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
66
|
+
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Ac(ee)}</div>
|
|
67
|
+
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Ac(he)}</div>
|
|
68
|
+
</div>
|
|
69
|
+
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
70
|
+
<button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
|
|
71
|
+
<button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
|
|
72
|
+
</div>
|
|
73
|
+
`,ke.style.top="52px",ke.style.height="calc(100% - 52px)";const Ee=Te.querySelector("[data-adhdev-popout-focus]");Ee&&(Ee.onclick=()=>{window.focus()});const We=Te.querySelector("[data-adhdev-popout-dock]");We&&(We.disabled=!Q,We.style.opacity=Q?"1":"0.5",We.style.cursor=Q?"pointer":"default",We.onclick=()=>{var Re;Q&&oe(Q),(Re=ge.defaultView)==null||Re.focus()})}},[D,oe]),de=l.useCallback(G=>{var le;const V=C.current,ae=V==null?void 0:V.getPanel(G);if(!(!V||!ae)){ae.group.model.openPanel(ae),ae.api.setActive(),q(G,"dockview-shortcut");try{const ge=ae.group.model.location;ge.type==="popout"?ge.getWindow().focus():no((le=ae.group.element)==null?void 0:le.ownerDocument)}catch{}}},[q]),U=l.useCallback(G=>{const V=C.current,ae=V==null?void 0:V.activePanel,le=(V==null?void 0:V.activeGroup)||(ae==null?void 0:ae.group);if(!V||!ae||!le)return;const ge=le.panels||[];if(ge.length<=1)return;const ke=ge.findIndex(he=>he.id===ae.id);if(ke<0)return;const Q=(ke+G+ge.length)%ge.length,ee=ge[Q];ee&&(ee.group.model.openPanel(ee),ee.api.setActive(),zt(ee.id)||q(ee.id,"dockview-shortcut"))},[q]),H=l.useCallback(G=>{var Ee;const V=C.current,ae=(V==null?void 0:V.activeGroup)||((Ee=V==null?void 0:V.activePanel)==null?void 0:Ee.group);if(!V||!ae)return;const le=V.groups||[],ge=le.find(We=>We.id===ae.id);if(!ge)return;const ke=ge.element.getBoundingClientRect(),Q=ke.left+ke.width/2,ee=ke.top+ke.height/2,he=(We,Re,Ye,st)=>Math.max(0,Math.min(Re,st)-Math.max(We,Ye)),Ie=We=>{const Re=We.element.getBoundingClientRect(),Ye=Re.left+Re.width/2,st=Re.top+Re.height/2;let ht=0,kt=0,xt=0,bt=!1;if(G==="left"?(bt=Ye<Q,ht=Math.max(0,ke.left-Re.right),kt=Math.abs(st-ee),xt=he(ke.top,ke.bottom,Re.top,Re.bottom)):G==="right"?(bt=Ye>Q,ht=Math.max(0,Re.left-ke.right),kt=Math.abs(st-ee),xt=he(ke.top,ke.bottom,Re.top,Re.bottom)):G==="above"?(bt=st<ee,ht=Math.max(0,ke.top-Re.bottom),kt=Math.abs(Ye-Q),xt=he(ke.left,ke.right,Re.left,Re.right)):(bt=st>ee,ht=Math.max(0,Re.top-ke.bottom),kt=Math.abs(Ye-Q),xt=he(ke.left,ke.right,Re.left,Re.right)),!bt)return Number.POSITIVE_INFINITY;const Ge=xt>0?0:120;return ht*3+kt+Ge};let Le=null,Te=Number.POSITIVE_INFINITY;for(const We of le){if(We.id===ge.id)continue;const Re=Ie(We);Number.isFinite(Re)&&(Re>=Te||(Te=Re,Le=We))}return Le||void 0},[]),Y=l.useCallback(G=>{var le;const V=H(G);if(!V)return;const ae=V.activePanel||V.panels[0];ae&&(V.model.openPanel(ae),ae.api.setActive(),zt(ae.id)||q(ae.id,"dockview-focus"),no((le=V.element)==null?void 0:le.ownerDocument))},[H,q]),se=l.useCallback((G,V)=>{const ae=C.current,le=ae==null?void 0:ae.activePanel,ge=(ae==null?void 0:ae.activeGroup)||(le==null?void 0:le.group);if(!ae||!le||!ge)return;let ke=H(G);!ke&&(V!=null&&V.createGroupIfMissing)&&(ke=ae.addGroup({referenceGroup:ge,direction:G})),ke&&(le.api.moveTo({group:ke,position:"center"}),le.group.model.openPanel(le),le.api.setActive(),zt(le.id)||q(le.id,V!=null&&V.createGroupIfMissing?"dockview-split":"dockview-move"))},[H,q]),{isMac:xe,tabShortcuts:Z,shortcutListening:P,setShortcutListening:ie,saveShortcuts:be}=_p({sortedTabKeys:e.map(G=>G.tabKey),onFocus:O,onSelectTab:de}),ue=l.useCallback(()=>{var ae;const G=C.current;if(!G)return;const V=G.activePanel;if(V){if(zt(V.id)){const le=((ae=V.params)==null?void 0:ae.routeId)||V.id.slice(7),ge=Gt(e,le);ge!=null&&ge.tabKey&&ie(ge.tabKey);return}D.has(V.id)&&ie(V.id)}},[D,de,ie,e]),te=l.useCallback(G=>{const V=[];return G.metaKey&&V.push(xe?"⌘":"Meta"),G.ctrlKey&&V.push("Ctrl"),G.altKey&&V.push(xe?"⌥":"Alt"),G.shiftKey&&G.key.length!==1&&V.push(xe?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(G.key)?null:(V.push(Dp(G.key)),V.join("+"))},[xe]),Me=l.useCallback(G=>{var V,ae;switch(G){case"splitActiveTabRight":se("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":se("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const le=fe();le&&ve(le);return}case"popoutActiveTab":{const le=fe();le&&ye(le);return}case"dockActiveTab":{const le=fe();if(!le)return;B(le)?oe(le):we(le)&&Ne(le);return}case"focusLeftPane":Y("left");return;case"focusRightPane":Y("right");return;case"focusUpPane":Y("above");return;case"focusDownPane":Y("below");return;case"moveActiveTabToLeftPane":se("left");return;case"moveActiveTabToRightPane":se("right");return;case"moveActiveTabToUpPane":se("above");return;case"moveActiveTabToDownPane":se("below");return;case"selectPreviousGroupTab":U(-1);return;case"selectNextGroupTab":U(1);return;case"setActiveTabShortcut":ue();return;case"hideCurrentTab":{const le=(ae=(V=C.current)==null?void 0:V.activePanel)==null?void 0:ae.id;le&&!zt(le)&&W(le);return}default:return}},[U,Ne,Y,ve,fe,W,we,B,oe,se,ye,ue]);l.useEffect(()=>{if(!M)return;const G=M.sourceDocument,V=G.defaultView??window,ae=le=>{const ge=G.querySelector("[data-dockview-tab-context-menu]");ge&&ge.contains(le.target)||A(null)};return V.addEventListener("mousedown",ae,!0),V!==window&&window.addEventListener("mousedown",()=>A(null),!0),()=>{V.removeEventListener("mousedown",ae,!0),V!==window&&window.removeEventListener("mousedown",()=>A(null),!0)}},[M]);const Ae=l.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:D,hasDetachedConversationPanels:K,ides:r,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:g,liveSessionInboxState:N,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:W,userName:u,scrollToBottomRequest:w,tabShortcuts:Z,openTabContextMenu:({x:G,y:V,tabKey:ae,sourceDocument:le})=>A({x:G,y:V,tabKey:ae,sourceDocument:le??document}),popoutTab:ye,moveTabBackToMain:oe,isTabInPopout:B,floatTab:ve,isTabFloating:we}),[n,t,D,K,r,i,c,g,N,a,o,W,u,w,Z,ye,oe,B,ve,we]),Ce=M?$w({isTabInPopout:B(M.tabKey),isTabFloating:we(M.tabKey),tabShortcut:Z[M.tabKey],actionShortcuts:m}):[],Ue=l.useCallback(G=>{var le;const V=C.current;if((((le=V==null?void 0:V.activePanel)==null?void 0:le.id)??null)===G.id){G.group.model.openPanel(G);return}G.group.model.openPanel(G),G.api.setActive()},[]),Qe=l.useCallback((G,V="requested-tab")=>{if(!G)return!1;const ae=C.current;if(!ae)return!1;const le=ae.getPanel(G);return le?(Ue(le),q(G,V),y==null||y(),!0):!1},[Ue,y,q]),pe=l.useCallback(()=>{if(_.current)return!1;const G=Qe($.current,"stored-layout-restore");return G&&(_.current=!0),G},[Qe]),De=l.useCallback(()=>{var V;const G=C.current;G&&mv(k,{activeTabId:((V=G.activePanel)==null?void 0:V.id)??null,layout:G.toJSON()})},[k]),$e=l.useCallback(()=>{fv(k,z.current)},[k]),tt=l.useCallback(G=>{var le,ge,ke,Q;const V=C.current;if(!V)return{kind:"grid"};const ae=V.toJSON();for(const ee of ae.floatingGroups||[])if((ge=(le=ee.data)==null?void 0:le.views)!=null&&ge.includes(G)&&ee.position)return{kind:"floating",position:ee.position};for(const ee of ae.popoutGroups||[])if((Q=(ke=ee.data)==null?void 0:ke.views)!=null&&Q.includes(G))return{kind:"popout",position:ee.position,popoutUrl:ee.url};return{kind:"grid"}},[]),Ke=l.useCallback(G=>{const V=C.current;if(!V)return;const ae=V.getPanel(G),le=z.current[G];if(!ae||!le||le.kind==="grid")return;if(ae.group.model.location.type===le.kind){delete z.current[G],$e();return}if(le.kind==="floating"){V.addFloatingGroup(ae,{x:le.position.left??24,y:le.position.top??24,width:le.position.width,height:le.position.height}),delete z.current[G],$e();return}delete z.current[G],$e()},[$e]);l.useEffect(()=>(h==null||h({setShortcutForActiveTab:ue,restoreHiddenTabToSavedLocation:Ke,activateConversationTab:de,resetAllPanelsToMain:re,activatePreviousTabInGroup:()=>U(-1),activateNextTabInGroup:()=>U(1),floatActiveTab:()=>{const G=fe();G&&ve(G)},popoutActiveTab:()=>{const G=fe();G&&ye(G)},dockActiveTab:()=>{const G=fe();G&&(B(G)?oe(G):we(G)&&Ne(G))},splitActiveTabRight:()=>se("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>se("below",{createGroupIfMissing:!0}),focusLeftPane:()=>Y("left"),focusRightPane:()=>Y("right"),focusUpPane:()=>Y("above"),focusDownPane:()=>Y("below"),moveActiveTabToLeftPane:()=>se("left"),moveActiveTabToRightPane:()=>se("right"),moveActiveTabToUpPane:()=>se("above"),moveActiveTabToDownPane:()=>se("below")}),()=>h==null?void 0:h(null)),[U,Ne,ve,Y,fe,we,B,se,oe,ye,h,re,Ke,de,ue]),l.useEffect(()=>()=>{var G;(G=R.current)==null||G.call(R),R.current=null},[]);const Ve=l.useCallback(G=>{var ae,le;C.current=G.api,(ae=R.current)==null||ae.call(R),R.current=null;const V=pv(k);if($.current=(V==null?void 0:V.activeTabId)??null,V!=null&&V.layout&&G.api.fromJSON(V.layout,{reuseExistingPanels:!1}),T.current=Sc({hasStoredLayout:!!(V!=null&&V.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),T.current||(_c(G.api,e),Rc(G.api,e,j)),G.api.totalPanels===0&&e.length>0){const ge=Kw(G.api,e,v);if(ge){const ke=G.api.getPanel(ge);ke&&Ue(ke)}}else!T.current&&!Qe(v)&&pe();if(L.current=!0,G.api.onDidActivePanelChange(ge=>{var Q;if($.current=(ge==null?void 0:ge.id)??null,_.current=!0,je(),ge&&zt(ge.id)){const ee=((Q=ge.params)==null?void 0:Q.routeId)||ge.id.slice(7),he=Gt(e,ee);b((he==null?void 0:he.tabKey)??null),De();return}if(b((ge==null?void 0:ge.id)??null),De(),!ge)return;const ke=D.get(ge.id);(ke==null?void 0:ke.streamSource)==="agent-stream"&&ke.agentType&&S(ke.routeId,ju(),{agentType:ke.agentType,...ke.sessionId&&{targetSessionId:ke.sessionId}}).catch(()=>{})}),G.api.onDidLayoutChange(()=>{De(),je(),F(ge=>ge+1)}),Ow()){const ge=Te=>({clientX:Te.clientX,clientY:Te.clientY}),ke=Te=>{const Ee=Te==null?void 0:Te.getBoundingClientRect();return Ee?{left:Ee.left,right:Ee.right,top:Ee.top,bottom:Ee.bottom}:null},Q=Te=>{var We;const Ee=(We=I.current)==null?void 0:We.getBoundingClientRect();return Ee?Te.clientX<Ee.left||Te.clientX>Ee.right||Te.clientY<Ee.top||Te.clientY>Ee.bottom:!1},ee=Fw({detachDelayMs:Ep,onDetach:({panelId:Te,clientX:Ee,clientY:We})=>{var xt,bt;const Re=G.api.getPanel(Te);if(!Re)return;try{if(Re.group.model.location.type!=="grid")return}catch{return}const Ye=(xt=I.current)==null?void 0:xt.getBoundingClientRect(),st=(bt=Re.group.element)==null?void 0:bt.getBoundingClientRect(),ht=Math.round(Math.min(Math.max((st==null?void 0:st.width)??600,360),720)),kt=Math.round(Math.min(Math.max((st==null?void 0:st.height)??500,260),640));G.api.addFloatingGroup(Re,{x:Ye?Math.max(0,Ee-Ye.left-32):void 0,y:Ye?Math.max(0,We-Ye.top-18):void 0,width:ht,height:kt}),Re.api.setActive(),De(),je(),F(Ge=>Ge+1)}}),he=[G.api.onWillDragPanel(Te=>{if(!(Te.nativeEvent.defaultPrevented||Te.nativeEvent.shiftKey)){try{if(Te.panel.group.model.location.type!=="grid")return}catch{return}ee.startDrag({panelId:Te.panel.id,selfPanelBounds:ke(Te.panel.group.element),...ge(Te.nativeEvent)})}}),G.api.onWillShowOverlay(Te=>{if(ee.hasDetached()){Te.preventDefault();return}ee.markDockTarget(ge(Te.nativeEvent))}),G.api.onWillDrop(Te=>{if(ee.hasDetached()){Te.preventDefault(),ee.endDrag();return}ee.markDockTarget(ge(Te.nativeEvent))}),G.api.onDidDrop(()=>ee.endDrag()),G.api.onUnhandledDragOverEvent(Te=>{ee.isDragging()&&ee.markSelfPanel(ge(Te.nativeEvent))})],Ie=Te=>{if(!ee.isDragging())return;const Ee=ge(Te);Q(Ee)&&ee.markNonSelfPanel(Ee)},Le=()=>ee.endDrag();window.addEventListener("dragover",Ie,!0),window.addEventListener("drop",Le,!0),window.addEventListener("dragend",Le,!0),R.current=()=>{ee.dispose();for(const Te of he)Te.dispose();window.removeEventListener("dragover",Ie,!0),window.removeEventListener("drop",Le,!0),window.removeEventListener("dragend",Le,!0)}}G.api.onDidAddGroup(ge=>{requestAnimationFrame(()=>{var ke,Q;try{const ee=(ke=ge.element)==null?void 0:ke.ownerDocument;if(!ee||ee===document)return;(Q=ee.getElementById("dv-popout-window"))==null||Q.classList.add("adhdev-dockview");const he=document.documentElement.getAttribute("data-theme");he&&ee.documentElement.setAttribute("data-theme",he),ee.body.className=document.body.className;const Ie=document.documentElement.getAttribute("style");Ie&&ee.documentElement.setAttribute("style",Ie)}catch{}je(),F(ee=>ee+1)})}),b(((le=G.api.activePanel)==null?void 0:le.id)??null)},[Ue,Qe,D,r,d,k,b,De,v,j,S,je,e]);l.useLayoutEffect(()=>{const G=C.current;if(!G||!L.current||T.current&&Sc({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;T.current&&(T.current=!1);const V=X.current,ae=new Set(V),le=e.map(Le=>Le.tabKey),ge=new Set(le),ke=Ew({previousVisibleConversationCount:V.length,visibleConversationCount:e.length,ides:r});let Q=!1;for(const Le of V)ge.has(Le)||ke||(z.current[Le]=tt(Le),Q=!0);Q&&$e(),ke||(_c(G,e),Rc(G,e,j));const ee=le.filter(Le=>!ae.has(Le));let he=!1;for(const Le of ee){const Te=G.getPanel(Le),Ee=z.current[Le];if(!Te||!Ee||Ee.kind==="grid")continue;if(Te.group.model.location.type===Ee.kind){delete z.current[Le],he=!0;continue}if(Ee.kind==="floating"){G.addFloatingGroup(Te,{x:Ee.position.left??24,y:Ee.position.top??24,width:Ee.position.width,height:Ee.position.height}),delete z.current[Le],he=!0;continue}}if(he&&$e(),X.current=le,v&&Qe(v))return;!G.activePanel&&G.panels[0]&&Ue(G.panels[0]),!!(G.activePanel&&G.getPanel(G.activePanel.id))||pe()},[Ue,Qe,pe,r,d,$e,tt,v,j,e]),l.useEffect(()=>{L.current&&Qe(v)},[Qe,v]),l.useEffect(()=>{const G=ae=>{const le=ae.target;if(!le)return;const ge=le.querySelector("[data-tab-key]")||le.closest("[data-tab-key]");if(ge){const ke=ge.getAttribute("data-tab-key");if(ke&&ae.dataTransfer){const Q=le.closest(".dv-tab")||ge.closest(".dv-tab")||ge;ae.dataTransfer.effectAllowed="move",ae.dataTransfer.setData("text/tab-key",ke),Q instanceof HTMLElement&&ae.dataTransfer.setDragImage(Q,Math.max(12,Math.round(Q.clientWidth/2)),Math.max(10,Math.round(Q.clientHeight/2)))}}};window.addEventListener("dragstart",G);const V=Tc(C.current);for(const ae of V)ae.addEventListener("dragstart",G);return()=>{window.removeEventListener("dragstart",G);for(const ae of V)ae.removeEventListener("dragstart",G)}},[E]),l.useEffect(()=>{var V;const G=(V=I.current)==null?void 0:V.querySelector(".adhdev-dockview");G instanceof HTMLElement&&ao(G,x),J(),je()},[je,J,x]),l.useEffect(()=>{je()},[je]),l.useEffect(()=>{const G=V=>{if(V.defaultPrevented||P)return;const ae=te(V);if(!ae)return;const le=V.metaKey||V.ctrlKey||V.altKey;Jo(V.target)&&!le||ca(xe).setActiveTabShortcut!==ae||(V.preventDefault(),V.stopPropagation(),ue())};return window.addEventListener("keydown",G,!0),()=>window.removeEventListener("keydown",G,!0)},[te,xe,P,ue]),l.useEffect(()=>{const G=I.current;if(!G)return;const V=ae=>{var ee,he;if(!ae.isTrusted)return;const le=(he=(ee=ae.target)==null?void 0:ee.closest)==null?void 0:he.call(ee,".dv-scrollable");if(!le)return;ae.preventDefault(),ae.stopPropagation();const ge=Math.abs(ae.deltaX),ke=Math.abs(ae.deltaY),Q=ge>ke?ae.deltaX:ae.deltaY;le.dispatchEvent(new WheelEvent("wheel",{deltaY:Q,deltaMode:ae.deltaMode,bubbles:!1,cancelable:!0}))};return G.addEventListener("wheel",V,{passive:!1,capture:!0}),()=>G.removeEventListener("wheel",V,{capture:!0})},[]),l.useEffect(()=>{const G=Tc(C.current);if(G.length===0)return;const V=G.map(ae=>{let le=[],ge=null;const ke=()=>{ge!=null&&ae.clearTimeout(ge),ge=null,le=[]},Q=()=>{ge!=null&&ae.clearTimeout(ge),ge=ae.setTimeout(()=>{ge=null,le=[]},1200)},ee=Ie=>{if(!Ie.ctrlKey&&!Ie.metaKey&&!Ie.altKey)return;const Le=te(Ie);if(!Le)return;const Te=Tp();for(const[Ee,We]of Object.entries(Te))if(e.some(Re=>Re.tabKey===Ee)&&We===Le){Ie.preventDefault(),de(Ee);return}},he=Ie=>{if(Ie.defaultPrevented||P)return;const Le=te(Ie);if(!Le)return;const Te=Ie.metaKey||Ie.ctrlKey||Ie.altKey;if(Jo(Ie.target))return;const Ee=ca(xe),We=Object.entries(Ee).filter(([Ge,Ot])=>!!Ot&&(Ge==="splitActiveTabRight"||Ge==="splitActiveTabDown"||Ge==="floatActiveTab"||Ge==="popoutActiveTab"||Ge==="dockActiveTab"||Ge==="focusLeftPane"||Ge==="focusRightPane"||Ge==="focusUpPane"||Ge==="focusDownPane"||Ge==="moveActiveTabToLeftPane"||Ge==="moveActiveTabToRightPane"||Ge==="moveActiveTabToUpPane"||Ge==="moveActiveTabToDownPane"||Ge==="selectPreviousGroupTab"||Ge==="selectNextGroupTab"||Ge==="setActiveTabShortcut"||Ge==="hideCurrentTab")),Re=Te?[Le]:[...le.slice(-1),Le].slice(-2),Ye=Re.join(" "),st=Re[Re.length-1],ht=We.find(([,Ge])=>Ge===Ye);if(ht){Ie.preventDefault(),ke(),Me(ht[0]);return}if(We.some(([,Ge])=>Ge.startsWith(`${Ye} `))){Ie.preventDefault(),le=Re,Q();return}const xt=We.find(([,Ge])=>Ge===st);if(xt){Ie.preventDefault(),ke(),Me(xt[0]);return}if(We.some(([,Ge])=>Ge.startsWith(`${st} `))){Ie.preventDefault(),le=[st],Q();return}ke()};return ae.addEventListener("keydown",ee),ae.addEventListener("keydown",he),()=>{ke(),ae.removeEventListener("keydown",ee),ae.removeEventListener("keydown",he)}});return()=>{for(const ae of V)ae()}},[te,xe,E,de,P,Me,e]);const _e=x==="light"?So:Co,He=((Pe=(Xe=(it=C.current)==null?void 0:it.activePanel)==null?void 0:Xe.group.element)==null?void 0:Pe.ownerDocument)??document;return s.jsxs(Bp.Provider,{value:Ae,children:[s.jsx("div",{ref:I,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(oh,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:Uw,remote:Gw},defaultTabComponent:qw,watermarkComponent:Vw,onReady:Ve,singleTabMode:"default",tabAnimation:"smooth",theme:_e,popoutUrl:"/popout.html"})}),M&&Er.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:M.x,top:M.y},children:Ce.map(G=>{if(G.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},G.id);let V=s.jsx(gf,{size:13,className:"shrink-0 opacity-70"}),ae=()=>{};switch(G.id){case"dockInWindow":case"dockBackToGrid":V=s.jsx(vf,{size:13,className:"shrink-0 opacity-70"}),ae=()=>{Ne(M.tabKey),A(null)};break;case"moveBackToMain":V=s.jsx(bf,{size:13,className:"shrink-0 opacity-70"}),ae=()=>{oe(M.tabKey),A(null)};break;case"floatAsPanel":V=s.jsx(yf,{size:13,className:"shrink-0 opacity-70"}),ae=()=>{ve(M.tabKey),A(null)};break;case"openInNewWindow":V=s.jsx(xf,{size:13,className:"shrink-0 opacity-70"}),ae=()=>{ye(M.tabKey),A(null)};break;case"setShortcut":ae=le=>{le.stopPropagation(),ie(M.tabKey),A(null)};break;case"removeShortcut":V=s.jsx(vt,{size:13,className:"shrink-0 opacity-70"}),ae=()=>{const le={...Z};delete le[M.tabKey],be(le),A(null)};break;case"hideTab":V=s.jsx(oi,{size:13,className:"shrink-0 opacity-70"}),ae=()=>{W(M.tabKey),A(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 ${G.tone==="muted"?"text-text-muted":""}`,onMouseDown:zw,onClick:ae,children:[V,s.jsx("span",{className:"flex-1 min-w-0",children:G.label}),G.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:G.shortcut}):null]},G.id)})}),M.sourceDocument.body),P&&Er.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:()=>ie(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:G=>G.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. ",xe?"⌘+1":"Ctrl+1",", ",xe?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),He.body)]})}const Fp="adhdev-recent-launch-args-v1",Jw=8;function Xw(e){return String(e||"").trim().replace(/\s+/g," ")}function Op(e,t){return`${e.trim()}::${t.trim()}`}function Hp(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Fp)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function Qw(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Fp,JSON.stringify(e))}catch{}}function Zw(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=Hp().byKey[Op(r,n)])==null?void 0:o.items)||[]}function ej(e,t,r){var p;const n=String(e||"").trim(),a=String(t||"").trim(),o=Xw(r);if(!n||!a||!o)return;const i=Hp(),c=Op(n,a),d=((p=i.byKey[c])==null?void 0:p.items)||[],u=[o,...d.filter(m=>m!==o)].slice(0,Jw);i.byKey[c]={items:u},Qw(i)}function tj(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Hn({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 sj({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 rj({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:i,onOpenHistory:c,onClearSelection:d}){const u=o?Sp(o):null,p=sj({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Hn,{title:"Saved history",description:Mi(),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:B0()})]}),children:[u?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:u.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:u.providerSessionId}),s.jsx("div",{className:"mt-1",children:u.metaLine}),u.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:u.updatedLabel}),u.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:u.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:p}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function zp({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 nj({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 oo(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>rr(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>rr(a,"acp"))?"acp":null}function Cn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function aj({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:u}){var Ge,Ot;const p=Yr(),m=l.useMemo(()=>[...e].sort(pi),[e]),[h,b]=l.useState(((Ge=m[0])==null?void 0:Ge.id)||""),g=l.useMemo(()=>m.find(ce=>ce.id===h)||m[0],[h,m]),f=l.useMemo(()=>((g==null?void 0:g.workspaces)||[]).map(ce=>({id:ce.id,path:ce.path,label:ce.label})),[g]),v=(g==null?void 0:g.defaultWorkspaceId)||null,[j,y]=l.useState("workspace"),[w,N]=l.useState(""),[k,x]=l.useState(""),[S,C]=l.useState([]),[I,R]=l.useState(""),[L,T]=l.useState(!1),[_,$]=l.useState(null),[X,M]=l.useState(""),[A,E]=l.useState(oo(m[0])),[F,z]=l.useState(""),[D,K]=l.useState(""),[O,q]=l.useState([]),[ne,J]=l.useState(""),[ye,oe]=l.useState([]),[B,W]=l.useState(!1),[ve,we]=l.useState(!1),[fe,Ne]=l.useState(""),[re,je]=l.useState(!1),[de,U]=l.useState(()=>_t()),[H,Y]=l.useState(null),[se,xe]=l.useState(!1),[Z,P]=l.useState(""),[ie,be]=l.useState(null),[ue,te]=l.useState(!1),[Me,Ae]=l.useState(""),[Ce,Ue]=l.useState([]),[Qe,pe]=l.useState(!1),[De,$e]=l.useState(""),[tt,Ke]=l.useState(!1),Ve=l.useRef(null),_e=l.useRef(0);l.useEffect(()=>{var ce;!h&&((ce=m[0])!=null&&ce.id)&&b(m[0].id)},[h,m]),l.useEffect(()=>{!g||!(!g.workspaces||!g.availableProviders||!g.detectedIdes||!g.recentLaunches)||p(g.id,{minFreshMs:3e4}).catch(()=>{})},[p,g]);const He=l.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(ce=>rr(ce,"cli")),[g]),it=l.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(ce=>rr(ce,"acp")),[g]),Xe=l.useMemo(()=>((g==null?void 0:g.detectedIdes)||[]).map(ce=>({id:ce.type,label:ce.name||ce.type,meta:ce.running?"Detected locally":"Available to open"})),[g]),Pe=l.useMemo(()=>A==="cli"?He.map(ce=>({id:ce.type,label:ce.displayName||ce.type,meta:"CLI provider"})):A==="acp"?it.map(ce=>({id:ce.type,label:ce.displayName||ce.type,meta:"ACP provider"})):Xe,[it,A,He,Xe]),G=l.useMemo(()=>S.find(ce=>ce.id===I)||null,[S,I]),V=l.useMemo(()=>He.find(ce=>ce.type===F)||null,[He,F]),ae=l.useMemo(()=>yp(V==null?void 0:V.meshCoordinator,{meshId:(G==null?void 0:G.id)||"",workspace:(G==null?void 0:G.workspace)||""}),[V,G]),le=ie||ae,ge=l.useCallback(async ce=>{T(!0),M("");try{const Fe=await c(ce);C(Fe),R(me=>{var Be;return Fe.some(It=>It.id===me)?me:((Be=Fe[0])==null?void 0:Be.id)||""}),$(ce)}catch(Fe){C([]),R(""),$(ce),M(Fe instanceof Error?Fe.message:"Could not load meshes")}finally{T(!1)}},[c]);l.useEffect(()=>{var Fe;if(!g)return;if(Ve.current!==g.id){Ve.current=g.id,y("workspace"),N(v||((Fe=f[0])==null?void 0:Fe.id)||"__home__"),x(""),C([]),R(""),$(null),M(""),E(oo(g)),z(""),K(""),J(""),oe([]),we(!1),Ne(""),U(_t()),P(""),be(null);return}N(me=>{var Be;return me==="__custom__"||me==="__home__"||f.some(It=>It.id===me)?me:v||((Be=f[0])==null?void 0:Be.id)||"__home__"}),E(me=>me==="ide"&&Xe.length>0||me==="cli"&&He.length>0||me==="acp"&&it.length>0?me:oo(g))},[it.length,He.length,v,Xe.length,g,f]),l.useEffect(()=>{!g||j!=="mesh"||_===g.id||L||ge(g.id)},[ge,_,L,g,j]),l.useEffect(()=>{j==="mesh"&&A!=="cli"&&He.length>0&&E("cli")},[A,He.length,j]),l.useEffect(()=>{var ce;A&&(Pe.some(Fe=>Fe.id===F)||z(((ce=Pe[0])==null?void 0:ce.id)||""))},[A,Pe,F]),l.useEffect(()=>{be(null)},[g==null?void 0:g.id,I,F,j]);const ke=l.useCallback(async(ce,Fe)=>{const me=_e.current+1;return _e.current=me,W(!0),Ne(""),u(ce,Fe).then(Be=>{_e.current===me&&oe(Be)}).catch(Be=>{_e.current===me&&(oe([]),Ne(Be instanceof Error?Be.message:"Could not load saved sessions"))}).finally(()=>{_e.current===me&&(W(!1),we(!0))})},[u]),Q=l.useCallback((ce,Fe)=>{q(Zw(ce,Fe))},[]);l.useEffect(()=>{_e.current+=1,J(""),U(_t()),!g||!F||A==="ide"?q([]):Q(g.id,F),we(!1),oe([]),Ne(""),W(!1)},[A,Q,ke,g,F]),l.useEffect(()=>{if(!ne)return;const ce=ye.find(Fe=>Fe.providerSessionId===ne);ce!=null&&ce.canResume||J("")},[ye,ne]);const ee=w==="__custom__"?k.trim():w==="__home__"?"":((Ot=f.find(ce=>ce.id===w))==null?void 0:Ot.path)||"",he=l.useMemo(()=>g?t.filter(ce=>ce.id!==g.id&&ce.daemonId===g.id).map(ce=>ce.workspace):[],[t,g]),Ie=l.useMemo(()=>((g==null?void 0:g.recentLaunches)||[]).map(ce=>ce.workspace),[g]),Le=l.useCallback(ce=>{const Fe=String(ce.workspace||"").trim();if(!Fe)return;const me=f.find(Be=>Cn(Be.path)===Cn(Fe));if(me){N(me.id),x("");return}N("__custom__"),x(Fe)},[f]),Te=l.useCallback(ce=>{const Fe=String(ce.workspace||"").trim();if(!Fe)return{workspaceId:null,workspacePath:null};const me=f.find(Be=>Cn(Be.path)===Cn(Fe));return me?{workspaceId:me.id,workspacePath:null}:{workspaceId:null,workspacePath:Fe}},[f]),Ee=l.useMemo(()=>ye.find(ce=>ce.providerSessionId===ne)||null,[ye,ne]),We=l.useMemo(()=>{var Fe;if(A!=="cli"||!g||!F)return null;const ce=((Fe=He.find(me=>me.type===F))==null?void 0:Fe.displayName)||F;return{routeId:g.id,daemonId:g.id,providerSessionId:ne||void 0,transport:"pty",mode:"chat",agentName:ce,agentType:F,status:"idle",title:ce,messages:[],ideType:F,workspaceName:ee,workspacePath:ee,displayPrimary:ce,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${g.id}:${F}`,machineName:Ft(g,{fallbackId:g.id})}},[A,He,ee,g,ne,F]),Re=l.useCallback(()=>{var Fe;if(!g)return;N("__custom__"),te(!0),$e("");const ce=Ei(g.platform,$i(k.trim(),ee,he,Ie,g.defaultWorkspacePath,(Fe=f.find(me=>me.id===v))==null?void 0:Fe.path,f.map(me=>me.path)));pe(!0),n(g.id,ce).then(me=>{Ae(me.path),x(me.path),Ue(me.directories)}).catch(me=>{$e(me instanceof Error?me.message:"Could not load folder")}).finally(()=>pe(!1))},[k,v,Ie,he,n,ee,g,f]),Ye=l.useCallback(ce=>{g&&(pe(!0),$e(""),n(g.id,ce).then(Fe=>{Ae(Fe.path),x(Fe.path),Ue(Fe.directories)}).catch(Fe=>{$e(Fe instanceof Error?Fe.message:"Could not load folder")}).finally(()=>pe(!1)))},[n,g]),st=l.useCallback(async()=>{if(!g||!ee)return;Ke(!0),P("");const ce=await a(g.id,ee);if(Ke(!1),!ce.ok){P(ce.error||"Could not save workspace");return}P("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,ee,g]),ht=l.useCallback(async()=>{if(!g)return;if(j==="mesh"){if(!I||!F)return;xe(!0),P(""),be(null);const me=await d(g.id,I,F);if(xe(!1),!me.ok){if(me.code==="mesh_coordinator_manual_mcp_setup_required"&&me.manualSetup){be(me.manualSetup),P("Manual MCP setup required before this provider can act as mesh coordinator.");return}P(me.error||"Could not start mesh coordinator");return}r();return}if(!A||!F)return;xe(!0),P("");const ce=D.trim()?D.trim().split(/\s+/).filter(Boolean):[],Fe=A==="ide"?await o(g.id,F,{workspacePath:ee||null}):await i(g.id,A,F,{workspaceId:w!=="__home__"&&w!=="__custom__"?w:null,workspacePath:w==="__custom__"&&ee||null,resumeSessionId:A==="cli"&&ne?ne:null,cliArgs:ce});if(xe(!1),!Fe.ok){P(Fe.error||"Could not start session");return}A!=="ide"&&D.trim()&&(ej(g.id,F,D),Q(g.id,F)),r()},[A,D,Q,r,o,d,i,ee,g,I,ne,F,w,j]),kt=j==="mesh"?"Start mesh coordinator":A?D0(A,A==="cli"&&!!ne):"Start",xt=j==="mesh"?"Starting coordinator…":A?$0(A,A==="cli"&&!!ne):"Starting…",bt=m.length>5;return g?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:s.jsx(vt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[m.length>1&&s.jsx(Hn,{title:"Machine",children:bt?s.jsx("select",{"aria-label":"Machine",value:g.id,onChange:ce=>b(ce.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:se,children:m.map(ce=>s.jsx("option",{value:ce.id,children:Ft(ce,{fallbackId:ce.id})},ce.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:m.map(ce=>{const Fe=Ft(ce,{fallbackId:ce.id}),me=g.id===ce.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${Fe}`,"aria-pressed":me,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${me?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/60 text-text-secondary hover:bg-bg-secondary hover:text-text-primary"}`,onClick:()=>b(ce.id),disabled:se,title:Fe,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${ce.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:Fe})]},ce.id)})})}),s.jsxs(Hn,{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:Re,disabled:se,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(ce=>s.jsxs("button",{type:"button",role:"radio","aria-checked":j===ce.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${j===ce.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{y(ce.id),P(""),ce.id==="mesh"&&g&&_!==g.id&&!L&&ge(g.id)},disabled:se,children:[s.jsx("div",{className:"text-sm font-semibold",children:ce.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:ce.desc})]},ce.id))}),j==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:w,onChange:ce=>{const Fe=ce.target.value;N(Fe),Fe==="__custom__"?Re():P("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:se,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),f.map(ce=>s.jsxs("option",{value:ce.id,children:[ce.id===v?"⭐ ":"",Ud(ce.path,ce.label)||ce.path]},ce.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.":ee||"Select a workspace folder."}),w==="__custom__"&&ee&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Re,disabled:se,children:[s.jsx(Qs,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:st,disabled:se||tt,children:tt?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[L&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!L&&X&&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:X}),!L&&!X&&S.length===0&&s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker."}),S.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:S.map(ce=>s.jsxs("button",{type:"button",role:"radio","aria-checked":I===ce.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${I===ce.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>R(ce.id),disabled:se,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:ce.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[ce.repoIdentity||"Repo mesh",typeof ce.nodesCount=="number"?` · ${ce.nodesCount} node${ce.nodesCount===1?"":"s"}`:""]}),ce.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",ce.workspace]})]},ce.id))}),G&&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(nj,{workspaceMode:j,activeKind:A,cliEnabled:He.length>0,ideEnabled:Xe.length>0,acpEnabled:it.length>0,busy:se,onSelect:E}),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:A==="ide"?"Choose IDE":A==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Pe.map(ce=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${F===ce.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>z(ce.id),disabled:se,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:ce.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ce.meta})]},ce.id)),Pe.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"&&le&&s.jsx(zp,{setup:le,providerName:(V==null?void 0:V.displayName)||(V==null?void 0:V.name)||F}),j!=="mesh"&&A!=="ide"&&s.jsxs(Hn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:D,onChange:ce=>K(ce.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:se}),O.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:O.map(ce=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>K(ce),disabled:se,title:ce,children:ce},ce))})]}),j!=="mesh"&&A==="cli"&&s.jsx(rj,{busy:se,savedSessionsLoading:B,savedSessionsError:fe,selectedSession:Ee,onRefresh:()=>{!g||!F||ke(g.id,F)},onOpenHistory:()=>{!g||!F||(je(!0),tj({hasLoadedInitialResults:ve,isLoading:B})&&ke(g.id,F))},onClearSelection:()=>J("")}),Z&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${Z.includes("saved")||Z.includes("requested")||Z.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:Z})]}),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:se,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:ht,disabled:se||(j==="mesh"?!I||!F||A!=="cli"||L:!A||!F||w==="__custom__"&&!ee),children:[s.jsx(Ad,{size:14}),se?xt:kt]})]})]})}),ue&&s.jsx(Oi,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:Me,directories:Ce,busy:Qe,error:De,onClose:()=>te(!1),onNavigate:Ye,onConfirm:ce=>{x(ce),Ae(ce),N("__custom__"),te(!1)}}),re&&We&&s.jsx(Uu,{activeConv:We,ides:[],isCreatingChat:!1,isRefreshingHistory:B,savedSessions:ye,isSavedSessionsLoading:B,isResumingSavedSessionId:H,savedHistoryFilters:de,missingWorkspaceResumePath:ee||null,onSavedHistoryFiltersChange:U,onClose:()=>je(!1),onNewChat:()=>{J(""),je(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!g||!F||ke(g.id,F)},onResumeSavedSession:ce=>{if(!g||!F||H||!ce.canResume)return;const Fe=Te(ce);J(ce.providerSessionId),Le(ce),Y(ce.providerSessionId),je(!1),xe(!0),P(""),i(g.id,"cli",F,{workspaceId:Fe.workspaceId,workspacePath:Fe.workspacePath,resumeSessionId:ce.providerSessionId}).then(me=>{if(!me.ok){P(me.error||"Could not resume session");return}r()}).finally(()=>{xe(!1),Y(me=>me===ce.providerSessionId?null:me)})}})]}):null}function Wp(e){return e.ahead<=0&&e.behind<=0?null:e.ahead>0&&e.behind>0?`ahead ${e.ahead} / behind ${e.behind}`:e.behind>0?`behind ${e.behind}`:`ahead ${e.ahead}`}function zi(e){if(e.type==="submoduleNode")return e.outOfSync||e.error?{label:"submodule drift",tone:"danger"}:e.dirty?{label:"submodule dirty",tone:"warn"}:null;const t=e.branchConvergence;if((t==null?void 0:t.status)==="not_mergeable")return{label:e.hasConflicts?"conflicts present":"dirty workspace",tone:"danger"};if((t==null?void 0:t.status)==="blocked_review"){if(t.reason==="upstream_unverified")return{label:"upstream unverified",tone:"warn"};const r=Wp(e);return r?{label:r,tone:"danger"}:!e.upstream&&e.branch&&e.branch!==t.defaultBranch?{label:"push branch",tone:"warn"}:{label:"blocked review",tone:"danger"}}return e.refineJobStatus==="failed"?{label:"refine failed",tone:"danger"}:e.refineJobStatus==="running"||e.refineJobStatus==="accepted"?{label:"refining…",tone:"info"}:(t==null?void 0:t.status)==="pushed_feature_branch_needs_merge"?{label:"needs merge",tone:"warn"}:(t==null?void 0:t.status)==="cleanup_candidate"?{label:"refine worktree",tone:"info"}:e.isOrphan?{label:"needs follow-up",tone:"warn"}:e.health==="offline"?{label:"offline",tone:"danger"}:null}function Wi(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function Kp(e){var t;return!Wi(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 In(e){return[...new Set(e.filter(t=>!!t))]}function oj(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?In([t==null?void 0:t.id,...n.map(i=>i.id)]):a.length>0?In(a.map(i=>i.id)):o.length>0?In(o.map(i=>i.id)):In(e.nodes.map(i=>i.id))}function Up(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 ij(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${Up(e)}::${n}x${a}`}const lj={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"},cj={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"},dj={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"},uj={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 Fs(e){return e==="light"?{theme:e,isDark:!1,flowColorMode:"light",textPrimary:"text-slate-900",textSecondary:"text-slate-700",textMuted:"text-slate-500",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-slate-200 bg-[radial-gradient(circle_at_top,_rgba(14,165,233,0.16),_rgba(248,250,252,0.98)_42%,_rgba(255,255,255,1))]",graphStatChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-slate-700 shadow-sm",graphHintChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-[10px] text-slate-500 shadow-sm",graphControlsClass:"!bottom-4 !left-4 !shadow-md",graphBackgroundDotColor:"rgba(148, 163, 184, 0.34)",edgeLabelTextColor:"#334155",edgeLabelBackgroundColor:"rgba(255, 255, 255, 0.96)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.45)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-stretch justify-center bg-[rgba(15,23,42,0.82)] p-0 md:items-center md:p-4",dialogShellClass:"flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden bg-white md:h-auto md:max-h-[90dvh] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-slate-200 md:bg-white/98 md:shadow-[0_28px_120px_rgba(148,163,184,0.28)]",dialogHeaderClass:"sticky top-0 z-10 flex shrink-0 flex-col gap-3 border-b border-slate-200 bg-white/96 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-slate-900 md:text-xl",dialogKickerClass:"rounded-full border border-slate-300 bg-slate-50 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-600",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-500",dialogRefreshedChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1.5 text-xs text-slate-600",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-300 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",dialogBodyClass:"min-h-0 flex-1 flex flex-col overflow-y-auto bg-[linear-gradient(180deg,rgba(248,250,252,0.98),rgba(241,245,249,0.96))] px-4 py-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-slate-300 bg-white/90 px-6 text-center text-sm text-slate-500",cardClass:"rounded-2xl border border-slate-200 bg-white/95 shadow-sm",cardHeaderClass:"border-b border-slate-200 px-4 py-3",cardTitleClass:"text-sm font-semibold text-slate-900",cardSubtitleClass:"mt-1 text-xs text-slate-500",rowClass:"flex min-w-0 items-start justify-between gap-3 border-b border-slate-200/80 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"shrink-0 text-slate-500",rowValueClass:"min-w-0 flex-1 break-all text-right text-slate-800",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-slate-200 bg-white/95 p-4 shadow-md md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-slate-200 bg-white/95 p-4 text-xs text-slate-500 shadow-sm md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-900",panelCloseButtonClass:"text-xs text-slate-500 hover:text-slate-900",panelFieldRowClass:"flex min-w-0 justify-between gap-3 border-b border-slate-200/80 py-0.5 text-[11px]",panelFieldLabelClass:"shrink-0 text-slate-500",panelFieldValueClass:"min-w-0 flex-1 break-all text-right font-medium text-slate-700",infoCalloutClass:"mt-1 rounded border border-sky-300 bg-sky-50 px-2 py-1.5 text-[10px] text-sky-700",badge:t=>cj[t],actionButton:t=>uj[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",graphStatChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-slate-200",graphHintChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-[10px] text-slate-300",graphControlsClass:"!bottom-4 !left-4 !shadow-lg",graphBackgroundDotColor:"rgba(148, 163, 184, 0.22)",edgeLabelTextColor:"#cbd5e1",edgeLabelBackgroundColor:"rgba(2, 6, 23, 0.86)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.2)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-stretch justify-center bg-[#030617]/[0.92] p-0 md:items-center md:p-4",dialogShellClass:"flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden bg-slate-950 md:h-auto md:max-h-[90dvh] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-white/10 md:bg-slate-950/96 md:shadow-[0_28px_120px_rgba(2,6,23,0.46)]",dialogHeaderClass:"sticky top-0 z-10 flex shrink-0 flex-col gap-3 border-b border-white/10 bg-slate-950/92 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-white md:text-xl",dialogKickerClass:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-300",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-400",dialogRefreshedChipClass:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 bg-white/6 text-slate-300 transition hover:bg-white/10 hover:text-white",dialogBodyClass:"min-h-0 flex-1 flex flex-col overflow-y-auto bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] px-4 py-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-white/10 bg-white/[0.03] px-6 text-center text-sm text-slate-400",cardClass:"rounded-2xl border border-white/10 bg-white/[0.04]",cardHeaderClass:"border-b border-white/10 px-4 py-3",cardTitleClass:"text-sm font-semibold text-white",cardSubtitleClass:"mt-1 text-xs text-slate-400",rowClass:"flex min-w-0 items-start justify-between gap-3 border-b border-white/5 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"shrink-0 text-slate-400",rowValueClass:"min-w-0 flex-1 break-all text-right text-slate-100",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-white/10 bg-white/[0.04] p-4 shadow-lg md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-white/10 bg-white/[0.04] p-4 text-xs text-slate-400 md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-100",panelCloseButtonClass:"text-xs text-slate-400 hover:text-slate-100",panelFieldRowClass:"flex min-w-0 justify-between gap-3 border-b border-white/6 py-0.5 text-[11px]",panelFieldLabelClass:"shrink-0 text-slate-400",panelFieldValueClass:"min-w-0 flex-1 break-all text-right font-medium text-slate-200",infoCalloutClass:"mt-1 rounded bg-blue-500/10 border border-blue-500/20 px-2 py-1.5 text-[10px] text-blue-300",badge:t=>lj[t],actionButton:t=>dj[t]}}const nr={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,layerGap:220,nodeGap:82,edgeLabelBuffer:180,placeholderTopOffset:0},Zr={worktreeCardWidth:188,submoduleCardWidth:188,minWorktreeCardHeight:88,minSubmoduleCardHeight:88,maxEstimatedCardHeight:178,layerGap:160,nodeGap:52,edgeLabelBuffer:120},pj={maxWidth:180};function mj(e){return e==="TB"?"DOWN":"RIGHT"}function Ki(e,t){return{"elk.algorithm":"layered","elk.direction":mj(t),"elk.edgeRouting":"ORTHOGONAL","elk.spacing.nodeNode":String(e.nodeGap),"elk.layered.spacing.nodeNodeBetweenLayers":String(e.layerGap),"elk.layered.spacing.edgeNodeBetweenLayers":String(e.edgeLabelBuffer),"elk.layered.layering.strategy":"NETWORK_SIMPLEX","elk.layered.nodePlacement.strategy":"NETWORK_SIMPLEX","elk.layered.crossingMinimization.strategy":"LAYER_SWEEP","elk.layered.considerModelOrder.strategy":"NODES_AND_EDGES","elk.layered.cycleBreaking.strategy":"GREEDY","elk.layered.mergeEdges":"false","elk.randomSeed":"1"}}const hj=Ki(nr,"LR");Ki(Zr,"LR");function fj(e){const t=e.nodes.length;if(t<8)return"LR";const r=new Map;for(const a of e.edges)r.set(a.source,(r.get(a.source)??0)+1);let n=0;for(const a of r.values())a>n&&(n=a);return n>=Math.max(6,Math.floor(t/2))?"TB":"LR"}const xj=new ih;function zr(e,t=!1){const r=t?Zr:nr;return e.type==="submoduleNode"?r.submoduleCardWidth:r.worktreeCardWidth}function zn(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=Wp(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 Gp(e,t=!1){const r=t?Zr:nr,n=zr(e,t),a=t?e.type==="submoduleNode"?20:22:e.type==="submoduleNode"?24:30,o=t?(e.type==="submoduleNode",2):e.type==="submoduleNode"?2:3,i=Math.ceil(bj(e)/o),c=Mn(e.label,a,2),d=Mn(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,a,2),u=Mn(zn(e),a+(t?1:4),t?2:3),p=zi(e),m=Kp(e)?Wi(e):null,h=t?0:Mn(m,Math.max(24,Math.floor(n/8)),4),b=t?40+c*16+d*12+(p?22:0)+Math.max(0,i-1)*18+Math.max(18,u*16):52+c*18+d*14+(p?30:0)+i*24+Math.max(22,u*18)+(h>0?22+h*16:0),g=e.type==="submoduleNode"?r.minSubmoduleCardHeight:r.minWorktreeCardHeight;return Math.min(r.maxEstimatedCardHeight,Math.max(g,Math.ceil(b)))}function Mn(e,t,r){const n=(e||"").trim();return n?Math.max(1,Math.min(r,Math.ceil(n.length/t))):0}function bj(e){let t=1;return e.type==="submoduleNode"&&(t+=1),e.branch&&e.type!=="submoduleNode"&&(t+=1),e.submoduleCommit&&e.type==="submoduleNode"&&(t+=1),e.dirty&&(t+=1),e.outOfSync&&(t+=1),e.hasConflicts&&(t+=1),e.type!=="submoduleNode"&&e.upstream&&e.upstreamStatus!=="fresh"&&(t+=1),e.isOrphan&&(t+=1),t}function gj(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 yj(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function vj(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 wj(e,t,r){return{id:e.id,x:t,y:r,width:zr(e),height:Gp(e)}}function jj(e,t){return{id:`${e.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:t.repoIdentity,branch:e.branch,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:null,locality:"unknown",connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null,health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],nextStepHint:"Waiting for worktree nodes to report live mesh status.",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{nodeId:`${e.id}__placeholder`,machineLabel:"",workspace:t.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}}function Vp(e){const t=[...e.nodes].sort(gj),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,jj(r,e)]}function kj(e,t=hj,r=!1,n="LR"){const a=Vp(e),o=new Set(a.map(d=>d.id)),i=a.map(d=>({id:d.id,width:zr(d,r),height:Gp(d,r)})),c=e.edges.filter(d=>o.has(d.source)&&o.has(d.target)).sort(yj).map(d=>({id:d.id,sources:[d.source],targets:[d.target]}));return{id:`${e.meshId||"mesh"}__elk_root`,layoutOptions:{...t},children:i,edges:c}}function Nj(e,t=!1){const r=[...new Set(e.map(a=>Math.round(a.x)))].sort((a,o)=>a-o),n=t?Zr.layerGap:nr.layerGap;return r.length<2?n:Math.min(...r.slice(1).map((a,o)=>a-r[o]))}async function qp(e,t=!1,r="LR",n){var g,f;const o=Ki(t?Zr:nr,r),i=Vp(e),c=new Map(i.map(v=>[v.id,v])),d=kj(e,o,t,r);if(n&&n.size>0)for(const v of d.children??[]){const j=n.get(v.id);j&&j>0&&(v.height=j)}const u=await xj.layout(d),p=(u.children??[]).map(v=>{const j=c.get(v.id);return j?vj(j,Math.round(v.x??0),Math.round(v.y??nr.placeholderTopOffset),!v.id.endsWith("__placeholder")):null}).filter(Boolean),m=new Map(i.map((v,j)=>[v.id,j]));p.sort((v,j)=>(m.get(v.id)??0)-(m.get(j.id)??0));const h=p.map(v=>wj(v.graphNode,v.position.x,v.position.y)),b=new Map;for(const v of u.edges??[]){const j=v.sections;if(!j||j.length===0)continue;const y=j[0],w=(g=v.sources)==null?void 0:g[0],N=(f=v.targets)==null?void 0:f[0];if(!w||!N)continue;const k=[];k.push({x:Math.round(y.startPoint.x),y:Math.round(y.startPoint.y)});for(const x of y.bendPoints??[])k.push({x:Math.round(x.x),y:Math.round(x.y)});k.push({x:Math.round(y.endPoint.x),y:Math.round(y.endPoint.y)}),b.set(v.id,{id:v.id,source:w,target:N,points:k})}return{nodes:p,bounds:h,edgeRoutes:b,columnGap:Nj(h,t),layoutOptions:{...o}}}function Sj(e){var t,r;return[e.id,e.type,e.label,e.branch??"",e.upstream??"",e.upstreamStatus??"",e.daemonId??"",e.machineId??"",e.machineLabel??"",e.locality,e.health,e.ahead,e.behind,e.dirty?1:0,e.dirtyFiles,e.hasConflicts?1:0,e.activeSessionCount,e.sessionDetails.map(n=>[n.sessionId,n.providerType??"",n.state??"",n.chatStatus??"",n.lifecycle??"",n.role??"",n.isSelfCoordinator?1:0,n.statusNote??"",n.startedAt??"",n.createdAt??""].join("/")).join(","),e.isOrphan?1:0,e.outOfSync?1:0,e.snapshotCompleteness,((t=e.branchConvergence)==null?void 0:t.status)??"",(r=e.branchConvergence)!=null&&r.needsConvergence?1:0,e.nextStepHint??"",e.error??"",e.parentNodeId??"",e.submodulePath??"",e.submoduleCommit??""].join("|")}function Yp(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function Cj(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(Sj),...e.edges.map(Yp)].join("::")}function Ij(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(Yp)].join("::")}const Mj=5*60*1e3;function Jp(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function Xp(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function Aj(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"||Jp(e)||Xp(e)?"remote":"unknown"}function Tj(e){const t=e.connection;if(!t)return{connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null};const r=t.rttMs,n=typeof r=="number"&&Number.isFinite(r)&&r>=0?r:null;return{connectionTransport:t.transport??null,connectionState:t.state??null,connectionReason:typeof t.reason=="string"&&t.reason.trim()?t.reason.trim():null,connectionReported:t.reported===!0,connectionRttMs:n}}function Qp(e){const t=e.connectionTransport;if(t==="direct"||t==="relay"||t==="local")return t;const r=e.connectionState;return r==="connecting"?"connecting":r==="disconnected"?"disconnected":r==="failed"?"failed":r==="closed"?"closed":null}function _j(e){if(e.connectionTransport==="local"||e.connectionState==="self")return null;const t=Qp(e);return!t||t==="local"||typeof e.connectionRttMs!="number"||!Number.isFinite(e.connectionRttMs)?null:`${Math.round(e.connectionRttMs)}ms`}function Rj(e){return gi(e)}function Zp(e){var t;return Rj(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function em(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function Pj(e){return e.activeSessionDetails&&e.activeSessionDetails.length>0?e.activeSessionDetails:(e.activeSessions??[]).map(t=>({sessionId:t,workspace:e.workspace,isCached:!0}))}function tm(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function sm(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function Ui(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function Lj(e){return Ui(e)?"degraded":sm(e)?"dirty":"online"}function Dj(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function Pc(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 io(e){return e.length===0?"unknown":e.reduce((t,r)=>Pc(r)>Pc(t)?r:t)}function $j(e){var o,i,c,d,u;const t=new Map,r=new Map;for(const p of e){const m=(i=(o=p.git)==null?void 0:o.branch)==null?void 0:i.trim();m&&(r.set(m,(r.get(m)??0)+1),(c=p.git)!=null&&c.upstream&&t.set(m,(t.get(m)??0)+1))}const n=[...t.entries()].sort((p,m)=>{if(m[1]!==p[1])return m[1]-p[1];const h=["main","master","develop","dev"],b=h.indexOf(p[0]),g=h.indexOf(m[0]);return b!==-1||g!==-1?b===-1?1:g===-1?-1:b-g:p[0].localeCompare(m[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((u=[...r.entries()].sort((p,m)=>m[1]-p[1])[0])==null?void 0:u[0])??null}function Ej(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 Lc(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 Bj(e){return e.reduce((t,r)=>Lc(r.status)>Lc(t.status)?r:t)}function Fj(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 Oj(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 Hj(e){const t=e.asyncRefineJobs;if(!Array.isArray(t))return[];const r=[];for(const n of t){if(!n||typeof n!="object")continue;const a=n,o=typeof a.jobId=="string"?a.jobId:null,i=a.status;o&&(i!=="accepted"&&i!=="running"&&i!=="completed"&&i!=="failed"||r.push({jobId:o,status:i,nodeId:typeof a.nodeId=="string"?a.nodeId:void 0,targetNodeId:typeof a.targetNodeId=="string"?a.targetNodeId:void 0,workspace:typeof a.workspace=="string"?a.workspace:void 0,branch:typeof a.branch=="string"?a.branch:void 0,into:typeof a.into=="string"?a.into:void 0,lastUpdatedAt:typeof a.lastUpdatedAt=="string"?a.lastUpdatedAt:void 0,startedAt:typeof a.startedAt=="string"?a.startedAt:void 0,completedAt:typeof a.completedAt=="string"?a.completedAt:void 0}))}return r}function Dc(e){switch(e){case"running":case"accepted":return 0;case"failed":return 1;case"completed":default:return 2}}function $c(e){const t=e.lastUpdatedAt||e.completedAt||e.startedAt||"";return em(t)??0}function zj(e){return e.length===0?null:e.reduce((t,r)=>{const n=Dc(t.status),a=Dc(r.status);return a!==n?a<n?r:t:$c(r)>$c(t)?r:t})}function Wj(e){var r,n;const t=new Map;for(const a of e){const o=((r=a.nodeId)==null?void 0:r.trim())||((n=a.targetNodeId)==null?void 0:n.trim());if(!o)continue;const i=t.get(o)??[];i.push(a),t.set(o,i)}return t}function Kj(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 Uj(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 Gj(e,t){if(Zp(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=tm(a)||sm(a),i=!!(a!=null&&a.hasConflicts)||Ui(a),c=(a==null?void 0:a.ahead)??0,d=(a==null?void 0:a.behind)??0,u=(a==null?void 0:a.branch)??null,p=(a==null?void 0:a.upstream)??null,m=(a==null?void 0:a.upstreamStatus)??null,h=r.defaultBranch??t??null;return{status:n,needsConvergence:r.needsConvergence??n!=="merged_to_main",reason:r.reason??"provided_by_coordinator",nextStep:r.nextStep??null,branch:r.branch??u,defaultBranch:h,upstream:r.upstream??p,upstreamStatus:r.upstreamStatus??m,ahead:r.ahead??c,behind:r.behind??d,dirty:r.dirty??o,hasConflicts:r.hasConflicts??i}}function Vj(e,t){const r=Gj(e,t);return r?{...r,defaultBranch:r.defaultBranch??t}:null}function qj(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function Yj(e){var d,u,p;const{nodeStatus:t,expectedSubmodulePaths:r,refreshedAtMs:n}=e,a=[],o=t.machineLabel||t.nodeId,i=t.git;if(!i){if(Zp(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const m=t.health==="online"||t.machineStatus==="online"||((d=t.connection)==null?void 0:d.state)==="connected"||((u=t.connection)==null?void 0:u.state)==="self";return a.push(m?`${o} is online but no peer git snapshot is visible yet.`:`${o} has no peer git snapshot visible yet.`),{snapshotCompleteness:"missing_git",snapshotWarnings:a}}const c=new Set((i.submodules??[]).map(m=>m.path));if(r.size>0){const m=[...r].filter(h=>!c.has(h));m.length>0&&a.push(`${o} is missing submodule visibility for ${m.join(", ")} even though another peer reported it.`)}return((p=t.connection)==null?void 0:p.state)!=="self"&&n!==null&&typeof i.lastCheckedAt=="number"&&n-i.lastCheckedAt>Mj&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(m=>m.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(m=>m.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function rm(e){const t=yi(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??$j(t.nodes),a=em(t.refreshedAt),o=new Set(t.nodes.flatMap(M=>{var A;return(((A=M.git)==null?void 0:A.submodules)??[]).map(E=>E.path)})),i=[],c=[],d=Oj(t),u=new Map,p=Wj(Hj(t));for(const M of t.nodes){const A=M.git,E=(A==null?void 0:A.branch)??null,F=Lj(A),z=tm(A)||F==="dirty",D=Ej(M,n),K=Vj(M,n),O=Yj({nodeStatus:M,expectedSubmodulePaths:o,refreshedAtMs:a}),q=typeof M.clonedFromNodeId=="string"?M.clonedFromNodeId:null,ne=Pj(M),J=zj(p.get(M.nodeId)??[]),ye=Tj(M),oe={id:M.nodeId,type:D.length>0?"orphanNode":"worktreeNode",label:M.machineLabel||M.nodeId.slice(0,8),workspace:M.workspace,branch:E,upstream:(A==null?void 0:A.upstream)??null,upstreamStatus:(A==null?void 0:A.upstreamStatus)??null,daemonId:Jp(M),machineId:Xp(M),machineLabel:M.machineLabel||null,locality:Aj(M),connectionTransport:ye.connectionTransport,connectionState:ye.connectionState,connectionReason:ye.connectionReason,connectionReported:ye.connectionReported,connectionRttMs:ye.connectionRttMs,health:io([M.health,F]),ahead:(A==null?void 0:A.ahead)??0,behind:(A==null?void 0:A.behind)??0,dirty:z,dirtyFiles:Dj(A),hasConflicts:(A==null?void 0:A.hasConflicts)??!1,activeSessionCount:ne.length,activeSessions:ne.map(B=>B.sessionId),sessionDetails:ne,providers:M.providers??[],isOrphan:D.length>0,orphanReasons:D,error:M.error,nextStepHint:O.snapshotWarnings[0]??D[0]??(K==null?void 0:K.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:q,worktreeBranch:M.worktreeBranch??null,submodulePath:null,submoduleCommit:(A==null?void 0:A.headCommit)??null,outOfSync:Ui(A),snapshotCompleteness:O.snapshotCompleteness,snapshotWarnings:O.snapshotWarnings,branchConvergence:K,refineJobStatus:(J==null?void 0:J.status)??null,refineJobId:(J==null?void 0:J.jobId)??null,refineJobBranch:(J==null?void 0:J.branch)??null,refineJobInto:(J==null?void 0:J.into)??null,source:M};if(i.push(oe),E){const B=u.get(E)??[];B.push(oe.id),u.set(E,B)}for(const B of(A==null?void 0:A.submodules)??[]){const W=`${oe.id}::submodule::${B.path}`,ve=B.path.split("/").filter(Boolean).pop()||B.path;i.push({id:W,type:"submoduleNode",label:ve,workspace:B.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:oe.daemonId,machineId:oe.machineId,machineLabel:oe.machineLabel,locality:oe.locality,connectionTransport:oe.connectionTransport,connectionState:oe.connectionState,connectionReason:oe.connectionReason,connectionReported:oe.connectionReported,connectionRttMs:oe.connectionRttMs,health:qj(B),ahead:0,behind:0,dirty:B.dirty,dirtyFiles:B.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],error:B.error,nextStepHint:B.error||(B.outOfSync?`${B.path} is out of sync with the parent checkout`:B.dirty?`${B.path} has local changes`:`${B.path} is in sync with the parent checkout`),parentNodeId:oe.id,submodulePath:B.path,submoduleCommit:B.commit,outOfSync:B.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:oe.id,parentWorkspace:M.workspace,submodule:B}}),c.push({id:`${oe.id}--${W}`,source:oe.id,target:W,type:"submoduleLink",label:B.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const m=n?`__branch_${n}`:null;if(m&&n){const A=(u.get(n)??[]).map(q=>i.find(ne=>ne.id===q)).filter(Boolean),E=A.map(q=>q.branchConvergence).filter(Boolean),F=Fj(t),z=A.length>0&&A.every(q=>Kj(q,n)),D=(F==null?void 0:F.length)===0&&z?Uj(n,A):E.length>0?Bj(E):null,K=(F==null?void 0:F.length)===0&&z?0:E.filter(q=>q.needsConvergence).length,O={id:m,type:"defaultBranchNode",label:n,workspace:t.repoIdentity,branch:n,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:"default branch",locality:"unknown",connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null,health:io(A.map(q=>q.health)),ahead:0,behind:0,dirty:A.some(q=>q.dirty),dirtyFiles:A.reduce((q,ne)=>q+ne.dirtyFiles,0),hasConflicts:A.some(q=>q.hasConflicts),activeSessionCount:A.reduce((q,ne)=>q+ne.activeSessionCount,0),activeSessions:A.flatMap(q=>q.activeSessions),sessionDetails:A.flatMap(q=>q.sessionDetails),providers:[...new Set(A.flatMap(q=>q.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:K>0?`${K} workspace(s) on ${n} still need follow-up`:A.length>0?`${A.length} workspace(s) currently on ${n}`:"No workspaces currently checked out to the default branch",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:D,source:{nodeId:m,machineLabel:n,workspace:t.repoIdentity,health:io(A.map(q=>q.health)),providers:[],activeSessions:[],activeSessionDetails:[]}};i.push(O);for(const q of i)if(!(q.id===m||q.type==="submoduleNode")){if(q.branch===n){c.push({id:`${m}--${q.id}`,source:m,target:q.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(q.branch){c.push({id:`${m}--${q.id}`,source:m,target:q.id,type:q.isOrphan?"orphanLink":"parentBranch",label:q.branch,direction:"undirected"});continue}q.isOrphan&&c.push({id:`${m}--${q.id}`,source:m,target:q.id,type:"orphanLink",label:"detached",direction:"undirected"})}}const h=new Set(i.map(M=>M.id)),b=new Set;for(const M of i){if(!M.clonedFromNodeId||M.type==="submoduleNode"||!h.has(M.clonedFromNodeId))continue;const A=`clone_${M.clonedFromNodeId}--${M.id}`;if(b.has(A))continue;b.add(A);const E=M.worktreeBranch??M.branch??void 0;c.push({id:A,source:M.clonedFromNodeId,target:M.id,type:"cloneLink",label:E?`cloned · ${E}`:"cloned",direction:"directed"})}const g=i.filter(M=>M.type!=="defaultBranchNode"),f=g.filter(M=>M.isOrphan).length,v=g.filter(M=>M.hasConflicts).length,j=g.filter(M=>M.health==="offline").length,y=g.filter(M=>M.type==="submoduleNode"&&M.outOfSync).length,w=g.filter(M=>{var A;return M.type!=="submoduleNode"&&((A=M.branchConvergence)==null?void 0:A.needsConvergence)}).length,N=g.filter(M=>{var A;return((A=M.branchConvergence)==null?void 0:A.status)==="blocked_review"}).length,k=g.filter(M=>{var A;return((A=M.branchConvergence)==null?void 0:A.status)==="pushed_feature_branch_needs_merge"}).length,x=g.filter(M=>{var A;return((A=M.branchConvergence)==null?void 0:A.status)==="cleanup_candidate"}).length,S=g.filter(M=>{var A;return((A=M.branchConvergence)==null?void 0:A.status)==="not_mergeable"}).length,C=g.filter(M=>M.snapshotWarnings.length>0).length,I=g.filter(M=>M.snapshotCompleteness==="pending_git").length,R=g.filter(M=>M.snapshotCompleteness==="missing_git").length,L=g.filter(M=>M.snapshotCompleteness==="missing_submodule_report").length,T=g.filter(M=>M.snapshotCompleteness==="stale").length,_=g.filter(M=>M.refineJobStatus==="running"||M.refineJobStatus==="accepted").length,$=g.filter(M=>M.refineJobStatus==="failed").length,X=[I>0?`${I} node(s) are still waiting for a live peer git snapshot`:null,R>0?`${R} node(s) have no visible peer git snapshot`:null,L>0?`${L} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,T>0?`${T} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return w>0&&d.push(`${w} workspace(s) still need follow-up before the mesh is converged`),f>0&&d.push(`${f} workspace(s) need attention before safe coordination`),N>0&&d.push(`${N} workspace(s) are blocked on branch convergence or upstream sync`),k>0&&d.push(`${k} clean feature branch workspace(s) still need merge follow-up`),x>0&&d.push(`${x} worktree workspace(s) are ready for refine / cleanup`),S>0&&d.push(`${S} workspace(s) have local changes or conflicts blocking convergence`),v>0&&d.push(`${v} workspace(s) report merge conflicts`),j>0&&d.push(`${j} node(s) are currently offline`),y>0&&d.push(`${y} submodule(s) are out of sync with their parent checkout`),d.push(...X),n||d.push("Could not infer a default branch from live mesh status"),{meshId:t.meshId,meshName:t.meshName,repoIdentity:t.repoIdentity,refreshedAt:t.refreshedAt,nodes:i,edges:c,stats:{totalNodes:g.length,onlineNodes:g.filter(M=>M.health==="online").length,dirtyNodes:g.filter(M=>M.dirty).length,orphanNodes:f,errorNodes:g.filter(M=>!!M.error||M.outOfSync).length,offlineNodes:j,followUpNodes:w,blockedReviewNodes:N,mergeReadyNodes:k,cleanupCandidateNodes:x,notMergeableNodes:S,incompleteSnapshotNodes:C,pendingGitSnapshotNodes:I,missingGitSnapshotNodes:R,missingSubmoduleSnapshotNodes:L,staleGitSnapshotNodes:T,activeRefineNodes:_,failedRefineNodes:$,totalActiveSessions:g.reduce((M,A)=>M+A.activeSessionCount,0)},warnings:d,snapshotWarnings:X}}function Jj(e){return!e.nodes.some(t=>t.snapshotCompleteness==="pending_git"||t.snapshotCompleteness==="missing_git"||t.snapshotCompleteness==="missing_submodule_report")}const Xj=7,Gi=l.createContext(Fs("dark")),nm=l.createContext(!1),am=l.createContext("LR"),om={overflowWrap:"anywhere",wordBreak:"break-word"},Qj={...om,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},Zj={...om,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function im(e){return e.activeSessionCount>0}function ek(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function Ec(e,t,r){const n=im(e),a=ek(e);let o;t?o="border-cyan-400/70 shadow-[0_0_0_1px_rgba(34,211,238,0.35),0_24px_60px_rgba(8,145,178,0.18)]":n?o=r?"border-emerald-400/40 shadow-[0_0_0_1px_rgba(52,211,153,0.18),0_18px_48px_rgba(3,7,18,0.22)]":"border-emerald-400/60 shadow-[0_0_0_1px_rgba(52,211,153,0.2),0_18px_48px_rgba(148,163,184,0.20)]":a?o=r?"border-white/6 shadow-[0_12px_32px_rgba(3,7,18,0.16)] opacity-60":"border-slate-200/70 shadow-[0_12px_32px_rgba(148,163,184,0.14)] opacity-60":o=r?"border-white/10 shadow-[0_18px_48px_rgba(3,7,18,0.22)]":"border-slate-300/90 shadow-[0_18px_48px_rgba(148,163,184,0.20)]";const i=zi(e);if((i==null?void 0:i.tone)==="danger")return`${o} ${r?"bg-rose-500/12":"bg-rose-50/95"}`;if((i==null?void 0:i.tone)==="warn")return`${o} ${r?"bg-amber-500/10":"bg-amber-50/95"}`;if((i==null?void 0:i.tone)==="info")return`${o} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;switch(e.health){case"online":return`${o} ${r?n?"bg-emerald-500/10":"bg-emerald-500/8":n?"bg-emerald-50":"bg-emerald-50/95"}`;case"dirty":return`${o} ${r?"bg-amber-500/8":"bg-amber-50/95"}`;case"degraded":return`${o} ${r?"bg-rose-500/10":"bg-rose-50/95"}`;case"wrong_branch":return`${o} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;case"offline":return`${o} ${r?"bg-slate-500/10":"bg-slate-100/90"}`;default:return`${o} ${r?"bg-slate-950/78":"bg-white/96"}`}}function St(e,t){switch(e){case"refineDone":return t?"border-emerald-400/25 bg-emerald-500/10 text-emerald-200":"border-emerald-300 bg-emerald-50 text-emerald-700";case"health":return t?"border-white/10 bg-slate-950/60 text-slate-200":"border-slate-300 bg-white/95 text-slate-700";case"dirty":return t?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700";case"conflict":return t?"border-rose-400/25 bg-rose-500/10 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700";case"orphan":return t?"border-fuchsia-400/25 bg-fuchsia-500/10 text-fuchsia-200":"border-fuchsia-300 bg-fuchsia-50 text-fuchsia-700";case"submodule":return t?"border-violet-400/25 bg-violet-500/10 text-violet-200":"border-violet-300 bg-violet-50 text-violet-700";case"meta":default:return t?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}}function Bc(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 Fc(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 tk(e){return e.replace(/_/g," ")}function Yt(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const r=t.toLowerCase().replace(/[\s-]+/g,"_");return r.includes("approval")?"awaiting approval":r.includes("generating")||r.includes("running")||r.includes("busy")?"generating":r.includes("failed")||r.includes("stopped")||r.includes("interrupted")?r.replace(/_/g," "):r.includes("idle")||r.includes("ready")||r.includes("waiting_input")?"idle":r.replace(/_/g," ")}function sk(e){var t;return((t=e.sessionDetails)==null?void 0:t.some(r=>Yt(r)==="generating"))??!1}function lo(e,t){const r=Yt(e);return r.includes("approval")?t?"border-amber-400/30 bg-amber-500/12 text-amber-100":"border-amber-300 bg-amber-50 text-amber-700":r==="generating"?t?"border-cyan-400/30 bg-cyan-500/12 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700":r==="idle"?t?"border-emerald-400/30 bg-emerald-500/12 text-emerald-100":"border-emerald-300 bg-emerald-50 text-emerald-700":r.includes("failed")||r.includes("stopped")||r.includes("interrupted")?t?"border-rose-400/30 bg-rose-500/12 text-rose-100":"border-rose-300 bg-rose-50 text-rose-700":St("health",t)}function rk(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function Oc(e){const t=rk(e);if(t===null)return"runtime age not reported";const r=Math.max(0,Math.floor((Date.now()-t)/1e3));if(r<60)return`${r}s`;const n=Math.floor(r/60);if(n<60)return`${n}m`;const a=Math.floor(n/60);return a<48?`${a}h ${n%60}m`:`${Math.floor(a/24)}d ${a%24}h`}function co(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function wr(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function nk(e){if(e.sessionDetails.length===0)return null;const t=e.sessionDetails.filter(o=>Yt(o)==="generating").length,r=e.sessionDetails.filter(o=>o.isSelfCoordinator).length,n=e.sessionDetails.length-r,a=[`${e.sessionDetails.length} chat${e.sessionDetails.length===1?"":"s"}`];return t>0&&a.push(`${t} generating`),r>0&&a.push(r===1?"coordinator attached":`${r} coordinators`),n>0&&a.push(`${n} worker${n===1?"":"s"}`),t===0&&r>0&&a.push("sampled status"),a.join(" · ")}function Hc(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function ak(e){return e.locality==="remote"?"meta":"health"}function ok({data:e,selected:t}){const r=l.useContext(Gi),n=l.useContext(nm),a=l.useContext(am),o=e.graphNode,i=o.type==="defaultBranchNode",c=o.type==="submoduleNode",d=Kp(o),u=i?"default branch anchor":c?o.submodulePath||"submodule checkout":[o.machineLabel,Hc(o.locality)].filter(Boolean).join(" · ")||o.workspace,p=o.submoduleCommit?o.submoduleCommit.slice(0,7):null,m=!c&&!i&&o.connectionState!=="self",h=m?Qp(o):null,b=h==="local"?null:h,g=m?_j(o):null,f=zi(o),v=Wi(o),j=im(o),y=o.sessionDetails,w=o.sessionDetails,N=nk(o),k=o.sessionDetails.map(S=>{const C=Yt(S),I=S.providerType||"provider unknown",R=wr(S),L=S.startedAt||S.createdAt||null,T=S.statusNote?` · ${S.statusNote}`:"";return`Session: ${S.sessionId} · ${I} · ${C} · ${R} · ${Oc(L)}${T}`});if(n)return s.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${Ec(o,t,r.isDark)}`,style:{width:zr(o,!0)},title:[o.label,o.branch?`Branch: ${o.branch}`:null,o.machineLabel?`Machine: ${o.machineLabel}`:null,o.workspace?`Workspace: ${o.workspace}`:null,f?`Status: ${f.label}`:null,zn(o),...k].filter(Boolean).join(`
|
|
74
|
+
`),children:[s.jsx(dn,{type:"target",position:a==="TB"?ds.Top:ds.Left,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-xs font-semibold leading-4 ${r.textPrimary}`,children:o.label}),!i&&s.jsx("div",{className:`truncate text-[10px] leading-3.5 ${r.textMuted}`,children:u})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[j&&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:Fc(o.health)},"aria-hidden":!0})]})]}),o.health==="unknown"&&!f&&s.jsx("div",{className:`mt-1.5 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[9px] italic ${St("health",r.isDark)}`,children:s.jsx("span",{className:"truncate",children:"Connecting..."})}),f&&s.jsx("div",{className:`mt-1.5 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[9px] font-semibold uppercase tracking-[0.14em] ${Bc(f.tone,r.isDark)}`,title:f.label,children:s.jsx("span",{className:"truncate",children:f.label})}),!f&&o.branch&&!c&&o.health!=="unknown"&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[10px] ${St("meta",r.isDark)} rounded-full border px-2 py-0.5 inline-block`,title:o.branch,children:o.branch}),N&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[9px] ${r.isDark?"text-cyan-100/85":"text-sky-700"}`,title:k.join(`
|
|
75
|
+
`),children:N}),w.length>0&&s.jsx("div",{className:"mt-1.5 flex max-h-28 min-w-0 flex-col gap-1 overflow-y-auto pr-1",children:w.map(S=>s.jsxs("div",{className:`min-w-0 rounded-md border px-1.5 py-1 ${r.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/80"}`,title:[`Session ID: ${S.sessionId}`,S.providerType?`Provider: ${S.providerType}`:null,`Status: ${Yt(S)}`,`Role: ${wr(S)}`].filter(Boolean).join(`
|
|
76
|
+
`),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-1.5",children:[s.jsx("span",{className:`min-w-0 truncate text-[9px] ${r.textMuted}`,children:S.providerType||"provider unknown"}),s.jsx("span",{className:`shrink-0 rounded-full border px-1 py-0 text-[8px] font-semibold uppercase tracking-[0.1em] ${lo(S,r.isDark)}`,children:Yt(S)})]}),s.jsxs("div",{className:`mt-0.5 flex min-w-0 items-center gap-1.5 text-[8px] ${r.textMuted}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",children:co(S.sessionId)}),s.jsx("span",{className:"shrink-0",children:wr(S)})]})]},S.sessionId))}),s.jsx(dn,{type:"source",position:a==="TB"?ds.Bottom:ds.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]});const x=[o.label,u,f?`Status: ${f.label}`:null,zn(o),o.branch?`Branch: ${o.branch}`:null,o.dirty?c?"Local changes":`${o.dirtyFiles} dirty`:null,o.hasConflicts?"Has conflicts":null,o.outOfSync?"Out of sync":null,!c&&o.upstream&&o.upstreamStatus!=="fresh"?"Upstream unverified":null,o.isOrphan?"Needs follow-up":null,d&&v?`Note: ${v}`:null,...k].filter(Boolean).join(`
|
|
77
|
+
`);return s.jsxs("div",{className:`rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all ${Ec(o,t,r.isDark)}${sk(o)?" mesh-node-generating":""}`,style:{width:zr(o)},title:x,children:[s.jsx(dn,{type:"target",position:a==="TB"?ds.Top:ds.Left,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${r.textPrimary}`,children:o.label}),s.jsx("div",{className:`truncate text-[11px] ${r.textMuted}`,children:u})]}),s.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 shrink-0",children:[j&&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:Fc(o.health)},"aria-hidden":!0})]})]}),f?s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${Bc(f.tone,r.isDark)}`,title:f.label,children:s.jsx("span",{className:"truncate",children:f.label})}):o.branch&&!c?s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[10px] ${St("meta",r.isDark)}`,title:o.branch,children:s.jsx("span",{className:"truncate",children:o.branch})}):null,N&&s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[10px] font-medium ${r.isDark?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}`,title:k.join(`
|
|
78
|
+
`),children:s.jsx("span",{className:"truncate",children:N})}),w.length>0&&s.jsx("div",{className:"mt-2 flex max-h-44 min-w-0 flex-col gap-1.5 overflow-y-auto pr-1",children:w.map(S=>{const C=wr(S);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/85"}`,title:[`Session ID: ${S.sessionId}`,S.providerType?`Provider: ${S.providerType}`:null,`Status: ${Yt(S)}`,`Role: ${C}`].filter(Boolean).join(`
|
|
79
|
+
`),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate text-[10px] ${r.textMuted}`,children:S.providerType||"provider unknown"}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${lo(S,r.isDark)}`,children:Yt(S)})]}),s.jsxs("div",{className:`mt-0.5 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",children:co(S.sessionId)}),s.jsx("span",{children:C})]})]},S.sessionId)})}),s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"flex min-w-0 flex-wrap gap-1.5 text-[10px]",children:[o.health==="unknown"?s.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${St("health",r.isDark)}`,children:"connecting..."}):s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${St("health",r.isDark)}`,children:tk(o.health)}),c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St("submodule",r.isDark)}`,children:"submodule"}),!i&&o.health==="unknown"&&!o.locality&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${St("health",r.isDark)}`,children:"..."}),!i&&(o.health!=="unknown"||o.locality)&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St(ak(o),r.isDark)}`,children:Hc(o.locality)}),b&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St("meta",r.isDark)}`,title:b==="relay"?"P2P link relayed through TURN (slower path)":`P2P transport: ${b}`,children:b}),g&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St("meta",r.isDark)}`,title:"P2P round-trip latency",children:g}),p&&c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St("meta",r.isDark)}`,children:p}),o.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St("dirty",r.isDark)}`,children:c?"local changes":`${o.dirtyFiles} dirty`}),o.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St("conflict",r.isDark)}`,children:"out of sync"}),o.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St("conflict",r.isDark)}`,children:"conflicts"}),!c&&o.upstream&&o.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St("orphan",r.isDark)}`,children:"upstream unverified"}),o.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St("orphan",r.isDark)}`,children:"needs follow-up"}),!c&&o.refineJobStatus==="completed"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${St("refineDone",r.isDark)}`,title:o.refineJobBranch?`refined ${o.refineJobBranch}${o.refineJobInto?` → ${o.refineJobInto}`:""}`:"refine completed",children:"refined"})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,style:Qj,children:zn(o)}),y.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[9px] font-semibold uppercase tracking-[0.16em] ${r.textMuted}`,children:"Attached Chats"}),s.jsx("div",{className:"flex max-h-56 flex-col gap-1.5 overflow-y-auto pr-1",children:y.map(S=>{const C=S.startedAt||S.createdAt||null,I=wr(S);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-white/8 bg-white/[0.035]":"border-slate-200 bg-white/80"}`,title:[`Session ID: ${S.sessionId}`,S.providerType?`Provider: ${S.providerType}`:null,`Status: ${Yt(S)}`,`Role: ${I}`,C?`Started: ${C}`:"Started: not reported",S.statusNote?`Note: ${S.statusNote}`:null].filter(Boolean).join(`
|
|
80
|
+
`),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono text-[10px] select-text ${r.textPrimary}`,children:co(S.sessionId)}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${lo(S,r.isDark)}`,children:Yt(S)})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"truncate",children:S.providerType||"provider unknown"}),s.jsx("span",{children:I}),s.jsx("span",{children:Oc(C)})]}),S.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${r.textMuted}`,children:S.statusNote})]},S.sessionId)})})]}),d&&v&&s.jsx("div",{className:`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${r.isDark?"border-cyan-400/15 bg-cyan-500/8 text-cyan-50/90":"border-sky-300 bg-sky-50 text-sky-700"}`,style:Zj,children:v})]}),s.jsx(dn,{type:"source",position:a==="TB"?ds.Bottom:ds.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const ik={meshNode:ok},lk=8;function ck(e){if(e.length<2)return null;if(e.length===2){const[u,p]=e;return{d:`M ${u.x},${u.y} L ${p.x},${p.y}`,labelX:(u.x+p.x)/2,labelY:(u.y+p.y)/2}}const t=lk,r=[`M ${e[0].x},${e[0].y}`];for(let u=1;u<e.length-1;u+=1){const p=e[u-1],m=e[u],h=e[u+1],b=Math.sign(m.x-p.x),g=Math.sign(m.y-p.y),f=Math.sign(h.x-m.x),v=Math.sign(h.y-m.y),j=Math.hypot(m.x-p.x,m.y-p.y),y=Math.hypot(h.x-m.x,h.y-m.y),w=Math.min(t,j/2,y/2);if(w<1||b===f&&g===v){r.push(`L ${m.x},${m.y}`);continue}const N=m.x-b*w,k=m.y-g*w,x=m.x+f*w,S=m.y+v*w;r.push(`L ${N},${k}`),r.push(`Q ${m.x},${m.y} ${x},${S}`)}const n=e[e.length-1];r.push(`L ${n.x},${n.y}`);let a=0;const o=[0];for(let u=1;u<e.length;u+=1)a+=Math.hypot(e[u].x-e[u-1].x,e[u].y-e[u-1].y),o.push(a);const i=a/2;let c=e[0].x,d=e[0].y;for(let u=1;u<e.length;u+=1)if(o[u]>=i){const p=o[u]-o[u-1],m=p===0?0:(i-o[u-1])/p;c=e[u-1].x+(e[u].x-e[u-1].x)*m,d=e[u-1].y+(e[u].y-e[u-1].y)*m;break}return{d:r.join(" "),labelX:c,labelY:d}}function dk(e){const t=e.data.routePoints;if(t&&t.length>=2){const o=ck(t);if(o)return[o.d,o.labelX,o.labelY]}const r={sourceX:e.sourceX,sourceY:e.sourceY,sourcePosition:e.sourcePosition,targetX:e.targetX,targetY:e.targetY,targetPosition:e.targetPosition},n=e.data.graphEdge;let a;return n.type==="parentBranch"?a=vh(r):n.type==="worktreeLink"||n.type==="submoduleLink"||n.type==="cloneLink"?a=gh(r):a=yh(r),[a[0],a[1],a[2]]}function uk(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 pk(e){const t=l.useContext(Gi),r=e.data.graphEdge,[n,a,o]=dk(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(mh,{id:e.id,path:n,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(hh,{children:s.jsx("div",{className:uk(r,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${a}px, ${o}px)`,pointerEvents:"none",maxWidth:pj.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const mk={meshEdge:pk};async function hk(e,t,r,n,a){const o=await qp(e,r,n,a);return lm(e,o,t,r)}async function fk(e,t=Fs("dark"),r=!1,n="LR"){const a=await qp(e,r,n);return lm(e,a,t,r)}function lm(e,t,r,n=!1){const a=new Set(t.nodes.map(u=>u.id)),o=t.nodes.map(u=>({id:u.id,type:u.type,position:u.position,data:{graphNode:u.graphNode,compact:n},selected:u.selected,draggable:u.draggable,selectable:u.selectable})),i=e.edges.filter(u=>a.has(u.source)&&a.has(u.target)),c=gk(i),d=i.map(u=>{var p;return{id:u.id,source:u.source,target:u.target,label:c.has(u.id)?u.label:void 0,type:"meshEdge",data:{graphEdge:u,routePoints:(p=t.edgeRoutes.get(u.id))==null?void 0:p.points},animated:u.type==="orphanLink",markerEnd:u.direction==="directed"?{type:bh.ArrowClosed,width:u.type==="submoduleLink"?16:18,height:u.type==="submoduleLink"?16:18,color:Wc(u)}:void 0,style:{stroke:Wc(u),strokeWidth:u.type==="orphanLink"?2.25:u.type==="submoduleLink"?1.7:u.type==="worktreeLink"?1.8:u.type==="cloneLink"?1.6:2,strokeDasharray:u.type==="orphanLink"?"5 4":u.type==="submoduleLink"?"4 3":u.type==="cloneLink"?"6 3":void 0},labelStyle:{fill:r.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:r.edgeLabelBackgroundColor,fillOpacity:1,stroke:r.edgeLabelBorderColor},labelBgPadding:[6,4],labelBgBorderRadius:7}});return{nodes:o,edges:d}}const xk=3,bk=2;function zc(e){switch(e.type){case"orphanLink":return 5;case"parentBranch":return 4;case"submoduleLink":return 3;case"cloneLink":return 2;case"worktreeLink":return 1;case"sessionLink":return 0;default:return 0}}function gk(e){const t=new Set,r=new Map;for(const n of e){if(!n.label)continue;const a=r.get(n.source);a?a.push(n):r.set(n.source,[n])}for(const n of r.values()){if(n.length<xk){for(const o of n)t.add(o.id);continue}const a=[...n].sort((o,i)=>{const c=zc(i)-zc(o);return c!==0?c:o.id.localeCompare(i.id)});for(const o of a.slice(0,bk))t.add(o.id)}return t}function Wc(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 yk(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 vk(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 wk({data:e,viewportKey:t}){const r=fh(),n=xh(),a=l.useRef(null),o=l.useMemo(()=>Up(e),[e]),i=l.useMemo(()=>oj(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 u=i.length>0&&i.length<e.nodes.length;n.fitView({nodes:u?i.map(p=>({id:p})):void 0,padding:u?.24:.2,maxZoom:u?.98:.9,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(d)}},[e.nodes.length,i,o,r,n,t]),null}const jk=12;function kk(e){return e>=16?"min-h-[720px]":e>=10?"min-h-[580px]":"min-h-[460px]"}function Nk({data:e,selectedNodeId:t=null,directionPref:r,onNodeClick:n,onEdgeClick:a,onNodeHoverChange:o,onEdgeHoverChange:i}){const{theme:c}=Bs(),d=l.useMemo(()=>Fs(c),[c]),u=l.useMemo(()=>Cj(e),[e]),p=l.useMemo(()=>Ij(e),[e]),m=e.nodes.length>=Xj,[h]=l.useState("LR"),b=r??h,g=l.useMemo(()=>b==="auto"?fj(e):b,[b,u,e]),f=e.nodes.length>=jk,[v,j]=l.useState({nodes:[],edges:[]}),y=l.useRef(null),[w,N]=l.useState({width:0,height:0}),k=l.useMemo(()=>`${ij(e,w.width,w.height)}::${g}`,[u,e,w.height,w.width,g]);l.useEffect(()=>{let S=!1;return fk(e,d,m,g).then(C=>{if(S)return;j(C);const I=requestAnimationFrame(()=>{if(S)return;const R=y.current;if(!R)return;const L=new Map;for(const T of C.nodes){const _=R.querySelector(`.react-flow__node[data-id="${CSS.escape(T.id)}"]`);_&&_.offsetHeight>0&&L.set(T.id,_.offsetHeight)}L.size!==0&&hk(e,d,m,g,L).then(T=>{S||j(T)})});return()=>cancelAnimationFrame(I)}),()=>{S=!0}},[e,p,d,m,g]);const x=l.useMemo(()=>v.nodes.map(S=>({...S,selected:S.id===t})),[v.nodes,t]);return l.useEffect(()=>{const S=y.current;if(!S)return;const C=()=>{const R=Math.max(0,Math.round(S.clientWidth)),L=Math.max(0,Math.round(S.clientHeight));N(T=>T.width===R&&T.height===L?T:{width:R,height:L})};C();const I=typeof ResizeObserver=="function"?new ResizeObserver(()=>C()):null;return I==null||I.observe(S),window.addEventListener("resize",C),()=>{I==null||I.disconnect(),window.removeEventListener("resize",C)}},[]),s.jsx(Gi.Provider,{value:d,children:s.jsx(nm.Provider,{value:m,children:s.jsx(am.Provider,{value:g,children:s.jsxs("div",{ref:y,className:`${d.graphShellClass} ${kk(e.nodes.length)}`,style:{height:"100%"},children:[s.jsx("div",{className:`pointer-events-none absolute left-1/2 top-2 z-10 -translate-x-1/2 px-3 py-1 text-[10px] ${d.graphStatChipClass}`,children:"drag or scroll to pan"}),s.jsx("div",{className:"w-full min-w-0 flex-1",style:{height:"100%"},children:s.jsxs(lh,{nodes:x,edges:v.edges,nodeTypes:ik,edgeTypes:mk,minZoom:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(S,C)=>n==null?void 0:n(C.data.graphNode),onEdgeClick:(S,C)=>{var R;const I=(R=C.data)==null?void 0:R.graphEdge;I&&(a==null||a(I))},onNodeMouseEnter:(S,C)=>o==null?void 0:o(C.data.graphNode),onNodeMouseLeave:()=>o==null?void 0:o(null),onEdgeMouseEnter:(S,C)=>{var I;return i==null?void 0:i(((I=C.data)==null?void 0:I.graphEdge)??null)},onEdgeMouseLeave:()=>i==null?void 0:i(null),className:"h-full w-full",colorMode:d.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(wk,{data:e,viewportKey:k}),s.jsx(ch,{className:d.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),f&&s.jsx(dh,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:yk,nodeClassName:vk,nodeStrokeWidth:3,className:d.isDark?"overflow-hidden rounded-xl border border-white/10 bg-slate-950/85":"overflow-hidden rounded-xl border border-slate-200 bg-white/95"}),s.jsx(uh,{variant:ph.Dots,gap:18,size:1.2,color:d.graphBackgroundDotColor})]})})]})})})})}const Sk=5,Ck={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function Na(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function cm(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const r=t.toLowerCase().replace(/[\s-]+/g,"_");return r.includes("approval")?"awaiting approval":r.includes("generating")||r.includes("running")||r.includes("busy")?"generating":r.includes("idle")||r.includes("ready")||r.includes("waiting_input")?"idle":r.replace(/_/g," ")}function dm(e){return e.includes("approval")?"amber":e.includes("generating")?"sky":e.includes("idle")?"emerald":e.includes("failed")||e.includes("stopped")||e.includes("interrupted")?"rose":"muted"}function Ik(e){const t=e.git;if(!t)return e.gitProbePending?"git probe pending":"no git probe";const r=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),n=[];return t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&n.push(`↑${t.ahead??0}/↓${t.behind??0}`),r>0&&n.push(`✎${r}`),t.hasConflicts&&n.push("conflicts"),n.join(" · ")||"clean"}function um(e){switch(e){case"active":return"emerald";case"paused":return"amber";case"completed":return"sky";case"abandoned":return"rose";default:return"muted"}}function Mk(e){switch(e){case"online":return"emerald";case"dirty":return"amber";case"degraded":case"offline":return"rose";case"wrong_branch":return"sky";default:return"muted"}}function pm(e){switch(e){case"completed":return"emerald";case"failed":return"rose";case"cancelled":return"muted";case"assigned":return"sky";case"pending":return"amber";default:return"muted"}}function Kc(e){switch(e){case"assigned":return 0;case"pending":return 1;case"failed":return 2;case"completed":return 3;case"cancelled":return 4;default:return 5}}function Vt(e){if(!e)return null;const t=Date.parse(e);if(!Number.isFinite(t))return null;const r=Math.max(0,Math.floor((Date.now()-t)/1e3));if(r<60)return`${r}s ago`;const n=Math.floor(r/60);if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<48?`${a}h ago`:`${Math.floor(a/24)}d ago`}function Uc(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return null;if(e<1e3)return`${Math.round(e)}ms`;const t=Math.round(e/1e3),r=t%60,n=Math.floor(t/60),a=n%60,o=Math.floor(n/60),i=[];return o>0&&i.push(`${o}h`),a>0&&i.push(`${a}m`),(r>0||i.length===0)&&i.push(`${r}s`),i.join(" ")}function Vi(e){return e.replace(/[_-]+/g," ")}function mm(e){const t=e.toLowerCase();return t.includes("fail")||t.includes("stall")||t.includes("error")?"rose":t.includes("complete")?"emerald":t.includes("dispatch")||t.includes("launch")||t.includes("assign")?"sky":t.includes("checkpoint")?"amber":"muted"}function hm(e){if(!e)return null;const t=e.message??e.summary??e.reason??e.title;return typeof t=="string"&&t.trim()?t.trim():null}function Ak({status:e}){var v,j,y,w;const{theme:t}=Bs(),r=l.useMemo(()=>Fs(t),[t]),n=l.useMemo(()=>yi(e),[e]),a=((v=n.queue)==null?void 0:v.summary)??null,o=((j=n.queue)==null?void 0:j.tasks)??[],i=((y=n.ledger)==null?void 0:y.summary)??Ck,c=((w=n.ledger)==null?void 0:w.entries)??[],d=n.missions??[],u=d.filter(N=>N.status==="active"||N.status==="paused"),p=d.filter(N=>N.status==="completed"||N.status==="abandoned"),m=n.asyncRefineJobs??[],[h,b]=l.useState(null),g=l.useCallback(()=>b(null),[]),f=l.useMemo(()=>{const N=[];for(const k of n.nodes){const x=k.activeSessionDetails&&k.activeSessionDetails.length>0?k.activeSessionDetails:(k.activeSessions??[]).map(S=>({sessionId:S,workspace:k.workspace,isCached:!0}));for(const S of x)N.push({node:k,session:S})}return N},[n.nodes]);return s.jsxs("div",{className:"flex flex-col gap-3 pb-2",children:[s.jsx($k,{meshTheme:r,liveMissions:u,historyMissions:p,hasMissionField:Array.isArray(n.missions),onSelect:N=>b({kind:"mission",mission:N})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(Ek,{meshTheme:r,ledgerSummary:i,entries:c,onSelect:N=>b({kind:"ledger",entry:N})}),s.jsx(Bk,{meshTheme:r,queueSummary:a,tasks:o,onSelect:N=>b({kind:"queue",task:N})})]}),s.jsx(Ok,{meshTheme:r,nodes:n.nodes}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(Hk,{meshTheme:r,entries:f,onSelect:(N,k)=>b({kind:"session",node:N,session:k})}),s.jsx(zk,{meshTheme:r,jobs:m})]}),h&&s.jsx(_k,{meshTheme:r,detail:h,onClose:g})]})}function Ls({meshTheme:e,title:t,count:r,children:n,action:a}){const o=e.isDark;return s.jsxs("div",{className:`flex min-w-0 flex-col overflow-hidden rounded-2xl border p-4 ${o?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,children:[s.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[s.jsx("span",{className:`text-[11px] font-semibold uppercase tracking-[0.14em] ${e.textSecondary}`,children:t}),r!==void 0&&s.jsx("span",{className:`tabular-nums text-[11px] ${e.textMuted}`,children:r}),a&&s.jsx("span",{className:"ml-auto",children:a})]}),n]})}function Lt({meshTheme:e,label:t,tone:r}){const n=e.isDark,a=r==="rose"?n?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700":r==="sky"?n?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700":r==="amber"?n?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700":r==="emerald"?n?"border-emerald-400/25 bg-emerald-500/10 text-emerald-200":"border-emerald-300 bg-emerald-50 text-emerald-700":n?"border-white/10 bg-white/[0.04] text-slate-300":"border-slate-200 bg-slate-50 text-slate-600";return s.jsx("span",{className:`shrink-0 rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${a}`,children:t})}function gt({meshTheme:e,label:t,value:r,tone:n}){const a=e.isDark,o=n==="rose"?a?"text-rose-300":"text-rose-600":n==="sky"?a?"text-sky-300":"text-sky-600":n==="amber"?a?"text-amber-300":"text-amber-600":n==="emerald"?a?"text-emerald-300":"text-emerald-600":n==="muted"?e.textMuted:e.textPrimary;return s.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-2 ${a?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[s.jsx("span",{className:`tabular-nums text-base font-semibold leading-none ${o}`,children:r}),s.jsx("span",{className:`mt-1 text-[9px] uppercase tracking-wide ${e.textMuted}`,children:t})]})}function en({meshTheme:e,children:t}){return s.jsx("div",{className:`text-xs ${e.textMuted}`,children:t})}function Sa({meshTheme:e,onClick:t,children:r}){const n=e.isDark,a=t?n?"hover:bg-white/[0.05]":"hover:bg-slate-100/70":"";return s.jsx("button",{type:"button",onClick:t,disabled:!t,className:`flex w-full min-w-0 items-center gap-2 overflow-hidden rounded-md px-1.5 py-1 text-left text-xs transition ${a} ${t?"cursor-pointer":"cursor-default"}`,children:r})}function Ca({meshTheme:e,expanded:t,hiddenCount:r,onToggle:n}){return r<=0?null:s.jsx("button",{type:"button",onClick:n,className:`mt-1 self-start rounded-md px-1.5 py-0.5 text-[11px] font-medium ${e.textSecondary} hover:underline`,children:t?"Show fewer":`+${r} more`})}function Ia(e,t=Sk){const[r,n]=l.useState(!1),a=r?e:e.slice(0,t),o=Math.max(0,e.length-t),i=l.useCallback(()=>n(c=>!c),[]);return{visible:a,hiddenCount:o,expanded:r,toggle:i}}function ut({meshTheme:e,label:t,value:r}){return s.jsxs("div",{className:e.rowClass,children:[s.jsx("span",{className:e.rowLabelClass,children:t}),s.jsx("span",{className:e.rowValueClass,children:r})]})}function Tk(e){switch(e.kind){case"mission":return{kicker:"Mission",title:e.mission.title};case"ledger":return{kicker:"Ledger entry",title:Vi(e.entry.kind)};case"queue":return{kicker:"Queue task",title:e.task.id};case"session":return{kicker:"Session",title:Na(e.session.sessionId)}}}function _k({meshTheme:e,detail:t,onClose:r}){l.useEffect(()=>{const d=u=>{u.key==="Escape"&&r()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[r]);const n=e.isDark,{kicker:a,title:o}=Tk(t),i=n?"bg-[#030617]/[0.92]":"bg-[rgba(15,23,42,0.82)]",c=n?"border-white/10 bg-slate-950 md:bg-slate-950/98 shadow-[0_28px_120px_rgba(2,6,23,0.5)]":"border-slate-200 bg-white md:bg-white/98 shadow-[0_28px_120px_rgba(148,163,184,0.3)]";return s.jsx("div",{className:`fixed inset-0 z-[1300] flex items-stretch justify-center p-0 md:items-center md:p-4 ${i}`,role:"dialog","aria-modal":"true",onClick:r,children:s.jsxs("div",{className:`flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden border ${c} md:h-auto md:max-h-[88dvh] md:max-w-[min(640px,calc(100vw-32px))] md:rounded-2xl`,onClick:d=>d.stopPropagation(),children:[s.jsxs("div",{className:`sticky top-0 z-10 flex shrink-0 items-start justify-between gap-3 border-b px-4 py-3 ${n?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:a}),s.jsx("div",{className:`mt-0.5 break-all text-sm font-semibold ${e.textPrimary}`,children:o})]}),s.jsx("button",{type:"button",onClick:r,"aria-label":"Close detail",className:n?"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white":"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",children:"✕"})]}),s.jsxs("div",{className:"min-h-0 min-w-0 flex-1 overflow-y-auto px-4 py-4",children:[t.kind==="mission"&&s.jsx(Rk,{meshTheme:e,mission:t.mission}),t.kind==="ledger"&&s.jsx(Pk,{meshTheme:e,entry:t.entry}),t.kind==="queue"&&s.jsx(Lk,{meshTheme:e,task:t.task}),t.kind==="session"&&s.jsx(Dk,{meshTheme:e,node:t.node,session:t.session})]})]})})}function Rk({meshTheme:e,mission:t}){var c;const r=t.tasks,n="goal"in t&&typeof t.goal=="string"&&t.goal?t.goal:"goalPreview"in t?t.goalPreview:"",a="goalTruncated"in t?t.goalTruncated===!0:!1,o=t.stats??null,i=((c=o==null?void 0:o.incompleteTaskIds)==null?void 0:c.length)??0;return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Lt,{meshTheme:e,label:t.status,tone:um(t.status)}),s.jsx(Lt,{meshTheme:e,label:`${r.total} tasks`,tone:"muted"})]}),n&&s.jsxs("div",{className:`max-h-64 overflow-y-auto whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:[n,a&&s.jsx("span",{className:e.textMuted,children:" … (truncated)"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5 sm:grid-cols-6",children:[s.jsx(gt,{meshTheme:e,label:"Completed",value:r.completed,tone:"emerald"}),s.jsx(gt,{meshTheme:e,label:"Assigned",value:r.assigned,tone:r.assigned>0?"sky":void 0}),s.jsx(gt,{meshTheme:e,label:"Pending",value:r.pending}),s.jsx(gt,{meshTheme:e,label:"Failed",value:r.failed,tone:r.failed>0?"rose":void 0}),s.jsx(gt,{meshTheme:e,label:"Blocked",value:r.blocked,tone:r.blocked>0?"amber":void 0}),s.jsx(gt,{meshTheme:e,label:"Cancelled",value:r.cancelled,tone:"muted"})]}),o&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(gt,{meshTheme:e,label:"Wall clock",value:Uc(o.wallClockMs)??"—"}),s.jsx(gt,{meshTheme:e,label:"Total runtime",value:Uc(o.totalDurationMs)??"—"}),s.jsx(gt,{meshTheme:e,label:"Retries",value:o.retries,tone:o.retries>0?"amber":void 0})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ut,{meshTheme:e,label:"Mission id",value:t.id}),s.jsx(ut,{meshTheme:e,label:"Created",value:Vt(t.createdAt)??t.createdAt}),s.jsx(ut,{meshTheme:e,label:"Updated",value:Vt(t.updatedAt)??t.updatedAt}),r.lastActivityAt&&s.jsx(ut,{meshTheme:e,label:"Last task activity",value:Vt(r.lastActivityAt)??r.lastActivityAt}),i>0&&o&&s.jsx(ut,{meshTheme:e,label:"Incomplete evidence",value:s.jsxs("details",{children:[s.jsxs("summary",{className:"cursor-pointer select-none",children:[i," task",i===1?"":"s"]}),s.jsx("div",{className:"mt-1 flex flex-col gap-0.5 break-all",children:o.incompleteTaskIds.map(d=>s.jsx("span",{className:`font-mono text-[10px] ${e.textMuted}`,children:d},d))})]})})]})]})}function Pk({meshTheme:e,entry:t}){const r=hm(t.payload);let n="";try{n=JSON.stringify(t.payload??{},null,2)}catch{n=String(t.payload)}return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:s.jsx(Lt,{meshTheme:e,label:Vi(t.kind),tone:mm(t.kind)})}),r&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:r}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ut,{meshTheme:e,label:"Entry id",value:t.id}),s.jsx(ut,{meshTheme:e,label:"When",value:Vt(t.timestamp)??t.timestamp}),t.nodeId&&s.jsx(ut,{meshTheme:e,label:"Node",value:t.nodeId}),t.sessionId&&s.jsx(ut,{meshTheme:e,label:"Session",value:Na(t.sessionId)}),t.providerType&&s.jsx(ut,{meshTheme:e,label:"Provider",value:t.providerType})]}),n&&n!=="{}"&&s.jsxs("div",{children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:"Payload"}),s.jsx("pre",{className:`max-h-60 max-w-full overflow-auto rounded-lg border p-2 text-[10px] leading-4 ${e.isDark?"border-white/8 bg-black/30 text-slate-300":"border-slate-200 bg-slate-50 text-slate-700"}`,children:n})]})]})}function Lk({meshTheme:e,task:t}){return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Lt,{meshTheme:e,label:t.status,tone:pm(t.status)}),(t.requeueCount??0)>0&&s.jsx(Lt,{meshTheme:e,label:`requeued ${t.requeueCount}`,tone:"amber"})]}),t.message&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:t.message}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ut,{meshTheme:e,label:"Task id",value:t.id}),s.jsx(ut,{meshTheme:e,label:"Created",value:Vt(t.createdAt)??t.createdAt}),s.jsx(ut,{meshTheme:e,label:"Updated",value:Vt(t.updatedAt)??t.updatedAt}),(t.assignedNodeId||t.targetNodeId)&&s.jsx(ut,{meshTheme:e,label:"Node",value:t.assignedNodeId||t.targetNodeId}),(t.assignedSessionId||t.targetSessionId)&&s.jsx(ut,{meshTheme:e,label:"Session",value:Na(t.assignedSessionId||t.targetSessionId)}),t.cancelReason&&s.jsx(ut,{meshTheme:e,label:"Cancel reason",value:t.cancelReason}),t.requeueReason&&s.jsx(ut,{meshTheme:e,label:"Requeue reason",value:t.requeueReason}),t.autoLaunch&&s.jsx(ut,{meshTheme:e,label:"Auto launch",value:`${t.autoLaunch.status}${t.autoLaunch.reason?` · ${t.autoLaunch.reason}`:""}`})]})]})}function Dk({meshTheme:e,node:t,session:r}){var a,o;const n=cm(r);return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Lt,{meshTheme:e,label:n,tone:dm(n)}),s.jsx(Lt,{meshTheme:e,label:r.providerType||"provider unknown",tone:"muted"})]}),r.statusNote&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:r.statusNote}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ut,{meshTheme:e,label:"Session id",value:r.sessionId}),s.jsx(ut,{meshTheme:e,label:"Node",value:t.machineLabel}),s.jsx(ut,{meshTheme:e,label:"Workspace",value:r.workspace||t.workspace}),(((a=t.git)==null?void 0:a.branch)??t.worktreeBranch)&&s.jsx(ut,{meshTheme:e,label:"Branch",value:((o=t.git)==null?void 0:o.branch)??t.worktreeBranch}),typeof r.role=="string"&&r.role&&s.jsx(ut,{meshTheme:e,label:"Role",value:r.role}),(r.startedAt||r.createdAt)&&s.jsx(ut,{meshTheme:e,label:"Started",value:Vt(r.startedAt||r.createdAt)??(r.startedAt||r.createdAt)})]})]})}function Gc({meshTheme:e,mission:t,onSelect:r}){const n=t.tasks,a=Vt(n.lastActivityAt);return s.jsxs(Sa,{meshTheme:e,onClick:r,children:[s.jsx(Lt,{meshTheme:e,label:t.status,tone:um(t.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate font-medium ${e.textPrimary}`,children:t.title}),s.jsxs("span",{className:`shrink-0 tabular-nums text-[11px] ${e.textMuted}`,children:["✓",n.completed,"/",n.total]}),a&&s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:a})]})}function $k({meshTheme:e,liveMissions:t,historyMissions:r,hasMissionField:n,onSelect:a}){const[o,i]=l.useState(!1),c=e.isDark,d=Ia(t);return s.jsxs(Ls,{meshTheme:e,title:"Missions",count:t.length||void 0,children:[t.length>0?s.jsxs("div",{className:"flex flex-col gap-0.5",children:[d.visible.map(u=>s.jsx(Gc,{meshTheme:e,mission:u,onSelect:()=>a(u)},u.id)),s.jsx(Ca,{meshTheme:e,expanded:d.expanded,hiddenCount:d.hiddenCount,onToggle:d.toggle})]}):s.jsx(en,{meshTheme:e,children:n?"No active missions. The coordinator creates a mission for multi-task work.":"Mission data unavailable from this daemon — update the daemon to see missions."}),r.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${c?"border-white/8":"border-slate-200"}`,children:[s.jsxs("button",{type:"button",onClick:()=>i(u=>!u),className:`flex w-full items-center gap-1.5 text-[11px] font-medium ${e.textSecondary}`,children:[s.jsx("span",{className:`inline-block transition-transform ${o?"rotate-90":""}`,children:"▸"}),s.jsx("span",{children:"Completed / abandoned history"}),s.jsx("span",{className:`tabular-nums ${e.textMuted}`,children:r.length})]}),o&&s.jsx("div",{className:"mt-2 flex flex-col gap-0.5",children:r.map(u=>s.jsx(Gc,{meshTheme:e,mission:u,onSelect:()=>a(u)},u.id))})]})]})}function Ek({meshTheme:e,ledgerSummary:t,entries:r,onSelect:n}){const a=Vt(t.lastActivityAt),o=l.useMemo(()=>[...r].reverse(),[r]),i=Ia(o);return s.jsxs(Ls,{meshTheme:e,title:"Ledger",children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(gt,{meshTheme:e,label:"Dispatched",value:t.taskDispatched}),s.jsx(gt,{meshTheme:e,label:"Completed",value:t.taskCompleted,tone:"emerald"}),s.jsx(gt,{meshTheme:e,label:"Failed",value:t.taskFailed,tone:t.taskFailed>0?"rose":void 0}),s.jsx(gt,{meshTheme:e,label:"Stalled",value:t.taskStalled,tone:t.taskStalled>0?"amber":void 0}),s.jsx(gt,{meshTheme:e,label:"Sessions",value:t.sessionLaunched}),s.jsx(gt,{meshTheme:e,label:"Checkpoints",value:t.checkpointCreated})]}),o.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:"Recent activity"}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[i.visible.map(c=>{const d=hm(c.payload);return s.jsxs(Sa,{meshTheme:e,onClick:()=>n(c),children:[s.jsx(Lt,{meshTheme:e,label:Vi(c.kind),tone:mm(c.kind)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,children:d||c.nodeId||c.sessionId||"—"}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:Vt(c.timestamp)??""})]},c.id)}),s.jsx(Ca,{meshTheme:e,expanded:i.expanded,hiddenCount:i.hiddenCount,onToggle:i.toggle})]})]}),(t.recentFailures>0||a&&o.length===0)&&s.jsxs("div",{className:`mt-2 flex items-center justify-between text-[11px] ${e.textMuted}`,children:[t.recentFailures>0?s.jsxs("span",{className:e.isDark?"text-amber-300":"text-amber-600",children:[t.recentFailures," recent failures"]}):s.jsx("span",{}),a&&o.length===0&&s.jsx("span",{children:a})]})]})}function Bk({meshTheme:e,queueSummary:t,tasks:r,onSelect:n}){const a=l.useMemo(()=>[...r].sort((i,c)=>{const d=Kc(i.status)-Kc(c.status);return d!==0?d:(c.updatedAt||"").localeCompare(i.updatedAt||"")}),[r]),o=Ia(a);return t?s.jsxs(Ls,{meshTheme:e,title:"Queue",count:t.active>0?`${t.active} active`:void 0,children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(gt,{meshTheme:e,label:"Pending",value:t.pending}),s.jsx(gt,{meshTheme:e,label:"Assigned",value:t.assigned,tone:t.assigned>0?"sky":void 0}),s.jsx(gt,{meshTheme:e,label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(gt,{meshTheme:e,label:"Completed",value:t.completed,tone:"emerald"}),s.jsx(gt,{meshTheme:e,label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0}),s.jsx(gt,{meshTheme:e,label:"Cancelled",value:t.cancelled,tone:"muted"})]}),a.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:"Recent tasks"}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.visible.map(i=>s.jsxs(Sa,{meshTheme:e,onClick:()=>n(i),children:[s.jsx(Lt,{meshTheme:e,label:i.status,tone:pm(i.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,children:i.message||i.id}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:Vt(i.updatedAt)??""})]},i.id)),s.jsx(Ca,{meshTheme:e,expanded:o.expanded,hiddenCount:o.hiddenCount,onToggle:o.toggle})]})]})]}):s.jsx(Ls,{meshTheme:e,title:"Queue",children:s.jsx(en,{meshTheme:e,children:"No queue activity."})})}function Fk(e){return e.autoFastForwardEligible||e.suggestedAction==="auto_fast_forward"?{label:"fast-forward",tone:"sky"}:e.launchBlockedReason?{label:"blocked",tone:"rose"}:null}function Ok({meshTheme:e,nodes:t}){const r=e.isDark;return s.jsx(Ls,{meshTheme:e,title:"Nodes",count:t.length,children:t.length===0?s.jsx(en,{meshTheme:e,children:"No nodes in this mesh yet."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:t.map(n=>{var c,d,u;const a=(((c=n.activeSessionDetails)==null?void 0:c.length)??0)||(((d=n.activeSessions)==null?void 0:d.length)??0),o=Fk(n),i=((u=n.git)==null?void 0:u.branch)??n.worktreeBranch??null;return s.jsxs("div",{className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 overflow-hidden rounded-xl border px-3 py-2 ${r?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx(Lt,{meshTheme:e,label:n.health,tone:Mk(n.health)}),s.jsx("span",{className:`min-w-0 max-w-full flex-1 truncate text-sm font-medium ${e.textPrimary}`,title:n.workspace,children:n.machineLabel}),i&&s.jsx("span",{className:`max-w-full truncate font-mono text-[11px] ${e.textSecondary}`,title:i,children:i}),s.jsx("span",{className:`max-w-full truncate font-mono text-[10px] ${e.textMuted}`,children:Ik(n)}),a>0&&s.jsxs("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:[a," session",a>1?"s":""]}),o&&s.jsx(Lt,{meshTheme:e,label:o.label,tone:o.tone})]},n.nodeId)})})})}function Hk({meshTheme:e,entries:t,onSelect:r}){const n=Ia(t);return s.jsx(Ls,{meshTheme:e,title:"Active sessions",count:t.length||void 0,children:t.length===0?s.jsx(en,{meshTheme:e,children:"No active sessions."}):s.jsxs("div",{className:"flex flex-col gap-0.5",children:[n.visible.map(({node:a,session:o})=>{const i=cm(o);return s.jsxs(Sa,{meshTheme:e,onClick:()=>r(a,o),children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:Na(o.sessionId)}),s.jsx("span",{className:`shrink-0 ${e.textMuted}`,children:o.providerType||"?"}),s.jsx(Lt,{meshTheme:e,label:i,tone:dm(i)})]},o.sessionId)}),s.jsx(Ca,{meshTheme:e,expanded:n.expanded,hiddenCount:n.hiddenCount,onToggle:n.toggle})]})})}function zk({meshTheme:e,jobs:t}){const r=e.isDark,n=t.filter(a=>a.status==="failed").length;return s.jsx(Ls,{meshTheme:e,title:"Refine jobs",count:t.length||void 0,action:n>0?s.jsx(Lt,{meshTheme:e,label:`${n} failed`,tone:"rose"}):void 0,children:t.length===0?s.jsx(en,{meshTheme:e,children:"No refine jobs."}):s.jsx("div",{className:"flex flex-col gap-1",children:t.slice(0,8).map(a=>s.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:[a.branch??a.jobId.slice(0,14),a.into?` → ${a.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[10px] font-semibold ${a.status==="failed"?r?"text-rose-300":"text-rose-600":a.status==="running"||a.status==="accepted"?r?"text-sky-300":"text-sky-600":r?"text-emerald-300":"text-emerald-600"}`,children:a.status})]},a.jobId))})})}const Wk=[{term:"Node",summary:"A workspace participating in the mesh — a repo checkout or an isolated git worktree.",details:["Base node vs worktree clone node — a clone isolates parallel work without conflicts.","Shows health (online/offline) alongside git state (branch · ahead/behind · dirty).","Multiple nodes can share the same daemon."]},{term:"P2P connection",summary:"How the selected coordinator reaches each remote node over WebRTC.",details:["direct — a direct host/STUN path; lowest latency.","relay — TURN-relayed; works through restrictive networks but is slower.","disconnected / failed — no live P2P link from the coordinator right now.","P2P connectivity is shown as transport and RTT chips on each node card (and in the node detail panel), not as a graph edge."]},{term:"Session",summary:"An agent CLI session running on a node.",details:["status = idle / generating / waiting_approval.","Distinguishes coordinator sessions (which dispatch and collect work) from delegated worker sessions (which do the work)."]},{term:"Task",summary:"A single unit of work handled by the queue-based pull model.",details:["States: pending → assigned → completed / failed / cancelled.","Idle nodes claim from the queue automatically; direct dispatch targets a specific session."]},{term:"Mission",summary:"A multi-task batch aimed at one goal, and the durable record of that effort.",details:["States: active / paused / completed / abandoned.","Progress is derived from the states of its member tasks."]},{term:"Refinery (refine)",summary:"The process of safely converging and merging a worktree branch into the base.",details:["Config-driven (.adhdev/refine.*) — guarded by a patch-equivalence preflight and a no-op guard.","ff-only by principle; no force-push.","If a submodule commit is unreachable from origin it must be published → classified as blocked_review."]},{term:"Completion model",summary:"Completion of delegated work is persisted to the queue (pending-events).",details:["The coordinator learns of completion via periodic polling or events.","Because it is persisted to the queue, completion signals are never lost."]},{term:"Branch convergence states",summary:"After worktree work, each branch is classified into exactly one final state.",details:["merged_to_main — merged into the base.","pushed_feature_branch_needs_merge — pushed, awaiting merge.","blocked_review — held back by review/reachability issues.","cleanup_candidate — ready to clean up.","not_mergeable — cannot be merged."]}];function Kk({meshTheme:e,open:t,onToggle:r}){const n=e.isDark,a="inline-flex h-7 w-7 items-center justify-center rounded-lg border transition",o=t?n?"border-sky-400/40 bg-sky-500/15 text-sky-100":"border-sky-400 bg-sky-100 text-sky-800":n?"border-white/10 bg-white/[0.04] text-slate-400 hover:bg-white/[0.08] hover:text-slate-100":"border-slate-200 bg-white text-slate-400 hover:bg-slate-50 hover:text-slate-700";return s.jsx("button",{type:"button",onClick:r,"aria-label":"Mesh help","aria-expanded":t,title:"Mesh concept help",className:`${a} ${o}`,children:s.jsx(ef,{size:15})})}function Uk({meshTheme:e,onClose:t}){const r=e.isDark;return l.useEffect(()=>{const n=a=>{a.key==="Escape"&&t()};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[t]),s.jsxs("div",{className:`shrink-0 rounded-2xl border p-4 ${r?"border-white/10 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,role:"region","aria-label":"Mesh concept help",children:[s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:"Help"}),s.jsx("div",{className:`mt-0.5 text-sm font-semibold ${e.textPrimary}`,children:"Mesh concepts at a glance"})]}),s.jsx("button",{type:"button",onClick:t,"aria-label":"Close help",className:r?"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white":"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",children:s.jsx(vt,{size:14})})]}),s.jsx("dl",{className:"grid gap-3 sm:grid-cols-2",children:Wk.map(n=>s.jsxs("div",{className:`rounded-xl border p-3 ${r?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx("dt",{className:`text-xs font-semibold ${e.textPrimary}`,children:n.term}),s.jsx("dd",{className:`mt-1 text-[11px] leading-5 ${e.textSecondary}`,children:n.summary}),n.details&&n.details.length>0&&s.jsx("ul",{className:`mt-1.5 flex flex-col gap-1 text-[11px] leading-5 ${e.textMuted}`,children:n.details.map((a,o)=>s.jsxs("li",{className:"flex gap-1.5",children:[s.jsx("span",{"aria-hidden":!0,className:"select-none",children:"·"}),s.jsx("span",{className:"min-w-0",children:a})]},o))})]},n.term))})]})}function fm({meshTheme:e,activeTab:t,onActiveTabChange:r,helpOpen:n,onHelpOpenChange:a}){const o=i=>i?e.isDark?"rounded-lg px-3.5 py-1.5 text-xs font-semibold text-slate-100 bg-white/[0.08] border border-white/12":"rounded-lg px-3.5 py-1.5 text-xs font-semibold text-slate-900 bg-white border border-slate-300 shadow-sm":`rounded-lg px-3.5 py-1.5 text-xs font-medium ${e.textSecondary} border border-transparent hover:bg-white/[0.04]`;return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:`inline-flex w-fit items-center gap-1 rounded-xl border p-1 ${e.isDark?"border-white/10 bg-slate-950/40":"border-slate-200 bg-slate-50"}`,role:"tablist","aria-label":"Mesh view",children:[s.jsx("button",{type:"button",role:"tab","aria-selected":t==="overview",className:o(t==="overview"),onClick:()=>r("overview"),children:"Overview"}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="graph",className:o(t==="graph"),onClick:()=>r("graph"),children:"Graph"})]}),s.jsx(Kk,{meshTheme:e,open:n,onToggle:()=>a(!n)})]})}const Gk={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0},qi=l.createContext(Fs("dark"));function et({label:e,tone:t="default"}){const r=l.useContext(qi);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 Nt({label:e,value:t}){const r=l.useContext(qi);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 Vk(e){switch(e){case"online":return"good";case"dirty":return"warn";case"degraded":case"offline":return"danger";case"wrong_branch":return"info";default:return"default"}}function uo(e){switch((e||"").toLowerCase()){case"idle":return"good";case"generating":case"running":return"info";case"waiting_approval":case"starting":case"pending":return"warn";case"failed":case"stopped":case"interrupted":return"danger";default:return"default"}}function Wn(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const r=t.toLowerCase().replace(/[\s-]+/g,"_");return r.includes("approval")?"awaiting approval":r.includes("generating")||r.includes("running")||r.includes("busy")?"generating":r.includes("idle")||r.includes("ready")||r.includes("waiting_input")?"idle":r.replace(/_/g," ")}function qk(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function Yk(e){return e.startedAt||e.createdAt||null}function Jk(e){const t=Yk(e);if(!t)return"runtime age not reported";const r=Date.parse(t);if(!Number.isFinite(r))return"runtime age not reported";const n=Math.max(0,Math.floor((Date.now()-r)/1e3));if(n<60)return`${n}s`;const a=Math.floor(n/60);if(a<60)return`${a}m`;const o=Math.floor(a/60);return o<48?`${o}h ${a%60}m`:`${Math.floor(o/24)}d ${o%24}h`}function xm(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function Xk(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 Qk(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 Zk(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 e1(e){return e.assignedNodeId||e.targetNodeId||null}function Vc(e){return e?e.slice(0,7):null}function t1(e,t){var o,i,c;const r=Vc((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?[Vc(a.commit),a.message].filter(Boolean).join(" · "):null}function s1(e,t){const r=t1(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function r1(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 n1(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 a1(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":Qk(e.connection)}function o1(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 qc(e){switch(e.type){case"parentBranch":return"default branch link";case"worktreeLink":return"worktree relationship";case"sessionLink":return"session relationship";case"orphanLink":return"orphan relationship";case"submoduleLink":return"submodule relationship";case"cloneLink":return"clone relationship";default:return e.type}}function i1(e){return e.direction==="directed"?"directed":"undirected"}function l1(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function c1(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,u,p,m,h,b,g,f,v,j,y,w,N,k,x,S,C,I,R,L;return[o.nodeId,o.daemonId??"",o.machineId??"",o.machineLabel,o.machineStatus??"",((i=o.connection)==null?void 0:i.state)??"",((c=o.connection)==null?void 0:c.transport)??"",((d=o.connection)==null?void 0:d.source)??"",o.health,o.gitProbePending?1:0,((u=o.git)==null?void 0:u.branch)??"",((p=o.git)==null?void 0:p.upstream)??"",((m=o.git)==null?void 0:m.upstreamStatus)??"",((h=o.git)==null?void 0:h.ahead)??"",((b=o.git)==null?void 0:b.behind)??"",((g=o.git)==null?void 0:g.headCommit)??"",((f=o.git)==null?void 0:f.staged)??"",((v=o.git)==null?void 0:v.modified)??"",((j=o.git)==null?void 0:j.untracked)??"",((y=o.git)==null?void 0:y.deleted)??"",((w=o.git)==null?void 0:w.renamed)??"",(N=o.git)!=null&&N.hasConflicts?1:0,((k=o.git)==null?void 0:k.lastCheckedAt)??"",((x=o.activeSessions)==null?void 0:x.join(","))??"",((S=o.activeSessionDetails)==null?void 0:S.length)??"",((C=o.activeSessionDetails)==null?void 0:C.map(T=>[T.sessionId,T.providerType??"",T.state??"",T.chatStatus??"",T.lifecycle??"",T.role??"",T.isSelfCoordinator?1:0,T.statusNote??"",T.startedAt??"",T.createdAt??""].join("/")).join(","))??"",((I=o.providers)==null?void 0:I.join(","))??"",((R=o.providerPriority)==null?void 0:R.join(","))??"",o.error??"",(((L=o.git)==null?void 0:L.submodules)??[]).map(T=>[T.path,T.commit,T.dirty?1:0,T.outOfSync?1:0,T.error??""].join("/")).join(",")].join("|")})].join("::")}function d1({canonicalStatus:e,queueSummary:t,ledgerSummary:r,isBootstrapMode:n,meshTheme:a,sessionEntries:o,inlineMode:i=!1}){var k;const c=t&&(t.active>0||t.historical>0),d=r.recentFailures>0||r.taskFailed>0,u=(k=e.queue)!=null&&k.tasks?e.queue.tasks.filter(x=>x.status==="failed"||x.status==="cancelled").slice(0,5):[],p=e.asyncRefineJobs,m=(p==null?void 0:p.filter(x=>x.status==="running"||x.status==="accepted"))??[],h=(p==null?void 0:p.filter(x=>x.status==="failed"))??[],b=e.staleDirectWorkSummary,g=b&&b.count>0;if(!c&&!d&&e.nodes.length===0&&!n&&m.length===0&&h.length===0&&!g&&o.length===0)return null;const f=a.isDark,v=`border-t ${f?"border-white/8":"border-slate-200"}`,j=`group w-full rounded-lg border text-xs ${f?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,y=`flex cursor-pointer list-none items-center gap-1.5 px-2.5 py-1.5 [&::-webkit-details-marker]:hidden ${a.textSecondary}`;function w({label:x,value:S,tone:C}){const I=C==="rose"?f?"text-rose-300":"text-rose-600":C==="sky"?f?"text-sky-300":"text-sky-600":C==="amber"?f?"text-amber-300":"text-amber-600":C==="emerald"?f?"text-emerald-300":"text-emerald-600":C==="muted"?a.textMuted:a.textPrimary;return s.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-1.5 ${f?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[s.jsx("span",{className:`tabular-nums text-sm font-semibold leading-none ${I}`,children:S}),s.jsx("span",{className:`mt-0.5 text-[9px] uppercase tracking-wide ${a.textMuted}`,children:x})]})}const N=s.jsxs("div",{className:"flex flex-col gap-3 text-xs",children:[s.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t?s.jsxs(s.Fragment,{children:[s.jsx(w,{label:"Pending",value:t.pending}),s.jsx(w,{label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(w,{label:"Done",value:t.completed,tone:"emerald"}),s.jsx(w,{label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0})]}):s.jsxs(s.Fragment,{children:[s.jsx(w,{label:"Done",value:r.taskCompleted,tone:"emerald"}),s.jsx(w,{label:"Failed",value:r.taskFailed,tone:r.taskFailed>0?"rose":void 0}),s.jsx(w,{label:"Sessions",value:r.sessionLaunched}),s.jsx(w,{label:"Recent↯",value:r.recentFailures,tone:r.recentFailures>0?"amber":"muted"})]})}),t&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(w,{label:"Ledger done",value:r.taskCompleted,tone:"emerald"}),s.jsx(w,{label:"Sessions",value:r.sessionLaunched}),s.jsx(w,{label:"Recent↯",value:r.recentFailures,tone:r.recentFailures>0?"amber":"muted"})]}),r.lastActivityAt&&s.jsxs("div",{className:`flex items-center justify-between ${a.textMuted}`,children:[s.jsx("span",{children:"Last activity"}),s.jsx("span",{className:"font-mono text-[10px]",children:r.lastActivityAt.slice(5,16)})]}),e.nodes.length>0&&s.jsx("div",{className:`pt-2.5 ${v}`,children:s.jsx("div",{className:"flex flex-col gap-1",children:e.nodes.map(x=>{var T;const S=((T=x.connection)==null?void 0:T.state)??"unknown",C=S==="unknown"||S==="connecting",L=C?"bg-amber-400":S==="failed"||S==="closed"||S==="disconnected"?f?"bg-rose-400":"bg-rose-500":S==="connected"||S==="self"?f?"bg-emerald-400":"bg-emerald-500":f?"bg-slate-500":"bg-slate-400";return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`size-1.5 shrink-0 rounded-full ${L}`}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${a.textSecondary}`,title:x.workspace,children:x.machineLabel}),s.jsx("span",{className:`shrink-0 font-mono text-[10px] ${a.textMuted}`,children:C?"…":S})]},x.nodeId)})})}),p&&p.length>0&&s.jsx("div",{className:`pt-2.5 ${v}`,children:s.jsxs("details",{className:j,children:[s.jsxs("summary",{className:y,children:[s.jsx("span",{className:"flex-1",children:"Refine jobs"}),s.jsx("span",{className:`tabular-nums ${f?"text-slate-400":"text-slate-500"}`,children:p.length}),h.length>0&&s.jsxs("span",{className:f?"text-rose-300":"text-rose-600",children:[h.length," failed"]})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:p.slice(0,8).map(x=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${a.textMuted}`,children:[x.branch??x.jobId.slice(0,14),x.into?` → ${x.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${x.status==="failed"?f?"text-rose-300":"text-rose-600":x.status==="running"||x.status==="accepted"?f?"text-sky-300":"text-sky-600":f?"text-emerald-300":"text-emerald-600"}`,children:x.status})]},x.jobId))})]})}),u.length>0&&s.jsx("div",{className:p&&p.length>0?"":`pt-2.5 ${v}`,children:s.jsxs("details",{className:j,children:[s.jsxs("summary",{className:y,children:[s.jsx("span",{className:`flex-1 ${f?"text-rose-300":"text-rose-600"}`,children:"Failed tasks"}),s.jsx("span",{className:`tabular-nums ${f?"text-rose-400":"text-rose-500"}`,children:u.length})]}),s.jsx("div",{className:"flex flex-col gap-1 px-2.5 pb-2",children:u.map(x=>s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`font-mono text-[10px] ${a.textMuted}`,children:x.id.slice(0,10)}),x.message&&s.jsx("span",{className:`flex-1 truncate ${f?"text-slate-300":"text-slate-700"}`,children:x.message.slice(0,55)})]}),x.cancelReason&&s.jsx("div",{className:`truncate text-[10px] ${a.textMuted}`,children:x.cancelReason.slice(0,55)})]},x.id))})]})}),g&&s.jsxs("div",{className:`flex items-center justify-between pt-2.5 ${v}`,children:[s.jsx("span",{className:a.textMuted,children:"Stale work"}),s.jsx("span",{className:`tabular-nums ${f?"text-amber-300":"text-amber-600"}`,children:b.count})]}),o.length>0&&s.jsx("div",{className:`pt-2.5 ${v}`,children:s.jsxs("details",{className:j,children:[s.jsxs("summary",{className:y,children:[s.jsx("span",{className:"flex-1",children:"Sessions"}),s.jsx("span",{className:`tabular-nums ${f?"text-slate-400":"text-slate-500"}`,children:o.length})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:o.map(x=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${a.textMuted}`,title:x.session.sessionId,children:xm(x.session.sessionId)}),s.jsx("span",{className:`shrink-0 ${a.textMuted}`,children:x.session.providerType||"?"}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${a.textMuted}`,children:Wn(x.session)})]},x.session.sessionId))})]})})]});return i?N:s.jsxs("details",{className:`rounded-2xl border text-xs ${a.isDark?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsxs("summary",{className:`flex cursor-pointer list-none items-center gap-2 px-4 py-3 font-medium [&::-webkit-details-marker]:hidden ${a.textSecondary}`,children:[s.jsx("span",{className:"flex-1",children:"Mesh Health Panel"}),m.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700"}`,children:[m.length," refining"]}),h.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[h.length," refine failed"]}),d&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[r.recentFailures," recent failures"]}),n&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:"awaiting live data"})]}),N]})}function u1(e){return e.nodes.length===0?!1:e.nodes.every(t=>t.health==="unknown"&&(!t.connection||t.connection.state==="unknown"))}function bm({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null,bootstrapFallback:a,activeTab:o,onActiveTabChange:i,helpOpen:c,onHelpOpenChange:d,hideControls:u=!1}){var Ae,Ce,Ue,Qe;const{theme:p}=Bs(),m=l.useMemo(()=>Fs(p),[p]),h=a??u1(e),b=l.useMemo(()=>yi(e),[e]),g=l.useMemo(()=>c1(b),[b]),f=l.useMemo(()=>rm(b),[g]),[v,j]=l.useState("overview"),[y,w]=l.useState(!1),N=o??v,k=c??y,x=l.useCallback(pe=>{i?i(pe):j(pe)},[i]),S=l.useCallback(pe=>{d?d(pe):w(pe)},[d]),[C,I]=l.useState(!1);l.useEffect(()=>{N==="graph"&&I(!0)},[N]);const[R,L]=l.useState(null),[T,_]=l.useState(null),[$,X]=l.useState(null),[M,A]=l.useState({}),[E,F]=l.useState(null),[z,D]=l.useState(null),K=l.useMemo(()=>new Map(b.nodes.map(pe=>[pe.nodeId,pe])),[b.nodes]),O=l.useMemo(()=>new Map(f.nodes.map(pe=>[pe.id,pe])),[f.nodes]),q=((Ae=b.queue)==null?void 0:Ae.summary)??null,ne=((Ce=b.ledger)==null?void 0:Ce.summary)??Gk,J=l.useMemo(()=>Zk(b),[b]),ye=l.useMemo(()=>{const pe=new Map;for(const De of J){const $e=Wn(De.session);pe.set($e,(pe.get($e)??0)+1)}return[...pe.entries()].sort((De,$e)=>$e[1]-De[1])},[J]);l.useEffect(()=>{R&&(O.has(R)||(L(null),X(pe=>!pe||"nodeId"in pe&&pe.nodeId===R?null:pe)))},[O,R]);const oe=R?K.get(R)??null:null,B=l1(f,R),W=($==null?void 0:$.kind)==="edge"&&T?f.edges.find(pe=>pe.id===T)??null:null,ve=W?f.nodes.find(pe=>pe.id===W.source)??null:null,we=W?f.nodes.find(pe=>pe.id===W.target)??null:null;l.useEffect(()=>{var pe,De,$e;if(R)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:b.meshId,selectedNodeId:R,canonicalNode:Ib(oe),graphNode:B?{id:B.id,branch:B.branch,upstream:B.upstream,headCommit:B.submoduleCommit,submoduleCount:((De=(pe=oe==null?void 0:oe.git)==null?void 0:pe.submodules)==null?void 0:De.length)??0,snapshotCompleteness:B.snapshotCompleteness,snapshotWarnings:B.snapshotWarnings,branchConvergence:(($e=B.branchConvergence)==null?void 0:$e.status)??null}:null})}catch{}},[b.meshId,B,R,oe]);const fe=($==null?void 0:$.kind)==="session"?J.find(pe=>pe.nodeId===$.nodeId&&pe.session.sessionId===$.sessionId)??null:null,Ne=l.useMemo(()=>J.filter(pe=>pe.nodeId===R),[R,J]),re=n1({coordinatorDaemonId:r,selectedNodeStatus:oe,selectedSessionEntry:fe}),je=(re==null?void 0:re.workspace)??null,de=je?M[je]??null:null,U=s1(oe,(de==null?void 0:de.entries)??[]),H=(B==null?void 0:B.daemonId)??(oe==null?void 0:oe.daemonId)??r??null,Y=!!(B&&n&&H&&B.type!=="submoduleNode"&&B.behind>0&&B.ahead===0&&B.dirtyFiles===0&&!B.dirty&&!B.hasConflicts&&B.upstreamStatus==="fresh"),se=l.useCallback(()=>{L(null),_(null),X(null),F(null)},[]);l.useEffect(()=>{F(null)},[R]);const xe=l.useCallback(async()=>{if(!B||!H||!n||!Y)return;D(B.id),F(null);const pe=(oe==null?void 0:oe.workspace)??B.workspace??"";try{const De=await n(H,"fast_forward_mesh_node",{meshId:b.meshId,nodeId:B.id,workspace:pe,updateSubmodules:!0,dryRun:!0,execute:!1}),$e=(De==null?void 0:De.result)??De;if(F({phase:"dry_run",code:typeof($e==null?void 0:$e.code)=="string"?$e.code:void 0,error:typeof($e==null?void 0:$e.operationError)=="string"?$e.operationError:null,executed:($e==null?void 0:$e.executed)===!0}),!($e!=null&&$e.success)||$e.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${B.label}?`))return;const Ke=await n(H,"fast_forward_mesh_node",{meshId:b.meshId,nodeId:B.id,workspace:pe,updateSubmodules:!0,dryRun:!1,execute:!0}),Ve=(Ke==null?void 0:Ke.result)??Ke;F({phase:"execute",code:typeof(Ve==null?void 0:Ve.code)=="string"?Ve.code:void 0,error:typeof(Ve==null?void 0:Ve.operationError)=="string"?Ve.operationError:null,executed:(Ve==null?void 0:Ve.executed)===!0})}catch(De){F({phase:"dry_run",error:De instanceof Error?De.message:"fast-forward failed"})}finally{D(null)}},[Y,b.meshId,B,H,n]);l.useEffect(()=>{if(!B&&!W)return;const pe=De=>{De.key==="Escape"&&se()};return window.addEventListener("keydown",pe),()=>window.removeEventListener("keydown",pe)},[se,W,B]),l.useEffect(()=>{if(!re||!n)return;const{daemonId:pe,workspace:De}=re,$e=M[De];if($e!=null&&$e.loading||$e&&($e.entries.length>0||$e.error))return;let tt=!1;return A(Ke=>{var Ve;return{...Ke,[De]:{loading:!0,error:null,entries:((Ve=Ke[De])==null?void 0:Ve.entries)??[]}}}),n(pe,"git_log",{workspace:De,limit:5}).then(Ke=>{tt||A(Ve=>({...Ve,[De]:{loading:!1,error:null,entries:r1(Ke)}}))}).catch(Ke=>{tt||A(Ve=>({...Ve,[De]:{loading:!1,error:Ke instanceof Error?Ke.message:"git_log failed",entries:[]}}))}),()=>{tt=!0}},[M,re,n]);const Z=[...f.warnings??[],...b.nodes.filter(pe=>pe.machineStatus&&pe.machineStatus!=="online").map(pe=>`${pe.machineLabel}: ${pe.machineStatus}`)],P=f.stats.incompleteSnapshotNodes>0,ie=f.stats.followUpNodes>0?`${f.stats.followUpNodes} need follow-up`:P?"mesh visibility incomplete":"mesh converged",be=f.stats.followUpNodes>0?"danger":P?"warn":"good",[ue,te]=l.useState("LR"),Me=pe=>pe?m.isDark?"rounded-md border border-cyan-400/40 bg-cyan-500/15 px-2 py-0.5 text-cyan-100":"rounded-md border border-sky-400 bg-sky-100 px-2 py-0.5 text-sky-800":m.isDark?"rounded-md border border-white/10 bg-white/[0.03] px-2 py-0.5 text-slate-400 hover:text-slate-200":"rounded-md border border-slate-300 bg-white/80 px-2 py-0.5 text-slate-500 hover:text-slate-800";return s.jsx(qi.Provider,{value:m,children:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[!u&&s.jsx("div",{className:"shrink-0 flex items-center justify-end",children:s.jsx(fm,{meshTheme:m,activeTab:N,onActiveTabChange:x,helpOpen:k,onHelpOpenChange:S})}),k&&s.jsx(Uk,{meshTheme:m,onClose:()=>S(!1)}),s.jsx("div",{className:`${N==="overview"?"flex":"hidden"} min-h-0 flex-1 flex-col overflow-y-auto`,children:N==="overview"&&s.jsx(Ak,{status:e})}),s.jsx("div",{className:`${N==="graph"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-4`,children:s.jsxs("div",{className:`${m.cardClass} relative flex min-h-0 flex-1 flex-col rounded-[28px]`,style:{minHeight:480},children:[s.jsxs("div",{className:`absolute inset-x-4 top-4 z-30 max-h-[42dvh] overflow-y-auto sm:static sm:mb-3 sm:overflow-visible shrink-0 flex flex-wrap items-start justify-between gap-2 px-4 pt-3 pb-2.5 border-b ${m.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-wrap gap-2 text-xs ${m.textSecondary}`,children:[s.jsx(et,{label:ie,tone:be}),f.stats.blockedReviewNodes>0&&s.jsx(et,{label:`${f.stats.blockedReviewNodes} blocked review`,tone:"danger"}),f.stats.notMergeableNodes>0&&s.jsx(et,{label:`${f.stats.notMergeableNodes} not mergeable`,tone:"danger"}),f.stats.mergeReadyNodes>0&&s.jsx(et,{label:`${f.stats.mergeReadyNodes} need merge`,tone:"warn"}),f.stats.cleanupCandidateNodes>0&&s.jsx(et,{label:`${f.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),f.stats.offlineNodes>0&&s.jsx(et,{label:`${f.stats.offlineNodes} offline`,tone:"danger"}),f.stats.incompleteSnapshotNodes>0&&s.jsx(et,{label:`${f.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),f.stats.missingGitSnapshotNodes>0&&s.jsx(et,{label:`${f.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),f.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(et,{label:`${f.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),f.stats.staleGitSnapshotNodes>0&&s.jsx(et,{label:`${f.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((q==null?void 0:q.active)??0)>0&&s.jsx(et,{label:`${(q==null?void 0:q.active)??0} active queue`,tone:"info"}),s.jsx(et,{label:`${f.stats.totalNodes} nodes`,tone:"default"}),f.stats.totalActiveSessions>0&&s.jsx(et,{label:`${f.stats.totalActiveSessions} attached chats`,tone:"info"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[s.jsxs("div",{className:m.isDark?"flex items-center gap-0.5 rounded-md border border-white/10 bg-slate-950/40 p-0.5 text-[10px]":"flex items-center gap-0.5 rounded-md border border-slate-300 bg-white/70 p-0.5 text-[10px]",role:"group","aria-label":"Graph layout direction",children:[s.jsx("button",{type:"button",onClick:()=>te("auto"),className:Me(ue==="auto"),title:"Auto-detect direction",children:"Auto"}),s.jsx("button",{type:"button",onClick:()=>te("LR"),className:Me(ue==="LR"),title:"Left to right",children:"LR"}),s.jsx("button",{type:"button",onClick:()=>te("TB"),className:Me(ue==="TB"),title:"Top to bottom",children:"TB"})]}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${m.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${m.textSecondary} [&::-webkit-details-marker]:hidden`,children:(()=>{var $e;const pe=(($e=b.asyncRefineJobs)==null?void 0:$e.filter(tt=>tt.status==="failed").length)??0,De=ne.recentFailures;return pe>0?s.jsxs("span",{className:m.isDark?"text-rose-300":"text-rose-600",children:[pe," refine failed"]}):De>0?s.jsxs("span",{className:m.isDark?"text-amber-300":"text-amber-600",children:[De," failures"]}):"Health"})()}),s.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 max-h-[70vh] overflow-y-auto rounded-xl border p-4 shadow-xl backdrop-blur-xl ${m.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsx(d1,{canonicalStatus:b,queueSummary:q,ledgerSummary:ne,isBootstrapMode:h,meshTheme:m,sessionEntries:J,inlineMode:!0})})]})}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${m.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${m.textSecondary} [&::-webkit-details-marker]:hidden`,children:"Legend"}),s.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 rounded-xl border p-3 shadow-xl backdrop-blur-xl ${m.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(et,{label:`${f.stats.dirtyNodes} dirty`,tone:f.stats.dirtyNodes>0?"warn":"good"}),s.jsx(et,{label:`${f.stats.orphanNodes} orphan`,tone:f.stats.orphanNodes>0?"warn":"good"}),s.jsx(et,{label:`${ne.recentFailures} recent failures`,tone:ne.recentFailures>0?"danger":"good"}),ye.length===0?s.jsx(et,{label:"no session metadata"}):ye.slice(0,2).map(([pe,De])=>s.jsx(et,{label:`${De} ${pe}`,tone:uo(pe)},pe))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(et,{label:"Anchor = default branch",tone:"info"}),s.jsx(et,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(et,{label:"Submodule link = child checkout",tone:"warn"})]}),Z.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:Z.map(pe=>s.jsx("span",{className:m.isDark?"rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1 text-xs text-amber-100":"rounded-full border border-amber-300 bg-amber-50 px-3 py-1 text-xs text-amber-700",children:pe},pe))}),s.jsx("div",{className:`text-xs ${m.textMuted}`,children:"Click a node or edge to pin its drill-down details in the side panel. Click it again to close."})]})})]})})]})]}),h&&f.nodes.length>0&&s.jsxs("div",{className:`shrink-0 mx-4 mt-2 flex items-center gap-2 rounded-xl border px-3.5 py-2 text-xs ${m.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full animate-pulse ${m.isDark?"bg-amber-400":"bg-amber-500"}`,"aria-hidden":!0}),s.jsx("span",{children:"Awaiting live data — showing setup inventory until peer mesh_status probes succeed."})]}),s.jsxs("div",{className:"relative flex flex-1 min-w-0",style:{minHeight:360},children:[s.jsx("div",{className:"flex-1 min-w-0",children:C?f.nodes.length>0?s.jsx(Nk,{data:f,selectedNodeId:R,directionPref:ue,onNodeClick:pe=>{if(($==null?void 0:$.kind)==="node"&&R===pe.id){se();return}_(null),L(pe.id),X({kind:"node",nodeId:pe.id})},onEdgeClick:pe=>{if(($==null?void 0:$.kind)==="edge"&&T===pe.id){se();return}L(null),_(pe.id),X({kind:"edge",edgeId:pe.id})}}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:t}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:"Loading graph…"})}),B&&($==null?void 0:$.kind)==="node"&&s.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${m.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${m.textMuted}`,children:"Selected node"}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${m.textPrimary}`,children:B.label}),s.jsx("div",{className:`mt-0.5 font-mono text-[11px] ${m.textMuted}`,children:B.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[B.behind>0&&s.jsx("button",{type:"button",onClick:()=>{xe()},disabled:!Y||z===B.id,className:m.isDark?"rounded-full border border-emerald-400/25 bg-emerald-500/10 px-2 py-0.5 text-xs font-semibold text-emerald-100 transition hover:bg-emerald-500/18 disabled:cursor-not-allowed disabled:opacity-45":"rounded-full border border-emerald-300 bg-emerald-50 px-2 py-0.5 text-xs font-semibold text-emerald-700 transition hover:bg-emerald-100 disabled:cursor-not-allowed disabled:opacity-45",children:z===B.id?"Checking":"Heal"}),s.jsx("button",{type:"button",onClick:se,"aria-label":"Close detail panel",className:m.isDark?"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[(()=>{const pe=(oe==null?void 0:oe.health)??B.health;return pe==="unknown"?s.jsx(et,{label:"connecting...",tone:"default"}):s.jsx(et,{label:pe,tone:Vk(pe)})})(),B.branch&&s.jsx(et,{label:B.branch,tone:"default"}),B.ahead>0&&s.jsx(et,{label:`ahead ${B.ahead}`,tone:"warn"}),B.behind>0&&s.jsx(et,{label:`behind ${B.behind}`,tone:"warn"}),B.dirtyFiles>0&&s.jsx(et,{label:`${B.dirtyFiles} dirty`,tone:"warn"}),(oe==null?void 0:oe.connection)&&oe.connection.state!=="unknown"&&s.jsx(et,{label:a1(oe),tone:Xk(oe.connection)}),((Ue=oe==null?void 0:oe.connection)==null?void 0:Ue.state)==="unknown"&&s.jsx(et,{label:"mesh connecting...",tone:"warn"}),Ne.length>0&&s.jsx(et,{label:`${Ne.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[B.machineLabel&&s.jsx(Nt,{label:"Machine",value:B.machineLabel}),B.locality&&B.locality!=="unknown"&&s.jsx(Nt,{label:"Locality",value:B.locality}),s.jsx(Nt,{label:"Workspace",value:(oe==null?void 0:oe.workspace)??B.workspace}),U&&s.jsx(Nt,{label:"HEAD",value:U}),(B.dirtyFiles>0||B.ahead>0||B.behind>0)&&s.jsx(Nt,{label:"Dirty/ahead/behind",value:`${B.dirtyFiles}/${B.ahead}/${B.behind}`}),Ne.length>0&&s.jsx(Nt,{label:"Sessions",value:String(Ne.length)}),B.upstream&&s.jsx(Nt,{label:"Upstream",value:B.upstream}),(()=>{var De;const pe=((De=oe==null?void 0:oe.connection)==null?void 0:De.source)??o1(B);return pe&&pe!=="unknown"?s.jsx(Nt,{label:"Source",value:String(pe)}):null})(),(()=>{var De;const pe=(De=oe==null?void 0:oe.connection)==null?void 0:De.transport;return pe&&pe!=="unknown"?s.jsx(Nt,{label:"Transport",value:pe}):null})(),(()=>{const pe=B.machineId??(oe==null?void 0:oe.machineId);return pe?s.jsx(Nt,{label:"Machine id",value:pe}):null})(),(()=>{const pe=B.daemonId??(oe==null?void 0:oe.daemonId);return pe?s.jsx(Nt,{label:"Daemon id",value:pe}):null})()]}),Ne.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${m.textMuted}`,children:"Active Sessions"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:Ne.map(pe=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${m.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono select-text ${m.textMuted}`,title:pe.session.sessionId,children:xm(pe.session.sessionId)}),s.jsx(et,{label:Wn(pe.session),tone:uo(Wn(pe.session))})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 ${m.textMuted}`,children:[s.jsx("span",{className:"truncate",children:pe.session.providerType||"provider unknown"}),s.jsx("span",{children:qk(pe.session)}),s.jsx("span",{children:Jk(pe.session)})]}),pe.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${m.textMuted}`,children:pe.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${m.textMuted}`,title:pe.session.workspace||pe.workspace,children:[(pe.session.workspace||pe.workspace).slice(0,38),pe.branch?` · ${pe.branch}`:""]})]},pe.session.sessionId))})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${m.textMuted}`,children:"Ledger (mesh-wide)"}),s.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[s.jsx(Nt,{label:"Completed",value:String(ne.taskCompleted)}),s.jsx(Nt,{label:"Failed",value:s.jsx("span",{className:ne.taskFailed>0?m.isDark?"text-rose-300":"text-rose-600":"",children:ne.taskFailed})}),s.jsx(Nt,{label:"Launched",value:String(ne.sessionLaunched)}),s.jsx(Nt,{label:"Recent failures",value:s.jsx("span",{className:ne.recentFailures>0?m.isDark?"text-amber-300":"text-amber-600":"",children:ne.recentFailures})})]})]}),(()=>{var $e,tt;const pe=(($e=b.queue)==null?void 0:$e.tasks)??((tt=b.queue)==null?void 0:tt.items)??null;if(!Array.isArray(pe)||pe.length===0)return null;const De=pe.filter(Ke=>e1(Ke)===R).slice(0,3);return De.length===0?null:s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${m.textMuted}`,children:"Queue tasks"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:De.map(Ke=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${m.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`font-mono ${m.textMuted}`,children:Ke.id.slice(0,12)}),s.jsx(et,{label:Ke.status??"unknown",tone:uo(Ke.status)})]}),Ke.message&&s.jsx("div",{className:`mt-0.5 truncate ${m.textMuted}`,children:Ke.message.slice(0,48)})]},Ke.id))})]})})(),B.snapshotWarnings.length>0&&s.jsxs("div",{className:m.isDark?"mt-3 rounded-xl border border-amber-400/20 bg-amber-500/10 p-3 text-xs text-amber-100":"mt-3 rounded-xl border border-amber-300 bg-amber-50 p-3 text-xs text-amber-800",children:[s.jsx("div",{className:"font-medium",children:"Key warning"}),s.jsx("div",{className:"mt-1",children:B.snapshotWarnings[0]})]}),((Qe=B.branchConvergence)==null?void 0:Qe.nextStep)&&s.jsxs("div",{className:m.isDark?"mt-3 rounded-xl border border-sky-400/20 bg-sky-500/10 p-3 text-xs text-sky-100":"mt-3 rounded-xl border border-sky-300 bg-sky-50 p-3 text-xs text-sky-800",children:[s.jsx("div",{className:"font-medium",children:"Follow-up"}),s.jsx("div",{className:"mt-1",children:B.branchConvergence.nextStep})]}),E&&s.jsxs("div",{className:m.isDark?"mt-3 rounded-xl border border-emerald-400/20 bg-emerald-500/10 p-3 text-xs text-emerald-100":"mt-3 rounded-xl border border-emerald-300 bg-emerald-50 p-3 text-xs text-emerald-800",children:[s.jsx("div",{className:"font-medium",children:E.phase==="execute"?"Heal result":"Heal preview"}),s.jsx("div",{className:"mt-1",children:E.code??E.error??"No result code returned."})]})]}),W&&($==null?void 0:$.kind)==="edge"&&s.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${m.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${m.textMuted}`,children:"Selected edge"}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${m.textPrimary}`,children:W.label||qc(W)}),s.jsx("div",{className:`mt-0.5 break-all font-mono text-[11px] ${m.textMuted}`,children:W.id})]}),s.jsx("button",{type:"button",onClick:se,"aria-label":"Close detail panel",className:m.isDark?"shrink-0 rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"shrink-0 rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[s.jsx(et,{label:qc(W),tone:"default"}),s.jsx(et,{label:i1(W),tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(Nt,{label:"From",value:(ve==null?void 0:ve.label)??W.source}),s.jsx(Nt,{label:"To",value:(we==null?void 0:we.label)??W.target}),s.jsx(Nt,{label:"Label",value:W.label??"none"})]})]})]})]})})]})})}function yt(e){return typeof e=="string"?e.trim():""}function Xo(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Yi(...e){const t=new Set;for(const r of e){const n=yt(r);n&&t.add(n)}return[...t]}function p1(e,t){var m,h;const r=Xo(e==null?void 0:e.settings),n=yt((m=e==null?void 0:e.coordinator)==null?void 0:m.meshId)||yt(r.meshCoordinatorFor),a=yt(r.meshNodeFor),o=!!n||!!a,i=n===t||a===t;if(o&&!i)return null;const c=Xo(e==null?void 0:e.activeChat),d=Yi(e==null?void 0:e.id,e==null?void 0:e.sessionId,e==null?void 0:e.session_id,e==null?void 0:e.providerSessionId,e==null?void 0:e.provider_session_id,e==null?void 0:e.targetSessionId,e==null?void 0:e.target_session_id,c.sessionId,c.session_id,c.providerSessionId,c.provider_session_id),u=d[0]||"";if(!u)return null;const p=n===t?yt((h=e==null?void 0:e.coordinator)==null?void 0:h.role)||"coordinator":a===t?yt(r.meshNodeRole)||"worker":yt(e==null?void 0:e.role)||yt(r.meshNodeRole)||void 0;return{sessionId:u,aliases:d,meshId:t,nodeId:i&&yt(r.meshNodeId)||null,providerType:yt(e==null?void 0:e.providerType)||void 0,state:yt(e==null?void 0:e.status)||void 0,chatStatus:yt(c.status)||void 0,lifecycle:yt(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:yt(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:yt(e==null?void 0:e.runtimeRecoveryState)||void 0,...p?{role:p}:{},...i?{isSelfCoordinator:n===t}:{},workspace:yt(e==null?void 0:e.workspace)||null}}function gm(e,t){var n;return t?(Array.isArray((n=e.status)==null?void 0:n.sessions)?e.status.sessions:[]).map(a=>p1(a,t)).filter(a=>a!==null):[]}function da(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function m1(e,t){const r=new Set(da(t));return da(e).some(n=>r.has(n))}function h1(e,t){const r=t.filter(a=>!!a);return r.length===0?e:[...e.filter(a=>!r.some(o=>m1(a,o))),...r]}function f1(e,t){if(t.length===0)return e;const r=new Map;for(const i of t)for(const c of da(i))r.set(c,i);let n=!1;const o=(e.nodes??[]).map((i,c)=>{const d=Array.isArray(i.activeSessionDetails)?i.activeSessionDetails:Array.isArray(i.sessions)?i.sessions:[],u=new Map;for(const h of d){const b=Yi(h==null?void 0:h.sessionId,h==null?void 0:h.session_id,h==null?void 0:h.id,h==null?void 0:h.providerSessionId,h==null?void 0:h.provider_session_id),g=b[0]||"";if(!g)continue;const f=b.map(v=>r.get(v)).find(Boolean);f&&(n=!0),u.set(g,f?{...h,sessionId:g,providerType:f.providerType||h.providerType,state:f.state||h.state,chatStatus:f.chatStatus||h.chatStatus,lifecycle:f.lifecycle||h.lifecycle,surfaceKind:f.surfaceKind||h.surfaceKind,recoveryState:f.recoveryState||h.recoveryState,role:f.role||h.role,isSelfCoordinator:f.isSelfCoordinator??h.isSelfCoordinator,workspace:f.workspace||h.workspace}:{...h,sessionId:g})}for(const h of i.activeSessions??[])u.has(h)||u.set(h,{sessionId:h,workspace:i.workspace,isCached:!0});const p=c===0;for(const h of t){if(da(h).some(v=>u.has(v)))continue;const g=h.nodeId!=null&&h.nodeId===i.nodeId,f=h.isSelfCoordinator&&!h.nodeId&&p;!g&&!f||(n=!0,u.set(h.sessionId,{sessionId:h.sessionId,providerType:h.providerType,state:h.state,chatStatus:h.chatStatus,lifecycle:h.lifecycle,surfaceKind:h.surfaceKind,recoveryState:h.recoveryState,role:h.role,isSelfCoordinator:h.isSelfCoordinator,workspace:h.workspace||i.workspace}))}const m=[...u.values()];return m.length===0?i:{...i,activeSessionDetails:m,activeSessions:m.map(h=>h.sessionId)}});return n?{...e,nodes:o}:e}function x1(e,t){const n=gm(e,t).map(a=>{var d;const o=(Array.isArray((d=e.status)==null?void 0:d.sessions)?e.status.sessions:[]).find(u=>yt(u==null?void 0:u.id)===a.sessionId),i=Xo(o==null?void 0:o.activeInteractivePrompt),c=o!=null&&o.meshQueueStats&&typeof o.meshQueueStats=="object"?JSON.stringify(o.meshQueueStats):"";return[a.sessionId,a.providerType??"",a.state??"",a.chatStatus??"",a.lifecycle??"",a.surfaceKind??"",a.recoveryState??"",yt(i.status)||yt(i.kind)||yt(i.type),a.nodeId??"",a.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(a=>!!a).sort();return n.length>0?n.join(`
|
|
81
|
+
`):null}function ym({status:e,daemonId:t,extraDaemonIds:r,meshId:n,sendData:a,extraLiveSessions:o=[]}){const[i,c]=l.useState(new Map),d=l.useRef(new Map),u=l.useMemo(()=>{const b=new Set;if(t&&b.add(t),r)for(const g of r)g&&b.add(g);return[...b].sort()},[t,r]),p=u.join(",");l.useEffect(()=>{d.current=new Map,c(new Map)},[t,n]),l.useEffect(()=>{if(!n||!a||u.length===0)return;const b=u.map(g=>ts.subscribe({sendData:a},g,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${g}`,params:{includeSessions:!0}},f=>{if(f.topic!=="daemon.metadata")return;const v=x1(f,n);if(v===(d.current.get(g)??null))return;d.current.set(g,v);const j=gm(f,n);c(y=>{const w=new Map(y);return w.set(g,j),w})}));return()=>{for(const g of b)g()}},[p,n,a]);const m=l.useMemo(()=>{const b=[];for(const g of i.values())b.push(...g);return b},[i]),h=l.useMemo(()=>h1(m,o),[o,m]);return l.useMemo(()=>e?f1(e,h):null,[h,e])}const Yc=[1500,4e3,9e3];function b1(e){var t,r,n,a,o,i;return!!(((t=e.git)==null?void 0:t.isGitRepo)===!0||(r=e.git)!=null&&r.branch||(n=e.git)!=null&&n.upstream||(a=e.git)!=null&&a.headCommit||(o=e.git)!=null&&o.workspace||(i=e.git)!=null&&i.repoRoot)}function g1(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>{var r;return b1(t)?!1:t.gitProbePending||((r=t.connection)==null?void 0:r.state)==="connecting"?!0:t.machineStatus==="online"||t.launchReady===!0})}function y1(e){return!Number.isInteger(e)||e<0?Yc[0]:Yc[e]??null}const po=new Map;function v1(e,t){return!e||!t?null:`${e}::${t}`}function w1(e,t){var o,i,c,d;if(!t||!e.sessionId)return null;const r=((o=e.coordinator)==null?void 0:o.meshId)??(typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),n=typeof((c=e.settings)==null?void 0:c.meshNodeFor)=="string"?e.settings.meshNodeFor:null;if(r!==t&&n!==t)return null;const a=typeof((d=e.settings)==null?void 0:d.meshNodeId)=="string"?e.settings.meshNodeId:null;return{sessionId:e.sessionId,aliases:Yi(e.sessionId,e.providerSessionId,e.historySessionId,e.nativeSessionId),meshId:t,nodeId:a,providerType:e.agentType,state:e.status,chatStatus:e.status,role:r===t?"coordinator":"worker",isSelfCoordinator:r===t,workspace:e.workspacePath??null}}function j1({activeConv:e,sendDaemonCommand:t,onClose:r}){var O,q,ne,J,ye,oe;const n=((O=e.coordinator)==null?void 0:O.meshId)??(typeof((q=e.settings)==null?void 0:q.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),a=e.daemonId??null,o=v1(a,n),i=o?po.get(o)??null:null,c=xi(),{sendData:d}=mt(),{theme:u}=Bs(),p=l.useMemo(()=>Fs(u),[u]),[m,h]=l.useState("overview"),[b,g]=l.useState(!1),f=l.useMemo(()=>w1(e,n),[e.agentType,(ne=e.coordinator)==null?void 0:ne.meshId,e.sessionId,(J=e.settings)==null?void 0:J.meshCoordinatorFor,(ye=e.settings)==null?void 0:ye.meshNodeFor,(oe=e.settings)==null?void 0:oe.meshNodeId,e.status,e.workspacePath,n]),[v,j]=l.useState(i),[y,w]=l.useState(!1),[N,k]=l.useState(!1),[x,S]=l.useState(null),[C,I]=l.useState((i==null?void 0:i.refreshedAt)??null),R=l.useRef(i!==null),L=l.useRef(!1),T=l.useRef(!1),_=l.useRef(!0),$=l.useRef(0),X=l.useRef(null);l.useEffect(()=>{R.current=v!==null},[v]);const M=l.useCallback(()=>{X.current!==null&&(clearTimeout(X.current),X.current=null)},[]);l.useEffect(()=>{M(),$.current=0;const B=o?po.get(o)??null:null;j(B),I((B==null?void 0:B.refreshedAt)??null),R.current=B!==null,T.current=!1,k(!1),S(null)},[o,M]);const A=l.useCallback(async(B=!1,W=!1)=>{if(!a||!n){S("This coordinator does not expose a live mesh id."),j(null);return}if(L.current){B&&(T.current=!0);return}W||(M(),$.current=0),L.current=!0;const ve=!R.current;w(ve),k(B&&R.current),S(null);try{const we=c!=null&&c.loadMeshStatus?await c.loadMeshStatus(a,n,{refresh:B,retryProfile:W?"interactive":"settled"}):await t(a,"mesh_status",{meshId:n,refresh:B}),fe=vi(we);if(!fe){S("mesh_status returned an unexpected payload.");return}if(o&&po.set(o,fe),j(fe),R.current=!0,I(fe.refreshedAt||new Date().toISOString()),g1(fe.nodes)){const Ne=y1($.current);Ne!==null&&_.current&&($.current+=1,X.current=setTimeout(()=>{_.current&&A(!0,!0)},Ne))}else $.current=0}catch(we){S(we instanceof Error?we.message:"Failed to load live mesh status")}finally{L.current=!1,w(!1),k(!1),T.current&&_.current&&(T.current=!1,window.setTimeout(()=>{_.current&&A(!0)},0))}},[o,M,a,n,c,t]);l.useEffect(()=>(_.current=!0,$.current=0,(async()=>(await A(!1,!0),_.current&&X.current===null&&!L.current&&A(!0,!0)))(),()=>{_.current=!1,M()}),[A,M]),l.useEffect(()=>{const B=W=>{W.key==="Escape"&&r()};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[r]);const E=(v==null?void 0:v.meshName)||n||"Repo Mesh",F=l.useMemo(()=>f?[f]:[],[f]),z=ym({status:v,daemonId:a,meshId:n,sendData:d,extraLiveSessions:F}),D=C?new Date(C).toLocaleTimeString():null,K=l.useMemo(()=>y?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[y]);return s.jsx("div",{className:p.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:p.dialogShellClass,onClick:B=>B.stopPropagation(),children:[s.jsxs("div",{className:p.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(as,{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:p.dialogTitleClass,children:E}),s.jsx("span",{className:p.dialogKickerClass,children:"Mesh observability"})]}),s.jsxs("p",{className:p.dialogSubtitleClass,children:[pt(e),e.workspaceName?` · ${e.workspaceName}`:"",v!=null&&v.repoIdentity?` · ${v.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[s.jsx(fm,{meshTheme:p,activeTab:m,onActiveTabChange:h,helpOpen:b,onHelpOpenChange:g}),D&&s.jsx("span",{className:p.dialogRefreshedChipClass,children:N?"Refreshing mesh...":`Refreshed ${D}`}),!N&&v&&s.jsx("span",{className:p.dialogRefreshedChipClass,children:d&&!x?"Live daemon metadata":"Metadata subscription unavailable"}),s.jsx("button",{type:"button",onClick:()=>{A(!0)},disabled:y||N,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:y||N?"Refreshing…":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:p.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:s.jsx(vt,{size:16})})]})]}),x&&s.jsx("div",{className:p.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:x}),s.jsx("div",{className:p.dialogBodyClass,children:z?s.jsx(bm,{status:z,emptyMessage:K,daemonId:a,sendDaemonCommand:t,activeTab:m,onActiveTabChange:h,helpOpen:b,onHelpOpenChange:g,hideControls:!0}):s.jsx("div",{className:p.dialogEmptyClass,children:K})})]})})}function k1(e,t){const{sendCommand:r}=mt(),[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 u=(d==null?void 0:d.result)??d;a(typeof(u==null?void 0:u.remoteUrl)=="string"?u.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>i(!1))},[e,t,r]);const c=N1(n);return{remoteUrl:n,githubUrl:c,loading:o}}function N1(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 vm=5e3;function S1(e){return`git:${e}`}function C1({workspace:e,includeDiffSummary:t=!1,intervalMs:r=vm}){return{type:"subscribe",topic:"workspace.git",key:S1(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function Ji(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Ds(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 I1(e){const t=Ji(e);return(t==null?void 0:t.success)===!1?{status:null,error:Ds(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Ds(t,"Git status response did not include status")}}function M1(e){const t=Ji(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Ds(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Ds(t,"Git diff summary response did not include diffSummary")}}function mo(e){return e===void 0||typeof e=="boolean"}function A1(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&mo(t.binary)&&mo(t.truncated)&&mo(t.staged)}function T1(e){const t=Ji(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Ds(t,"Git file diff request failed")}:A1(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Ds(t,"Git file diff response did not include a valid diff object")}}function _1({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=vm}){const{sendCommand:o,sendData:i}=mt(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[u,p]=l.useState(null),[m,h]=l.useState(null),[b,g]=l.useState(!1),[f,v]=l.useState(null),j=l.useCallback(async()=>{if(!(!d||!e||!c)){g(!0),v(null);try{const w=I1(await o(e,"git_status",{workspace:c}));if(w.error){p(null),h(null),v(w.error);return}if(p(w.status),!n){h(null);return}const N=M1(await o(e,"git_diff_summary",{workspace:c}));if(N.error){h(null),v(N.error);return}h(N.diffSummary)}catch(w){v(Ds(w,"Git status request failed"))}finally{g(!1)}}},[d,e,n,o,c]),y=l.useMemo(()=>c?C1({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return l.useEffect(()=>{if(!d||!e||!c||!y){p(null),h(null),g(!1),v(null);return}const w=i?ts.subscribe({sendData:i},e,y,N=>{var k,x;N.workspace===c&&(p(N.status),h(N.diffSummary??null),v(((k=N.status)==null?void 0:k.error)||((x=N.diffSummary)==null?void 0:x.error)||null),g(!1))},{retryIntervalMs:1e3}):null;return j(),()=>{w==null||w()}},[d,e,j,y,i,c]),{status:u,diffSummary:m,loading:b,error:f,refresh:j}}const R1={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},P1={added:"text-emerald-400",modified:"text-orange-400",deleted:"text-red-400",renamed:"text-sky-400",copied:"text-sky-400",untracked:"text-zinc-400",conflict:"text-red-400 font-bold"};function Jc(e){return e.split("/").pop()??e}function L1(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function D1({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=R1[o.status]??"?",d=P1[o.status]??"text-zinc-400",u=L1(o.path),p=Jc(o.path),m=o.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${i?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(o),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:o.status,children:c}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[u&&s.jsxs("span",{className:"text-text-secondary",children:[u,"/"]}),s.jsx("span",{className:"text-text-primary",children:p}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",Jc(o.oldPath)]}),m]}),!o.binary&&(o.insertions>0||o.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",o.insertions]}),o.insertions>0&&o.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),o.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",o.deletions]})]}),o.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${o.path}-${o.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function $1(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 wm({diff:e,binary:t,truncated:r,loading:n,error:a,className:o=""}){const i=l.useRef(null);if(l.useEffect(()=>{i.current&&(i.current.scrollTop=0)},[e]),n)return s.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${o}`,children:"Loading diff…"});if(a)return s.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${o}`,children:a});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"No diff available."});const c=e.split(`
|
|
82
|
+
`);return s.jsxs("div",{ref:i,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((d,u)=>$1(d,u))}),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 E1(e,t){const r=[`Branch: ${e||"unknown"}`];r.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const n={};for(const a of t.files)n[a.status]||(n[a.status]=[]),n[a.status].push(a.path);for(const[a,o]of Object.entries(n))r.push(`${a}: ${o.slice(0,5).join(", ")}${o.length>5?` (+${o.length-5} more)`:""}`);return r.join(`
|
|
83
|
+
`)}function jm({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=mt(),{status:a,diffSummary:o,loading:i,error:c,refresh:d}=_1({daemonId:e,workspace:t,includeDiffSummary:!0}),[u,p]=l.useState(null),[m,h]=l.useState(null),[b,g]=l.useState(""),[f,v]=l.useState(!1),[j,y]=l.useState(!1),[w,N]=l.useState(null),[k,x]=l.useState(null),{githubUrl:S}=k1(e,t),C=l.useCallback(async $=>{if(!((u==null?void 0:u.path)===$.path&&!u.loading)){p({path:$.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const X=await n(e,"git_diff_file",{workspace:t,path:$.path,staged:$.staged}),M=T1(X);if(M.error||!M.diff){p({path:$.path,diff:"",binary:!1,truncated:!1,loading:!1,error:M.error??"Failed to load diff"});return}p({path:$.path,diff:M.diff.diff,binary:M.diff.binary??!1,truncated:M.diff.truncated??!1,loading:!1,error:null})}catch(X){const M=X instanceof Error?X.message:"Failed to load diff";p({path:$.path,diff:"",binary:!1,truncated:!1,loading:!1,error:M})}}},[e,n,u,t]),I=l.useCallback($=>{g(""),v(!1),N(null),x(null),h($)},[]),R=l.useCallback(()=>{h(null),N(null),y(!1)},[]),L=l.useCallback(async()=>{var $,X,M;if(m){y(!0),N(null);try{let A;m==="checkpoint"?A=await n(e,"git_checkpoint",{workspace:t,message:b,includeUntracked:f}):m==="stash"?A=await n(e,"git_stash_push",{workspace:t,message:b,includeUntracked:f}):m==="stash_pop"?A=await n(e,"git_stash_pop",{workspace:t}):m==="checkout_files"&&u&&(A=await n(e,"git_checkout_files",{workspace:t,paths:[u.path]}));const E=(A==null?void 0:A.result)??A;if((E==null?void 0:E.success)===!1||E!=null&&E.error){N((E==null?void 0:E.error)??"Action failed"),y(!1);return}m==="checkpoint"?x(`Checkpoint created: ${((X=($=E==null?void 0:E.checkpoint)==null?void 0:$.commit)==null?void 0:X.slice(0,7))??"done"}`):m==="stash"?x(`Stashed as ${((M=E==null?void 0:E.stash)==null?void 0:M.stashRef)??"stash@{0}"}`):m==="stash_pop"?x("Stash restored"):(x("File reverted"),p(null)),h(null),await d()}catch(A){N(A instanceof Error?A.message:"Action failed")}finally{y(!1)}}},[m,n,e,t,b,f,u,d]),T=!!(a!=null&&a.hasConflicts),_=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:$=>{$.target===$.currentTarget&&r()},children:s.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),S&&s.jsx("a",{href:`${S}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-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(vt,{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"}),_===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(D1,{files:o.files,truncated:o.truncated,selectedPath:(u==null?void 0:u.path)??null,onFileClick:C}),!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:u?s.jsx(wm,{diff:u.diff,binary:u.binary,truncated:u.truncated,loading:u.loading,error:u.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"})})]}),k&&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:k}),s.jsx("button",{onClick:()=>x(null),className:"ml-2 text-emerald-400 hover:text-text-primary",children:"×"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[s.jsx("button",{onClick:()=>I("checkpoint"),disabled:T,title:T?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),s.jsx("button",{onClick:()=>I("stash"),disabled:T,title:T?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),s.jsx("button",{onClick:()=>I("stash_pop"),disabled:T||!(a!=null&&a.stashCount),title:T?"Resolve conflicts before restoring a stash":a!=null&&a.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),s.jsx("button",{onClick:()=>I("checkout_files"),disabled:!u,title:u?`Revert changes to ${u.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 $=E1((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText($),x("Copied to clipboard"),setTimeout(()=>x(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),m&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[m==="checkpoint"&&"Create checkpoint commit",m==="stash"&&"Stash changes",m==="stash_pop"&&"Restore latest stash?",m==="checkout_files"&&`Revert changes to ${(u==null?void 0:u.path)??"file"}?`]}),(m==="checkpoint"||m==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:b,onChange:$=>g($.target.value),maxLength:200,placeholder:"Message (required)",className:"rounded border border-border bg-surface-alt px-2 py-1 text-xs text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-border",autoFocus:!0}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:f,onChange:$=>v($.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:R,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:L,disabled:j||(m==="checkpoint"||m==="stash")&&!b.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:j?"Working…":"Confirm"})]})]})})]})})}function B1({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=l.useState(!1),[o,i]=l.useState(!1),[c,d]=l.useState(!1),[u,p]=l.useState(!1),[m,h]=l.useState(!1),[b,g]=l.useState("quickstart"),[f,v]=l.useState("workspace"),j=l.useMemo(()=>!t&&!e,[t,e]),y=l.useCallback(C=>{a(C),C&&i(!1)},[]),w=l.useCallback(C=>{i(C),C&&a(!1)},[]),N=l.useCallback(()=>{g(r===0?"quickstart":"shortcuts"),v("workspace"),d(!0),a(!1),i(!1)},[r]),k=l.useCallback(()=>{d(!1)},[]),x=l.useCallback(()=>{p(!0)},[]),S=l.useCallback(()=>{p(!1)},[]);return l.useEffect(()=>{if(!j){h(!1);return}h(!0);const C=window.setTimeout(()=>{h(!1)},1e4);return()=>window.clearTimeout(C)},[j]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:u,guideNudgeVisible:m,guideTab:b,shortcutSection:f,isDesktopDashboard:j,setGuideTab:g,setShortcutSection:v,handleInboxOpenChange:y,handleHiddenOpenChange:w,handleOpenShortcutHelp:N,closeShortcutHelp:k,openNewSession:x,closeNewSession:S}}function F1(e){switch(e.id){case"triggerPrimaryApprovalAction":case"triggerSecondaryApprovalAction":case"triggerTertiaryApprovalAction":return"approvals";case"splitActiveTabRight":case"splitActiveTabDown":case"focusLeftPane":case"focusRightPane":case"focusUpPane":case"focusDownPane":case"moveActiveTabToLeftPane":case"moveActiveTabToRightPane":case"moveActiveTabToUpPane":case"moveActiveTabToDownPane":return"panes";default:return"workspace"}}function O1(e){return e instanceof Error?e.message:String(e||"")}function H1(e){const t=O1(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function z1({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:i,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:u,mobileChatConversations:p,hiddenConversations:m,ides:h,actionLogs:b,sendDaemonCommand:g,setActionLogs:f,setCliViewModeOverrides:v,isStandalone:j,initialDataLoaded:y,userName:w,requestedMobileTabKey:N,onRequestedMobileTabConsumed:k,requestedMachineId:x,onRequestedMachineConsumed:S,requestedMobileSection:C,onRequestedMobileSectionConsumed:I,containerRef:R,isSplitMode:L,numGroups:T,groupSizes:_,groupedConvs:$,clearedTabs:X,focusedGroup:M,focusGroup:A,moveTabToGroup:E,splitTabRelative:F,closeGroup:z,handleResizeStart:D,groupActiveTabIds:K,setGroupActiveTab:O,groupTabOrders:q,setGroupTabOrder:ne,toggleHiddenTab:J,visibleConversations:ye,requestedDesktopTabKey:oe,onRequestedDesktopTabConsumed:B,onDesktopActiveTabChange:W,onRequestScrollToBottom:ve,onHideConversation:we,onShowHiddenConversation:fe,onShowAllHiddenConversations:Ne,scrollToBottomRequest:re,machineEntries:je,layoutProfile:de,onBrowseMachineDirectory:U,onSaveMachineWorkspace:H,onLaunchMachineIde:Y,onLaunchMachineProvider:se,onListMachineMeshes:xe,onLaunchMeshCoordinator:Z,onListMachineSavedSessions:P,notifications:ie,notificationUnreadCount:be,liveSessionInboxState:ue,onMarkNotificationRead:te,onMarkNotificationUnread:Me,onDeleteNotification:Ae}){const Ce=Ct.useRef(null),{inboxOpen:Ue,hiddenOpen:Qe,shortcutHelpOpen:pe,newSessionOpen:De,guideNudgeVisible:$e,guideTab:tt,shortcutSection:Ke,isDesktopDashboard:Ve,setGuideTab:_e,setShortcutSection:He,handleInboxOpenChange:it,handleHiddenOpenChange:Xe,handleOpenShortcutHelp:Pe,closeShortcutHelp:G,openNewSession:V,closeNewSession:ae}=B1({isMobile:t,showMobileChatMode:e,visibleConversationCount:ye.length}),[le,ge]=Ct.useState(null),[ke,Q]=Ct.useState(null),ee=Ct.useCallback((me,Be)=>{ge({daemonId:me,workspace:Be})},[]),he=Ct.useCallback(me=>{Q(me)},[]),Ie=Ct.useCallback(me=>{var Be;Er.flushSync(()=>{fe(me)}),(Be=Ce.current)==null||Be.restoreHiddenTabToSavedLocation(me.tabKey)},[fe]),Le=Ct.useCallback(me=>{var It;const Be=p.find(Pt=>Lo(Pt,me))||m.find(Pt=>Lo(Pt,me));Be&&(m.some(Pt=>Pt.tabKey===Be.tabKey)&&Ie(Be),W(Be.tabKey),(It=Ce.current)==null||It.activateConversationTab(Be.tabKey),ve(Be.tabKey,"notification-open")),te(me.id),it(!1)},[Ie,m,p,W,te,ve]),Te=Ct.useCallback(()=>{var Be;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Be=Ce.current)==null||Be.resetAllPanelsToMain(),Xe(!1))},[Xe]),Ee=Ct.useCallback(async me=>{var Oe;if(!r)return;const Be=(Oe=r.modalButtons)==null?void 0:Oe[me];if(!Be)return;const It=Ss(r);if(!It)return;const Pt=Be.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),ls=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Pt);try{await g(It,"resolve_action",{button:Be,action:ls?"approve":"reject",buttonIndex:me,...Ns(r)})}catch(at){H1(at)||console.error("[Shortcut approval] Failed:",at)}},[r,g]),{isMac:We,actionDefinitions:Re,actionShortcuts:Ye,shortcutListening:st,shortcutListeningDraft:ht,setShortcutListening:kt,setShortcutListeningDraft:xt,saveShortcuts:bt}=Dw({enabled:Ve&&!pe,onTrigger:me=>{var Be,It,Pt,ls,Oe,at,cs,tn,sn,rn,nn,an,on,ln,cn,gs;if(me==="openShortcutHelp"){Pe();return}if(me==="openNewSession"){V();return}if(me==="hideCurrentTab"){r&&we(r);return}if(me==="toggleHiddenTabs"){Xe(!Qe);return}if(me==="openHistoryForActiveTab"){r&&!rt(r)&&o(r);return}if(me==="openRemoteForActiveTab"){r&&!nt(r)&&!rt(r)&&i(r);return}if(me==="splitActiveTabRight"){(Be=Ce.current)==null||Be.splitActiveTabRight();return}if(me==="splitActiveTabDown"){(It=Ce.current)==null||It.splitActiveTabDown();return}if(me==="floatActiveTab"){(Pt=Ce.current)==null||Pt.floatActiveTab();return}if(me==="popoutActiveTab"){(ls=Ce.current)==null||ls.popoutActiveTab();return}if(me==="dockActiveTab"){(Oe=Ce.current)==null||Oe.dockActiveTab();return}if(me==="focusLeftPane"){(at=Ce.current)==null||at.focusLeftPane();return}if(me==="focusRightPane"){(cs=Ce.current)==null||cs.focusRightPane();return}if(me==="focusUpPane"){(tn=Ce.current)==null||tn.focusUpPane();return}if(me==="focusDownPane"){(sn=Ce.current)==null||sn.focusDownPane();return}if(me==="moveActiveTabToLeftPane"){(rn=Ce.current)==null||rn.moveActiveTabToLeftPane();return}if(me==="moveActiveTabToRightPane"){(nn=Ce.current)==null||nn.moveActiveTabToRightPane();return}if(me==="moveActiveTabToUpPane"){(an=Ce.current)==null||an.moveActiveTabToUpPane();return}if(me==="moveActiveTabToDownPane"){(on=Ce.current)==null||on.moveActiveTabToDownPane();return}if(me==="triggerPrimaryApprovalAction"){Ee(0);return}if(me==="triggerSecondaryApprovalAction"){Ee(1);return}if(me==="triggerTertiaryApprovalAction"){Ee(2);return}if(me==="setActiveTabShortcut"){(ln=Ce.current)==null||ln.setShortcutForActiveTab();return}if(me==="selectPreviousGroupTab"){(cn=Ce.current)==null||cn.activatePreviousTabInGroup();return}if(me==="selectNextGroupTab"){(gs=Ce.current)==null||gs.activateNextTabInGroup();return}!r||!nt(r)||rt(r)||me==="toggleCliView"&&u(d==="chat"?"terminal":"chat")}}),Ge=Ct.useCallback(()=>{G(),kt(null),xt([])},[G,kt,xt]),Ot=Ct.useMemo(()=>Ke==="all"?Re:Re.filter(me=>F1(me)===Ke),[Re,Ke]),ce=Ct.useCallback(()=>{const me=Object.fromEntries(Re.map(Be=>[Be.id,""]));bt(me)},[Re,bt]),Fe=Ct.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const me=Object.fromEntries(Re.map(Be=>[Be.id,Be.defaultShortcut]));bt(me)},[Re,bt]);return Ct.useEffect(()=>{const me=Be=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Be.metaKey&&Be.key.toLowerCase()==="w":Be.ctrlKey&&Be.key.toLowerCase()==="w")&&(Be.preventDefault(),r&&we&&we(r))};return window.addEventListener("keydown",me),()=>window.removeEventListener("keydown",me)},[r,we]),Ct.useEffect(()=>{if(!pe||st)return;const me=Be=>{Be.key==="Escape"&&(Be.preventDefault(),Ge())};return window.addEventListener("keydown",me,!0),()=>window.removeEventListener("keydown",me,!0)},[Ge,pe,st]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(T0,{activeConv:r,wsStatus:n,isConnected:a,conversations:ye,hiddenConversations:m,onOpenHistory:o,onHideConversation:we,onShowConversation:Ie,onShowAllHidden:Ne,onResetPanelsToMain:Te,notifications:ie,notificationUnreadCount:be,onOpenNotification:Le,onMarkNotificationRead:te,onMarkNotificationUnread:Me,onDeleteNotification:Ae,inboxOpen:Ue,onInboxOpenChange:it,hiddenOpen:Qe,onHiddenOpenChange:Xe,onOpenNewSession:t?void 0:V,onOpenDashboardGuide:Pe,guideNudgeVisible:$e,actionShortcuts:Ye,onOpenRemote:()=>{!r||nt(r)||rt(r)||i(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:u,onOpenGitDialog:ee,onOpenMeshGraph:he}),e?s.jsx(kw,{conversations:p,hiddenConversations:m,ides:h,actionLogs:b,sendDaemonCommand:g,setActionLogs:f,setCliViewModeOverrides:v,isStandalone:j,userName:w,requestedActiveTabKey:N,onRequestedActiveTabConsumed:k,requestedMachineId:x,onRequestedMachineConsumed:S,requestedMobileSection:C,onRequestedMobileSectionConsumed:I,onOpenHistory:o,onOpenRemote:i,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Ne,onHideConversation:we,onOpenMeshGraph:he,onOpenNewSession:V,liveSessionInboxState:ue}):t?s.jsx(_w,{containerRef:R,isSplitMode:L,numGroups:T,groupSizes:_,groupedConvs:$,clearedTabs:X,ides:h,actionLogs:b,sendDaemonCommand:g,setActionLogs:f,isStandalone:j,hasRegisteredMachines:je.length>0,userName:w,focusedGroup:M,focusGroup:A,moveTabToGroup:E,splitTabRelative:F,closeGroup:z,handleResizeStart:D,groupActiveTabIds:K,setGroupActiveTab:O,groupTabOrders:q,setGroupTabOrder:ne,toggleHiddenTab:J,onOpenNewSession:V,allowTabShortcuts:!1,liveSessionInboxState:ue}):s.jsx(Yw,{visibleConversations:ye,clearedTabs:X,ides:h,actionLogs:b,sendDaemonCommand:g,setActionLogs:f,isStandalone:j,hasRegisteredMachines:je.length>0,initialDataLoaded:y,userName:w,toggleHiddenTab:J,actionShortcuts:Ye,registerActionHandlers:me=>{Ce.current=me},onActiveTabChange:W,requestedActiveTabKey:oe,onRequestedActiveTabConsumed:B,onRequestScrollToBottom:ve,scrollToBottomRequest:re,onOpenNewSession:V,liveSessionInboxState:ue,layoutProfile:de}),De&&s.jsx(aj,{machines:je,ides:h,onClose:ae,onBrowseDirectory:U,onSaveWorkspace:H,onLaunchIde:Y,onLaunchProvider:se,onListMeshes:xe,onLaunchMeshCoordinator:Z,onListSavedSessions:P}),ke&&s.jsx(j1,{activeConv:ke,sendDaemonCommand:g,onClose:()=>Q(null)}),le&&s.jsx(jm,{daemonId:le.daemonId,workspace:le.workspace,onClose:()=>ge(null)}),pe&&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:Ge,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",onClick:me=>me.stopPropagation(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:Ge,"aria-label":"Close dashboard guide",children:s.jsx(vt,{size:14})})]}),s.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(me=>s.jsx("button",{type:"button",className:`btn btn-sm ${tt===me.id?"btn-primary":"btn-secondary"}`,onClick:()=>_e(me.id),children:me.label},me.id))}),tt==="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 ",We?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),tt==="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."]})]})]})]}),tt==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(me=>s.jsx("button",{type:"button",className:`btn btn-sm ${Ke===me.id?"btn-primary":"btn-secondary"}`,onClick:()=>He(me.id),children:me.label},me.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ce,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:Fe,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Ot.map(me=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${st===me.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:me.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:me.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:me.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:st===me.id?ht.length>0?`${ht.join(" ")} ...`:"Listening...":Ye[me.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{kt(me.id),xt([])},children:st===me.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Be={...Ye};Be[me.id]="",bt(Be)},children:"Disable"})]})]})},me.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",We?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",", or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs."]})]})]})})]})}const ho=[{icon:"🦦",title:"Welcome to ADHDev",desc:"Monitor and control your AI coding agents from anywhere — web, mobile, or CLI.",visual:"🎉"},{icon:"💬",title:"Real-time chat",desc:"See what your AI agent is doing in real-time. Send messages, approve or reject actions — all from your browser or phone.",visual:"📱"},{icon:"🖥️",title:"Remote desktop",desc:"View and control your IDE screen via P2P connection. Click, type, scroll — just like being there.",visual:"🖱️"},{icon:"🚀",title:"Get started",desc:"Install the daemon and link it to your dashboard. It connects automatically.",code:"npm install -g @adhdev/daemon-standalone && adhdev-standalone"}];function W1({onClose:e}){const[t,r]=l.useState(0),n=ho[t],a=t===ho.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:o=>{o.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(vt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:ho.map((o,i)=>s.jsx("div",{style:{width:i===t?24:8,height:8,borderRadius:4,background:i===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},i))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx("span",{children:n.icon})," ",n.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&s.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>a?e():r(o=>o+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
|
|
84
|
+
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
85
|
+
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
86
|
+
`})]})}function K1({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 U1({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,i]=l.useState(()=>a||"native"),c=l.useMemo(()=>Vu(t),[t]),d=l.useMemo(()=>e?Ai(e,{machineNames:c,connectionStates:r,defaultConnectionState:"new"}):[],[e,c,r]),u=l.useMemo(()=>d.find(f=>f.streamSource==="native"),[d]),p=l.useMemo(()=>d.filter(f=>f.streamSource==="agent-stream"),[d]),m=l.useMemo(()=>e?Gt(d,e.id):null,[d,e]);l.useEffect(()=>{a&&i(a)},[a]),l.useEffect(()=>{if(a||!m)return;const f=m.streamSource==="native"?"native":m.tabKey;!f||o===f||o==="native"&&i(f)},[o,m,a]),l.useEffect(()=>{var f;o!=="native"&&(p.some(v=>v.tabKey===o)||i(((f=p[0])==null?void 0:f.tabKey)||"native"))},[o,p]),l.useEffect(()=>{o==="native"&&(u||p[0]&&i(p[0].tabKey))},[o,u,p]);const h=l.useMemo(()=>o==="native"&&u?u:p.find(f=>f.tabKey===o)||m||u||p[0],[o,u,m,p]),b=l.useMemo(()=>p.map(f=>({tabKey:f.tabKey,title:Eu(f)||n,status:f.status})),[p,n]),g=l.useCallback(f=>{if(f)return d.find(v=>Lo(v,{sessionId:f,routeId:f,tabKey:f,providerSessionId:f}))},[d]);return{activeChatTab:o,setActiveChatTab:i,activeConv:h,conversations:d,extensionTabs:b,hasExtensions:b.length>0,resolveConversationByTarget:g}}function G1({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:i,isStandalone:c,userName:d,onOpenHistory:u,onConversationChange:p,onClose:m}){const[h,b]=l.useState("split"),[g,f]=l.useState(()=>bs(e)?"native":e.tabKey),v=l.useRef(null),j=l.useMemo(()=>t||r.find(A=>A.id===e.routeId),[e.routeId,t,r]),y=l.useMemo(()=>Mt((j==null?void 0:j.type)||""),[j==null?void 0:j.type]),{conversations:w,extensionTabs:N,hasExtensions:k}=U1({ideData:j,allIdes:r,connectionStates:n,ideName:y||"IDE",preferredTabKey:bs(e)?void 0:e.tabKey}),x=l.useMemo(()=>j?Gt(w,j.id):null,[j,w]);l.useEffect(()=>{const A=v.current,E={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(v.current=E,!(A&&A.routeId===E.routeId&&A.tabKey===E.tabKey&&A.streamSource===E.streamSource)){if(bs(e)){f("native");return}f(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),l.useEffect(()=>{if(g==="native"){if(w.some(A=>A.streamSource==="native"))return;(x==null?void 0:x.streamSource)==="agent-stream"&&f(x.tabKey);return}if(!w.some(A=>A.tabKey===g)){if((x==null?void 0:x.streamSource)==="agent-stream"){f(x.tabKey);return}f("native")}},[w,g,x]);const S=l.useMemo(()=>g==="native"?w.find(A=>A.streamSource==="native")||e:w.find(A=>A.tabKey===g)||e,[e,w,g]),C=ap(S),I=l.useMemo(()=>C.status||C.modalMessage||C.modalButtons?{...S,...C.status?{status:C.status}:{},...C.modalMessage!==void 0?{modalMessage:C.modalMessage}:{},...C.modalButtons!==void 0?{modalButtons:C.modalButtons}:{}}:S,[S,C]),R=qr(I),L=wa({sendDaemonCommand:o,activeConv:I,setActionLogs:i,isStandalone:c}),{connScreenshot:T,screenshotUsage:_,handleRemoteAction:$}=Rp({doId:R,targetSessionId:wu(I),connState:I.connectionState||"new",viewMode:h}),X=l.useMemo(()=>a.filter(A=>A.routeId===I.tabKey),[a,I.tabKey]);l.useEffect(()=>{p==null||p(I)},[I,p]),l.useEffect(()=>{const A=E=>{E.key==="Escape"&&m()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[m]);const M=l.useCallback(A=>{A.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:m,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:M,children:[s.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[s.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(qt,{size:16})}),s.jsx("span",{className:"truncate",children:wi(S)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:m,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(A=>{const E=h===A;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${E?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>b(A),title:A==="split"?"Split view":"Remote only",children:A==="split"?s.jsx(nf,{size:15}):s.jsx(qt,{size:15})},A)})}),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:()=>u(S),title:"Chat History",children:[s.jsx(ai,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:m,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${h==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[h!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${h==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(K1,{hasExtensions:k,ideName:y||"IDE",activeChatTab:g,extensionTabs:N,onSelectTab:f}),s.jsx(Kd,{activeConv:I,onModalButton:L.handleModalButton}),s.jsx(Wo,{activeConv:I,ideEntry:j,showMetaChips:!1,handleSendChat:L.handleSendChat,handleForceSendChat:L.handleForceSendChat,isSendingChat:L.isSendingChat,sendFeedbackMessage:L.sendFeedbackMessage,handleFocusAgent:L.handleFocusAgent,isFocusingAgent:L.isFocusingAgent,actionLogs:X,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${h==="split"?"order-1 md:order-2":""}`,children:s.jsx(Od,{addLog:()=>{},connState:I.connectionState||"new",connScreenshot:T,screenshotUsage:_,transportType:I.transport,onAction:$})})]})]})})}function V1({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=d0(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 q1({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o,interactivePrompt:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(S0,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(Uu,{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(G1,{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&&(nt(r.targetConv)||rt(r.targetConv))&&s.jsx(V1,{activeConv:r.targetConv,canSaveAndStop:nt(r.targetConv)&&!rt(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(Gu,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),s.jsx(zd,{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(W1,{onClose:o.onClose})]})}function Y1({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(fa,{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=Ft(i,{fallbackId:i.id}),d=n[i.id],u=i.version||i.daemonVersion||"unknown",p=i.versionUpdateRequired===!0,h=xp(i)==="preview"?"Update to preview":p?"Update now":"Upgrade";return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:p?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${p?"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",u]}),p&&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:p?"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:p?"var(--status-danger)":"var(--status-warning)",background:p?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${p?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(i.id),children:h})]},i.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:s.jsx(vt,{size:16})})]})}function J1(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function X1(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 Q1(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>X1(t)).map(t=>t.id)}}function Z1(){var nl,al,ol,il;const{sendCommand:e}=mt(),t=Yr(),r=np(),n=si(),a=Kr(),[o,i]=wh(),c=o.get("activeTab"),d=((nl=n.state)==null?void 0:nl.openRemoteForTabKey)||null,u=((al=n.state)==null?void 0:al.openMachineId)||null,p=((ol=n.state)==null?void 0:ol.mobileSection)||null,m=Pu(),h=m.ides||[],b=m.initialLoaded??!0,{updateRouteChats:g,setToasts:f}=m,[v,j]=l.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),y=m.toasts||[],w=m.wsStatus||"connected",N=m.isConnected??!0,k=m.connectionStates||{},x=m.showReconnected||!1,{layoutProfile:S,groupAssignments:C,updateGroupAssignments:I,focusedGroup:R,updateFocusedGroup:L,focusGroup:T,groupActiveTabIds:_,updateGroupActiveTabIds:$,setGroupActiveTab:X,groupTabOrders:M,updateGroupTabOrders:A,setGroupTabOrder:E,groupSizes:F,updateGroupSizes:z,isMobile:D,hasHydratedStoredLayout:K,hydrateStoredLayout:O,focusConversationTab:q}=gv(),[ne,J]=l.useState(()=>Pi());l.useEffect(()=>Ay(J),[]);const ye=l.useMemo(()=>J1({isMobile:D,mobileViewMode:ne}),[D,ne]),[oe,B]=l.useState([]),[W,ve]=l.useState({}),[we,fe]=l.useState({});Gr("Dashboard",{ideCount:h.length,toastCount:y.length,focusedGroup:R,groupCount:Object.keys(C).length,actionLogCount:oe.length});const Ne=l.useMemo(()=>h.filter(Je=>Je.type==="adhdev-daemon").sort(pi),[h]),je=!!Ne[0];l.useEffect(()=>{const{metadataDaemonIds:Je,runtimeDaemonIds:Ht}=Q1(Ne);for(const cr of Je)t(cr,{minFreshMs:3e4}).catch(()=>{});for(const cr of Ht)r(cr,{minFreshMs:3e4}).catch(()=>{})},[t,r,Ne]);const de=l.useMemo(()=>Ky(h,W),[h,W]),{hiddenTabs:U,autoHiddenTabs:H,autoHideTarget:Y,hideTarget:se,toggleTarget:xe,showTarget:Z,showAllTabs:P}=Px(),{conversations:ie,visibleConversations:be,visibleTabKeys:ue,resolveConversationBySessionId:te,resolveConversationByTarget:Me}=rv({ides:de,connectionStates:k,clearedTabs:we,hiddenTabs:U}),Ae=l.useMemo(()=>new Map(ie.map(Je=>[Je.tabKey,Je])),[ie]),Ce=l.useMemo(()=>Rx(ie,U,H),[ie,U,H]);l.useEffect(()=>{for(const Je of Ce)Y(Je)},[Ce,Y]);const{autoMuteIfCoordinator:Ue}=lu();l.useEffect(()=>{for(const Je of ie)Ue(Je)},[ie,Ue]),$g(be,ye),l.useEffect(()=>{Object.keys(W).length!==0&&ve(Je=>Uy(Je,h))},[h,W]);const Qe=l.useMemo(()=>nx(h),[h]),{notifications:pe,unreadCount:De}=Lv({conversations:ie,liveSessionInboxState:Qe}),{handleMarkDashboardNotificationRead:$e,handleMarkDashboardNotificationUnread:tt,handleDeleteDashboardNotification:Ke}=Dv({notifications:pe,sendDaemonCommand:e}),{containerRef:Ve,normalizedGroupAssignments:_e,numGroups:He,isSplitMode:it,groupedConvs:Xe,moveTabToGroup:Pe,closeGroup:G,handleResizeStart:V,splitTabRelative:ae}=Sv({groupAssignments:C,updateGroupAssignments:I,updateFocusedGroup:L,updateGroupActiveTabIds:$,updateGroupTabOrders:A,groupSizes:F,updateGroupSizes:z,isMobile:D,visibleConversations:be,visibleTabKeys:ue}),{activeConv:le,openDesktopConversation:ge,requestScrollToBottom:ke,scrollToBottomRequest:Q,setDesktopActiveTab:ee}=qv({isMobile:D,conversations:ie,visibleConversations:be,groupActiveTabIds:_,focusedGroup:R,groupedConvs:Xe,setSearchParams:i});Xv({activeConv:le,isMobile:D,liveSessionInboxState:Qe,sendDaemonCommand:e});const{requestedDesktopTabKey:he,requestedMobileTabKey:Ie,consumeRequestedActiveTab:Le}=nv({isMobile:D,urlActiveTab:c,resolveConversationBySessionId:te,setSearchParams:i}),{remoteDialogConv:Te,remoteDialogIdeEntry:Ee,remoteDialogActiveConv:We,setRemoteDialogActiveConv:Re,openRemoteDialog:Ye,closeRemoteDialog:st,cliStopDialogOpen:ht,cliStopTargetConv:kt,requestCliStop:xt,cancelCliStop:bt,confirmCliStop:Ge}=ew({isMobile:D,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:he,conversations:ie,ides:h,resolveConversationByTarget:Me,activeConv:le,sendDaemonCommand:e}),{historyModalOpen:Ot,openHistoryModal:ce,closeHistoryModal:Fe,historyTargetConv:me,isSavedSessionHistoryTarget:Be,isHistoryCreatingChat:It,isHistoryRefreshingHistory:Pt,handleHistorySwitchSession:ls,handleHistoryNewChat:Oe,handleHistoryRefresh:at,savedHistorySessions:cs,savedHistoryFilters:tn,setSavedHistoryFilters:sn,missingWorkspaceResumePath:rn,isSavedHistoryLoading:nn,resumingSavedHistorySessionId:an,handleRefreshSavedHistory:on,handleResumeSavedHistorySession:ln}=Qv({activeConv:le,remoteDialogConv:Te,remoteDialogActiveConv:We,ides:h,sendDaemonCommand:e,updateRouteChats:g,setToasts:f,setClearedTabs:fe,setSearchParams:i}),cn=l.useMemo(()=>be,[be]),gs=D&&ne==="chat",Rm=l.useMemo(()=>ie.filter(Je=>ya(U,Je)),[ie,U]),tl=l.useCallback(Je=>{const Ht=new URLSearchParams(o);Ht.set("activeTab",Je),i(Ht,{replace:!0})},[o,i]),{trackPendingLaunch:Pm}=Kv({ides:h,conversations:ie,onOpenSession:tl}),{handleBrowseMachineDirectory:Lm,handleSaveMachineWorkspace:Dm,handleLaunchMachineIde:$m,handleLaunchMachineProvider:Em,handleListMachineMeshes:Bm,handleLaunchMeshCoordinator:Fm,handleListMachineSavedSessions:Om,setActiveCliViewMode:Hm}=Uv({sendDaemonCommand:e,trackPendingLaunch:Pm,onOpenSession:tl,activeConv:le,ides:h,setCliViewModeOverrides:ve});Gy({visibleConversations:be,clearedTabs:we,setClearedTabs:fe,setActionLogs:B}),av({ides:h,sendDaemonCommand:e,setToasts:f,resolveConversationByTarget:Me});const zm=op(),{isRefreshingHistory:Wm,handleRefreshHistory:Km}=fp({sendDaemonCommand:e,activeConv:le,chats:(il=h.find(Je=>Je.id===(le==null?void 0:le.routeId)))==null?void 0:il.chats,updateRouteChats:g,setToasts:f,setClearedTabs:fe});vv({urlActiveTab:D&&!gs?c:null,conversations:ie,resolveConversationBySessionId:te,normalizedGroupAssignments:_e,hasHydratedStoredLayout:D&&!gs?K:!0,hydrateStoredLayout:D&&!gs?O:()=>{},focusConversationTab:q,setSearchParams:i,historyModalOpen:Ot,activeConv:le,isRefreshingHistory:Wm,ides:h,handleRefreshHistory:Km});const Um=l.useMemo(()=>!le||!nt(le)||rt(le)?null:lr(le),[le]),{versionMismatchDaemons:Gm,hasRequiredVersionDaemons:sl,targetVersion:Vm,versionBannerDismissed:qm,setVersionBannerDismissed:Ym,upgradingDaemons:Jm,handleBannerUpgrade:Xm}=Iv({ides:h,sendDaemonCommand:e}),rl=l.useCallback(Je=>{Z(Je),ge(Je)},[ge,Z]),Qm=l.useCallback(Je=>{se(Je)},[se]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[(!qm||sl)&&s.jsx(Y1,{daemons:Gm,targetVersion:Vm,required:sl,upgradingDaemons:Jm,onUpgrade:Xm,onDismiss:()=>Ym(!0)}),s.jsx(z1,{showMobileChatMode:gs,isMobile:D,activeConv:le,wsStatus:w,isConnected:N,onOpenHistory:Je=>{Je&&Re(Je),ce()},onOpenRemote:Ye,onStopCli:xt,activeCliViewMode:Um,onSetActiveCliViewMode:Hm,mobileChatConversations:cn,ides:h,actionLogs:oe,sendDaemonCommand:e,setActionLogs:B,setCliViewModeOverrides:ve,isStandalone:je,initialDataLoaded:b,userName:m.userName,requestedMobileTabKey:Ie,onRequestedMobileTabConsumed:Le,requestedMachineId:u,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:p,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:Ve,isSplitMode:it,numGroups:He,groupSizes:F,groupedConvs:Xe,clearedTabs:we,focusedGroup:R,focusGroup:T,moveTabToGroup:Pe,splitTabRelative:ae,closeGroup:G,handleResizeStart:V,groupActiveTabIds:_,setGroupActiveTab:X,groupTabOrders:M,setGroupTabOrder:E,toggleHiddenTab:Je=>xe(Ae.get(Je)||{tabKey:Je}),visibleConversations:be,hiddenConversations:Rm,requestedDesktopTabKey:he,onRequestedDesktopTabConsumed:Le,onDesktopActiveTabChange:ee,onRequestScrollToBottom:ke,onHideConversation:Qm,onShowHiddenConversation:rl,onShowAllHiddenConversations:P,scrollToBottomRequest:Q,machineEntries:Ne,layoutProfile:S,onBrowseMachineDirectory:Lm,onSaveMachineWorkspace:Dm,onLaunchMachineIde:$m,onLaunchMachineProvider:Em,onListMachineMeshes:Bm,onLaunchMeshCoordinator:Fm,onListMachineSavedSessions:Om,notifications:pe,notificationUnreadCount:De,liveSessionInboxState:Qe,onMarkNotificationRead:$e,onMarkNotificationUnread:tt,onDeleteNotification:Ke}),s.jsx("style",{children:`
|
|
87
|
+
body { overflow: hidden; overscroll-behavior: none; }
|
|
88
|
+
`}),s.jsx(q1,{historyModal:{open:Ot,targetConv:me,ides:h,isCreatingChat:It,isRefreshingHistory:Be?!1:Pt,savedSessions:cs,savedHistoryFilters:tn,missingWorkspaceResumePath:rn||null,onSavedHistoryFiltersChange:sn,isSavedSessionsLoading:nn,isResumingSavedSessionId:an,onClose:Fe,onNewChat:Oe,onSwitchSession:ls,onRefreshHistory:Be?on:at,onResumeSavedSession:ln},remoteDialog:{conversation:Te,ideEntry:Ee,ides:h,connectionStates:k,actionLogs:oe,sendDaemonCommand:e,setActionLogs:B,isStandalone:je,userName:m.userName,onOpenHistory:Je=>{Je&&Re(Je),ce()},onConversationChange:Re,onClose:st},cliStopDialog:{open:ht,targetConv:kt,onCancel:bt,onStopNow:async()=>{await Ge("hard")},onSaveAndStop:async()=>{await Ge("save")}},connectionBanner:{wsStatus:w,showReconnected:x,loginUrl:m.connectionLoginUrl,onReconnect:m.retryServerConnection},toastOverlay:{toasts:y,onDismiss:Je=>f(Ht=>Ht.filter(cr=>cr.id!==Je)),onClick:Je=>{if(Je.targetKey){const Ht=Me(Je.targetKey);Ht&&(q(Ht.tabKey,_e),rl(Ht),ke(Ht.tabKey,"toast-open"))}}},onboarding:{open:v,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}j(!1)}},interactivePrompt:zm})]})}function eN({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const{launchCli:o}=ma(),[i,c]=l.useState([]),[d,u]=l.useState(null),[p,m]=l.useState(null),[h,b]=l.useState(!1),[g,f]=l.useState(null),[v,j]=l.useState(!1),[y,w]=l.useState(""),N=l.useRef(null),k=l.useCallback(z=>{N.current=z},[]),x=l.useCallback((z,D,K=!1)=>{c(O=>[...O.slice(-100),{timestamp:Date.now(),level:z,message:D}]),setTimeout(()=>{var O;return(O=a.current)==null?void 0:O.scrollIntoView({behavior:"smooth"})},100),K&&ot.showToast(D,z==="error"||z==="warn"?"warning":"success")},[a]),S=l.useCallback(z=>{const D=z instanceof Error?z.message:String(z||"");return D.includes("P2P command timeout")||D.includes("P2P not connected")||D.includes("P2P not available")},[]),C=l.useCallback(async(z,D)=>{var K;if(!e||d)return!1;u(z),x("info",`Launching ${Mt(z)}${D!=null&&D.workspace?` in ${D.workspace}`:""}...`);try{const O={ideType:z,enableCdp:!0};(K=D==null?void 0:D.workspace)!=null&&K.trim()?O.workspace=D.workspace.trim():D!=null&&D.useDefaultWorkspace&&(O.useDefaultWorkspace=!0);const q=await r(e,"launch_ide",O);return x(q!=null&&q.success?"info":"error",q!=null&&q.success?`${Mt(z)} launched`:`Failed: ${q==null?void 0:q.error}`,!0),!!(q!=null&&q.success)}catch(O){return x("error",`Launch error: ${O.message}`,!0),!1}finally{u(null)}},[e,d,x,r]),I=l.useCallback(async z=>{if(!e)return{success:!1};const{cliType:D,dir:K,workspaceId:O,useDefaultWorkspace:q,useHome:ne,argsStr:J,model:ye,resumeSessionId:oe}=z;if(!D)return x("warn","Select a CLI or ACP provider first",!0),{success:!1};const B=J?J.split(/\s+/).filter(Boolean):void 0,W=(K==null?void 0:K.trim())||(O?"(saved id)":q?"(default workspace)":ne?"(home)":"");x("info",`Launching ${D}${W?` in ${W}`:""}${ye?` (model: ${ye})`:""}...`),m(D);try{const ve={cliType:D,cliArgs:B,initialModel:ye||void 0};K!=null&&K.trim()?ve.dir=K.trim():O?ve.workspaceId=O:q?ve.useDefaultWorkspace=!0:ne&&(ve.useHome=!0),oe&&(ve.resumeSessionId=oe);const we=await o(e,ve),fe=(we==null?void 0:we.result)||we;return we!=null&&we.success?(x("info",`${D} launched`,!0),(fe==null?void 0:fe.launchSource)==="home"?x("info","📂 Running in home directory (explicit choice)"):(fe==null?void 0:fe.launchSource)==="defaultWorkspace"&&x("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:fe==null?void 0:fe.sessionId}):(x("error",`Failed: ${(we==null?void 0:we.error)||(fe==null?void 0:fe.error)}`,!0),(we==null?void 0:we.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&f({cliType:D,argsStr:J,model:ye}),{success:!1,sessionId:fe==null?void 0:fe.sessionId})}catch(ve){return S(ve)?(x("warn",`${D} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(x("error",`Launch error: ${ve.message}`,!0),{success:!1})}finally{m(null)}},[e,x,S,r]),R=l.useCallback(async(z,D,K,O)=>e?z?D.trim()?I({cliType:z,dir:D,argsStr:K,model:O}):(f({cliType:z,argsStr:K,model:O}),{success:!1}):(x("warn","Select a provider",!0),{success:!1}):{success:!1},[e,x,I]),L=l.useCallback(async(z,D,K)=>{if(e&&window.confirm(`Stop ${z}?
|
|
89
|
+
This will terminate the process.`))try{const O=await r(e,"stop_cli",{cliType:z,dir:D,targetSessionId:K});O!=null&&O.success?x("info",`${z} stopped`,!0):x("error",`Stop failed: ${(O==null?void 0:O.error)||"Unknown error"}`,!0)}catch(O){x("error",`Stop failed: ${O.message}`,!0)}},[e,x,r]),T=l.useCallback(async z=>{try{await r(z.daemonId,"restart_ide",{ideType:z.type}),x("info",`${Mt(z.type)} restart initiated`,!0)}catch(D){x("error",`Restart failed: ${D.message}`,!0)}},[x,r]),_=l.useCallback(async z=>{if(window.confirm(`Stop ${Mt(z.type)}?
|
|
90
|
+
This will disconnect CDP and optionally kill the process.`))try{const D=await r(z.daemonId,"stop_ide",{ideType:z.type,killProcess:!0});D!=null&&D.success?x("info",`${Mt(z.type)} stopped`,!0):x("error",`Stop failed: ${(D==null?void 0:D.error)||"Unknown error"}`,!0)}catch(D){x("error",`Stop failed: ${D.message}`,!0)}},[x,r]),$=l.useCallback(async()=>{if(e)try{const z=await r(e,"detect_ides",{});x("info",`Found ${((z==null?void 0:z.result)||[]).length} IDE(s)`,!0)}catch(z){x("error",`Detection failed: ${z.message}`,!0)}},[e,x,r]),X=l.useCallback(async z=>{if(!e||!z.trim())return!1;b(!0);try{const D=await r(e,"workspace_add",{path:z.trim()});return D!=null&&D.success?(x("info",`Workspace added: ${z.trim()}`),!0):(x("error",(D==null?void 0:D.error)||"workspace_add failed"),!1)}catch(D){return x("error",D.message),!1}finally{b(!1)}},[e,x,r]),M=l.useCallback(async z=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){b(!0);try{const D=await r(e,"workspace_remove",{id:z});D!=null&&D.success?x("info","Workspace removed",!0):x("error",(D==null?void 0:D.error)||"workspace_remove failed",!0)}catch(D){x("error",D.message,!0)}finally{b(!1)}}},[e,x,r]),A=l.useCallback(async z=>{var D;if(e){b(!0);try{const K=await r(e,"workspace_set_default",z===null?{clear:!0}:{id:z});if(K!=null&&K.success){x("info",z?"Default workspace updated":"Default workspace cleared",!0);const O=typeof K.defaultWorkspacePath=="string"?K.defaultWorkspacePath:"";O&&((D=N.current)==null||D.call(N,O))}else x("error",(K==null?void 0:K.error)||"workspace_set_default failed",!0)}catch(K){x("error",K.message,!0)}finally{b(!1)}}},[e,x,r]),E=l.useCallback(async z=>{var K;if(!e||!z.trim())return;const D=z.trim();b(!0);try{const O=await r(e,"workspace_set_default",{path:D});O!=null&&O.success?(x("info","Default workspace set from history"),(K=N.current)==null||K.call(N,D)):x("error",(O==null?void 0:O.error)||"Could not set default (path missing on disk?)")}catch(O){x("error",O.message)}finally{b(!1)}},[e,x,r]),F=l.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:y}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:y})}catch(z){x("warn",`Live nickname updated, but account sync failed: ${z.message}`)}x("info",`Nickname set to "${y||"(cleared)"}"`),j(!1)}catch(z){x("error",`Failed: ${z.message}`)}},[e,y,t,x,n,r]);return{logs:i,launchingIde:d,launchingAgentType:p,workspaceBusy:h,launchPick:g,setLaunchPick:f,editingNickname:v,setEditingNickname:j,nicknameInput:y,setNicknameInput:w,addLog:x,handleLaunchIde:C,runLaunchCliCore:I,handleLaunchCli:R,handleStopCli:L,handleRestartIde:T,handleStopIde:_,handleDetectIdes:$,handleWorkspaceAdd:X,handleWorkspaceRemove:M,handleWorkspaceSetDefault:A,handleWorkspaceResumePath:E,handleSaveNickname:F,setOnDefaultWorkspaceChanged:k}}function tN({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(pn,{icon:s.jsx(Md,{size:16}),label:"Uptime",value:typeof e.uptime=="number"?dx(e.uptime):"Waiting…"}),s.jsx(pn,{icon:s.jsx(qt,{size:16}),label:"IDEs",value:`${t.length}`}),s.jsx(pn,{icon:s.jsx(ii,{size:16}),label:"CLIs",value:`${r.length}`}),s.jsx(pn,{icon:s.jsx(of,{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(jl,{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(jl,{value:i,max:100,label:"Memory",color:"#3b82f6",detail:a?`${$a(e.totalMem-o)} / ${$a(e.totalMem)}${e.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${$a(e.totalMem)} total`})]})]})]})}function sN(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 rN(e,t,r){const n=[];for(const[a,o]of Object.entries(e.settings)){const i=r!=null&&r.filterSchema?r.filterSchema(o):o;if(i.length===0)continue;const c=t.find(d=>d.type===a);n.push({type:a,displayName:(c==null?void 0:c.displayName)||a,icon:(c==null?void 0:c.icon)||"",category:(c==null?void 0:c.category)||"unknown",schema:i,values:e.values[a]||{}})}return n}function fo(e){if(!e||typeof e!="object")return!1;const t=e;return(t.sourceMode==="normal"||t.sourceMode==="no-upstream")&&typeof t.disableUpstream=="boolean"&&(t.explicitProviderDir===null||typeof t.explicitProviderDir=="string")&&typeof t.userDir=="string"&&typeof t.upstreamDir=="string"&&Array.isArray(t.providerRoots)}function Xc(e){if(!e||typeof e!="object")return null;if(fo(e))return e;const t=e,r=t.result;return fo(r)?r:fo(t.sourceConfig)?t.sourceConfig:null}function nN(e){const t=e.trim();return t||null}function aN({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var k;const o=t.filter(x=>x.category==="ide"),[i,c]=l.useState(((k=o[0])==null?void 0:k.type)||""),[d,u]=l.useState(""),[p,m]=l.useState(""),[h,b]=l.useState(!1),[g,f]=l.useState(""),[v,j]=l.useState(!1),y=x=>{const S=x.toLowerCase().replace(/[^a-z0-9-]/g,"");u(S),(!p||p===w(d))&&m(w(S))},w=x=>x.split("-").map(S=>S.charAt(0).toUpperCase()+S.slice(1)).join(" "),N=async()=>{if(!(!d||!p||!i)){b(!0),f("");try{const x=await r(e,"provider_clone",{type:d,name:p,category:"ide",location:"user",cloneFrom:i});x!=null&&x.success||x!=null&&x.created?(j(!0),a==null||a(d)):f((x==null?void 0:x.error)||"Failed to create provider")}catch(x){f((x==null?void 0:x.message)||"Connection failed")}b(!1)}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:s.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:x=>x.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:v?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:d})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:o.map(x=>s.jsxs("button",{onClick:()=>c(x.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:i===x.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:i===x.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:x.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:i===x.type?"#a78bfa":"var(--text-secondary)"},children:x.displayName})]},x.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:d,onChange:x=>y(x.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",d||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:p,onChange:x=>m(x.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),g&&s.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:g})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:v?s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:N,disabled:!d||!p||h,className:"machine-btn",style:{background:d&&p?"rgba(34,197,94,0.12)":void 0,borderColor:d&&p?"rgba(34,197,94,0.3)":void 0,color:d&&p?"#86efac":void 0,opacity:!d||!p||h?.4:1},children:h?"⏳ Creating...":"✨ Create Provider"})]})})]})})}const Qc={"user-custom":"Custom",trusted:"Official","trusted-with-scripts":"Official · runs JS","external-safe":"External · spec-only","external-untrusted":"⚠ External · untrusted JS"},oN={"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 iN({trust:e,sourceName:t,description:r}){const n=t&&(e==="external-safe"||e==="external-untrusted")?`${Qc[e]} · ${t}`:Qc[e];return s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded border whitespace-nowrap ${oN[e]}`,title:r,children:n})}function lN(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 cN={detected:"Detected",not_detected:"Not detected",enabled_unchecked:"Enabled (unchecked)",disabled:"Disabled"},Zc={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"},dN={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 ed(e){if(!e)return"—";const t=e.ok?"OK":"Failed",r=e.message||e.path||e.command||"";return r?`${t} — ${r}`:t}function uN(e){return e==="cli"||e==="acp"}function pN({prov:e,providerInfo:t,savingKey:r,onSetSetting:n,onEnableToggle:a,onDetect:o,onResetCommand:i}){const[c,d]=l.useState(!1),u=(t==null?void 0:t.enabled)===!0||e.values.enabled===!0,p=t==null?void 0:t.machineStatus,m=u&&p==="disabled"?"enabled_unchecked":p||(u?"enabled_unchecked":"disabled"),h=uN(e.category);return s.jsxs("div",{className:"rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("button",{onClick:()=>d(b=>!b),className:"w-full px-4 py-2.5 flex items-center gap-3 text-left",children:[s.jsx("span",{className:"text-base shrink-0",children:e.icon}),s.jsx("span",{className:"text-[13px] font-semibold text-text-primary truncate",children:e.displayName}),s.jsx("span",{className:`text-[9px] font-semibold px-1.5 py-px rounded border ${dN[e.category]??"border-border-subtle text-text-muted"}`,children:e.category.toUpperCase()}),(t==null?void 0:t.trust)&&s.jsx(iN,{trust:t.trust,sourceName:t.sourceName??null,description:t.trustDescription}),h&&s.jsx("span",{className:`text-[9px] font-semibold px-1.5 py-px rounded border ${Zc[m]??Zc.disabled}`,children:cN[m]??m}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[h&&s.jsx("button",{onClick:b=>{b.stopPropagation(),a(e.type,!u)},disabled:r===`${e.type}.enabled`,className:`machine-btn text-[10px] px-2 py-0.5 ${u?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:u?"Disable":"Enable"}),s.jsx("span",{className:"text-text-muted text-xs",children:c?"▾":"▸"})]})]}),c&&s.jsxs("div",{className:"border-t border-border-subtle px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{className:"grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Type:"})," ",s.jsx("span",{className:"font-mono",children:e.type})]}),(t==null?void 0:t.providerVersion)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Version:"})," ",t.providerVersion]}),(t==null?void 0:t.binary)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Binary:"})," ",s.jsx("span",{className:"font-mono",children:t.binary})]}),(t==null?void 0:t.status)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Status:"})," ",t.status]}),(t==null?void 0:t.details)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Details:"})," ",t.details]}),(t==null?void 0:t.sourceLayer)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Source:"})," ",t.sourceLayer,t.sourceName?` · ${t.sourceName}`:""]}),(t==null?void 0:t.trust)&&(t==null?void 0:t.trustDescription)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Trust:"})," ",t.trustDescription]}),(()=>{const b=t==null?void 0:t.links;if(!b)return null;const g=Object.entries(b).map(([f,v])=>({k:f,href:lN(v)})).filter(f=>f.href!==null);return g.length===0?null:s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Links:"})," ",g.map(({k:f,href:v})=>s.jsx("a",{href:v,target:"_blank",rel:"noopener noreferrer",className:"text-violet-400 hover:underline mr-2",children:f},f))]})})()]}),h&&s.jsxs("div",{className:"grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Detection:"})," ",ed(t==null?void 0:t.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Verification:"})," ",ed(t==null?void 0:t.lastVerification)]})]}),e.schema.length>0&&s.jsx("div",{className:"flex flex-col gap-1.5",children:e.schema.map(b=>s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-[11px] font-medium text-text-primary",children:[b.label||b.key,r===`${e.type}.${b.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving…"})]}),b.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:b.description})]}),s.jsx("div",{className:"shrink-0",children:b.type==="boolean"?s.jsx("button",{onClick:()=>void n(e.type,b.key,!(e.values[b.key]??b.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:e.values[b.key]??b.default?"#8b5cf6":"var(--border-subtle)"},children:s.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:e.values[b.key]??b.default?21:3}})}):b.type==="number"?s.jsx("input",{type:"number",value:Number(e.values[b.key]??b.default??0)||0,min:b.min,max:b.max,onChange:g=>{const f=parseInt(g.target.value)||0;b.min!==void 0&&f<b.min||b.max!==void 0&&f>b.max||n(e.type,b.key,f)},className:"machine-input w-20 text-center text-[11px]"}):b.type==="select"&&b.options?s.jsx("select",{value:String(e.values[b.key]??b.default??""),onChange:g=>void n(e.type,b.key,g.target.value),className:"machine-input text-[11px]",children:b.options.map(g=>s.jsx("option",{value:g,children:g},g))}):s.jsx("input",{type:"text",defaultValue:String(e.values[b.key]??b.default??""),onBlur:g=>void n(e.type,b.key,g.target.value),className:"machine-input w-[180px] text-[11px]"})})]},b.key))}),s.jsx("div",{className:"flex gap-1.5 flex-wrap pt-1 border-t border-border-subtle",children:h&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>void o(e.type),disabled:!u||r===`${e.type}.detect`,className:`machine-btn text-[10px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${u?"":"opacity-40 cursor-not-allowed"}`,title:u?"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 An(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function mN({machineId:e,sendDaemonCommand:t,onChange:r}){const[n,a]=l.useState([]),[o,i]=l.useState([]),[c,d]=l.useState(!1),[u,p]=l.useState(null),[m,h]=l.useState(!1),[b,g]=l.useState(""),[f,v]=l.useState("main"),[j,y]=l.useState(""),[w,N]=l.useState(!1),[k,x]=l.useState(null),[S,C]=l.useState(null),I=l.useCallback(async()=>{if(e){d(!0),p(null);try{const _=An(await t(e,"list_provider_sources",{}));if(!(_!=null&&_.success)){p((_==null?void 0:_.error)||"Failed to load sources");return}a(_.sources||[]),i(_.conflicts||[])}catch(_){p((_==null?void 0:_.message)||String(_))}finally{d(!1)}}},[e,t]);l.useEffect(()=>{I()},[I]);const R=async()=>{if(b.trim()){N(!0),p(null);try{const _=An(await t(e,"add_provider_source",{url:b.trim(),ref:f.trim()||"main",...j.trim()?{name:j.trim()}:{}}));_!=null&&_.success?(h(!1),g(""),v("main"),y(""),await I(),r==null||r()):p((_==null?void 0:_.error)||"Failed to add source")}catch(_){p((_==null?void 0:_.message)||String(_))}finally{N(!1)}}},L=async _=>{if(confirm(`Remove provider source ${_}? This deletes the cloned manifests and clears any active-source entries that pointed here.`)){x(_),p(null);try{const $=An(await t(e,"remove_provider_source",{name:_}));$!=null&&$.success?(await I(),r==null||r()):p(($==null?void 0:$.error)||"Failed to remove source")}catch($){p(($==null?void 0:$.message)||String($))}finally{x(null)}}},T=async(_,$)=>{C(`${_}:${$}`),p(null);try{const X=An(await t(e,"set_active_provider_source",{type:_,sourceName:$}));X!=null&&X.success?(await I(),r==null||r()):p((X==null?void 0:X.error)||"Failed to set active source")}catch(X){p((X==null?void 0:X.message)||String(X))}finally{C(null)}};return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-sky-400",children:"External sources"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"3rd-party git URLs you've added. Providers here may ship JavaScript the daemon will execute — activation requires a confirmation."})]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsxs("button",{onClick:()=>void I(),disabled:c,className:"machine-btn text-[10px]",children:[c?"⏳":"↻"," Refresh"]}),s.jsx("button",{onClick:()=>h(!0),className:"machine-btn text-[10px] bg-sky-500/[0.08] border-sky-500/20 text-sky-300 hover:bg-sky-500/[0.14]",children:"+ Add source"})]})]}),u&&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:u}),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(_=>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:_.name}),s.jsxs("div",{className:"text-[10px] text-text-muted truncate",children:[_.url," ",s.jsxs("span",{className:"opacity-60",children:["@ ",_.ref]})]})]}),s.jsx("button",{type:"button",onClick:()=>void L(_.name),disabled:k===_.name,className:"machine-btn text-[10px] text-red-400 hover:bg-red-500/[0.10]",children:k===_.name?"…":"Remove"})]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:Object.entries(_.providers).map(([$,X])=>s.jsxs("span",{className:"mr-3",children:[s.jsxs("span",{className:"text-text-secondary",children:[$,":"]})," ",X.length]},$))})]},_.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(_=>s.jsxs("li",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"font-mono text-[11px]",children:[_.type," ",s.jsxs("span",{className:"text-text-muted",children:["(",_.category,")"]})]}),s.jsx("div",{className:"flex gap-1.5 flex-wrap",children:_.candidates.map($=>s.jsxs("button",{type:"button",onClick:()=>void T(_.type,$),disabled:S===`${_.type}:${$}`,className:`text-[10px] px-2 py-0.5 rounded border ${_.active===$?"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:_.active===$?"Active":`Switch active to ${$}`,children:[_.active===$?"● ":"",$]},$))})]},_.type))})]}),m&&s.jsxs("div",{className:"mt-3 rounded border border-sky-500/30 bg-sky-500/[0.06] px-3 py-3",children:[s.jsx("div",{className:"text-[11px] font-semibold text-sky-300 mb-2",children:"Add external source"}),s.jsxs("div",{className:"grid md:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[10px] text-text-secondary md:col-span-3",children:[s.jsx("span",{children:"Git URL"}),s.jsx("input",{type:"text",value:b,onChange:_=>g(_.target.value),placeholder:"https://github.com/vendor/extra-providers",className:"machine-input text-[11px] font-mono"})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[10px] text-text-secondary",children:[s.jsx("span",{children:"Ref (branch/tag)"}),s.jsx("input",{type:"text",value:f,onChange:_=>v(_.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:_=>y(_.target.value),placeholder:"@vendor-extra-providers",className:"machine-input text-[11px] font-mono"})]})]}),s.jsxs("div",{className:"mt-3 flex items-center justify-end gap-2",children:[s.jsx("button",{type:"button",onClick:()=>h(!1),className:"machine-btn text-[10px]",children:"Cancel"}),s.jsx("button",{type:"button",onClick:()=>void R(),disabled:w||!b.trim(),className:"machine-btn text-[10px] bg-sky-500/[0.10] border-sky-500/30 text-sky-200 hover:bg-sky-500/[0.18]",children:w?"Cloning…":"Clone + register"})]})]})]})}function hN({machineId:e,providers:t,sendDaemonCommand:r}){var A;const[n,a]=l.useState([]),[o,i]=l.useState(!1),[c,d]=l.useState(null),[u,p]=l.useState("all"),[m,h]=l.useState(!1),[b,g]=l.useState(!1),[f,v]=l.useState(!1),[j,y]=l.useState(null),[w,N]=l.useState("normal"),[k,x]=l.useState(""),[S,C]=l.useState(!1),I=l.useCallback(async()=>{if(e)try{const E=await r(e,"get_provider_source_config",{}),F=Xc(E);F&&(y(F),N(F.sourceMode),x(F.explicitProviderDir||""))}catch{}},[e,r]),R=l.useCallback(async()=>{if(e){i(!0);try{const E=await r(e,"get_provider_settings",{}),F=sN(E);if(F){const z=rN(F,t,{filterSchema:D=>D.filter(K=>K.key!=="enabled")});z.sort((D,K)=>D.category.localeCompare(K.category)||D.displayName.localeCompare(K.displayName)),a(z)}}catch{}i(!1)}},[e,t,r]);l.useEffect(()=>{n.length===0&&R(),j||I()},[]);const L=async(E,F,z)=>{d(`${E}.${F}`),a(D=>D.map(K=>K.type===E?{...K,values:{...K.values,[F]:z}}:K));try{const D=await r(e,"set_provider_setting",{providerType:E,key:F,value:z});D!=null&&D.success||R()}catch{R()}d(null)},T=async(E,F)=>{await L(E,"enabled",F),await R()},_=async E=>{d(`${E}.detect`);try{await r(e,"detect_provider",{providerType:E})}finally{await R(),d(null)}},$=async E=>{await L(E,"executablePath",""),await L(E,"executableArgs",""),await R()},X=async()=>{C(!0);try{const E=await r(e,"set_provider_source_config",{providerSourceMode:w,providerDir:nN(k)}),F=Xc(E);F?(y(F),N(F.sourceMode),x(F.explicitProviderDir||"")):await I(),await R()}catch{await I()}C(!1)},M=n.filter(E=>u==="all"||E.category===u);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(E=>s.jsx("button",{onClick:()=>p(E),className:`machine-btn text-[10px] px-2 py-0.5 ${u===E?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:E.toUpperCase()},E))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>g(E=>!E),className:`machine-btn text-[10px] ${b?"bg-sky-500/[0.10] border-sky-500/30 text-sky-300":""}`,title:"Manage 3rd-party provider sources",children:"🌐 Sources"}),s.jsx("button",{onClick:()=>h(!0),className:"machine-btn text-[10px]",title:"Create a new provider from an existing one",children:"✨ Create"}),s.jsxs("button",{onClick:R,disabled:o,className:"machine-btn text-[10px]",children:[o?"⏳":"↻"," Refresh"]}),s.jsx("button",{onClick:()=>v(E=>!E),className:"machine-btn text-[10px]",title:"Show source configuration (advanced)",children:"⚙ Advanced"})]})]}),b&&s.jsx(mN,{machineId:e,sendDaemonCommand:r,onChange:()=>{R()}}),f&&s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Where the daemon looks for provider manifests. Affects resolution and reloads."})]}),s.jsx("button",{onClick:I,className:"machine-btn text-[10px]",children:"↻ Refresh"})]}),s.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),s.jsxs("select",{value:w,onChange:E=>N(E.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:k,onChange:E=>x(E.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void X(),disabled:S,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:S?"Applying…":"Apply + Reload"})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"User root:"})," ",(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:"})," ",((A=j==null?void 0:j.providerRoots)==null?void 0:A.join(" → "))||"—"]})]})]}),o&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings…"}):M.length===0?s.jsx("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:u==="all"?'No providers installed yet. Open "Add provider" above to install one.':`No ${u.toUpperCase()} providers installed.`})}):s.jsx("div",{className:"flex flex-col gap-1.5",children:M.map(E=>s.jsx(pN,{prov:E,providerInfo:t.find(F=>F.type===E.type),savingKey:c,onSetSetting:L,onEnableToggle:T,onDetect:_,onResetCommand:$},E.type))}),m&&s.jsx(aN,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>h(!1),onCreated:()=>{h(!1),R()}})]})}const fN=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function xN({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function bN(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function gN(e){return e.trim().toLowerCase()}function Ma(e,t){const r=gN(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function Xi(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function ar(e,t=220){const r=Xi(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function yN(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 vN(e,t){return e.filter(r=>Ma([r.level,r.message],t))}function td(e){return`${e.timestamp}:${e.level}:${e.message}`}function wN(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const i of e.entries)n.set(td(i),i);for(const i of t.entries)n.set(td(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 jN(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 kN(e,t){return e.split(`
|
|
91
|
+
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>Ma([r],t))}function NN(e,t){return e.filter(r=>Ma([r.level,r.category,r.stage,r.interactionId,Xi(r.payload)],t))}function SN(e,t){return e.filter(r=>Ma([r.kind,r.topic,r.interactionId,Xi(r.payload)],t))}function sd(e){return e==="warn"||e==="error"}function CN({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=>sd(a.level)).length+r.filter(a=>sd(a.level)).length}}function IN({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(o=>`${new Date(o.timestamp).toISOString()} ${o.level.toUpperCase()} ${o.message}`)].join(`
|
|
92
|
+
`)):t.length>0&&a.push(["[daemon logs]",...t].join(`
|
|
93
|
+
`)),r.length>0&&a.push(["[trace]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${ar(o.payload,500)}`.trim())].join(`
|
|
94
|
+
`)),n.length>0&&a.push(["[browser events]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${ar(o.payload,500)}`.trim())].join(`
|
|
95
|
+
`)),a.join(`
|
|
96
|
+
|
|
97
|
+
`)}function MN({machineId:e,sendDaemonCommand:t}){const[r,n]=l.useState([]),[a,o]=l.useState("empty"),[i,c]=l.useState(""),[d,u]=l.useState([]),[p,m]=l.useState([]),[h,b]=l.useState(null),[g,f]=l.useState(!0),[v,j]=l.useState("info"),[y,w]=l.useState("all"),[N,k]=l.useState(!0),[x,S]=l.useState(!0),[C,I]=l.useState(""),[R,L]=l.useState(""),[T,_]=l.useState(0),$=l.useRef(0),X=l.useRef(0),M=l.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),A=l.useRef([]),E=l.useCallback(()=>{const ne={entries:[],kind:"empty",rawText:"",lastTs:0};M.current=ne,$.current=0,n([]),c(""),o("empty"),k(!0)},[]),F=l.useCallback(()=>{A.current=[],X.current=0,u([]),S(!0)},[]),z=l.useCallback(ne=>{ne!==v&&(E(),j(ne))},[v,E]),D=l.useCallback(ne=>{w(J=>J===ne?J:ne)},[]),K=l.useCallback(()=>{E(),F(),m([]),b(null),I(""),L(""),Js.clear()},[E,F]),O=l.useCallback(()=>{_(ne=>ne+1)},[]),q=l.useCallback(async()=>{if(!e)return;const ne=$.current,J=X.current,[ye,oe]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:v,since:ne}),t(e,"get_debug_trace",xN({count:120,since:J,category:y}))]);if(ye.status==="fulfilled"){const B=ye.value,W=(B==null?void 0:B.result)||B,ve=yN(W),we=wN(M.current,ve,300);M.current=we,$.current=we.lastTs,k(!1),I((B==null?void 0:B.success)===!1?String((B==null?void 0:B.error)||"Could not load daemon logs"):""),o(we.kind),c(we.rawText),n(we.entries)}else k(!1),I(ye.reason instanceof Error?ye.reason.message:"Could not load daemon logs");if(oe.status==="fulfilled"){const B=oe.value,W=(B==null?void 0:B.result)||B;if((B==null?void 0:B.success)===!1)L(String((B==null?void 0:B.error)||"Could not load daemon trace"));else if(Array.isArray(W==null?void 0:W.trace)){const ve=W.trace,we=jN(A.current,ve,120),fe=ve.reduce((Ne,re)=>Math.max(Ne,Number(re.ts||0)),J);A.current=we,fe>J&&(X.current=fe),L(""),u(we)}else L("");S(!1)}else S(!1),L(oe.reason instanceof Error?oe.reason.message:"Could not load daemon trace");m(Js.list({limit:120})),b(Date.now())},[v,e,t,y]);return l.useEffect(()=>{F()},[F,y]),l.useEffect(()=>{if(!e||(q(),!g))return;const ne=setInterval(()=>{q()},3e3);return()=>clearInterval(ne)},[g,q,e,T]),{daemonLogs:r,daemonLogKind:a,daemonRawText:i,debugTrace:d,webEvents:p,lastUpdatedAt:h,autoRefresh:g,logLevel:v,traceCategory:y,daemonLoading:N,traceLoading:x,daemonFetchError:C,traceFetchError:R,setAutoRefresh:f,setLogLevel:z,setTraceCategory:D,refresh:O,clear:K}}function AN({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:i,traceCount:c,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":o>0||i>0?"ok":"empty",detail:r||(a==="text"?`${i} raw file-fallback line(s)`:`${o} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:n?"error":t?"loading":c>0?"ok":"empty",detail:n||`${c} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:d>0?"ok":"empty",detail:d>0?`${d} local browser event(s)`:"No browser events captured"}]}function rd(e){return e==="warn"||e==="error"}function TN(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 _N(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 nd(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function RN(e){const t=ar(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function PN(e){const t=ar(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function LN({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:PN(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:RN(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:_N(o,i),severity:TN(o),message:o,raw:o})}),a.sort((o,i)=>o.ts!==i.ts?o.ts-i.ts:nd(o.source)-nd(i.source))}function DN(e){return`${e.source}:${e.severity}:${e.message}`}function $N(e){const t=e.filter(n=>rd(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!rd(n.severity))continue;const a=DN(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 EN(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function ad(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${EN(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function BN({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
|
|
98
|
+
`)),a.push(["[source status]",...r.map(i=>`${i.label}: ${i.status} - ${i.detail}`)].join(`
|
|
99
|
+
`)),t.latestIssue&&a.push(["[latest issue]",ad(t.latestIssue)].join(`
|
|
100
|
+
`)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(i=>`${i.count}x ${i.severity.toUpperCase()} ${i.source} ${i.message}`)].join(`
|
|
101
|
+
`));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(ad):["No diagnostic events captured."]].join(`
|
|
102
|
+
`)),a.join(`
|
|
103
|
+
|
|
104
|
+
`)}function FN(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function ON(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function HN({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:i,searchQuery:c,daemonLoading:d,traceLoading:u,daemonFetchError:p,traceFetchError:m}){const h=bN(n,o),b=vN(e,c),g=kN(t,c),f=NN(h,c),v=SN(a,c),j=FN(b,i),y=i==="all"?g:[],w=ON(f,i),N=i==="issues"?[]:v,k=CN({daemonLogs:b,daemonRawLines:g,trace:f,webEvents:v}),x=LN({daemonLogs:j,daemonRawLines:y,trace:w,webEvents:N}),S=$N(x),C=AN({daemonLoading:d,traceLoading:u,daemonFetchError:p,traceFetchError:m,daemonLogKind:r,daemonLogsCount:b.length,daemonRawLineCount:g.length,traceCount:f.length,webEventCount:v.length});return{filteredDaemonLogs:b,filteredDaemonRawLines:g,filteredTraceEntries:f,filteredWebEvents:v,visibleDaemonLogs:j,visibleDaemonRawLines:y,visibleTraceEntries:w,visibleWebEvents:N,quickFilterCounts:k,diagnosticEvents:x,diagnosticsSummary:S,sourceStates:C}}function zN(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function km(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Qo(e){return e==="error"?"text-red-300 border-red-500/25 bg-red-500/[0.05]":e==="warn"?"text-amber-200 border-amber-500/25 bg-amber-500/[0.05]":e==="debug"?"text-slate-300 border-slate-500/25 bg-slate-500/[0.05]":"text-text-secondary border-border-subtle bg-bg-primary"}function xo(e){return e==="good"?"border-emerald-500/20 bg-emerald-500/[0.05]":e==="warning"?"border-amber-500/20 bg-amber-500/[0.05]":e==="danger"?"border-red-500/20 bg-red-500/[0.05]":"border-border-subtle bg-bg-secondary"}function Qi(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function WN({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Qo(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:km(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:Qi(e.source)}),e.category&&e.stage&&s.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&s.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&s.jsxs("span",{children:["ix=",e.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function KN({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:i,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:u,onClear:p}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(m=>s.jsx("button",{type:"button",onClick:()=>a(m.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===m.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:m.label},m.id))}),s.jsx("input",{value:r,onChange:m=>o(m.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:i,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:d,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:p,className:"machine-btn",children:"Clear"})]})]})}function UN({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:fN.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 GN({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:i,traceFetchError:c}){var p,m;const d=((p=e.latestIssue)==null?void 0:p.severity)==="error"?"danger":((m=e.latestIssue)==null?void 0:m.severity)==="warn"?"warning":"good",u=i||c?"danger":o?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${xo(e.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:n.trim()?`Filtered by “${n.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${xo(d)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[Qi(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:km(e.latestIssue.ts)})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${xo(u)}`,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: ",zN(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(h=>s.jsxs("div",{children:[h.label,": ",h.status]},h.id))})]})]})}function VN({patterns:e}){return e.length===0?null:s.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(t=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[s.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[t.count,"× ",t.severity.toUpperCase()," · ",Qi(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function qN({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:i,visibleWebEvents:c,quickFilter:d,searchQuery:u}){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(p=>({...p,timeline:!p.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(p=>s.jsx(WN,{event:p},p.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(p=>({...p,daemon:!p.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((p,m)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:p},`raw-${m}`)),e.daemonLogKind!=="text"&&a.map((p,m)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Qo(p.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(p.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:p.level==="error"?"ERR":p.level==="warn"?"WRN":p.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:p.message})]},`log-${m}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(p=>({...p,trace:!p.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:u.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(p=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Qo(p.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(p.ts).toLocaleTimeString()}),s.jsx("span",{children:p.level.toUpperCase()}),s.jsxs("span",{children:[p.category,".",p.stage]}),p.interactionId&&s.jsxs("span",{children:["ix=",p.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:ar(p.payload,360)||"No payload"})]},p.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(p=>({...p,web:!p.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:u.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),c.map(p=>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(p.ts).toLocaleTimeString()}),s.jsx("span",{children:p.kind}),p.topic&&s.jsxs("span",{children:["topic=",p.topic]}),p.interactionId&&s.jsxs("span",{children:["ix=",p.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:ar(p.payload,360)||"No payload"})]},p.id))]})]})]})}function YN({machineId:e,sendDaemonCommand:t}){const r=MN({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}),u=l.useRef(null),p=l.useRef(!1),m=l.useMemo(()=>HN({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:o,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,o,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);l.useEffect(()=>{if(r.autoRefresh&&m.diagnosticEvents.length>0){const g=p.current?"smooth":"instant";setTimeout(()=>{var f;(f=u.current)==null||f.scrollIntoView({behavior:g}),p.current=!0},50)}},[m.diagnosticEvents.length,r.autoRefresh]);const h=l.useCallback(async()=>{var f;const g=IN({daemonLogs:m.visibleDaemonLogs,daemonRawLines:m.visibleDaemonRawLines,trace:m.visibleTraceEntries,webEvents:m.visibleWebEvents});if(!g.trim()){ot.showToast("No visible logs to copy.","info");return}try{await((f=navigator.clipboard)==null?void 0:f.writeText(g)),ot.showToast("Copied visible logs to clipboard.","success")}catch(v){ot.showToast(v instanceof Error?v.message:"Could not copy visible logs","warning")}},[m.visibleDaemonLogs,m.visibleDaemonRawLines,m.visibleTraceEntries,m.visibleWebEvents]),b=l.useCallback(async()=>{var f;const g=BN({events:m.diagnosticEvents,summary:m.diagnosticsSummary,sources:m.sourceStates});try{await((f=navigator.clipboard)==null?void 0:f.writeText(g)),ot.showToast("Copied diagnostic bundle to clipboard.","success")}catch(v){ot.showToast(v instanceof Error?v.message:"Could not copy diagnostic bundle","warning")}},[m.diagnosticEvents,m.diagnosticsSummary,m.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(KN,{quickFilter:n,quickFilterCounts:m.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:()=>{b()},onCopyVisible:()=>{h()},onToggleAutoRefresh:()=>r.setAutoRefresh(g=>!g),onRefresh:r.refresh,onClear:r.clear}),s.jsx(UN,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(GN,{diagnosticsSummary:m.diagnosticsSummary,diagnosticEventsCount:m.diagnosticEvents.length,sourceStates:m.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(VN,{patterns:m.diagnosticsSummary.repeatedPatterns}),s.jsx(qN,{streams:r,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:m.diagnosticEvents,visibleDaemonLogs:m.visibleDaemonLogs,visibleDaemonRawLines:m.visibleDaemonRawLines,visibleTraceEntries:m.visibleTraceEntries,visibleWebEvents:m.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:u})]})}function JN(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 Nm(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 XN(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=Nm((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 QN(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function bo(e){return e==="live"?"These runtimes are live now and are the only attachable targets.":e==="recovery"?"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.":"These inactive records are shown for reference and usually need restart before they are useful again."}function go(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function yo(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function od(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 ZN(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function eS(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 tS(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 sS({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=l.useState(""),[o,i]=l.useState(null),[c,d]=l.useState(!1),u=$y(e,{enabled:!!e,includeSessions:!0,limit:Gl,intervalMs:ug}),p=u.diagnostics,m=u.loading,h=u.applyDiagnostics,b=l.useMemo(()=>JN({diagnostics:p,loading:m,refreshing:c,error:n}),[p,m,c,n]),g=l.useMemo(()=>new Map(t.map(L=>[L.sessionId||L.id,L])),[t]),f=l.useCallback(async()=>{if(e){d(!0);try{const L=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Gl}),T=go(L);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Could not load hosted runtime diagnostics");h(T.diagnostics||T.result||null),a("")}catch(L){const T=L instanceof Error?L.message:"Could not load hosted runtime diagnostics";a(T)}finally{d(!1)}}},[h,e,r]);l.useEffect(()=>{!e||p||m||c||f()},[p,m,e,f,c]);const v=l.useCallback(async(L,T)=>{const _=`${L}:${T.sessionId}`;if(!(L==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
|
|
105
|
+
This will terminate the hosted runtime.`))){i(_);try{const $=await r(e,L,{sessionId:T.sessionId}),X=go($);if(!(X!=null&&X.success))throw new Error((X==null?void 0:X.error)||"Session host action failed");const M=L==="session_host_resume_session"?"resumed":L==="session_host_restart_session"?"restarted":"stopped";ot.showToast(`Session host ${M}: ${T.displayName}`,"success"),await f()}catch($){const X=$ instanceof Error?$.message:"Session host action failed";ot.showToast(X,"warning"),a(X)}finally{i($=>$===_?null:$)}}},[e,f,r]),j=l.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
106
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const T=await r(e,"session_host_prune_duplicate_sessions",{}),_=go(T);if(!(_!=null&&_.success))throw new Error((_==null?void 0:_.error)||"Duplicate prune failed");const $=_.result||{},X=Array.isArray($.prunedSessionIds)?$.prunedSessionIds.length:0,M=typeof $.duplicateGroupCount=="number"?$.duplicateGroupCount:0;ot.showToast(`Pruned ${X} duplicate runtime(s) across ${M} group(s)`,"success"),await f()}catch(T){const _=T instanceof Error?T.message:"Duplicate prune failed";ot.showToast(_,"warning"),a(_)}finally{i(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,f,r]),y=l.useMemo(()=>[...(p==null?void 0:p.sessions)||[]].sort((L,T)=>(T.lastActivityAt||0)-(L.lastActivityAt||0)),[p==null?void 0:p.sessions]),w=l.useMemo(()=>p!=null&&p.liveRuntimes||p!=null&&p.recoverySnapshots||p!=null&&p.inactiveRecords?{liveRuntimes:(p==null?void 0:p.liveRuntimes)||[],recoverySnapshots:(p==null?void 0:p.recoverySnapshots)||[],inactiveRecords:(p==null?void 0:p.inactiveRecords)||[]}:XN(y),[p==null?void 0:p.inactiveRecords,p==null?void 0:p.liveRuntimes,p==null?void 0:p.recoverySnapshots,y]),N=w.liveRuntimes,k=w.recoverySnapshots,x=w.inactiveRecords,S=l.useMemo(()=>tS(N),[N]),C=l.useMemo(()=>[...(p==null?void 0:p.recentTransitions)||[]].slice(-6).reverse(),[p==null?void 0:p.recentTransitions]),I=l.useMemo(()=>[...(p==null?void 0:p.recentLogs)||[]].reverse().find(L=>L.level==="warn"||L.level==="error")||null,[p==null?void 0:p.recentLogs]),R=(L,T)=>{var D;const _=o===`session_host_resume_session:${L.sessionId}`,$=o===`session_host_restart_session:${L.sessionId}`,X=o===`session_host_stop_session:${L.sessionId}`,M=Nm(L.meta),A=g.get(L.sessionId),E=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,F=T==="recovery"?"Recover":"Resume",z=QN(T);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:L.displayName||(A==null?void 0:A.cliName)||L.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${eS(L.lifecycle)}`,children:L.lifecycle}),M&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:M})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:L.workspaceLabel||(A==null?void 0:A.runtimeWorkspaceLabel)||L.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:L.runtimeKey}),L.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",L.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((D=L.writeOwner)==null?void 0:D.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:ZN(L.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(Nd,{size:11})," ",E]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",od(L.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",z]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[T==="recovery"&&(L.lifecycle==="interrupted"||L.lifecycle==="failed"||L.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{v("session_host_resume_session",L)},children:_?`${F}ing…`:F}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{v("session_host_restart_session",L)},children:$?"Restarting…":"Restart"}),T==="live"&&(L.lifecycle==="running"||L.lifecycle==="starting"||L.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{v("session_host_stop_session",L)},children:X?"Stopping…":"Stop"})]})]})},L.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(xs,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:E0()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[S>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 (${S})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${b.toneClass}`,children:b.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{f()},disabled:m||c,children:[s.jsx(fa,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),n&&!p&&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(Zs,{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})]})]})}),p&&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:p.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:k.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:p.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:od(p.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:yo(p.hostStartedAt)})]})]}),I&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(Zs,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:I.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[yo(I.timestamp),I.sessionId?` · ${I.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(ii,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:bo("live")}),N.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:N.map(L=>R(L,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(xs,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:bo("recovery")}),k.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:k.map(L=>R(L,"recovery"))})]}),x.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:bo("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:x.map(L=>R(L,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),C.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:C.map(L=>{var _;const T=y.find($=>$.sessionId===L.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(T==null?void 0:T.displayName)||((_=g.get(L.sessionId))==null?void 0:_.cliName)||L.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[L.action,L.lifecycle?` · ${L.lifecycle}`:"",L.detail?` · ${L.detail}`:"",L.error?` · ${L.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${L.success===!1?"text-red-300":"text-text-secondary"}`,children:yo(L.timestamp)})]},`${L.sessionId}:${L.timestamp}:${L.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:p.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function rS({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 nS(e,t){const r=xp(e),n=Gs(e,t),a=Ti(e,n),o=Pr(e,n),i=r==="preview"?"Update to preview":"Update daemon";return a?{visible:!0,showButton:!0,title:o?"Daemon update required":"Version mismatch detected",description:o?"This machine is on an incompatible daemon version. Update it before starting more sessions.":r==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",buttonLabel:i,targetVersion:n,channel:r,required:o,tone:"warn"}:r==="preview"?{visible:!0,showButton:!1,title:n?"Preview daemon is up to date":"Preview update status unknown",description:n?"This machine is already on the current preview daemon target.":"The app is connected to preview, but the server did not report a preview target version yet.",buttonLabel:i,targetVersion:n,channel:r,required:!1,tone:n?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:i,targetVersion:n,channel:r,required:!1,tone:"info"}}function vo({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function wo({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function aS({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),p=nS(e,"0.9.82");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[c.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(vo,{icon:s.jsx($s,{size:13}),children:"Current Chats"}),s.jsx(wo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(m=>{const h=qo(m);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(m),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:pt(m)}),h>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:xa(h)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Ps(m)})]},m.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(vo,{icon:s.jsx(Md,{size:13}),children:"Recent Launches"}),s.jsx(wo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(m=>{const{metaText:h,updatedLabel:b}=Mp(m);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>o(m),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:m.label}),b&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:b})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:h})]},m.id)})})})]}),p.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(vo,{icon:s.jsx(Zs,{size:13}),children:"Daemon Update"}),s.jsx(wo,{className:p.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":p.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:p.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[p.description,p.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",p.targetVersion,p.channel?` (${p.channel})`:""]})]}),p.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(fa,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:p.buttonLabel})]}):s.jsx("div",{className:p.tone==="good"?"text-xs font-medium text-emerald-300":"text-xs font-medium text-sky-300",children:"No preview update action is needed."})]})})]})]})}function oS({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:u,handleWorkspaceSetDefault:p}=o,[m,h]=l.useState(!1),[b,g]=l.useState(""),[f,v]=l.useState([]),[j,y]=l.useState(!1),[w,N]=l.useState(""),k=l.useCallback(async S=>{y(!0),N("");try{const C=await Bi(i,e,S);g(C.path),v(C.directories)}catch(C){N(C instanceof Error?C.message:"Could not load folder")}finally{y(!1)}},[e,i]),x=l.useCallback(()=>{h(!0);const S=[...r.map(I=>I.workspace),...n.map(I=>I.workspace),...a.map(I=>I.workspace)],C=Ei(t.platform,$i(S,t.defaultWorkspacePath,(t.workspaces||[]).map(I=>I.path)));k(C)},[a,n,r,k,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(Qs,{size:14})," Workspaces"]}),s.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick:x,children:"+ Add workspace"})]}),(t.workspaces||[]).length===0?s.jsxs("div",{className:"text-[11px] text-text-muted py-4 text-center",children:["No saved workspaces yet. Click ",s.jsx("span",{className:"text-text-secondary",children:"+ Add workspace"})," to pick a folder."]}):s.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(S=>{const C=S.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${C?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:C?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void p(C?null:S.id),className:`text-base leading-none shrink-0 transition-colors ${C?"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:Ud(S.path,S.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:S.path,children:S.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void u(S.id),children:"Remove"})]},S.id)})})]}),m&&s.jsx(Oi,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:b,directories:f,busy:j,error:w,confirmLabel:"Add workspace",onClose:()=>h(!1),onNavigate:S=>{k(S)},onConfirm:S=>{(async()=>{if(!S)return;await d(S)&&h(!1)})()}})]})}function iS({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(oS,{machineId:t,machine:e,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function lS({onNicknameSynced:e}={}){var Ne,re,je,de,U,H,Y,se,xe,Z;const{id:t}=jh(),r=Kr(),n=si(),{sendCommand:a}=mt(),o=Yr(),i=np(),c=Pu(),d=c.ides||[],u=c.initialLoaded??!0,p=d.find(P=>P.id===t&&P.type==="adhdev-daemon"),m=d.some(P=>P.type==="adhdev-daemon"),h=t?(Ne=c.connectionRetryStatuses)==null?void 0:Ne[t]:void 0,b=!!(h!=null&&h.blocked),[g,f]=l.useState("workspace"),[v,j]=l.useState(null);l.useCallback((P,ie)=>{j({daemonId:P,workspace:ie})},[]);const[,y]=l.useState("ide"),w=l.useRef(null),[N,k]=l.useState(null),x=l.useRef("__home__"),[S,C]=l.useState("__home__"),[I,R]=l.useState(!1),L=l.useRef(null);l.useEffect(()=>{!t||!p||!(!p.workspaces||!p.availableProviders||!p.detectedIdes||!p.recentLaunches)||o(t,{minFreshMs:3e4}).catch(()=>{})},[o,p,t]),l.useEffect(()=>{if(!t||!p||g!=="overview")return;const P=p.machine;(typeof(P==null?void 0:P.cpus)!="number"||typeof(P==null?void 0:P.totalMem)!="number"||typeof(P==null?void 0:P.arch)!="string"||typeof(P==null?void 0:P.release)!="string")&&i(t,{minFreshMs:3e4}).catch(()=>{})},[g,i,p,t]),Dy(t&&g==="overview"?[t]:[],{enabled:g==="overview",intervalMs:ig});const T=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},_=eN({machineId:t,registeredMachineId:(p==null?void 0:p.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:L});l.useEffect(()=>ot.onToast(ie=>{c.setToasts(ue=>{if(ue.some(Ae=>Ae.message===ie.message&&ie.timestamp-Ae.timestamp<3e3))return ue;const Me={id:ie.id,message:ie.message,type:ie.type,timestamp:ie.timestamp,targetKey:ie.targetKey,actions:ie.actions};return[...ue.slice(-4),Me]});const be=ie.duration||5e3;setTimeout(()=>c.setToasts(ue=>ue.filter(te=>te.id!==ie.id)),be)}),[c]);const $=(p==null?void 0:p.availableProviders)||[],X={};for(const P of $)X[P.type]=P.icon;const M=p?{id:p.id,hostname:Gd(p,{fallbackId:p.id}),platform:((re=p.machine)==null?void 0:re.platform)||"unknown",arch:((je=p.machine)==null?void 0:je.arch)||"",cpus:((de=p.machine)==null?void 0:de.cpus)||0,totalMem:((U=p.machine)==null?void 0:U.totalMem)||0,freeMem:(H=p.machine)==null?void 0:H.freeMem,availableMem:(Y=p.machine)==null?void 0:Y.availableMem,loadavg:(se=p.machine)==null?void 0:se.loadavg,uptime:(xe=p.machine)==null?void 0:xe.uptime,release:((Z=p.machine)==null?void 0:Z.release)||"",cdpConnected:!!p.cdpConnected,machineNickname:p.machineNickname||null,p2p:p.p2p?{screenshotActive:!1,...p.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:p.detectedIdes||[],workspaces:p.workspaces||[],defaultWorkspaceId:p.defaultWorkspaceId??p.activeWorkspaceId??null,defaultWorkspacePath:p.defaultWorkspacePath??p.activeWorkspacePath??null}:null,A=d.filter(P=>P.daemonId===t&&P.type!=="adhdev-daemon").filter(P=>!Fr(P)&&!qs(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,version:P.version||"",instanceId:P.instanceId||"",status:P.status,workspace:P.workspace||null,terminals:P.terminals||0,aiAgents:gx(P.aiAgents||(P.agents||[]).map(ie=>({id:ie.name,name:ie.name,status:ie.status,version:ie.version}))),activeChat:P.activeChat||null,chats:P.chats||[],childSessions:P.childSessions||[],cdpConnected:P.cdpConnected||!1,daemonId:t,lastMessageAt:P.lastMessageAt})),E=d.filter(P=>P.daemonId===t&&Fr(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,cliName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,mode:P.mode,runtimeKey:P.runtimeKey,runtimeDisplayName:P.runtimeDisplayName,runtimeWorkspaceLabel:P.runtimeWorkspaceLabel,runtimeWriteOwner:P.runtimeWriteOwner||null,runtimeAttachedClients:P.runtimeAttachedClients||[],daemonId:t,lastMessageAt:P.lastMessageAt})),F=d.filter(P=>P.daemonId===t&&qs(P)).map(P=>({id:P.id,sessionId:P.sessionId,type:P.type,acpName:P.cliName||P.type,status:P.status,workspace:P.workspace||"",activeChat:P.activeChat||null,providerSessionId:P.providerSessionId,daemonId:t,lastMessageAt:P.lastMessageAt})),z=p?Ft(p,{fallbackId:t}):"",D="workspace",K=n.state,O=K==null?void 0:K.initialMachineTab,q=K==null?void 0:K.initialWorkspaceCategory;K==null||K.initialWorkspaceId,K==null||K.initialWorkspacePath;const ne=O==="ides"||O==="clis"||O==="acps"?"workspace":O||D,J=O==="ides"?"ide":O==="clis"?"cli":O==="acps"?"acp":q,ye=[...A.map(P=>{var ie;return{id:`ide:${P.type}:${P.workspace||""}`,label:((ie=P.activeChat)==null?void 0:ie.title)||P.type,kind:"ide",providerType:P.type,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:P.lastMessageAt||0}}),...E.map(P=>{var ie;return{id:`cli:${P.type}:${P.workspace||""}`,label:((ie=P.activeChat)==null?void 0:ie.title)||P.cliName,kind:"cli",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:P.lastMessageAt||0}}),...F.map(P=>{var ie;return{id:`acp:${P.type}:${P.workspace||""}`,label:((ie=P.activeChat)==null?void 0:ie.title)||P.acpName,kind:"acp",providerType:P.type,providerSessionId:P.providerSessionId,subtitle:_s(P.summaryMetadata)||P.workspace||void 0,workspace:P.workspace||void 0,lastLaunchedAt:P.lastMessageAt||0}})].sort((P,ie)=>(ie.lastLaunchedAt||0)-(P.lastLaunchedAt||0)),oe=((p==null?void 0:p.recentLaunches)||[]).length>0?((p==null?void 0:p.recentLaunches)||[]).map(P=>({id:P.id,label:P.title||P.providerName||P.providerType,kind:P.kind,providerType:P.providerType,providerSessionId:P.providerSessionId,subtitle:_s(P.summaryMetadata)||P.workspace||void 0,workspace:P.workspace,summaryMetadata:P.summaryMetadata,lastLaunchedAt:P.lastLaunchedAt})):ye,B=l.useMemo(()=>{var ie;const P=((ie=c.connectionStates)==null?void 0:ie[t||""])||void 0;return d.filter(be=>be.daemonId===t&&be.type!=="adhdev-daemon").flatMap(be=>Ai(be,{connectionStates:t&&P?{[t]:P}:void 0,defaultConnectionState:P})).filter(be=>!(be.transport==="pty"&&be.mode==="terminal")).sort((be,ue)=>qo(ue)-qo(be))},[d,c.connectionStates,t]),W=l.useCallback(P=>{const ie=vp(P);ie&&r(Hr(ie))},[r]),ve=l.useCallback(()=>{w.current&&(R(!0),w.current().finally(()=>{w.current=null,R(!1),k(null)}))},[]),we=l.useCallback(P=>{if(!M)return;const{options:ie,selectedKey:be}=Ip({machine:M,currentWorkspacePath:P.workspace}),ue=async()=>{y(P.kind),f("workspace")};w.current=async()=>{const te=ie.find(Ce=>Ce.key===x.current),Me=(te==null?void 0:te.workspacePath)??null,Ae=(te==null?void 0:te.workspaceId)??null;if(P.kind==="ide"&&P.providerType){await _.handleLaunchIde(P.providerType,Me?{workspace:Me}:void 0);return}if((P.kind==="cli"||P.kind==="acp")&&P.providerType){await _.runLaunchCliCore({cliType:P.providerType,dir:Ae?void 0:Me||"",workspaceId:Ae||void 0,model:P.kind==="acp"&&qd(P.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:P.providerSessionId});return}await ue()},x.current=be,C(be),k({title:P.kind==="ide"?sa("restart-ide",P.label):P.providerSessionId?Wu(P.label):sa("start-fresh",P.label),description:P.kind==="ide"?ra("restart-ide"):P.providerSessionId?Ku():ra("start-fresh"),confirmLabel:P.kind==="ide"?na("restart-ide"):P.providerSessionId?ta(!0):na("start-fresh"),busyLabel:P.kind==="ide"?aa("restart-ide"):P.providerSessionId?Ii(!0):aa("start-fresh"),workspaceOptions:ie,details:[{label:"Mode",value:P.kind.toUpperCase()},...P.providerType?[{label:"Provider",value:P.providerType}]:[]]})},[_,M]);if(l.useEffect(()=>{f(ne)},[D,ne,t]),l.useEffect(()=>{J&&y(J)},[J,t]),!M)return u?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:T,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 fe=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(qt,{size:14})," Workspace"]}),count:A.length+E.length+F.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xs,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ha,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(rf,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zh,{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:T,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:[_.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:_.nicknameInput,onChange:P=>_.setNicknameInput(P.target.value),onKeyDown:P=>{P.key==="Enter"&&_.handleSaveNickname(),P.key==="Escape"&&_.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:_.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:()=>_.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:()=>{_.setEditingNickname(!0),_.setNicknameInput(M.machineNickname||"")},title:"Click to set nickname",children:z}),b?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),c.retryConnection&&t&&s.jsx("button",{onClick:()=>c.retryConnection(t),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:"Reconnect"})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[M.platform," · ",M.arch]}),s.jsxs("span",{children:[M.cpus," cores"]}),(p==null?void 0:p.version)&&s.jsxs("span",{children:["v",p.version]}),M.p2p.available&&s.jsxs("span",{children:["P2P ",M.p2p.state==="connected"?"connected":M.p2p.state]}),M.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:M.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:fe.map(P=>s.jsxs("button",{onClick:()=>f(P.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${g===P.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[P.label,P.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${g===P.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:P.count})]},P.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[g==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(aS,{machineEntry:p,providers:$,recentLaunches:oe,currentConversations:B,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",bp(p))}catch{}},onOpenRecent:we,onOpenConversation:W}),s.jsx(iS,{machine:M,machineId:t,ideSessions:A,cliSessions:E,acpSessions:F,actions:_,sendDaemonCommand:a})]}),g==="providers"&&s.jsx(hN,{machineId:t,providers:$,sendDaemonCommand:a}),g==="overview"&&s.jsx(tN,{machine:M,ideSessions:A,cliSessions:E,acpSessions:F}),g==="session-host"&&s.jsx(sS,{machineId:t,cliSessions:E,sendDaemonCommand:a}),g==="logs"&&s.jsx(YN,{machineId:t,sendDaemonCommand:a})]})})}),_.launchPick&&M&&s.jsx(rS,{machine:M,launchPick:_.launchPick,actions:_}),N&&s.jsx(Cp,{title:N.title,description:N.description,details:N.details,workspaceOptions:N.workspaceOptions,selectedWorkspaceKey:S,onWorkspaceChange:P=>{x.current=P,C(P)},confirmLabel:N.confirmLabel,busyLabel:N.busyLabel,busy:I,onConfirm:ve,onCancel:()=>{w.current=null,k(null)}}),v&&s.jsx(jm,{daemonId:v.daemonId,workspace:v.workspace,onClose:()=>j(null)}),s.jsx(Gu,{toasts:c.toasts||[],onDismiss:P=>c.setToasts(ie=>ie.filter(be=>be.id!==P)),onClickToast:P=>{P.targetKey&&r(Hr(P.targetKey))}}),s.jsx("style",{children:`
|
|
107
|
+
@keyframes toast-in {
|
|
108
|
+
from { opacity: 0; transform: translateX(40px); }
|
|
109
|
+
to { opacity: 1; transform: translateX(0); }
|
|
110
|
+
}
|
|
111
|
+
`})]})}const cS={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},Sm=l.createContext(null);function dS(){const e=l.useContext(Sm);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function Zi({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("polyline",{points:"1 20 1 14 7 14"}),s.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function uS({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"6",cy:"18",r:"3"}),s.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function pS({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"3 6 5 6 21 6"}),s.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})}function Cm({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function Im({status:e}){const r={online:{color:"#22c55e",label:"Online"},dirty:{color:"#f59e0b",label:"Dirty"},offline:{color:"#6b7280",label:"Offline"},degraded:{color:"#ef4444",label:"Degraded"},enabled:{color:"#22c55e",label:"Enabled"},pending:{color:"#a855f7",label:"Pending"},assigned:{color:"#3b82f6",label:"Assigned"},completed:{color:"#22c55e",label:"Completed"},failed:{color:"#ef4444",label:"Failed"},unknown:{color:"#6b7280",label:"Unknown"}}[e]||{color:"#6b7280",label:e};return s.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-md",style:{background:r.color+"15",color:r.color,border:`1px solid ${r.color}25`},children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:r.color}}),r.label]})}function mS(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function hS({meshes:e,loading:t,error:r,onDismissError:n,daemons:a,features:o,showCreate:i,onToggleCreate:c,createName:d,onCreateNameChange:u,createRepoIdentity:p,onCreateRepoIdentityChange:m,createRepoRemoteUrl:h,onCreateRepoRemoteUrlChange:b,newMeshDaemonId:g,onNewMeshDaemonIdChange:f,newMeshWorkspace:v,onNewMeshWorkspaceChange:j,createPickerWorkspaces:y,onSelectMesh:w,onCreate:N,onCancelCreate:k}){return s.jsxs(Qr,{icon:s.jsx(as,{}),title:"Repo Meshes",subtitle:`${e.length} mesh${e.length!==1?"es":""}`,widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,children:"+ Create Mesh"}),children:[r&&s.jsx(fs,{variant:"error",onDismiss:n,className:"mb-4",children:r}),i&&s.jsxs(dt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:"Create Repo Mesh"}),o.createDaemonPicker&&s.jsx(jt,{label:"Create on machine",hint:"Mesh setup is stored by the selected daemon.",children:s.jsx("select",{className:"input w-full",value:g,onChange:x=>f(x.target.value),disabled:!a.length,children:a.length===0?s.jsx("option",{value:"",children:"No connected daemon"}):a.map(x=>s.jsx("option",{value:x.id,children:mS(x)},x.id))})}),o.createDaemonPicker&&s.jsx(jt,{label:"Workspace",hint:"Choose from workspaces registered by the selected daemon.",children:s.jsx("select",{className:"input w-full",value:v,onChange:x=>j(x.target.value),disabled:!g||!y.length,children:g?y.length===0?s.jsx("option",{value:"",children:"No registered workspaces"}):y.map(x=>s.jsx("option",{value:x.path,children:x.label?`${x.label} · ${x.path}`:x.path},x.id||x.path)):s.jsx("option",{value:"",children:"Select a machine first"})})}),s.jsx(jt,{label:"Name",children:s.jsx(Rr,{value:d,onChange:x=>u(x.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(jt,{label:"Repo remote URL (optional)",hint:"Provide a remote URL OR a stable identity.",children:s.jsx(Rr,{value:h,onChange:x=>b(x.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(jt,{label:"Repo identity (optional)",hint:"Provide a remote URL OR a stable identity.",children:s.jsx(Rr,{value:p,onChange:x=>m(x.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:N,disabled:!d.trim()||!h.trim()&&!p.trim()||o.createDaemonPicker&&(!g||!v),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:k,children:"Cancel"})]})]}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):e.length===0?s.jsx(ja,{icon:s.jsx(as,{}),title:"No Repo Meshes",description:a.length>0?"Create a mesh to get started.":"Connect an ADHDev daemon first.",action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!a.length,onClick:c,children:"Create First Mesh"})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(x=>{var S;return s.jsx("button",{type:"button",onClick:()=>w(x.id),className:"w-full text-left bg-bg-glass border border-border-subtle rounded-xl px-5 py-4 transition-colors hover:border-border-default hover:bg-bg-secondary/70",children:s.jsxs("div",{className:"flex justify-between items-start",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(as,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:x.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:x.repoIdentity||x.repo_identity||"No repo identity"}),(x.defaultBranch||x.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(uS,{size:11}),x.defaultBranch||x.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(x.createdAt||x.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((S=x.nodes)==null?void 0:S.length)??x.nodeCount??0," node(s)"]})]})]})},x.id)})})]})}function id(e){if(e.status!=="completed"&&e.status!=="failed")return null;const t=e.dispatchTimestamp?new Date(e.dispatchTimestamp).getTime():NaN,r=e.updatedAt?new Date(e.updatedAt).getTime():NaN;if(!Number.isFinite(t)||!Number.isFinite(r)||r<t)return null;const n=Math.round((r-t)/1e3);if(n<60)return`${n}s`;const a=Math.floor(n/60);return a<60?`${a}m ${n%60}s`:`${Math.floor(a/60)}h ${a%60}m`}function fS({queueSummary:e,queueLoading:t,queueError:r,activeDaemonId:n,onRefresh:a}){return s.jsxs(dt,{title:"Queue",description:"Inspect active queue work separately from historical completed, failed, and cancelled task records.",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-7 gap-2 flex-1 min-w-[260px]",children:[["Active",(e==null?void 0:e.active)??0,"text-accent-primary"],["Pending",(e==null?void 0:e.activeCounts.pending)??(e==null?void 0:e.counts.pending)??0,"text-text-primary"],["Assigned",(e==null?void 0:e.activeCounts.assigned)??(e==null?void 0:e.counts.assigned)??0,"text-blue-400"],["Stale",(e==null?void 0:e.staleAssignedCount)??0,"text-amber-400"],["Historical",(e==null?void 0:e.historical)??0,"text-text-muted"],["Completed",(e==null?void 0:e.historicalCounts.completed)??(e==null?void 0:e.counts.completed)??0,"text-green-400"],["Failed",(e==null?void 0:e.historicalCounts.failed)??(e==null?void 0:e.counts.failed)??0,"text-red-400"]].map(([o,i,c])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-text-muted",children:o}),s.jsx("div",{className:`text-lg font-bold ${c}`,children:i})]},String(o)))}),s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:a,disabled:t||!n,children:[s.jsx(Zi,{size:13}),t?"Loading...":"Refresh Queue"]})]}),r&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:r}),e?e.recent.length===0?s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:"Queue is empty."}):s.jsx("div",{className:"flex flex-col gap-2",children:e.recent.map(o=>{var i;return s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"font-mono text-[11px] text-text-muted",children:o.id.slice(0,12)}),s.jsx(Im,{status:o.status}),o.staleAssigned&&s.jsx("span",{className:"text-[10px] text-amber-300 bg-amber-500/10 border border-amber-500/20 rounded-full px-2 py-0.5",title:o.staleReason||"Stale assignment",children:"stale"}),(((i=o.waitingOn)==null?void 0:i.length)??0)>0&&s.jsxs("span",{className:"text-[10px] text-sky-300 bg-sky-500/10 border border-sky-500/20 rounded-full px-2 py-0.5",title:`Waiting on: ${o.waitingOn.join(", ")}`,children:["waits on ",o.waitingOn.length," task",o.waitingOn.length>1?"s":""]}),o.blockedReason&&s.jsx("span",{className:"text-[10px] text-red-300 bg-red-500/10 border border-red-500/20 rounded-full px-2 py-0.5",title:o.blockedReason,children:"blocked"}),id(o)&&s.jsxs("span",{className:"text-[10px] text-text-muted bg-bg-tertiary border border-border-subtle rounded-full px-2 py-0.5",title:"Dispatched → terminal wall clock",children:[id(o),(o.requeueCount??0)>0?` · ${o.requeueCount} retr${o.requeueCount===1?"y":"ies"}`:""]})]}),o.message&&s.jsx("div",{className:"text-[12px] text-text-primary truncate",children:o.message})]}),s.jsxs("div",{className:"text-right text-[10px] text-text-muted shrink-0",children:[o.nodeId&&s.jsxs("div",{children:["node ",o.nodeId.slice(0,10)]}),o.sessionId&&s.jsxs("div",{children:["session ",o.sessionId.slice(0,10)]}),o.updatedAt&&s.jsx("div",{children:new Date(o.updatedAt).toLocaleTimeString()})]})]})},o.id)})}):s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:"Refresh the queue to view host-owned task counts and recent assignments."})]})}function xS(e){return e==="refine_blocked_review"?{label:"Blocked review",color:"text-amber-400 bg-amber-500/10 border-amber-500/20"}:{label:"Merge candidate",color:"text-blue-400 bg-blue-500/10 border-blue-500/20"}}function bS(e){if(!e)return null;const t=typeof e.stage=="string"?e.stage:null,r=e.passed===!0;if(!t)return null;const n={ran:r?"text-green-400 bg-green-500/10 border-green-500/20":"text-red-400 bg-red-500/10 border-red-500/20",cached:"text-blue-400 bg-blue-500/10 border-blue-500/20",failed:"text-red-400 bg-red-500/10 border-red-500/20",skipped:"text-text-muted bg-bg-secondary border-border-subtle",legacy:"text-text-muted bg-bg-secondary border-border-subtle",not_configured:"text-text-muted bg-bg-secondary border-border-subtle"};return{label:`bootstrap: ${t}`,color:n[t]??"text-text-muted bg-bg-secondary border-border-subtle"}}function gS({file:e}){const r={added:"text-green-400",deleted:"text-red-400",modified:"text-amber-400",renamed:"text-blue-400"}[e.status??""]??"text-text-muted";return s.jsxs("div",{className:"flex items-center justify-between gap-2 py-0.5",children:[s.jsx("span",{className:`text-[11px] font-mono truncate flex-1 ${r}`,children:e.path}),(e.insertions!=null||e.deletions!=null)&&s.jsxs("span",{className:"text-[10px] text-text-muted shrink-0",children:[e.insertions!=null&&s.jsxs("span",{className:"text-green-400",children:["+",e.insertions]}),e.deletions!=null&&s.jsxs("span",{className:"text-red-400 ml-1",children:["-",e.deletions]})]})]})}function yS({item:e,activeDaemonId:t,sendCommand:r,onDismiss:n,onRefineNode:a,onRequeueLast:o}){var N,k,x;const[i,c]=l.useState(null),[d,u]=l.useState(null),[p,m]=l.useState(!1),[h,b]=l.useState(null),{label:g,color:f}=xS(e.reviewReason),v=bS(e.evidence.bootstrap),j=((N=e.diffSummary)==null?void 0:N.files)??[],y=((k=e.diffSummary)==null?void 0:k.baseRef)??null,w=l.useCallback(async S=>{if(!(!e.workspace||!t)){if(i===S){c(null),u(null);return}c(S),u(null),m(!0),b(null);try{const C=await r(t,"git_diff_file",{workspace:e.workspace,path:S,...y?{base:y}:{}});(C==null?void 0:C.success)!==!1&&typeof(C==null?void 0:C.diff)=="string"?u(C.diff):(C==null?void 0:C.diff)!=null?u(String(C.diff)):b((C==null?void 0:C.error)||"No diff available")}catch(C){b((C==null?void 0:C.message)||"Failed to load diff")}finally{m(!1)}}},[e.workspace,t,r,i,y]);return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary p-4 space-y-3",children:[s.jsxs("div",{className:"flex flex-wrap items-start gap-2 justify-between",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2 min-w-0",children:[s.jsx("span",{className:"text-[12px] font-semibold text-text-primary font-mono truncate max-w-[240px]",children:e.branch??e.nodeId}),s.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${f}`,children:g}),v&&s.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${v.color}`,children:v.label}),e.activeRefineJob&&s.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded border text-blue-400 bg-blue-500/10 border-blue-500/20",children:"refine running"})]}),s.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[s.jsx("button",{className:"btn btn-primary btn-sm text-[11px]",onClick:()=>a(e.nodeId),disabled:!!e.activeRefineJob,children:"Refine"}),s.jsx("button",{className:"btn btn-secondary btn-sm text-[11px]",onClick:()=>o(e.nodeId),children:"Requeue"}),s.jsx("button",{className:"btn btn-secondary btn-sm text-[11px]",onClick:()=>n(e.nodeId),children:"Dismiss"})]})]}),e.workspace&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate",children:e.workspace}),e.evidence.available&&s.jsxs("div",{className:"text-[11px] text-text-secondary space-y-0.5",children:[e.evidence.source==="task_completion"&&e.evidence.worker&&s.jsxs("span",{children:["Last task: ",s.jsx("span",{className:e.evidence.worker.status==="success"?"text-green-400":"text-red-400",children:e.evidence.worker.status}),e.evidence.worker.classification&&s.jsxs("span",{className:"text-text-muted ml-1",children:["(",e.evidence.worker.classification,")"]}),e.evidence.worker.errors.length>0&&s.jsxs("span",{className:"text-red-400 ml-1",children:["· ",e.evidence.worker.errors[0]]})]}),e.evidence.source==="refine_job"&&s.jsxs("span",{children:["Refinery: ",s.jsx("span",{className:"text-amber-400",children:e.convergence.status}),e.convergence.nextStep&&s.jsxs("span",{className:"text-text-muted ml-1",children:["→ ",e.convergence.nextStep]})]})]}),e.diffSummary&&e.diffSummary.files.length>0&&s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-3",children:[s.jsxs("span",{children:[e.diffSummary.totalFiles," file",e.diffSummary.totalFiles!==1?"s":""]}),s.jsxs("span",{className:"text-green-400",children:["+",e.diffSummary.totalInsertions]}),s.jsxs("span",{className:"text-red-400",children:["-",e.diffSummary.totalDeletions]}),e.diffSummary.truncated&&s.jsx("span",{className:"text-amber-400",children:"truncated"}),y&&s.jsxs("span",{className:"font-mono",children:["vs ",y]})]}),s.jsxs("div",{className:"border border-border-subtle rounded px-2 py-1 bg-bg-primary space-y-0.5",children:[j.slice(0,20).map(S=>s.jsxs("div",{children:[s.jsx("button",{className:"w-full text-left hover:bg-bg-secondary rounded px-1 transition-colors",onClick:()=>w(S.path),children:s.jsx(gS,{file:S})}),i===S.path&&s.jsx("div",{className:"mt-1 mb-1",children:s.jsx(wm,{diff:d??"",loading:p,error:h??void 0,truncated:!1,className:"text-[10px]"})})]},S.path)),j.length>20&&s.jsxs("div",{className:"text-[10px] text-text-muted px-1 pt-0.5",children:["+",j.length-20," more files"]})]})]}),((x=e.diffSummary)==null?void 0:x.error)&&s.jsxs("div",{className:"text-[11px] text-amber-400",children:["Diff probe: ",e.diffSummary.error]})]})}function vS({items:e,loading:t,error:r,remoteNodesExcluded:n,meshId:a,activeDaemonId:o,onRefresh:i,onDismiss:c,onRefineNode:d,onRequeueLast:u,sendCommand:p}){return s.jsxs(dt,{title:"Review Inbox",description:"Local worktree nodes that need review: merge candidates and Refinery-blocked results. Click a file to preview its diff.",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[e.length>0&&s.jsxs("span",{className:"text-[12px] font-semibold text-accent-primary",children:[e.length," item",e.length!==1?"s":""]}),n&&s.jsx("span",{className:"text-[10px] text-text-muted px-1.5 py-0.5 rounded border border-border-subtle bg-bg-secondary",children:"remote nodes excluded"})]}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:i,disabled:t,children:[s.jsx(Zi,{size:12}),t?"Loading...":"Refresh"]})]}),r&&s.jsx("div",{className:"mb-3 text-[12px] text-red-400 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2",children:r}),!t&&!r&&e.length===0&&s.jsxs("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:["No local nodes require review.",n&&" Remote nodes are excluded in this view."]}),s.jsx("div",{className:"space-y-3",children:e.map(m=>s.jsx(yS,{item:m,activeDaemonId:o,sendCommand:p,onDismiss:c,onRefineNode:d,onRequeueLast:u},m.nodeId))})]})}function wS(e){const t=new Map;for(const r of e)r!=null&&r.id&&t.set(r.id,sr(r.availableProviders||[]));return t}function jS(e,t){const r=String(e.daemon_id||e.daemonId||"");return r&&t.has(r)?t.get(r):[]}function kS(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function NS(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",r=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${r}`}function Mm(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function SS(e){const t=Mm(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"launch not ready unless an explicit provider is selected"}}function CS(e){return e.isLocalWorktree===!0}function IS(e){var r;const t=Number((r=e.policy)==null?void 0:r.schedulingPriority);return Number.isFinite(t)?t:0}function MS(e){var r;const t=(r=e.policy)==null?void 0:r.providerRoles;return Array.isArray(t)?t.filter(n=>!!n&&typeof n=="object"&&typeof n.providerType=="string"&&n.providerType.trim().length>0).map(n=>({providerType:n.providerType.trim(),maxParallel:Number.isFinite(Number(n.maxParallel))&&Number(n.maxParallel)>=0?Math.floor(Number(n.maxParallel)):void 0})):[]}function AS(e,t){const r=t;return[...Array.isArray(r==null?void 0:r.cliSessions)?r.cliSessions:[],...Array.isArray(r==null?void 0:r.acpSessions)?r.acpSessions:[],...Array.isArray(r==null?void 0:r.sessions)?r.sessions:[]].filter(a=>{var o;return((o=a==null?void 0:a.settings)==null?void 0:o.meshNodeId)===e.id||(a==null?void 0:a.workspace)===e.workspace}).map(a=>{var o;return{id:a.sessionId||a.id||a.instanceId||"unknown",provider:a.providerType||a.cliType||a.acpType||a.type||"unknown",status:a.status||((o=a.activeChat)==null?void 0:o.status)||"unknown"}})}function ld(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function TS(e,t){var r;return(e==null?void 0:e.ownerName)||(e==null?void 0:e.userName)||((r=e==null?void 0:e.user)==null?void 0:r.name)||t||"You"}function _S({nodes:e,meshQueue:t,activeDaemon:r,daemons:n,selectedMeshId:a,userName:o,features:i,coordinatorDaemonId:c,schedulingStrategy:d,nodeProviderPriorityDrafts:u,onNodeProviderPriorityDraftChange:p,availableCliProviders:m,savingNodePolicyId:h,onUpdateNodeProviderPriority:b,savingNodeSchedulingId:g,onUpdateNodeScheduling:f,nodeSystemPromptDrafts:v,onNodeSystemPromptDraftChange:j,savingNodeSystemPromptId:y,onSaveNodeSystemPrompt:w,selectedNodeId:N,onSelectNode:k,showAddNode:x,onShowAddNode:S,onCancelAddNode:C,nodeWorkspace:I,onNodeWorkspaceChange:R,nodeProviderPriority:L,onNodeProviderPriorityChange:T,nodeDaemonId:_,onNodeDaemonIdChange:$,nodeCustomPath:X,onNodeCustomPathChange:M,nodePickerWorkspaces:A,nodePickerProviders:E,attachableDaemons:F,onAddNode:z,onRemoveNode:D}){const K=l.useMemo(()=>wS(n),[n]);return s.jsxs(dt,{title:i.addNodeDaemonPicker?`Nodes & Providers (${e.length})`:"Nodes & Providers",description:i.addNodeDaemonPicker?"Workspaces in this mesh and their preferred AI tools. Setup inventory only — live graph/git/session truth is owned by the Mesh Host status above.":"Workspaces participating in this mesh and their preferred AI tools.",children:[i.addNodeDaemonPicker&&s.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Machine daemon candidates"}),s.jsx("div",{className:"text-[12px] text-text-muted",children:"Choose connected daemons to attach to the selected Mesh Host setup."})]}),s.jsxs("span",{className:"text-[11px] text-text-muted",children:[F.length," available"]})]}),n.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:"No connected machine daemons are currently available."}):F.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:"All connected machine daemons are already attached."}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:F.map(O=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${O.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{$(O.id),R(""),M(!1),T(Or(sr(O.availableProviders||[]))),S()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate",children:ld(O)}),O.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary",children:"selected host"})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:O.id}),s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted",children:[(O.workspaces||[]).length," workspace(s) detected"]})]},O.id))})]}),!x&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:S,children:[s.jsx(Cm,{size:13})," ",i.addNodeDaemonPicker?"Attach Machine Daemon":"+ Add Node"]}),x&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:i.addNodeDaemonPicker?"Attach Machine Daemon":"Add Node"}),s.jsx("button",{onClick:()=>{C(),$(""),M(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(vt,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(jt,{label:"Machine",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:_,onChange:O=>{var q;$(O.target.value),R(""),M(!1),T(Or(sr(((q=n.find(ne=>ne.id===O.target.value))==null?void 0:q.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:"Select a machine..."}),n.map(O=>s.jsx("option",{value:O.id,children:ld(O)},O.id))]})}),(i.addNodeDaemonPicker?_:!0)&&s.jsx(jt,{label:"Workspace Path",children:i.addNodeDaemonPicker&&!X&&A.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:A.map(O=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${I===O.path?"border-accent-primary bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-primary hover:bg-violet-500/10 text-text-primary"}`,onClick:()=>R(O.path),children:[s.jsx("span",{className:"font-medium block truncate",children:O.label||O.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:O.path})]},O.id||O.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{M(!0),R("")},children:"Or enter a custom path →"})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(Rr,{value:I,onChange:O=>R(O.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:O=>{O.key==="Enter"&&z()}}),A.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{M(!1),R("")},children:"← Pick from saved workspaces"})]}):(()=>{var ne;const O=Array.isArray(r==null?void 0:r.workspaces)?r.workspaces:[],q=`mesh-add-node-workspaces-${a||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(Rr,{value:I,onChange:J=>R(J.target.value),placeholder:((ne=O[0])==null?void 0:ne.path)||"/Users/dev/projects/myapp",list:O.length>0?q:void 0,autoFocus:!0}),O.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:q,children:O.map(J=>s.jsx("option",{value:J.path,children:J.label||J.path},J.id||J.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:O.slice(0,6).map(J=>s.jsx("button",{type:"button",onClick:()=>R(J.path),className:"text-[11px] px-2 py-0.5 rounded-full border border-border-subtle hover:border-accent-primary/50 text-text-muted hover:text-text-primary transition-colors bg-transparent cursor-pointer",title:J.path,children:J.label||J.path.split("/").filter(Boolean).pop()||J.path},J.id||J.path))})]})]})})()})}),s.jsx(jt,{label:"Preferred AI tools (in order)",hint:"Order used when launching without an explicit provider.",children:s.jsx(lc,{value:L,availableProviders:i.addNodeDaemonPicker?E:m,onChange:T})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:z,disabled:!I.trim()||i.addNodeDaemonPicker&&!_,className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>{C(),$(""),M(!1)},className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-300 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:"Setup inventory only — live git/session/branch detail is shown in the graph popup after direct aggregate mesh_status truth is available from the Mesh Host."}),e.length===0?s.jsx(ja,{icon:s.jsx(Qs,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:e.map(O=>{const q=SS(O),ne=kS(O,t),J=AS(O,r),ye=N===O.id,oe=CS(O),B=O.status||O.machine_status||(ne.length>0||J.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${i.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${ye?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:i.addNodeDaemonPicker?void 0:"button",tabIndex:i.addNodeDaemonPicker?void 0:0,onClick:i.addNodeDaemonPicker?void 0:()=>k(ye?null:O.id),onKeyDown:i.addNodeDaemonPicker?void 0:W=>{(W.key==="Enter"||W.key===" ")&&(W.preventDefault(),k(ye?null:O.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.addNodeDaemonPicker?s.jsx("span",{className:"font-semibold text-sm text-text-primary truncate",children:O.machine_label||O.machine_nickname||O.hostname||O.workspace}):s.jsx("span",{className:"text-sm font-medium",children:O.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx(Im,{status:B}),ne.length>0&&!i.addNodeDaemonPicker&&s.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-orange-500/15 text-orange-300 border border-orange-500/25",children:[ne.length," active task",ne.length===1?"":"s"]}),oe&&s.jsx("span",{className:`text-[10px] px-2 py-0.5 rounded-full ${i.addNodeDaemonPicker?"bg-cyan-400/10 text-cyan-300 border border-cyan-400/30":"bg-cyan-500/15 text-cyan-300 border border-cyan-500/25"}`,children:"worktree"}),i.addNodeDaemonPicker&&s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:"setup inventory"})]}),i.addNodeDaemonPicker&&s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Owner: ",TS(n.find(W=>W.id===String(O.daemon_id||"")),o)," · Machine: ",O.machine_label||O.daemon_id||O.workspace]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:O.workspace}),oe&&s.jsxs("div",{className:`mt-2 rounded-lg px-3 py-2 text-[11px] ${i.addNodeDaemonPicker?"border border-cyan-400/20 bg-cyan-400/10 text-cyan-200":"border border-cyan-500/20 bg-cyan-500/10 text-cyan-200"}`,children:["Worktree node",O.worktreeBranch?` · ${O.worktreeBranch}`:"",". Provider priority saved here is node-local and disappears when removed."]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:"Live branch/git/session detail is graph-owned; use the node popup in the live graph above."}),s.jsxs("div",{className:`mt-3 max-w-2xl ${i.addNodeDaemonPicker,""}`,onClick:W=>W.stopPropagation(),children:[s.jsxs(jt,{label:"Preferred AI tools (in order)",hint:oe?"Worktree-local launch defaults. Configure the source node for durable defaults.":i.addNodeDaemonPicker?"Used for coordinator/session launches when no tool is selected explicitly.":"Used when launches omit an explicit tool.",children:[s.jsx(lc,{value:u[O.id]??Mm(O),availableProviders:jS(O,K),onChange:W=>p(O.id,W),disabled:h===O.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:W=>{W.stopPropagation(),b(O)},disabled:h===O.id,children:h===O.id?"Saving…":"Save"})}),s.jsxs("div",{className:"mt-2 text-[12px]",children:[s.jsx("span",{className:"text-text-muted",children:"Effective order: "}),s.jsx("span",{className:q.configured?"text-text-primary font-mono":"text-amber-400",children:q.label}),!q.configured&&q.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",q.launchBlockedMessage,")"]})]})]}),i.nodeInstruction&&s.jsxs(jt,{label:"Node instruction (optional)",hint:"Surfaced in the coordinator system prompt as 📌 Node instruction.",children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:v[O.id]??"",onChange:W=>{const ve=W.target.value;j(O.id,ve)},onClick:W=>W.stopPropagation(),disabled:y===O.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:W=>{W.stopPropagation(),w(O)},disabled:y===O.id,children:y===O.id?"Saving…":"Save instruction"})})]}),s.jsx(RS,{node:O,schedulingStrategy:d,saving:g===O.id,onSave:W=>f(O,W)})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${i.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:W=>{W.stopPropagation(),D(O.id)},title:"Remove node",children:i.addNodeDaemonPicker?s.jsx(pS,{size:14}):s.jsx(vt,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:W=>W.stopPropagation(),children:[s.jsxs("summary",{className:"cursor-pointer select-none text-[12px] text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[s.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," Details"]}),s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Node ID:"})," ",s.jsx("span",{className:"font-mono break-all",children:O.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:q.configured?"text-green-400":"text-amber-400",children:q.configured?"yes":"no preferred tool configured"})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Repo root:"})," ",s.jsx("span",{className:"font-mono break-all",children:O.repoRoot||O.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",J.length]}),i.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Added:"})," ",new Date(O.created_at||O.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),ne.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:ne.map(W=>s.jsx("li",{className:"font-mono",children:NS(W)},W.id))})]}),J.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:J.map(W=>s.jsxs("li",{className:"font-mono",children:[W.provider," / ",W.status," / ",W.id]},W.id))})]})]})]})]},O.id)})})]})}function RS({node:e,schedulingStrategy:t,saving:r,onSave:n}){const a=IS(e),o=l.useMemo(()=>MS(e),[e]),[i,c]=l.useState(String(a)),[d,u]=l.useState(o),p=t!=="first_eligible";function m(){u(f=>[...f,{providerType:""}])}function h(f,v){u(j=>j.map((y,w)=>w===f?{...y,...v}:y))}function b(f){u(v=>v.filter((j,y)=>y!==f))}function g(){const f=d.map(j=>({providerType:j.providerType.trim(),maxParallel:Number.isFinite(Number(j.maxParallel))&&Number(j.maxParallel)>=0?Math.floor(Number(j.maxParallel)):void 0})).filter(j=>j.providerType.length>0),v=Number(i);n({schedulingPriority:Number.isFinite(v)?v:0,providerRoles:f})}return s.jsxs("details",{className:"mt-3 group",onClick:f=>f.stopPropagation(),children:[s.jsxs("summary",{className:"cursor-pointer select-none text-[12px] text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[s.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," Advanced",(a!==0||o.length>0)&&s.jsxs("span",{className:"ml-1 rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 text-[10px] text-text-muted",children:[a!==0?`priority ${a}`:"",a!==0&&o.length>0?" · ":"",o.length>0?`${o.length} cap${o.length===1?"":"s"}`:""]})]}),s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx(jt,{label:"Scheduling priority",hint:p?"Higher = preferred when the mesh distributes work. Not an eligibility gate.":"Used only when the mesh Distribution strategy spreads work (currently First available — no effect).",children:s.jsx("input",{type:"number",step:1,className:"w-32 px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:i,onChange:f=>c(f.target.value),onClick:f=>f.stopPropagation(),disabled:r})}),s.jsx(jt,{label:"Per-provider max parallel (optional)",hint:"Cap concurrent active tasks for a tool on this node. Routing is governed by task required_tags, not by this entry.",children:s.jsxs("div",{className:"flex flex-col gap-2",children:[d.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"No per-provider caps. This node uses global caps only."}),d.map((f,v)=>s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",placeholder:"provider type (e.g. claude-cli)",className:"flex-1 min-w-[10rem] px-2 py-1.5 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary",value:f.providerType,onChange:j=>h(v,{providerType:j.target.value}),onClick:j=>j.stopPropagation(),disabled:r}),s.jsx("input",{type:"number",min:0,step:1,placeholder:"max ∥",className:"w-20 px-2 py-1.5 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary",value:f.maxParallel??"",onChange:j=>h(v,{maxParallel:j.target.value===""?void 0:Number(j.target.value)}),onClick:j=>j.stopPropagation(),disabled:r}),s.jsx("button",{type:"button",className:"text-text-muted hover:text-red-400 bg-transparent border-none cursor-pointer",onClick:j=>{j.stopPropagation(),b(v)},title:"Remove cap",disabled:r,children:s.jsx(vt,{size:13})})]},v)),s.jsxs("button",{type:"button",className:"self-start text-[12px] text-accent-primary bg-transparent border-none cursor-pointer p-0 inline-flex items-center gap-1",onClick:f=>{f.stopPropagation(),m()},disabled:r,children:[s.jsx(Cm,{size:12})," Add cap"]})]})}),s.jsx("div",{className:"mt-2 flex items-center gap-2",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:f=>{f.stopPropagation(),g()},disabled:r,children:r?"Saving…":"Save advanced"})})]})]})}function PS(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function LS({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:r,coordinatorCliType:n,onCoordinatorCliTypeChange:a,launchingCoordinator:o,launchResult:i,attachedDaemonIds:c,isHostNodeAttached:d,selectedHostNode:u,onLaunchCoordinator:p,onAttachSelectedHost:m}){return s.jsxs(dt,{title:"Mesh Host daemon",description:"Choose the daemon that will own the coordinator. Host-owned live truth is required before cloud renders status, queue, graph, or node detail.",children:[s.jsxs(fs,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:"Start with one host workspace."})," ","Create a mesh on a connected daemon, then attach additional machine workspaces below. Live status, queue, and graph data come from the selected host daemon."]}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-[1fr_180px_auto] items-end",children:[s.jsx(jt,{label:"Mesh Host daemon",hint:"Cloud selects the connected daemon to command over P2P; the host must be attached before it can own a coordinator.",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:t,onChange:h=>r(h.target.value),children:[s.jsx("option",{value:"",children:"Select a Mesh Host..."}),e.map(h=>s.jsxs("option",{value:h.id,children:[PS(h)," · ",c.has(h.id)?"attached":"not attached"]},h.id))]})}),s.jsx(jt,{label:"CLI provider",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:n,onChange:h=>a(h.target.value),children:[s.jsx("option",{value:"",children:"Use node provider priority"}),s.jsx("option",{value:"claude-cli",children:"Claude Code"}),s.jsx("option",{value:"codex-cli",children:"Codex"}),s.jsx("option",{value:"gemini-cli",children:"Gemini"}),s.jsx("option",{value:"hermes-cli",children:"Hermes"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm",onClick:p,disabled:!t||!d||o,title:!d&&t?"Attach this Mesh Host daemon first.":void 0,children:o?"Launching...":"Launch Host Coordinator"})]}),s.jsx("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:t?d?s.jsxs(s.Fragment,{children:["Host setup node: ",s.jsx("span",{className:"font-mono text-text-primary",children:u==null?void 0:u.workspace}),". Live graph/status/detail renders only from this daemon."]}):s.jsx(s.Fragment,{children:"Selected host is not attached yet. Attach one of its workspaces below before launching."}):"Select a connected daemon to become the Mesh Host."}),!d&&t&&s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm mt-3",onClick:m,children:"Attach selected host daemon"}),i&&s.jsx("div",{className:"mt-3 text-[12px] text-green-400 bg-green-500/10 border border-green-500/20 rounded-lg px-3 py-2",children:i})]})}function DS({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const o=a.id.toLowerCase();return o==="hermes-cli"||o.includes("hermes")||a.name.toLowerCase().includes("hermes")}),n=yp(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(dt,{title:"Hermes MCP Config",description:"Hermes does not auto-import repo-local .mcp.json. Add this YAML under mcp_servers in Hermes config, then start a fresh Hermes session.",children:s.jsx(zp,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}const jo=[{value:"preserve",label:"Preserve history and runtimes",description:"Keep completed chat history and leave live runtimes alone."},{value:"stop",label:"Stop live runtimes only",description:"Release running session processes, but keep chat records/transcripts."},{value:"delete_stopped",label:"Delete stopped sessions only",description:"Clean completed/stopped chat clutter without killing live runtimes."},{value:"stop_and_delete",label:"Stop and delete sessions",description:"Stop matching runtimes, then remove their session records/transcripts."}],$S=[{value:"first_eligible",label:"First available (default)",description:"Send work to the first eligible node in order. No load-spreading — preserves the original behavior."},{value:"least_loaded",label:"Spread evenly (least-loaded)",description:"Prefer the eligible node with the fewest active tasks so work spreads instead of piling on one node."},{value:"round_robin",label:"Round-robin",description:"Among the least-loaded nodes, rotate the winner each pass for fair distribution."},{value:"priority_only",label:"Priority order",description:"Always send to the highest-priority eligible node (see each node's scheduling priority), ignoring load."}],ES={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function ua(e){return{...ES,...(e==null?void 0:e.policy)||{}}}function BS({selectedMesh:e,error:t,onDismissError:r,onBack:n,onDelete:a,displayedMeshStatus:o,graphLoading:i,graphError:c,graphProvenance:d,graphBootstrapFallback:u=!1,onRefreshGraph:p,queueSummary:m,queueLoading:h,queueError:b,onLoadQueue:g,savingPolicy:f,onUpdatePolicy:v,coordinatorPromptDraft:j,onCoordinatorPromptDraftChange:y,savingCoordinatorPrompt:w,onSaveCoordinatorPrompt:N,daemons:k,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:S,coordinatorCliType:C,onCoordinatorCliTypeChange:I,launchingCoordinator:R,launchResult:L,attachedDaemonIds:T,isHostNodeAttached:_,selectedHostNode:$,onLaunchCoordinator:X,activeDaemon:M,activeDaemonId:A,meshQueue:E,userName:F,nodeProviderPriorityDrafts:z,onNodeProviderPriorityDraftChange:D,availableCliProviders:K,savingNodePolicyId:O,onUpdateNodeProviderPriority:q,savingNodeSchedulingId:ne,onUpdateNodeScheduling:J,schedulingStrategy:ye,nodeSystemPromptDrafts:oe,onNodeSystemPromptDraftChange:B,savingNodeSystemPromptId:W,onSaveNodeSystemPrompt:ve,selectedNodeId:we,onSelectNode:fe,showAddNode:Ne,onShowAddNode:re,onCancelAddNode:je,nodeWorkspace:de,onNodeWorkspaceChange:U,nodeProviderPriority:H,onNodeProviderPriorityChange:Y,nodeDaemonId:se,onNodeDaemonIdChange:xe,nodeCustomPath:Z,onNodeCustomPathChange:P,nodePickerWorkspaces:ie,nodePickerProviders:be,attachableDaemons:ue,onAddNode:te,onRemoveNode:Me,availableCliAgents:Ae,features:Ce,reviewInboxItems:Ue,reviewInboxLoading:Qe,reviewInboxError:pe,reviewInboxRemoteNodesExcluded:De,onLoadReviewInbox:$e,onDismissReviewInboxItem:tt,onRefineNode:Ke,onRequeueLast:Ve,sendCommand:_e}){var Xe;const He=ua(e),it=e.nodes||[];return s.jsxs(Qr,{icon:s.jsx(as,{}),title:e.name,subtitle:e.repoIdentity||e.repo_identity||"Repo Mesh",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:n,children:"← Back"}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>p(!0),disabled:i,children:[s.jsx(Zi,{size:13}),i?"Probing…":"Refresh"]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>a(e.id),children:"Delete"})]}),children:[t&&s.jsx(fs,{variant:"error",onDismiss:r,className:"mb-4",children:t}),Ce.meshHostDaemonSection&&s.jsx(LS,{daemons:k,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:Pe=>{S(Pe),p()},coordinatorCliType:C,onCoordinatorCliTypeChange:I,launchingCoordinator:R,launchResult:L,attachedDaemonIds:T,isHostNodeAttached:_,selectedHostNode:$,onLaunchCoordinator:X,onAttachSelectedHost:()=>{xe(x),re()}}),Ce.queueSection&&s.jsx(fS,{queueSummary:m,queueLoading:h,queueError:b,activeDaemonId:A,onRefresh:g}),s.jsxs(dt,{title:"Mesh",description:"Overview cards (missions, ledger, queue, nodes, sessions) with the live topology graph behind the Graph tab.",children:[s.jsx("div",{className:"mb-4 text-[12px] text-text-muted max-w-2xl",children:Ce.meshHostDaemonSection?s.jsxs(s.Fragment,{children:["Direct aggregate mesh_status from the selected Mesh Host is preferred. Use Refresh above to ask the host for the latest peer git provenance.",d==="settling"&&s.jsx("span",{className:"ml-1 text-amber-300",children:"Refreshing peer data…"})]}):s.jsx(s.Fragment,{children:"Overview shows live mesh state as cards; switch to the Graph tab for the topology view."})}),u&&s.jsxs("div",{className:"mb-3 flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2.5 text-[12px] text-amber-200",children:[s.jsx("span",{className:"mt-0.5 shrink-0 text-amber-400","aria-hidden":!0,children:"⚠"}),s.jsx("span",{children:"Connecting to coordinator — showing setup inventory. Live data will appear shortly."})]}),c&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:c}),o?s.jsx(bm,{status:o,emptyMessage:Ce.meshHostDaemonSection?"No mesh graph data is available yet. Refresh after the selected Mesh Host is reachable.":"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology.",daemonId:A,sendDaemonCommand:_e,bootstrapFallback:u}):s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:i?"Loading graph...":Ce.meshHostDaemonSection?"No mesh graph data is available yet. Refresh after the selected Mesh Host is reachable.":"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology."})]}),Ce.reviewInbox&&s.jsx(vS,{items:Ue,loading:Qe,error:pe,remoteNodesExcluded:De,meshId:e.id,activeDaemonId:A,onRefresh:$e,onDismiss:tt,onRefineNode:Ke,onRequeueLast:Ve,sendCommand:_e}),s.jsx(_S,{nodes:it,meshQueue:E,activeDaemon:M,daemons:k,selectedMeshId:e.id,userName:F,features:{addNodeDaemonPicker:Ce.addNodeDaemonPicker,nodeInstruction:Ce.nodeInstruction},coordinatorDaemonId:x,schedulingStrategy:ye,nodeProviderPriorityDrafts:z,onNodeProviderPriorityDraftChange:D,availableCliProviders:K,savingNodePolicyId:O,onUpdateNodeProviderPriority:q,savingNodeSchedulingId:ne,onUpdateNodeScheduling:J,nodeSystemPromptDrafts:oe,onNodeSystemPromptDraftChange:B,savingNodeSystemPromptId:W,onSaveNodeSystemPrompt:ve,selectedNodeId:we,onSelectNode:fe,showAddNode:Ne,onShowAddNode:re,onCancelAddNode:je,nodeWorkspace:de,onNodeWorkspaceChange:U,nodeProviderPriority:H,onNodeProviderPriorityChange:Y,nodeDaemonId:se,onNodeDaemonIdChange:xe,nodeCustomPath:Z,onNodeCustomPathChange:P,nodePickerWorkspaces:ie,nodePickerProviders:be,attachableDaemons:ue,onAddNode:te,onRemoveNode:Me}),s.jsxs(dt,{title:"Scheduling",description:"How untargeted queue work is distributed across eligible nodes.",children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:s.jsx(jt,{label:"Max parallel tasks",hint:"Cap on concurrently assigned tasks across the mesh.",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(He.maxParallelTasks??2),onChange:Pe=>v({maxParallelTasks:Number(Pe.target.value)}),disabled:f,children:[1,2,3,4,5,6,7,8].map(Pe=>s.jsx("option",{value:Pe,children:Pe},Pe))})})}),s.jsxs("fieldset",{className:"mt-4 border-none p-0 m-0",children:[s.jsx("legend",{className:"text-[13px] font-medium text-text-secondary mb-2",children:"Distribution strategy"}),s.jsx("div",{className:"flex flex-col gap-2",children:$S.map(Pe=>{const G=(He.schedulingStrategy||"first_eligible")===Pe.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${G?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:[s.jsx("input",{type:"radio",name:"mesh-scheduling-strategy",className:"mt-0.5 accent-[var(--accent-primary)]",value:Pe.value,checked:G,disabled:f,onChange:()=>v({schedulingStrategy:Pe.value})}),s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block text-sm text-text-primary",children:Pe.label}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:Pe.description})]})]},Pe.value)})}),(He.schedulingStrategy==="priority_only"||He.schedulingStrategy==="least_loaded"||He.schedulingStrategy==="round_robin")&&s.jsxs("div",{className:"mt-2 text-[12px] text-text-muted",children:["Per-node scheduling priority is set in each node's ",s.jsx("span",{className:"text-text-secondary",children:"Advanced"})," panel above."]})]}),f&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving…"})]}),Ce.coordinatorPrompt&&s.jsxs(dt,{title:"Coordinator prompt",collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:"advanced"}),description:"Customize the system prompt for coordinator sessions. Leave empty to use the daemon default.",children:[s.jsx(jt,{label:"Override (replaces default)",hint:"When set, replaces the daemon's default base prompt. Leave empty to keep the default.",children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:j.override,onChange:Pe=>y({...j,override:Pe.target.value}),disabled:w,placeholder:"(empty — daemon default applies)"})}),s.jsx(jt,{label:"Append (added after the base)",hint:"Always added after whichever base prompt wins.",children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:4,value:j.append,onChange:Pe=>y({...j,append:Pe.target.value}),disabled:w,placeholder:"(empty — nothing appended)"})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:"Available placeholders"}),s.jsx("p",{className:"mt-1 font-mono break-words",children:"{{meshName}}, {{repo}}, {{defaultBranch}}, {{cliType}}, {{nodes}}, {{policy}}, {{tools}}, {{workflow}}, {{rules}}, {{toolExposurePreflight}}"})]}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:N,disabled:w,children:w?"Saving…":"Save coordinator prompt"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>y({override:"",append:""}),disabled:w,title:"Clear both fields. Click Save to commit.",children:"Clear"})]})]}),s.jsxs(dt,{title:"Safety & Git",collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:"advanced"}),description:"Checkpointing, approval gates, and git safety behavior for coordinator-driven tasks.",children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:"Auto-commit a checkpoint before each task",key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:Pe=>Pe?"yes":"no",parse:Pe=>Pe==="yes"},{label:"Auto-commit a checkpoint after each task",key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:Pe=>Pe?"yes":"no",parse:Pe=>Pe==="yes"},{label:"Push approval",key:"requireApprovalForPush",opts:[["required","Require approval before push"],["not_required","Do not require approval"]],val:Pe=>Pe?"required":"not_required",parse:Pe=>Pe==="required"},{label:"Destructive git approval",key:"requireApprovalForDestructiveGit",opts:[["required","Require approval"],["not_required","Do not require approval"]],val:Pe=>Pe?"required":"not_required",parse:Pe=>Pe==="required"},{label:"When the workspace has uncommitted changes",key:"dirtyWorkspaceBehavior",opts:[["warn","Warn and continue"],["block","Block task"],["checkpoint_then_continue","Checkpoint then continue"]],val:Pe=>Pe||"warn",parse:Pe=>Pe},{label:"Auto-publish submodule commits (advanced)",key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled","Require explicit approval"],["enabled","Allow Refinery non-force publish"]],val:Pe=>Pe?"enabled":"disabled",parse:Pe=>Pe==="enabled"}].map(({label:Pe,key:G,opts:V,val:ae,parse:le})=>s.jsx(jt,{label:Pe,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:ae(He[G]),onChange:ge=>v({[G]:le(ge.target.value)}),disabled:f,children:V.map(([ge,ke])=>s.jsx("option",{value:ge,children:ke},ge))})},G))}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(jt,{label:"When removing a node, its sessions…",hint:"Separate transcript cleanup from runtime/process cleanup.",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:He.sessionCleanupOnNodeRemove||"preserve",onChange:Pe=>v({sessionCleanupOnNodeRemove:Pe.target.value}),disabled:f,children:jo.map(Pe=>s.jsx("option",{value:Pe.value,children:Pe.label},Pe.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((Xe=jo.find(Pe=>Pe.value===He.sessionCleanupOnNodeRemove))==null?void 0:Xe.description)||jo[0].description})]}),f&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving…"})]}),Ce.hermesMcpConfig&&s.jsx(DS,{meshId:e.id,availableCliAgents:Ae}),Ce.meshHostDaemonSection&&s.jsxs(fs,{variant:"info",className:"mt-4",children:[s.jsx("strong",{children:"MCP Mode:"})," ",s.jsxs("code",{className:"bg-bg-secondary px-1 rounded text-xs",children:["adhdev mcp --repo-mesh ",e.id]})," · The mesh MCP server can be used directly from your CLI agent."]})]})}function FS({daemons:e,primaryDaemonId:t,sendCommand:r,unwrapResult:n,normalizeMesh:a,features:o}){const[i,c]=l.useState([]),[d,u]=l.useState(null),[p,m]=l.useState(!0),[h,b]=l.useState(null),[g,f]=l.useState(!1),[v,j]=l.useState(""),[y,w]=l.useState(""),[N,k]=l.useState(""),[x,S]=l.useState(""),[C,I]=l.useState(""),R=l.useMemo(()=>e.find(A=>A.id===x),[e,x]),L=(R==null?void 0:R.workspaces)||[],T=l.useMemo(()=>sr((R==null?void 0:R.availableProviders)||[]),[R]),_=l.useCallback(async()=>{m(!0);try{if(o.createDaemonPicker){const A=await Promise.allSettled(e.map(async F=>{if(!F.id)return[];const z=await r(F.id,"list_meshes",{}),D=n(z);if((D==null?void 0:D.success)===!1)throw new Error(D.error||"Failed to load meshes");return(Array.isArray(D==null?void 0:D.meshes)?D.meshes:[]).map(K=>a(K,F.id)).filter(K=>K.id)})),E=new Map;for(const F of A)if(F.status==="fulfilled")for(const z of F.value)E.has(z.id)||E.set(z.id,z);c(Array.from(E.values()))}else{if(!t)return;const A=await r(t,"list_meshes");A!=null&&A.success?(c((A.meshes||[]).map(E=>a(E,t))),b(null)):b((A==null?void 0:A.error)||"Failed to load meshes")}}catch(A){b((A==null?void 0:A.message)||"Failed to load meshes")}finally{m(!1)}},[e,t,r,n,a,o.createDaemonPicker]);async function $(){var z,D;const A=o.createDaemonPicker?x:t;if(!A||!v.trim())return;const E=N.trim(),F=y.trim();if(!(!E&&!F))try{const K={name:v.trim()};E&&(K.repoRemoteUrl=E),F&&(K.repoIdentity=F);const O=await r(A,"create_mesh",K),q=n(O);if((q==null?void 0:q.success)===!1)throw new Error(q.error||"Create failed");const ne=typeof((z=q==null?void 0:q.mesh)==null?void 0:z.id)=="string"?q.mesh.id:"";if(ne&&o.createDaemonPicker&&C){const J=await r(A,"add_mesh_node",{meshId:ne,daemonId:A,machineId:R==null?void 0:R.machineId,workspace:C,role:"host",providerPriority:Or(T)}),ye=n(J);if((ye==null?void 0:ye.success)===!1)throw new Error(ye.error||"Mesh created but failed to attach workspace")}f(!1),j(""),w(""),k(""),I(""),await _(),(D=q==null?void 0:q.mesh)!=null&&D.id&&u(q.mesh.id)}catch(K){b((K==null?void 0:K.message)||"Create failed")}}async function X(A){var F;if(!confirm("Delete this mesh? This cannot be undone."))return;const E=((F=i.find(z=>z.id===A))==null?void 0:F.__sourceDaemonId)||t;try{const z=await r(E,"delete_mesh",{meshId:A}),D=n(z);if((D==null?void 0:D.success)===!1)throw new Error(D.error||"Failed to delete");d===A&&u(null),await _()}catch(z){b((z==null?void 0:z.message)||"Delete failed")}}function M(){f(!1),j(""),w(""),k("")}return{meshes:i,setMeshes:c,selectedMeshId:d,setSelectedMeshId:u,loading:p,error:h,setError:b,showCreate:g,setShowCreate:f,createName:v,setCreateName:j,createRepoIdentity:y,setCreateRepoIdentity:w,createRepoRemoteUrl:N,setCreateRepoRemoteUrl:k,newMeshDaemonId:x,setNewMeshDaemonId:S,newMeshWorkspace:C,setNewMeshWorkspace:I,createPickerWorkspaces:L,createPickerProviders:T,loadMeshes:_,handleCreate:$,handleDelete:X,cancelCreate:M}}function OS({selectedMesh:e,selectedMeshId:t,primaryDaemonId:r,activeDaemonId:n,daemons:a,availableCliProviders:o,sendCommand:i,unwrapResult:c,loadLiveMesh:d,resolveCommandTarget:u,launchCoordinator:p,features:m,loadMeshes:h,loadQueue:b,queueSection:g,setError:f}){const[v,j]=l.useState({}),[y,w]=l.useState(null),[N,k]=l.useState(null),[x,S]=l.useState(!1),[C,I]=l.useState(""),[R,L]=l.useState([]),[T,_]=l.useState(""),[$,X]=l.useState(!1),[M,A]=l.useState(""),[E,F]=l.useState(!1),[z,D]=l.useState(null),[K,O]=l.useState(!1),[q,ne]=l.useState({override:"",append:""}),[J,ye]=l.useState(!1),[oe,B]=l.useState({}),[W,ve]=l.useState(null),we=l.useMemo(()=>a.find(ie=>ie.id===T),[a,T]),fe=(we==null?void 0:we.workspaces)||[],Ne=l.useMemo(()=>sr((we==null?void 0:we.availableProviders)||[]),[we]);async function re(){const ie=(e==null?void 0:e.__sourceDaemonId)||r;if(!t||!ie)return;const be=C.trim();if(be)try{const ue={meshId:t,workspace:be};m.addNodeDaemonPicker&&T?(ue.daemonId=T,ue.machineId=we==null?void 0:we.machineId,ue.providerPriority=Dn(R,Ne)):ue.providerPriority=Dn(R,o);const te=await i(ie,"add_mesh_node",ue),Me=c(te);if((Me==null?void 0:Me.success)===!1)throw new Error(Me.error||"Add node failed");S(!1),I(""),L([]),_(""),X(!1),await h(),g||await b(t)}catch(ue){f((ue==null?void 0:ue.message)||"Add node failed")}}async function je(ie){var Me;if(!e)return;const be=ua(e),ue=((Me=[{value:"preserve",label:"Preserve history and runtimes"},{value:"stop",label:"Stop live runtimes only"},{value:"delete_stopped",label:"Delete stopped sessions only"},{value:"stop_and_delete",label:"Stop and delete sessions"}].find(Ae=>Ae.value===be.sessionCleanupOnNodeRemove))==null?void 0:Me.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
|
|
112
|
+
|
|
113
|
+
Node removal cleanup policy: ${ue}`))return;const te=e.__sourceDaemonId||r;try{const Ae=await i(te,"remove_mesh_node",{meshId:e.id,nodeId:ie}),Ce=c(Ae);if((Ce==null?void 0:Ce.success)===!1)throw new Error(Ce.error||"Remove failed");N===ie&&k(null),await h(),g||await b(t)}catch(Ae){f((Ae==null?void 0:Ae.message)||"Remove node failed")}}async function de(ie){if(!e)return;const be={...ua(e),...ie},ue=e.__sourceDaemonId||r;try{O(!0),f(null);const te=await i(ue,"update_mesh",{meshId:e.id,policy:be}),Me=c(te);if((Me==null?void 0:Me.success)===!1)throw new Error(Me.error||"Policy update failed");await h()}catch(te){f((te==null?void 0:te.message)||"Policy update failed")}finally{O(!1)}}async function U(ie){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||r,ue=m.addNodeDaemonPicker?Ne:o,te=v[ie.id]||HS(ie),Me=ue.length>0?Dn(te,ue):Xr(te),Ae={...ie.policy||{}};delete Ae.provider_priority,Me.length?Ae.providerPriority=Me:delete Ae.providerPriority;try{w(ie.id),f(null);const Ce=await i(be,"update_mesh_node",{meshId:t,nodeId:ie.id,policy:Ae,providerPriority:Me}),Ue=c(Ce);if((Ue==null?void 0:Ue.success)===!1){f(Ue.error||"Node policy update failed");return}await h()}catch(Ce){f((Ce==null?void 0:Ce.message)||"Node policy update failed")}finally{w(null)}}const[H,Y]=l.useState(null);async function se(ie,be){if(!t)return;const ue=(e==null?void 0:e.__sourceDaemonId)||r,te={};Object.prototype.hasOwnProperty.call(be,"schedulingPriority")&&(te.schedulingPriority=Number.isFinite(be.schedulingPriority)?be.schedulingPriority:0);const Me={meshId:t,nodeId:ie.id,policy:te};Object.prototype.hasOwnProperty.call(be,"providerRoles")&&(Me.providerRoles=be.providerRoles);try{Y(ie.id),f(null);const Ae=await i(ue,"update_mesh_node",Me),Ce=c(Ae);if((Ce==null?void 0:Ce.success)===!1){f(Ce.error||"Node scheduling update failed");return}await h()}catch(Ae){f((Ae==null?void 0:Ae.message)||"Node scheduling update failed")}finally{Y(null)}}async function xe(){if(!r||!t)return;const be={...(e==null?void 0:e.coordinator)||{}};q.override.trim()?be.systemPromptOverride=q.override:delete be.systemPromptOverride,q.append.trim()?be.systemPromptAppend=q.append:delete be.systemPromptAppend,delete be.systemPromptSuffix;try{ye(!0),f(null);const ue=await i(r,"update_mesh",{meshId:t,coordinator:be}),te=c(ue);if((te==null?void 0:te.success)===!1){f(te.error||"Coordinator prompt save failed");return}await h()}catch(ue){f((ue==null?void 0:ue.message)||"Coordinator prompt save failed")}finally{ye(!1)}}async function Z(ie){if(!r||!t)return;const be=(oe[ie.id]||"").trim();try{ve(ie.id),f(null);const ue=await i(r,"update_mesh_node",{meshId:t,nodeId:ie.id,systemPrompt:be}),te=c(ue);if((te==null?void 0:te.success)===!1){f(te.error||"Node instruction save failed");return}await h()}catch(ue){f((ue==null?void 0:ue.message)||"Node instruction save failed")}finally{ve(null)}}async function P(){if(e){f(null),D(null);try{F(!0);const ie=d?await d(n,e.id,e):null,be=u(n,e.id,e,e.nodes||[],ie);if("error"in be)throw new Error(be.error);const ue=await p(be.targetDaemonId,{meshId:e.id,inlineMesh:be.inlineMesh,coordinatorNodeId:be.coordinatorNodeId,cliType:M.trim()||void 0});D(ue.message)}catch(ie){f((ie==null?void 0:ie.message)||"Coordinator launch failed")}finally{F(!1)}}}return{nodeProviderPriorityDrafts:v,setNodeProviderPriorityDrafts:j,savingNodePolicyId:y,selectedNodeId:N,setSelectedNodeId:k,showAddNode:x,setShowAddNode:S,nodeWorkspace:C,setNodeWorkspace:I,nodeProviderPriority:R,setNodeProviderPriority:L,nodeDaemonId:T,setNodeDaemonId:_,nodeCustomPath:$,setNodeCustomPath:X,nodePickerWorkspaces:fe,nodePickerProviders:Ne,coordinatorCliType:M,setCoordinatorCliType:A,launchingCoordinator:E,launchResult:z,savingPolicy:K,coordinatorPromptDraft:q,setCoordinatorPromptDraft:ne,savingCoordinatorPrompt:J,nodeSystemPromptDrafts:oe,setNodeSystemPromptDrafts:B,savingNodeSystemPromptId:W,savingNodeSchedulingId:H,handleAddNode:re,handleRemoveNode:je,handleUpdatePolicy:de,handleUpdateNodeProviderPriority:U,handleUpdateNodeScheduling:se,handleSaveCoordinatorPrompt:xe,handleSaveNodeSystemPrompt:Z,handleLaunchCoordinator:P}}function HS(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function zS(e){const t=e.filter(n=>n.status==="pending"||n.status==="assigned"),r=e.filter(n=>n.status==="completed"||n.status==="failed"||n.status==="cancelled");return{active:t.length,historical:r.length,activeCounts:{pending:t.filter(n=>n.status==="pending").length,assigned:t.filter(n=>n.status==="assigned").length},historicalCounts:{completed:r.filter(n=>n.status==="completed").length,failed:r.filter(n=>n.status==="failed").length},counts:{pending:e.filter(n=>n.status==="pending").length,assigned:e.filter(n=>n.status==="assigned").length,completed:e.filter(n=>n.status==="completed").length,failed:e.filter(n=>n.status==="failed").length},staleAssignedCount:e.filter(n=>n.staleAssigned).length,recent:e.slice(0,20)}}function WS({primaryDaemonId:e,activeDaemonId:t,sendCommand:r,unwrapResult:n,loadLiveMesh:a,resolveCommandTarget:o}){const[i,c]=l.useState([]),[d,u]=l.useState(null),[p,m]=l.useState(!1),[h,b]=l.useState(null),g=l.useCallback(async v=>{if(!e||!v){c([]);return}try{const j=await r(e,"get_mesh_queue",{meshId:v});c(j!=null&&j.success?Array.isArray(j.queue)?j.queue:[]:[])}catch{c([])}},[e,r]);async function f(v){var j,y;if(v){m(!0),b(null);try{const w=a?await a(t,v.id,v):null,N=o(t,v.id,v,v.nodes||[],w);if("error"in N)throw new Error(N.error);const k=await r(N.targetDaemonId,"get_mesh_queue",{meshId:v.id}),x=n(k);if((x==null?void 0:x.success)===!1)throw new Error(x.error||"Queue load failed");const S=Array.isArray(((j=x==null?void 0:x.result)==null?void 0:j.rows)??(x==null?void 0:x.rows)??(x==null?void 0:x.queue))?((y=x==null?void 0:x.result)==null?void 0:y.rows)??(x==null?void 0:x.rows)??(x==null?void 0:x.queue):[];u(zS(S))}catch(w){b((w==null?void 0:w.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:d,queueLoading:p,queueError:h,loadQueue:g,handleLoadQueue:f}}function KS(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}function US({selectedMeshId:e,loadMeshStatus:t,extractStatus:r,normalizeNode:n,gateIncompleteGraph:a}){const[o,i]=l.useState(null),[c,d]=l.useState(!1),[u,p]=l.useState(null),[m,h]=l.useState("idle"),[b,g]=l.useState(!1),f=l.useRef(!1);async function v(j,y=e,w=!1){if(!(!j||!y))try{d(!w&&o===null),h(w?"settling":"first_paint"),p(null);const N=await t(j,y,{refresh:w,retryProfile:w?"settled":"interactive"});g(KS(N));const k=r(N),x=n&&k?{...k,nodes:(k.nodes??[]).map(S=>n(S,k.meshId??y,""))}:k;if(x){if(a&&!w&&o!==null&&!Jj(rm(x))){h("settling"),f.current||(f.current=!0,Promise.resolve().then(()=>v(j,y,!0)).finally(()=>{f.current=!1}));return}i(x),h("settled")}else i(null),p("mesh_status returned an unexpected payload."),h("idle")}catch(N){o||i(null),p((N==null?void 0:N.message)||"Failed to load mesh graph"),h("idle")}finally{d(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:u,setGraphError:p,graphProvenance:m,graphBootstrapFallback:b,loadGraph:v}}function GS({primaryDaemonId:e,sendCommand:t}){const[r,n]=l.useState([]),[a,o]=l.useState(!1),[i,c]=l.useState(null),[d,u]=l.useState(!1),[p,m]=l.useState(new Set),h=l.useCallback(async f=>{if(!e||!f){n([]);return}o(!0),c(null);try{const v=await t(e,"get_mesh_review_inbox",{meshId:f});v!=null&&v.success?(n(Array.isArray(v.inbox)?v.inbox:[]),u(v.remoteNodesExcluded===!0)):(c((v==null?void 0:v.error)||"Failed to load review inbox"),n([]))}catch(v){c((v==null?void 0:v.message)||"Failed to load review inbox"),n([])}finally{o(!1)}},[e,t]),b=l.useCallback(f=>{m(v=>new Set([...v,f]))},[]);return{items:r.filter(f=>!p.has(f.nodeId)),allItems:r,loading:a,error:i,remoteNodesExcluded:d,dismissedNodeIds:p,loadInbox:h,dismissItem:b}}function VS(){const e=dS(),{sendCommand:t,sendData:r,daemons:n,userName:a,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:d,unwrapResult:u,normalizeMesh:p,normalizeNode:m,resolveCommandTarget:h,features:b,gateIncompleteGraph:g}=e,f=n[0],v=(f==null?void 0:f.id)||"",j=l.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(at=>at.category==="cli").map(at=>({id:at.type||at.id,name:at.displayName||at.name||at.type,meshCoordinator:at.meshCoordinator})),[f]),y=l.useMemo(()=>sr((f==null?void 0:f.availableProviders)||[]),[f]),{meshes:w,selectedMeshId:N,setSelectedMeshId:k,loading:x,error:S,setError:C,showCreate:I,setShowCreate:R,createName:L,setCreateName:T,createRepoIdentity:_,setCreateRepoIdentity:$,createRepoRemoteUrl:X,setCreateRepoRemoteUrl:M,newMeshDaemonId:A,setNewMeshDaemonId:E,newMeshWorkspace:F,setNewMeshWorkspace:z,createPickerWorkspaces:D,loadMeshes:K,handleCreate:O,handleDelete:q,cancelCreate:ne}=FS({daemons:n,primaryDaemonId:v,sendCommand:t,unwrapResult:u,normalizeMesh:p,features:b}),J=w.find(Oe=>Oe.id===N)||null,{meshGraphStatus:ye,setMeshGraphStatus:oe,graphLoading:B,graphError:W,setGraphError:ve,graphProvenance:we,graphBootstrapFallback:fe,loadGraph:Ne}=US({selectedMeshId:N,loadMeshStatus:o,extractStatus:d,normalizeNode:m,gateIncompleteGraph:g}),[re,je]=l.useState(""),de=b.meshHostDaemonSection&&re||v,{meshQueue:U,queueSummary:H,queueLoading:Y,queueError:se,loadQueue:xe,handleLoadQueue:Z}=WS({primaryDaemonId:v,activeDaemonId:de,sendCommand:t,unwrapResult:u,loadLiveMesh:c,resolveCommandTarget:h}),{items:P,loading:ie,error:be,remoteNodesExcluded:ue,loadInbox:te,dismissItem:Me}=GS({primaryDaemonId:v,sendCommand:t}),{nodeProviderPriorityDrafts:Ae,setNodeProviderPriorityDrafts:Ce,savingNodePolicyId:Ue,selectedNodeId:Qe,setSelectedNodeId:pe,showAddNode:De,setShowAddNode:$e,nodeWorkspace:tt,setNodeWorkspace:Ke,nodeProviderPriority:Ve,setNodeProviderPriority:_e,nodeDaemonId:He,setNodeDaemonId:it,nodeCustomPath:Xe,setNodeCustomPath:Pe,nodePickerWorkspaces:G,nodePickerProviders:V,coordinatorCliType:ae,setCoordinatorCliType:le,launchingCoordinator:ge,launchResult:ke,savingPolicy:Q,coordinatorPromptDraft:ee,setCoordinatorPromptDraft:he,savingCoordinatorPrompt:Ie,nodeSystemPromptDrafts:Le,setNodeSystemPromptDrafts:Te,savingNodeSystemPromptId:Ee,savingNodeSchedulingId:We,handleAddNode:Re,handleRemoveNode:Ye,handleUpdatePolicy:st,handleUpdateNodeProviderPriority:ht,handleUpdateNodeScheduling:kt,handleSaveCoordinatorPrompt:xt,handleSaveNodeSystemPrompt:bt,handleLaunchCoordinator:Ge}=OS({selectedMesh:J,selectedMeshId:N,primaryDaemonId:v,activeDaemonId:de,daemons:n,availableCliProviders:y,sendCommand:t,unwrapResult:u,loadLiveMesh:c,resolveCommandTarget:h,launchCoordinator:i,features:{addNodeDaemonPicker:b.addNodeDaemonPicker},loadMeshes:K,loadQueue:xe,queueSection:b.queueSection,setError:C}),Ot=l.useMemo(()=>n.find(Oe=>Oe.id===de)||f,[n,de,f]),ce=l.useMemo(()=>new Set(((J==null?void 0:J.nodes)||[]).map(Oe=>String(Oe.daemon_id||Oe.daemonId||""))),[J]),Fe=l.useMemo(()=>n.filter(Oe=>Oe.id&&!ce.has(Oe.id)),[n,ce]),me=(J==null?void 0:J.nodes)||[],Be=l.useMemo(()=>me.find(Oe=>String(Oe.daemon_id||Oe.daemonId||"")===re),[me,re]),It=b.meshHostDaemonSection?!!Be:!0,Pt=l.useMemo(()=>ye?[...new Set((ye.nodes??[]).map(Oe=>String(Oe.daemonId||Oe.daemon_id||"")).filter(Boolean))]:[],[ye]),ls=ym({status:ye,daemonId:de||null,extraDaemonIds:Pt,meshId:N,sendData:r});return l.useEffect(()=>{Ce(Object.fromEntries(((J==null?void 0:J.nodes)||[]).map(Oe=>[Oe.id,qS(Oe)])))},[J]),l.useEffect(()=>{const Oe=(J==null?void 0:J.coordinator)||{};he({override:typeof Oe.systemPromptOverride=="string"?Oe.systemPromptOverride:"",append:typeof Oe.systemPromptAppend=="string"?Oe.systemPromptAppend:typeof Oe.systemPromptSuffix=="string"?Oe.systemPromptSuffix:""}),Te(Object.fromEntries(((J==null?void 0:J.nodes)||[]).map(at=>[at.id,typeof at.systemPrompt=="string"?at.systemPrompt:""])))},[J]),l.useEffect(()=>{const Oe=b.addNodeDaemonPicker?Or(V):Or(y);De&&Ve.length===0&&Oe.length>0&&_e(Oe)},[De,y,V,Ve.length,b.addNodeDaemonPicker]),l.useEffect(()=>{const Oe=new Set(((J==null?void 0:J.nodes)||[]).map(at=>at.id));Qe&&!Oe.has(Qe)&&pe(null)},[J,Qe]),l.useEffect(()=>{if(b.meshHostDaemonSection){if(!n.length){je("");return}(!re||!n.some(Oe=>Oe.id===re))&&je(n[0].id)}},[n,re,b.meshHostDaemonSection]),l.useEffect(()=>{if(b.createDaemonPicker){if(!n.length){E("");return}(!A||!n.some(Oe=>Oe.id===A))&&E(n[0].id)}},[n,A,b.createDaemonPicker]),l.useEffect(()=>{var Oe;if(!b.createDaemonPicker||!A){z("");return}if(!D.length){z("");return}D.some(at=>at.path===F)||z(((Oe=D[0])==null?void 0:Oe.path)||"")},[A,F,D,b.createDaemonPicker]),l.useEffect(()=>{N&&(oe(null),ve(null),Ne(de,N))},[N,de]),l.useEffect(()=>{b.queueSection||xe(N)},[N,b.queueSection]),l.useEffect(()=>{!b.reviewInbox||!N||te(N)},[N,b.reviewInbox]),l.useEffect(()=>{K()},[K]),v?J?s.jsx(BS,{selectedMesh:J,error:S,onDismissError:()=>C(null),onBack:()=>{k(null),oe(null)},onDelete:q,displayedMeshStatus:ls,graphLoading:B,graphError:W,graphProvenance:we,graphBootstrapFallback:fe,onRefreshGraph:()=>Ne(de,N,!0),queueSummary:H,queueLoading:Y,queueError:se,onLoadQueue:()=>Z(J),savingPolicy:Q,onUpdatePolicy:st,coordinatorPromptDraft:ee,onCoordinatorPromptDraftChange:he,savingCoordinatorPrompt:Ie,onSaveCoordinatorPrompt:xt,daemons:n,coordinatorDaemonId:re,onCoordinatorDaemonIdChange:Oe=>{je(Oe),oe(null)},coordinatorCliType:ae,onCoordinatorCliTypeChange:le,launchingCoordinator:ge,launchResult:ke,attachedDaemonIds:ce,isHostNodeAttached:It,selectedHostNode:Be,onLaunchCoordinator:Ge,activeDaemon:Ot,activeDaemonId:de,meshQueue:U,userName:a,nodeProviderPriorityDrafts:Ae,onNodeProviderPriorityDraftChange:(Oe,at)=>Ce(cs=>({...cs,[Oe]:at})),availableCliProviders:y,savingNodePolicyId:Ue,onUpdateNodeProviderPriority:ht,savingNodeSchedulingId:We,onUpdateNodeScheduling:kt,schedulingStrategy:ua(J).schedulingStrategy,nodeSystemPromptDrafts:Le,onNodeSystemPromptDraftChange:(Oe,at)=>Te(cs=>({...cs,[Oe]:at})),savingNodeSystemPromptId:Ee,onSaveNodeSystemPrompt:bt,selectedNodeId:Qe,onSelectNode:pe,showAddNode:De,onShowAddNode:()=>$e(!0),onCancelAddNode:()=>$e(!1),nodeWorkspace:tt,onNodeWorkspaceChange:Ke,nodeProviderPriority:Ve,onNodeProviderPriorityChange:_e,nodeDaemonId:He,onNodeDaemonIdChange:it,nodeCustomPath:Xe,onNodeCustomPathChange:Pe,nodePickerWorkspaces:G,nodePickerProviders:V,attachableDaemons:Fe,onAddNode:Re,onRemoveNode:Ye,availableCliAgents:j,features:{coordinatorPrompt:b.coordinatorPrompt,meshHostDaemonSection:b.meshHostDaemonSection,queueSection:b.queueSection,hermesMcpConfig:b.hermesMcpConfig,addNodeDaemonPicker:b.addNodeDaemonPicker,nodeInstruction:b.nodeInstruction,reviewInbox:b.reviewInbox??!1},reviewInboxItems:P,reviewInboxLoading:ie,reviewInboxError:be,reviewInboxRemoteNodesExcluded:ue,onLoadReviewInbox:()=>N&&void te(N),onDismissReviewInboxItem:Me,onRefineNode:async Oe=>{N&&(await t(de,"refine_mesh_node",{meshId:N,nodeId:Oe,inlineMesh:J}),te(N))},onRequeueLast:async Oe=>{N&&(await t(de,"requeue_mesh_queue_task",{meshId:N,nodeId:Oe}),te(N))},sendCommand:t}):s.jsx(hS,{meshes:w,loading:x,error:S,onDismissError:()=>C(null),daemons:n,features:{createDaemonPicker:b.createDaemonPicker},showCreate:I,onToggleCreate:()=>R(!I),createName:L,onCreateNameChange:T,createRepoIdentity:_,onCreateRepoIdentityChange:$,createRepoRemoteUrl:X,onCreateRepoRemoteUrlChange:M,newMeshDaemonId:A,onNewMeshDaemonIdChange:E,newMeshWorkspace:F,onNewMeshWorkspaceChange:z,createPickerWorkspaces:D,onSelectMesh:k,onCreate:O,onCancelCreate:ne}):s.jsx(Qr,{icon:s.jsx(as,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})})}function qS(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 YS({children:e}){const{sendCommand:t,sendData:r}=mt(),{ides:n}=ss(),a=l.useMemo(()=>n.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[n]),o=l.useMemo(()=>({sendCommand:t,sendData:r,daemons:a,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var h;const d={meshId:c.meshId};c.cliType&&(d.cliType=c.cliType);const u=await t(i,"launch_mesh_coordinator",d),p=(u==null?void 0:u.result)??u;if((p==null?void 0:p.success)===!1)throw new Error(p.error||"Coordinator launch failed");const m=(p==null?void 0:p.sessionId)||((h=p==null?void 0:p.session)==null?void 0:h.id)||(p==null?void 0:p.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:vi,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:cS}),[t,r,a]);return s.jsx(Sm.Provider,{value:o,children:e})}function el(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function JS(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=el();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 Xt(e,t){return await fetch(JS(e),{credentials:"same-origin",...t})}function Am(){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 XS{constructor(){Ze(this,"adapters",new Map);Ze(this,"states",new Map);Ze(this,"runtimeListeners",new Map);Ze(this,"screenshotCallbacks",new Map);Ze(this,"statusCallbacks",new Set);Ze(this,"stateChangeCallbacks",new Set);Ze(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 Xt(`${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 Jt=new XS;function QS(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=el();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Tn=QS(),cd=3e3,ZS=3e4;let Wt=null,eC=0;const pa=new Map;let ws=null,Dr=null;function dd(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function jr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function tC(e){return e==="connected"?"connected":e}async function $r(e,t,r){const n=Ju(e,r||{}),a=Wt;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++eC}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{pa.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);pa.set(o,{resolve:u=>{clearTimeout(d),i(u)},reject:u=>{clearTimeout(d),c(u)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Zo(e,t){const r=Wt;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 Tm(e,t,r){const n=Wt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Ju(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}}Jt.registerPtyInputSender(Tm);class sC{constructor(t){Ze(this,"daemonId");Ze(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Wt==null?void 0:Wt.readyState)===WebSocket.OPEN}get connectionState(){return(Wt==null?void 0:Wt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return $r(this.daemonId,t,r)}async sendInput(t,r){return $r(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,ws&&(clearInterval(ws),ws=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await $r(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());Jt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ws=setInterval(r,2e3)}stopScreenshots(t){ws&&(clearInterval(ws),ws=null)}}let Et=null;function rC(e){return(!Et||Et.daemonId!==e)&&(Et=new sC(e)),Et}function nC({children:e}){const t=l.useRef(Br()),r=Br();t.current=r;const{setUserName:n}=ss(),a=l.useRef(n);a.current=n;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((f,v)=>{c(f),Dr==null||Dr(f,v)},[]),u=l.useRef(null),p=l.useRef(),m=l.useRef(cd),h=l.useRef(!0),b=l.useRef(!1),g=l.useRef("initial_connect");return l.useEffect(()=>{h.current=!0,b.current=!1;function f(){var y,w;if(!h.current||((y=u.current)==null?void 0:y.readyState)===WebSocket.OPEN||((w=u.current)==null?void 0:w.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Tn}...`),jr("connect_attempt",{url:Tn,reason:g.current,delayMs:m.current});let j;try{j=new WebSocket(Tn)}catch(N){console.error("[Standalone WS] Failed to create WebSocket:",N),v();return}u.current=j,j.onopen=()=>{if(!h.current){j.close();return}d("connected"),m.current=cd,jr("open",{url:Tn,reason:g.current}),ts.resubscribeAll({sendData:Zo}),console.log("[Standalone WS] Connected")},Wt=j,j.onmessage=N=>{var k,x;try{const S=JSON.parse(N.data);if((S.type==="command_result"||S.type==="error")&&S.requestId){const C=pa.get(S.requestId);C&&(pa.delete(S.requestId),S.type==="error"?C.reject(new Error(((k=S.data)==null?void 0:k.message)||"Command failed")):C.resolve(S.data));return}if(S.type==="session_output"){const C=S.sessionId||S.cliId||S.cliType;C&&Jt.emitSessionOutput(C,typeof S.data=="string"?S.data:"",typeof S.seq=="number"?S.seq:void 0);return}if(S.type==="runtime_snapshot"){Jt.emitRuntimeSnapshot(S.sessionId,typeof S.text=="string"?S.text:"",typeof S.seq=="number"?S.seq:0,!!S.truncated,typeof S.cols=="number"?S.cols:void 0,typeof S.rows=="number"?S.rows:void 0);return}if(S.type==="topic_update"){const C=S.update;C&&ts.publish(C);return}if(S.type==="status"||S.type==="initial_state"){const C=S.data;if(!C)return;const{injectEntries:I,markLoaded:R,getIdes:L}=t.current,T=C.instanceId||"standalone",_=L().find(M=>M.id===T),$=rC(T);Jt.register(T,$),Jt.setState(T,"connected"),d("connected",T),Jt.emitStatus(T,C);const X=Qn(C,{daemonId:T,existingDaemon:_,existingEntries:L()});dd("ws_status",{type:S.type,daemonId:T,sessions:(C.sessions||[]).map(M=>({id:M.id,parentId:M.parentId,providerType:M.providerType,kind:M.kind,transport:M.transport,unread:M.unread,inboxBucket:M.inboxBucket,lastSeenAt:M.lastSeenAt,lastUpdated:M.lastUpdated,title:M.title})),recentLaunches:(C.recentLaunches||[]).map(M=>({id:M.id,providerType:M.providerType,kind:M.kind,workspace:M.workspace,lastLaunchedAt:M.lastLaunchedAt}))}),dd("entries",{daemonId:T,entries:X.filter(M=>M.type!=="adhdev-daemon").map(M=>({id:M.id,type:M.type,unread:M.unread,inboxBucket:M.inboxBucket,lastSeenAt:M.lastSeenAt,lastUpdated:M.lastUpdated,sessionId:M.sessionId}))}),X.length>0&&I(X,{authoritativeDaemonIds:[T]}),R(),i.current!==T&&((x=o.current)==null||x.call(o),i.current=T,o.current=ts.subscribe({sendData:Zo},T,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${T}`,params:{includeSessions:!0}},M=>{if(M.topic!=="daemon.metadata")return;const A=t.current.getIdes(),E=A.find(z=>z.id===T),F=Qn(M.status,{daemonId:T,existingDaemon:E,existingEntries:A,timestamp:M.timestamp});F.length>0&&t.current.injectEntries(F,{authoritativeDaemonIds:[T]}),M.userName&&a.current&&a.current(M.userName)}))}}catch(S){console.error("[Standalone WS] Parse error:",S)}},j.onclose=N=>{h.current&&(Et==null||Et.stopScreenshots(),Et&&Jt.setState(Et.daemonId,"disconnected"),d("disconnected"),u.current=null,g.current=`close:${N.code}${N.wasClean?":clean":":unclean"}`,jr("close",{code:N.code,reason:N.reason||"",wasClean:N.wasClean}),v())},j.onerror=N=>{b.current||!h.current||(g.current="error",jr("error",{message:N instanceof Event?"event":String(N),readyState:j.readyState}),console.warn("[Standalone WS] Error, will reconnect:",N))}}function v(){if(!h.current)return;clearTimeout(p.current);const j=m.current;console.log(`[Standalone WS] Reconnecting in ${j}ms...`),jr("schedule_reconnect",{reason:g.current,delayMs:j}),p.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,ZS),f()},j)}return f(),()=>{var j;h.current=!1,b.current=!0,(j=o.current)==null||j.call(o),o.current=null,i.current=null,clearTimeout(p.current),u.current&&(u.current.onerror=null,u.current.onclose=null,u.current.close(),u.current=null,Wt=null),Et&&(Et.stopScreenshots(),Jt.unregister(Et.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function aC({children:e}){const[t,r]=l.useState("disconnected"),[n,a]=l.useState(null);l.useEffect(()=>(Dr=(i,c)=>{r(i),c&&a(c)},()=>{Dr=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=tC(t),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d}},[t,n]);return s.jsx(Fh,{connectionOverrides:o,children:s.jsx(nC,{children:e})})}const _m="adhdev_standalone_font_preferences",Ts={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Aa=[{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"}],Wr=[{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"}],oC=new Set(Aa.map(e=>e.id)),iC=new Set(Wr.map(e=>e.id));function Zt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Kn("chat",t.chat),code:Kn("code",t.code),terminal:Kn("terminal",t.terminal)}}function Kn(e,t){const r=Ts[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"?oC:iC).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Un(e,t){var a;const r=Kn(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?Aa:Wr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function lC(e){const t=Zt(e),r=Un("chat",t.chat),n=Un("code",t.code),a=Un("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function ks(e,t=document.documentElement){const r=Zt(e),n=lC(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function ei(e){const t=Zt(e);try{localStorage.setItem(_m,JSON.stringify(t))}catch{}return t}function cC(){try{const e=localStorage.getItem(_m);if(e)return Zt(JSON.parse(e))}catch{}return Ts}function dC(){return ks(cC())}function kr(e,t){var n;const r=e==="chat"?Aa:Wr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const uC=[{id:"dashboard",path:"/dashboard",icon:s.jsx(kd,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(xs,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(er,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(ha,{}),label:"Settings"}];function pC({children:e}){const t=Kr(),r=si(),n=l.useMemo(()=>uC.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(Sd,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Cd,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(ay,{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 mC=[{icon:s.jsx(xs,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx($s,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Id,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(qt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(er,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Sd,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],hC=[{icon:s.jsx(af,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(kd,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Ur,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Qh,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Nd,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(tf,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],fC=[{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 xC(){return s.jsxs(Qr,{icon:s.jsx(Cd,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.9.82"]}),children:[s.jsx(dt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),s.jsx(dt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:mC.map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(dt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Xu.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Zu.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Qu.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(dt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:hC.map(e=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(dt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),s.jsx("tbody",{children:fC.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(ja,{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(ff,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function ko(e,t,r){return{...e,[t]:r}}function No({surface:e,title:t,description:r,value:n,options:a,onChange:o}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:i=>{const c=i.target.value;o(c==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:c})},children:a.map(i=>s.jsx("option",{value:i.id,children:i.label},i.id))}),n.preset==="custom"&&s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:i=>o({preset:"custom",customFamily:i.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:Un(e,n)})]})]})]})}function bC({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:d}){const u=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&s.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&s.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(No,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Aa,onChange:p=>o(ko(e,"chat",p))}),s.jsx(No,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Wr,onChange:p=>o(ko(e,"code",p))}),s.jsx(No,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Wr,onChange:p=>o(ko(e,"terminal",p))})]}),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: ",kr("chat",e.chat.preset)," · Code: ",kr("code",e.code.preset)," · Terminal: ",kr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",kr("chat",Ts.chat.preset)," / ",kr("code",Ts.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||!u,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||!u,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 gC(){const{ides:e}=ss(),t=e.find(B=>B.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=mt(),{userName:a}=ss(),[o,i]=l.useState(a||""),[c,d]=l.useState(null),[u,p]=l.useState(null),[m,h]=l.useState(Ts),[b,g]=l.useState(!1),[f,v]=l.useState(""),[j,y]=l.useState(""),[w,N]=l.useState("127.0.0.1"),[k,x]=l.useState(""),[S,C]=l.useState(""),[I,R]=l.useState(""),[L,T]=l.useState(""),[_,$]=l.useState(""),[X,M]=l.useState(!1),A=async()=>{const W=await(await Xt("/auth/session")).json();d(W)},E=async()=>{const W=await(await Xt("/api/v1/standalone/preferences")).json();p(W),N(W.standaloneBindHost);const ve=Zt(W.standaloneFontPreferences);h(ve),ks(ve),ei(ve)};l.useEffect(()=>{a!==void 0&&i(a)},[a]),l.useEffect(()=>{Promise.all([A(),E()]).catch(B=>{T(B instanceof Error?B.message:String(B))})},[]),l.useEffect(()=>{ks(m)},[m]);const F=B=>{const W=B.target.value.trim();t!=null&&t.id&&W!==a&&n(t.id,"set_user_name",{userName:W}).catch(console.error)},[z,D]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),K=B=>{D(B);try{localStorage.setItem("adhdev_sound",B?"1":"0")}catch{}},O=async()=>{v(""),y(""),g(!0);try{const B=Zt(m),W=await Xt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:B})}),ve=await W.json();if(!W.ok)throw new Error((ve==null?void 0:ve.error)||"Failed to save standalone font preferences");const we=Zt(ve.standaloneFontPreferences);p(ve),h(we),ks(we),ei(we),y("Standalone chat fonts saved for this self-hosted dashboard.")}catch(B){v(B instanceof Error?B.message:String(B))}finally{g(!1)}},q=()=>{const B=Zt(u==null?void 0:u.standaloneFontPreferences);v(""),y(""),h(B),ks(B)},ne=()=>{v(""),y(""),h(Ts),ks(Ts)},J=async()=>{T(""),$(""),M(!0);try{const B=await Xt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:w})}),W=await B.json();if(!B.ok)throw new Error((W==null?void 0:W.error)||"Failed to save standalone network preference");p(W),N(W.standaloneBindHost),$(W.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(B){T(B instanceof Error?B.message:String(B))}finally{M(!1)}},ye=async()=>{if(T(""),$(""),S.trim().length<4){T("Password must be at least 4 characters.");return}if(S!==I){T("New password and confirmation do not match.");return}M(!0);try{const B=await Xt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,newPassword:S})}),W=await B.json();if(!B.ok)throw new Error((W==null?void 0:W.error)||"Failed to save password");d(W),await E(),x(""),C(""),R(""),$(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Am()}catch(B){T(B instanceof Error?B.message:String(B))}finally{M(!1)}},oe=async()=>{T(""),$(""),M(!0);try{const B=await Xt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,clear:!0})}),W=await B.json();if(!B.ok)throw new Error((W==null?void 0:W.error)||"Failed to clear password");d(W),await E(),x(""),C(""),R(""),$("Standalone password disabled.")}catch(B){T(B instanceof Error?B.message:String(B))}finally{M(!1)}};return s.jsxs(Qr,{icon:s.jsx(ha,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(fs,{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(fs,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),s.jsx(dt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:"Version"}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.82"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(u==null?void 0:u.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:(u==null?void 0:u.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:c!=null&&c.hasPasswordAuth?"Password enabled":c!=null&&c.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(dt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:w==="127.0.0.1",onChange:()=>N("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:()=>N("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:()=>{J()},disabled:X,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:X?"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 ",(u==null?void 0:u.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(dt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:c!=null&&c.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),L&&s.jsx(fs,{variant:"error",children:L}),_&&s.jsx(fs,{variant:"success",children:_}),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:k,onChange:B=>x(B.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:S,onChange:B=>C(B.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:I,onChange:B=>R(B.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{ye()},disabled:X,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:X?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{oe()},disabled:X,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),s.jsx(dt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(B=>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 ${B.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:B.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:B.type})]},B.type))})}),s.jsx(dt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(hy,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(dt,{title:"Coordinator prompts",description:"User-level overrides for the mesh coordinator system prompt. Per-mesh overrides live in the Repo Mesh page.",children:s.jsx(gy,{daemonId:t==null?void 0:t.id})}),s.jsx(dt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(vy,{})]}),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(My,{})]}),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(bC,{value:m,savedValue:Zt(u==null?void 0:u.standaloneFontPreferences),saving:b,error:f,notice:j,onChange:h,onSave:()=>{O()},onResetToSaved:q,onResetToDefaults:ne})]}),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(_y,{})]})]})}),s.jsx(dt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(uy,{}),s.jsx(js,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(hf,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:z,onChange:K})]})}),s.jsx(dt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(Xh,{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:B=>i(B.target.value),onBlur:F,onKeyDown:B=>{B.key==="Enter"&&B.currentTarget.blur()}})]})})})]})}const yC=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],Ir="adhdev_onboarding_done",vC=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],wC={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function jC({onDone:e}){const[t,r]=l.useState([]),[n,a]=l.useState(new Set(yC)),[o,i]=l.useState(!0),[c,d]=l.useState(null),[u,p]=l.useState(!1),[m,h]=l.useState(null),[b,g]=l.useState("all");l.useEffect(()=>{let k=!1;const x=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${x}/providers?sort=popular&limit=100`).then(S=>{if(!S.ok)throw new Error(`HTTP ${S.status}`);return S.json()}).then(S=>{k||r(S.providers??[])}).catch(S=>{k||d(S instanceof Error?S.message:String(S))}).finally(()=>{k||i(!1)}),()=>{k=!0}},[]);const f=t.filter(k=>b==="all"||k.category===b),v=["cli","ide","extension","acp"].map(k=>({category:k,items:f.filter(x=>x.category===k)})).filter(k=>k.items.length>0),j=l.useCallback(k=>{a(x=>{const S=new Set(x);return S.has(k)?S.delete(k):S.add(k),S})},[]),y=l.useCallback(async()=>{if(n.size===0){localStorage.setItem(Ir,"1"),e();return}p(!0);const k=[];for(const x of n)try{const C=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:x})})).json().catch(()=>({}));k.push({type:x,ok:!!C.success,error:C.error})}catch(S){k.push({type:x,ok:!1,error:S instanceof Error?S.message:String(S)})}h(k),p(!1),k.every(x=>x.ok)&&localStorage.setItem(Ir,"1")},[n,e]),w=l.useCallback(()=>{localStorage.setItem(Ir,"1"),e()},[e]),N=l.useCallback(()=>{m&&m.every(k=>k.ok)?e():u||w()},[m,u,e,w]);return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60",onClick:N,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:k=>k.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:vC.map(k=>{const x=k.key==="all"?t.length:t.filter(S=>S.category===k.key).length;return x===0&&k.key!=="all"?null:s.jsxs("button",{onClick:()=>g(k.key),className:`machine-btn text-[10px] px-2 py-0.5 ${b===k.key?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:[k.label," ",s.jsxs("span",{className:"opacity-60",children:["(",x,")"]})]},k.key)})}),o&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"Loading registry…"}),!o&&c&&s.jsxs("div",{className:"rounded-xl border border-red-500/30 bg-red-500/5 px-3 py-2 text-[12px] text-red-400",children:["Failed to load registry: ",c]}),!o&&!c&&f.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"No providers in this category."}),!o&&!c&&f.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:v.map(k=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:wC[k.category]??k.category}),s.jsx("div",{className:"grid gap-1.5",children:k.items.map(x=>{var L,T;const S=n.has(x.type),C=m==null?void 0:m.find(_=>_.type===x.type),I=((L=x.manifest)==null?void 0:L.icon)??"📦",R=((T=x.manifest)==null?void 0:T.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${S?"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:S,onChange:()=>j(x.type),disabled:u,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:I}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:x.displayName}),R&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:R})]}),C&&s.jsx("span",{className:`text-[10px] font-semibold ${C.ok?"text-green-400":"text-red-400"}`,children:C.ok?"✓ installed":`✗ ${C.error??"failed"}`})]},x.type)})})]},k.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:u,className:"machine-btn text-[11px] px-3 py-1",children:"Skip"}),s.jsx("button",{onClick:()=>{m?(localStorage.setItem(Ir,"1"),e()):y()},disabled:u||!m&&n.size===0,className:"machine-btn text-[11px] px-3 py-1 bg-violet-500/15 border-violet-500/40 text-violet-400 hover:bg-violet-500/25",children:u?"Installing…":m?"Done":`Install ${n.size}`})]})]})]})})}function kC(){try{return localStorage.getItem(Ir)==="1"}catch{return!1}}ry();Cy();dC();const NC=gd({baseUrl:"",getToken:el});function SC({children:e}){const[t,r]=l.useState(null),[n,a]=l.useState(!0),[o,i]=l.useState(""),[c,d]=l.useState(""),[u,p]=l.useState(!1),m=async()=>{a(!0),d("");try{const g=await(await Xt("/auth/session")).json();r(g)}catch(b){d(b instanceof Error?b.message:String(b))}finally{a(!1)}};l.useEffect(()=>{m()},[]),l.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let b=!1;return(async()=>{try{const g=await Xt("/api/v1/standalone/preferences");if(!g.ok)return;const f=await g.json();if(b)return;const v=Zt(f.standaloneFontPreferences);ks(v),ei(v)}catch{}})(),()=>{b=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const h=async b=>{b.preventDefault(),p(!0),d("");try{const g=await Xt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),f=await g.json();if(!g.ok)throw new Error((f==null?void 0:f.error)||"Login failed");r(f),i(""),Am()}catch(g){d(g instanceof Error?g.message:String(g))}finally{p(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:h,children:[s.jsx("input",{type:"password",value:o,onChange:b=>i(b.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.jsx("button",{type:"submit",disabled:u||!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:u?"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 ud(){const{ides:e,initialLoaded:t}=ss();if(!t)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?s.jsx(Io,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Io,{to:"/dashboard",replace:!0})}function CC(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let r=!1;if(!kC())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(jC,{onDone:()=>t(!1)}):null}function IC(){const{ides:e}=ss(),t=l.useMemo(()=>{for(const u of e)if(u.activeInteractivePrompt)return u.instanceId??u.id;return null},[e]),{promptSession:r,hasActivePrompt:n,responseError:a,isSubmitting:o,submit:i,cancel:c,reopen:d}=op(t);return n?s.jsxs("div",{className:"relative",children:[!r&&s.jsx("button",{type:"button",onClick:d,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:"Awaiting your input ↑"}),s.jsx(zd,{promptSession:r,isSubmitting:o,error:a,onSubmit:i,onCancel:c})]}):null}function MC(){const e=l.useMemo(()=>({sendCommand:$r,sendData:Zo,sendPtyInput:Tm}),[]);return s.jsx(kh,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(zh,{client:NC,children:s.jsx(SC,{children:s.jsx(aC,{children:s.jsx(Kh,{value:e,children:s.jsxs(qh,{sendDaemonCommand:$r,children:[s.jsx(IC,{}),s.jsxs(pC,{children:[s.jsx(CC,{}),s.jsxs(Nh,{children:[s.jsx(us,{path:"/dashboard",element:s.jsx(Z1,{})}),s.jsx(us,{path:"/machine",element:s.jsx(ud,{})}),s.jsx(us,{path:"/machines/:id",element:s.jsx(lS,{})}),s.jsx(us,{path:"/machines",element:s.jsx(ud,{})}),s.jsx(us,{path:"/about",element:s.jsx(xC,{})}),s.jsx(us,{path:"/settings",element:s.jsx(gC,{})}),s.jsx(us,{path:"/mesh",element:s.jsx(YS,{children:s.jsx(VS,{})})}),s.jsx(us,{path:"*",element:s.jsx(Io,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}s0({connectionManager:Jt});Sh(document.getElementById("root")).render(s.jsx(MC,{}));
|