@adhdev/daemon-standalone 0.9.82-rc.321 → 0.9.82-rc.323
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 +45 -6
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/index-COSRbW4F.js +113 -0
- package/public/index.html +1 -1
- package/vendor/mcp-server/index.js +22 -1
- package/vendor/mcp-server/index.js.map +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 Fm=Object.defineProperty;var Om=(e,t,r)=>t in e?Fm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Qe=(e,t,r)=>Om(e,typeof t!="symbol"?t+"":t,r);import{r as l,j as s,M as ti,a as Hm,b as zm,c as Wm,R as St,d as Dr,t as Km,e as Um,u as Wr,D as Gm,f as Co,g as Io,E as Vm,i as qm,C as Ym,h as Jm,B as Xm,k as Qm,l as Zm,m as eh,H as cn,P as cs,n as th,o as sh,p as rh,q as nh,s as ah,v as oh,w as si,x as ih,y as lh,z as ch,A as dh,F as ds,N as Mo,G as uh}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 ph(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 qs=ph();function il(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 mh(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function ll(e){return Array.isArray(e)?[...e]:[]}function cd(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?ll(e.messages):i?[]:t.messages,activeModal:n?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...r?{messages:ll(e.messages)}:{},...n?{activeModal:e.activeModal??null}:{}}}function jr(e,t){const r=mh(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:cd(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 dd(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?jr(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 cl(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:cl(o)?String(o.text||""):"").join(r):cl(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Ys(e){return ri(e,{normalizeWhitespace:!0})}const ud=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}),pd=l.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function dl(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 md(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 hh(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=hh(Ys(t.content).slice(0,512));return[String(t.id||""),String(t._localId||""),String(t._turnKey||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),r].join(":")}function fh(e,t){if(!Array.isArray(e))return e;if(t!=null&&t.has(e))return{count:e.length,sharedRef:!0};let r=2166136261;for(const n of e){const a=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 Ao(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function To(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(Ao(e)&&Ao(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)To(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"&&To(n[i],a[i],r)}function Cr(e,t){return Array.isArray(e)?e.map(r=>Cr(r,t)):!e||typeof e!="object"?e:Ao(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?fh(a,t):Cr(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,Cr(n,t)]))}function xh(e,t){try{const r=new WeakSet;return To(e,t,r),JSON.stringify(Cr(e,r))===JSON.stringify(Cr(t,r))}catch{return!1}}function _o(e,t,r){return xh(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function hd(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function bh(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function ul(e,t,r,n){var c;const a=(c=t.chats)!=null&&c.length?t.chats:e.chats,o=dd(e.childSessions,t.childSessions,{preserveMissing:n}),i=cd(t.activeChat,e.activeChat);return md(e,t,{...e,...t,chats:a,childSessions:o,activeChat:i,_lastUpdate:r})}function gh(e,t,r){var a,o;const n={};t.status&&t.status!==e.status&&(n.status=t.status),t.cdpConnected!==void 0&&(n.cdpConnected=t.cdpConnected),t.childSessions!==void 0&&(n.childSessions=dd(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(n.chats=t.chats);for(const i of["title","workspace","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","activeInteractivePrompt","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])bh(n,t,i);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function yh(e,t,r,n){const a=gh(e,t,n),o=Object.keys(a).length>0?md(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return _o(e,o,r)}function vh(e){const t=new Set(e.map(o=>o.id)),r=new Set,n=new Set,a=new Set;for(const o of e){const i=hd(o);i&&r.add(i),i&&o.type!=="adhdev-daemon"&&n.add(i),i&&o.type==="adhdev-daemon"&&o._sessionListAuthoritative&&a.add(i)}return{incomingIds:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function wh(e,t,r,n,a,o){return!a.has(t)||!o.has(t)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function jh(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function kh(e,t,r){var m,u;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(h=>({...h,_lastUpdate:n}));const o=new Map;for(const h of t)o.set(h.id,h);const{incomingIds:i,incomingDaemonIds:c,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:p}=vh(e);for(const h of e){const b=o.get(h.id);if(!b){o.set(h.id,{...h,_lastUpdate:n});continue}const y=dl(h),f=dl(b),w=hd(h),j=!a.has(w);if(y>f){const k=ul(b,h,n,j);o.set(h.id,_o(b,k,n));continue}if(y<f){o.set(h.id,yh(b,h,n,j));continue}const g=h.timestamp||n,v=b._lastUpdate||b.timestamp||0;if(g>=v){const k=ul(b,h,n,j);o.set(h.id,_o(b,k,n));continue}(m=h.chats)!=null&&m.length&&!((u=b.chats)!=null&&u.length)&&o.set(h.id,{...b,chats:h.chats})}for(const[h,b]of o){const y=b.daemonId||h.split(":")[0];if(!c.has(y))continue;if(a.has(y)&&p.has(y)&&!i.has(h)){o.delete(h);continue}const f=n-(b._lastUpdate||b.timestamp||0);wh(b,y,f,i,a,d)&&o.delete(h)}for(const[h,b]of o){const y=b.daemonId||h.split(":")[0];if(jh(b,y,c,d,o))continue;n-(b._lastUpdate||b.timestamp||0)>3e5&&b.status!=="online"&&o.delete(h)}return Array.from(o.values())}function Nh(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 Sh({children:e,connectionOverrides:t}){const[r,n]=l.useState([]),[a,o]=l.useState(!1),[i,c]=l.useState([]),[d,p]=l.useState(void 0),m=l.useRef(r);l.useEffect(()=>{m.current=r},[r]);const u=l.useCallback((j,g)=>{n(v=>{let k=!1;const N=v.map(x=>x.id!==j||x.chats===g?x:(k=!0,{...x,chats:g}));return k?N:v})},[]),h=l.useCallback((j,g)=>{n(v=>{const k=v.length===0?j:kh(j,v,g),N=!Nh(v,k);return N&&qs.record({kind:"dashboard.entries_applied",payload:{incoming:il(j),next:il(k)}}),N?k:v})},[]),b=l.useCallback(()=>o(!0),[]),y=l.useMemo(()=>({injectEntries:h,markLoaded:b,getIdes:()=>m.current}),[h,b]),f=t,w=l.useMemo(()=>({ides:r,updateRouteChats:u,initialLoaded:a,toasts:i,setToasts:c,wsStatus:(f==null?void 0:f.wsStatus)??"connected",isConnected:(f==null?void 0:f.isConnected)??!0,connectionStates:(f==null?void 0:f.connectionStates)??{},connectionTransports:(f==null?void 0:f.connectionTransports)??{},showReconnected:(f==null?void 0:f.showReconnected)??!1,retryConnection:f==null?void 0:f.retryConnection,retryServerConnection:f==null?void 0:f.retryServerConnection,connectionLoginUrl:f==null?void 0:f.connectionLoginUrl,isP2PActive:(f==null?void 0:f.isP2PActive)??!1,p2pStates:(f==null?void 0:f.p2pStates)??{},userRole:f==null?void 0:f.userRole,connectionRetryStatuses:f==null?void 0:f.connectionRetryStatuses,userName:d,setUserName:p}),[r,u,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(pd.Provider,{value:y,children:s.jsx(ud.Provider,{value:w,children:e})})}function ss(){return l.useContext(ud)}function $r(){return l.useContext(pd)}function fd(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(c){return c.startsWith("http")?c:`${t}${c.startsWith("/")?"":"/"}${c}`}function o(c){const d=r==null?void 0:r(),p=a(c),m=c.startsWith("http")?new URL(p):new URL(p,typeof window<"u"?window.location.origin:"http://localhost");return d&&m.searchParams.set("token",d),!c.startsWith("http")&&!t?`${m.pathname}${m.search}${m.hash}`:m.toString()}async function i(c,d={}){const p={"Content-Type":"application/json",...d.headers||{}},m=r==null?void 0:r();m&&(p.Authorization=`Bearer ${m}`);const u=a(c),h=new AbortController,b=setTimeout(()=>h.abort(),15e3);try{const y=await fetch(u,{...d,headers:p,signal:h.signal});if(y.status===401)throw n==null||n(),new Error("Unauthorized");if(!y.ok){const f=await y.json().catch(()=>({error:y.statusText}));throw new Error(f.error||`API Error: ${y.status}`)}return y.json()}finally{clearTimeout(b)}}return{getDaemons:()=>i("/api/v1/daemons"),getDaemonStatus:c=>i(`/api/v1/daemons/${c}/status`),sendCommand:(c,d,p={})=>i(`/api/v1/daemons/${c}/command`,{method:"POST",body:JSON.stringify({type:d,payload:p})}),execTerminal:(c,d,p)=>i(`/api/v1/daemons/${c}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:p})}),sendAgentMessage:(c,d,p)=>i(`/api/v1/shortcuts/${c}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:p})}),getAgentStatus:c=>i(`/api/v1/shortcuts/${c}/status`),approveAgent:(c,d,p)=>i(`/api/v1/shortcuts/${c}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:p?"approve":"reject"})}),getMuxState:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/state`),getMuxSocketInfo:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/socket-info`),controlMux:(c,d,p={})=>i(`/api/v1/mux/${encodeURIComponent(c)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:p})}),getMuxEventsUrl:c=>o(`/api/v1/mux/${encodeURIComponent(c)}/events`),getRuntimeEventsUrl:c=>o(`/api/v1/runtime/${encodeURIComponent(c)}/events`),request:i}}const Ch=fd({baseUrl:"http://localhost:3847"}),Ih=l.createContext(Ch);function Mh({client:e,children:t}){return s.jsx(Ih.Provider,{value:e,children:t})}const Ah={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},xd=l.createContext(Ah);function Th({value:e,children:t}){return s.jsx(xd.Provider,{value:e,children:t})}function mt(){return l.useContext(xd)}function bd(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function _h(e){const t=bd(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 Rh(e){const[t,r]=l.useState(null),n=l.useCallback(async(i,c)=>{const d=u=>e(i,"launch_cli",{...c,...u}),p=await d({}),m=_h(p);return m?new Promise(u=>{r({providerType:m.providerType||String(c.cliType??"?"),sourceName:m.sourceName,description:m.description,retry:()=>d({confirmExternalUntrusted:!0}),resolve:h=>{h.cancelled?u({success:!1,error:"user_cancelled_untrusted_launch"}):u(h.response)}})}):p},[e]),a=l.useCallback(async()=>{const i=t;if(i){r(null);try{const c=await i.retry(),d=bd(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 Lh({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 gd=l.createContext(null);function Ph({sendDaemonCommand:e,children:t}){const r=Rh(e),n=l.useMemo(()=>({launchCli:r.launchCli}),[r.launchCli]);return s.jsxs(gd.Provider,{value:n,children:[t,r.pending&&s.jsx(Lh,{providerType:r.pending.providerType,sourceName:r.pending.sourceName,description:r.pending.description,onConfirm:r.confirm,onCancel:r.cancel})]})}function ma(){const e=l.useContext(gd);return e||{launchCli:async()=>{throw new Error("useLaunchCli must be used inside <LaunchCliProvider>")}}}function Dh(e){let t=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)t^=n.charCodeAt(a),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function $h(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function yd(e){return e?Dh([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),$h(e.content)]):""}const We={size:18};function vd({size:e=We.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=We.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 fs({size:e=We.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 wd({size:e=We.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 Eh({size:e=We.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 Bh({size:e=We.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 jd({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),s.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),s.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),s.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function Fh({size:e=We.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=We.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 kd({size:e=We.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 Oh({size:e=We.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 Hh({size:e=We.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 Ps({size:e=We.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=We.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=We.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 Js({size:e=We.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=We.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 Xs({size:e=We.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 Qs({size:e=We.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=We.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 zh({size:e=We.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 Nd({size:e=We.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=We.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 Sd({size:e=We.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 Wh({size:e=We.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=We.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 Kh({size:e=We.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 Cd({size:e=We.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 Id({size:e=We.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=We.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 Uh({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),s.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),s.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),s.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function Gh({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),s.jsx("path",{d:"M12 2v6"}),s.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Vh({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function qh({size:e=We.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 Kr({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function Yh({size:e=We.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 Jh({size:e=We.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 Xh({size:e=We.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 Md({size:e=We.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),s.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Qh({size:e=We.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function Zh({size:e=We.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 ef({size:e=We.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 tf({size:e=We.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 sf({size:e=We.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 rf({size:e=We.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 nf({size:e=We.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 af({size:e=We.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 Ad="adhdev_chat_activity_visible",pl=new Set(["hidden","debug","internal"]),ml=new Set(["visible","user","chat"]),of=new Set(["debug","trace","internal"]),lf=new Set(["tool_call","terminal_command","runtime_activity"]),cf=new Set(["runtime_status","provider_chrome","control"]),df=new Set(["thought","tool","terminal"]);function Td(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Os(e){return typeof e=="string"?e.trim().toLowerCase():""}function _a(e,t,r){return e[r]??(t==null?void 0:t[r])}function hl(e,t,r){const n=e;return r.some(a=>n[a]===!0||(t==null?void 0:t[a])===!0)}function uf(e,t){const r=Os(e.kind);return r||(t==="tool"?"tool":"standard")}function Ra(e,t,r){const n=Td(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 pf(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=Td(e),r=Os(e.role),n=uf(e,r),a=Os(_a(e,t,"visibility")),o=Os(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),i=Os(_a(e,t,"audience")),c=Os(_a(e,t,"source")),d=pl.has(a)||pl.has(o)||of.has(i)||hl(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),p=ml.has(a)||ml.has(o)||i==="chat"||hl(e,t,["userFacing"]),m=df.has(n)||lf.has(c);if(d)return{surface:m?"activity":"internal",isUserFacing:!1,isActivityFacing:m,isInternal:!m,role:r,kind:n,label:Ra(e,n,c)};if(p)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:Ra(e,n,c)};if((r==="system"||n==="system")&&pf(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:"Chat"};if(cf.has(c)||r==="system"||n==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:r,kind:n,label:"Internal"};if(m)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:r,kind:n,label:Ra(e,n,c)};const u=(r==="user"||r==="human"||r==="assistant")&&(n==="standard"||n==="");return{surface:u?"chat":"internal",isUserFacing:u,isActivityFacing:!1,isInternal:!u,role:r,kind:n,label:u?"Chat":"Internal"}}function mf(e){return(Array.isArray(e)?e:[]).filter(t=>li(t).isUserFacing)}function _d(e){return(Array.isArray(e)?e:[]).filter(t=>li(t).isActivityFacing)}function hf(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 fl(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(Ad))==="1"}catch{return!1}}const Rd=[Hm,{singleTilde:!1}],Ld=[Rd,zm,Wm],ff=[Rd],ci=200,xf=80,xl=650,ir=new Map;function Gn(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function bf(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}:${yd(n)}`}function gf(e,t,r,n){return e||!t?!1:Gn(r,n)}function yf({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=xf,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 vf(e){return yf({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function kr(e,t=ci){return!!e&&e.fromBottom>=t}function wf(e,t){return Gn(e,t)?!kr(e):!0}function jf({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function kf({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function La(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function Pd(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Nf(e,t,r){return Number(e.receivedAt||r[Vn(e,t)]||0)||0}function Dd(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Sf(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function lr(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 Pa(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 dn(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 bl(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Dd(e)?s.jsx(ti,{remarkPlugins:Ld,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}const Cf=l.memo(function({content:t,renderAsPreformatted:r,renderAsMarkdown:n}){return r?s.jsx("pre",{className:"chat-preformatted",children:t}):n?s.jsx(ti,{remarkPlugins:Ld,children:t}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:t})});function cr({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:bl(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=Pa(r),o=r.alt||r.description||lr(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:dn("Image",o,r.mimeType)},`image-fallback-${n}`)}if(r.type==="audio"){const a=Pa(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:dn("Audio",lr(r.uri,"audio"),r.transcript||r.mimeType)},`audio-fallback-${n}`)}if(r.type==="video"){const a=Pa(r),o=r.title||r.name||r.alt||lr(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"}):dn("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||lr(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}):dn("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=lr(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}),bl(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 If=l.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(ti,{remarkPlugins:ff,children:t.text}),s.jsx("span",{className:"action-time",children:Pd(t.timestamp)})]})},(e,t)=>e.log===t.log);function gl(e){const t=e.meta;return[yd(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 Mf=l.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:i,onToggleTextExpanded:c}){var S,I,P;const d=(t.role||"").toLowerCase(),p=d==="user"||d==="human",m=t.kind||(d==="tool"?"tool":"standard"),u=li(t),h=Sf(t.content)?t.content:null,b=!!(h!=null&&h.some(L=>L.type!=="text")),y=ri(t.content,{joiner:`
|
|
6
|
+
`});if(u.isActivityFacing&&m!=="thought"&&m!=="tool"&&m!=="terminal"){const L=u.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(cr,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:y})]})}if(m==="thought"){const L=typeof((S=t.meta)==null?void 0:S.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":u.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(Vh,{size:13}),s.jsx("span",{children:L})]}),s.jsx("div",{className:"chat-msg-body",children:y})]})}if(m==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":u.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(cr,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:y})]});if(m==="terminal"){const L=(I=t.meta)!=null&&I.isRunning?"⏳":"✅",A=typeof((P=t.meta)==null?void 0:P.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":u.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:L}),s.jsx("span",{children:A})]}),b&&h?s.jsx("div",{className:"chat-msg-body",children:s.jsx(cr,{parts:h,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:y})]})}if(m==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:b&&h?s.jsx(cr,{parts:h,renderAsPreformatted:!1}):y.slice(0,100)});const f=t.meta,j=(typeof(f==null?void 0:f.renderMode)=="string"?f.renderMode.trim():"")==="preformatted",g=y,v=!1,k=g,N=j,x=!p&&!N&&Dd(k),C=["chat-message-row",p?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:C,children:(g||b||p)&&s.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${g||b?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:p?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:Pd(r)})]}),(g||b)&&s.jsx("div",{className:"chat-markdown",children:b&&h?s.jsx(cr,{parts:h,renderAsPreformatted:N}):s.jsx(Cf,{content:k,renderAsPreformatted:N,renderAsMarkdown:x})}),v]})})},(e,t)=>(e.message===t.message||gl(e.message)===gl(t.message))&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),Af=l.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:o=!1,isWorking:i=!1,contextKey:c="",receivedAtMap:d={},lastMessageHash:p,showActivityMessages:m=!1,emptyState:u,onLoadMore:h,isLoadingMore:b,hasMoreHistory:y,hiddenLiveCount:f=0,loadError:w,scrollToBottomRequestNonce:j,isVisible:g=!0},v){const k=l.useRef(null),N=l.useRef(null),x=l.useRef(null),C=l.useRef(0),S=l.useRef(""),I=l.useRef(""),P=l.useRef(!1),L=l.useRef(null),A=l.useRef(!1),R=l.useRef(null),$=l.useRef(!1),[X,T]=l.useState(new Set),[M,_]=l.useState({showTop:!1,showBottom:!1}),B=l.useRef(!1),E=l.useRef(!1),F=l.useRef(g),K=l.useRef(g),z=l.useRef(null);K.current=g;const ne=()=>{const ae=k.current;return ae?ae.scrollHeight-ae.scrollTop-ae.clientHeight<ci:!0},q=l.useCallback(()=>{const ae=k.current,D=ae?vf(ae):{showTop:!1,showBottom:!1};_(oe=>oe.showTop===D.showTop&&oe.showBottom===D.showBottom?oe:D)},[]),J=l.useCallback((ae="auto")=>{var oe;const D=k.current;D&&(D.scrollTo({top:D.scrollHeight,behavior:ae}),(oe=D.ownerDocument.defaultView)==null||oe.requestAnimationFrame(()=>q()))},[q]),xe=l.useCallback((ae="auto")=>{var oe;const D=k.current;D&&(D.scrollTo({top:0,behavior:ae}),(oe=D.ownerDocument.defaultView)==null||oe.requestAnimationFrame(()=>q()))},[q]),ue=l.useCallback(()=>{var pe;const ae=k.current,D=(pe=window.getSelection)==null?void 0:pe.call(window);if(!ae||!D||D.rangeCount===0||D.isCollapsed){$.current=!1;return}const oe=D.anchorNode,ge=D.focusNode;$.current=!!(oe&&ge&&ae.contains(oe)&&ae.contains(ge))},[]),O=l.useMemo(()=>{const ae=mf(t),D=_d(t);return hf(ae,D,m)},[t,m]),H=O.length===t.length?p:void 0,ve=bf(O,H),we=l.useCallback(()=>{const ae=k.current;if(!ae||!c||!K.current)return;const D={top:ae.scrollTop,fromBottom:Math.max(0,ae.scrollHeight-ae.scrollTop-ae.clientHeight),messageFingerprint:ve};z.current={contextKey:c,snapshot:D},ir.set(c,D)},[c,ve]),be=l.useCallback((ae="auto")=>{L.current!=null&&cancelAnimationFrame(L.current),L.current=requestAnimationFrame(()=>{L.current=null,J(ae)})},[J]),Ne=l.useCallback(()=>{B.current=!1,A.current=!0,E.current=!0,R.current!=null&&window.clearTimeout(R.current),R.current=window.setTimeout(()=>{A.current=!1,R.current=null},xl)},[]);l.useEffect(()=>{const ae=!P.current,D=I.current!==c;if(I.current=c,ae||D){P.current=!0;const ge=c?ir.get(c):null,pe=!!ge&&Gn(ge,ve);B.current=pe?kr(ge):!1,A.current=wf(ge,ve),$.current||(pe?requestAnimationFrame(()=>{const te=k.current;te&&(La(te,ge),B.current=kr(ge),q(),E.current=!0)}):be("auto")),C.current=O.length,S.current=ve;return}O.length>C.current;const oe=ve!==S.current;jf({hasSelection:$.current,userScrolledUp:B.current,hasChatContentChanged:oe})&&be("auto"),C.current=O.length,S.current=ve},[ve,c,O.length,be,q]),l.useEffect(()=>{j&&(Ne(),$.current||be("auto"))},[Ne,be,j]),l.useEffect(()=>{const ae=F.current;ae&&!g&&we(),K.current=g,F.current=g;const D=c?ir.get(c):null;if(gf(ae,g,D,ve)){if(!D)return;B.current=kr(D),A.current=!1,$.current||requestAnimationFrame(()=>{const oe=k.current;oe&&(La(oe,D),q())});return}},[g,c,ve,Ne,we,be,q]),l.useEffect(()=>()=>{const ae=z.current;ae&&ir.set(ae.contextKey,ae.snapshot),L.current!=null&&cancelAnimationFrame(L.current),R.current!=null&&window.clearTimeout(R.current)},[]),l.useEffect(()=>{const ae=N.current,D=k.current;if(!ae||!D)return;const oe=()=>{R.current!=null&&window.clearTimeout(R.current),R.current=window.setTimeout(()=>{A.current=!1,R.current=null},xl)},ge=new ResizeObserver(()=>{q();const pe=A.current;kf({hasSelection:$.current,userScrolledUp:B.current,contextAutoScrollActive:pe})&&(be("auto"),pe&&oe())});return ge.observe(ae),D!==ae&&ge.observe(D),()=>{ge.disconnect(),R.current!=null&&(window.clearTimeout(R.current),R.current=null)}},[be,c,q]),l.useImperativeHandle(v,()=>({scrollToBottom:(ae="smooth")=>{J(ae)}}),[J]),l.useEffect(()=>{const ae=k.current;if(!ae)return;let D;const oe=()=>{we(),clearTimeout(D),D=setTimeout(()=>{B.current=!ne(),q()},50)};return ae.addEventListener("scroll",oe,{passive:!0}),()=>{ae.removeEventListener("scroll",oe),clearTimeout(D)}},[we,q]),l.useEffect(()=>(document.addEventListener("selectionchange",ue),()=>document.removeEventListener("selectionchange",ue)),[ue]);const re=l.useRef(0),je=l.useRef(!1);l.useEffect(()=>{const ae=k.current;if(!ae||!je.current||re.current===0)return;const D=ae.scrollHeight-re.current;D>0&&(ae.scrollTop=D),q(),we(),re.current=0,je.current=!1},[O.length,we,q]),l.useEffect(()=>{if(E.current||!c)return;const ae=ir.get(c),D=k.current;if(!(!ae||!D)){if(!Gn(ae,ve)){J("auto"),E.current=!0;return}La(D,ae),B.current=kr(ae),q(),E.current=!0}},[c,ve,O.length,J,q]);const ce=()=>{const ae=k.current;ae&&(re.current=ae.scrollHeight),je.current=!0,h==null||h()},U=()=>{B.current=!0,xe("smooth"),we()},W=()=>{Ne(),J("smooth"),we()},Y=l.useMemo(()=>{const ae=O.map((pe,te)=>({type:"message",data:pe,index:te,ts:Nf(pe,te,d)}));if(!r||r.length===0)return ae;const D=[...r].sort((pe,te)=>pe.timestamp-te.timestamp).map((pe,te)=>({type:"action",data:pe,index:te,ts:pe.timestamp})),oe=[];let ge=0;for(const pe of ae){for(;ge<D.length&&pe.ts>0&&D[ge].ts<pe.ts;)oe.push(D[ge++]);oe.push(pe)}for(;ge<D.length;)oe.push(D[ge++]);return oe},[O,r,d]),se=f>0||!!y,ie=f>0?`↑ Show ${Math.min(f,80)} earlier messages${f>80?` (${f} hidden)`:""}`:w?`↻ ${w}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:k,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:N,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:ce,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${w&&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:ie})}),Y.length===0&&!se&&(u||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),Y.map(ae=>{if(ae.type==="action"){const _e=ae.data;return s.jsx(If,{log:_e},`action-${ae.index}`)}const D=ae.data,oe=ae.index,ge=Vn(D,oe),pe=D.receivedAt||d[ge],te=`${c}-${ge}`,Me=X.has(te);return s.jsx(Mf,{message:D,receivedAt:pe,agentName:n,userName:a,isCliMode:o,isTextExpanded:Me,onToggleTextExpanded:()=>T(_e=>{const Ce=new Set(_e);return Me?Ce.delete(te):Ce.add(te),Ce})},`msg-${ge}`)}),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})]})}),(M.showTop||M.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[M.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:U,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),M.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:W,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Tf=l.memo(Af,(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),_f="modulepreload",Rf=function(e){return"/"+e},yl={},Lf=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=Rf(d),d in yl)return;yl[d]=!0;const p=d.endsWith(".css"),m=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${m}`))return;const u=document.createElement("link");if(u.rel=p?"stylesheet":_f,p||(u.as="script"),u.crossOrigin="",u.href=d,c&&u.setAttribute("nonce",c),document.head.appendChild(u),p)return new Promise((h,b)=>{u.addEventListener("load",h),u.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 vl=!1;const $d=l.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:o="measured"},i)=>{const c=l.useRef(null),[d,p]=l.useState(null),m=l.useRef([]),u=l.useRef(!1),h=l.useRef(!1),b=l.useRef(!1),y=l.useRef(!1),f=()=>{const w=c.current;if(w){u.current&&(w.clear(),u.current=!1);for(const j of m.current)w.write(j.data,j.onProcessed);m.current=[],h.current&&(w.fit(),h.current=!1),b.current&&(w.bumpResize(),b.current=!1),y.current&&(w.scrollToTop(),y.current=!1)}};return l.useImperativeHandle(i,()=>({write:(w,j)=>{c.current?c.current.write(w,j):m.current.push({data:w,onProcessed:j})},clear:()=>{c.current?c.current.clear():(m.current=[],u.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(m.current=[],u.current=!0)},resize:(w,j)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(w,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():y.current=!0},getSelection:()=>{var w,j;return((j=(w=c.current)==null?void 0:w.getSelection)==null?void 0:j.call(w))||""},getVisibleText:()=>{var w,j;return((j=(w=c.current)==null?void 0:w.getVisibleText)==null?void 0:j.call(w))||""}}),[]),l.useEffect(()=>{d&&f()},[d]),l.useEffect(()=>{let w=!1;return Lf(()=>import("./terminal-DsCRNxW_.js"),__vite__mapDeps([0,1,2])).then(j=>{vl||(vl=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),w||p(()=>j.GhosttyTerminalView)}).catch(j=>{console.error("[CliTerminal] failed to load terminal renderer",j)}),()=>{w=!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"}})});$d.displayName="CliTerminal";function un({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 wl({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 Pf({cursorPos:e,viewportRef:t,imgRef:r}){var g;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(g=t.current)==null?void 0:g.getBoundingClientRect();if(!o)return null;const i=n.naturalWidth||a.width,c=n.naturalHeight||a.height,d=i/c,p=a.width/a.height;let m,u,h,b;d>p?(m=a.width,u=a.width/d,h=0,b=(a.height-u)/2):(u=a.height,m=a.height*d,h=(a.width-m)/2,b=0);const y=a.left-o.left+h+m*e.nx,f=a.top-o.top+b+u*e.ny,w=Math.max(8,Math.min(o.width-8,y)),j=Math.max(8,Math.min(o.height-8,f));return s.jsxs("div",{style:{position:"absolute",left:w-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 Df({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:i,setImeText:c,handleImeSubmit:d,isConnActive:p,zoom:m,isMobile:u,mobileFillZoom:h,onZoomOut:b,onZoomReset:y,onZoomIn:f,transportType:w,screenshotUsage:j,lastActionStatus:g}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:v=>v.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[s.jsxs("div",{onClick:t,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{n(v=>!v),o(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&s.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:s.jsx("input",{type:"text",placeholder:"Type & Enter...",value:i,autoFocus:!0,onTouchStart:v=>v.stopPropagation(),onChange:v=>c(v.target.value),onKeyDown:v=>{d(v)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{o(v=>!v),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:p?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:p?"#22c55e":"#eab308",boxShadow:p?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:p?"#22c55e":"#eab308"},children:p?"Connected":"WS"})]}),m>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(m*100),"%"]}),w==="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"}),w==="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`}),g&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:g})]})]}),a&&s.jsxs("div",{onTouchStart:v=>v.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",m<=(u?h:1)+.01?u?"FILL":"FIT":`${Math.round(m*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:v=>{v.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:v=>{v.stopPropagation(),y()},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:u?"FILL":"FIT"}),s.jsx("button",{onClick:v=>{v.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 $f({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 Ef(){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 jl(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 Ur(e,t){const r=l.useRef(null),n=l.useRef(0);l.useEffect(()=>{if(!Ef())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,jl(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,jl(t[i])]))}),r.current=t})}function Bf({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:i,panXRef:c,panYRef:d,setPanX:p,setPanY:m,setZoom:u,lastWheelTimeRef:h,onAction:b,setLastActionStatus:y,spawnRippleFromNormalized:f,clampPan:w,isMobile:j,mobileFillZoom:g}){const[v,k]=l.useState(null),N=l.useRef(null),x=l.useRef(null),C=l.useRef(null),S=l.useRef(!1),I=l.useRef(null),P=l.useRef(0),L=l.useRef(null),A=l.useRef(1),R=l.useRef({x:0,y:0}),$=l.useRef(!1),X=l.useRef(n),T=l.useRef(b),M=30,_=550,B=18,E=60,F=400,K=12,z=()=>{if(N.current)return;const J={nx:.5,ny:.5};N.current=J,k(J)};return l.useEffect(()=>{X.current=n,n==="mouse"&&z()},[n]),l.useEffect(()=>{T.current=b},[b]),l.useEffect(()=>{const J=e.current;if(!J)return;const xe=be=>{if(!r.current)return null;const Ne=r.current.getBoundingClientRect();return!Ne.width||!Ne.height?null:{nx:Math.max(0,Math.min(1,(be.clientX-Ne.left)/Ne.width)),ny:Math.max(0,Math.min(1,(be.clientY-Ne.top)/Ne.height))}},ue=(be,Ne)=>{if(!r.current)return{dnx:0,dny:0};const re=r.current,je=re.getBoundingClientRect(),ce=re.naturalWidth||je.width,U=re.naturalHeight||je.height,W=ce/U,Y=je.width/je.height;let se,ie;return W>Y?(se=je.width,ie=je.width/W):(ie=je.height,se=je.height*W),{dnx:be/se,dny:Ne/ie}},O=(be,Ne,re)=>{if(re<=1.05)return;const je=-(be-.5)*100,ce=-(Ne-.5)*100,U=w(je,ce,re);(Math.abs(U.x-c.current)>.1||Math.abs(U.y-d.current)>.1)&&(p(U.x),m(U.y),c.current=U.x,d.current=U.y)},H=be=>{const Ne=t.current;if(Ne&&be.target instanceof Node&&Ne.contains(be.target))be.preventDefault();else return;if(be.touches.length===1){const re=be.touches[0];x.current={x:re.clientX,y:re.clientY,time:Date.now()},C.current={x:re.clientX,y:re.clientY},$.current||(S.current=!1),I.current=setTimeout(()=>{if(!S.current&&!$.current)if(S.current=!0,X.current==="mouse"){const je=N.current||{nx:.5,ny:.5};y("Right Click"),f(je.nx,je.ny,"right"),T.current("input_click",{...je,button:"right"}).catch(()=>{})}else{const je=xe(re);je&&(y("Right Click"),f(je.nx,je.ny,"right"),T.current("input_click",{...je,button:"right"}).catch(()=>{}))}},500);return}if(be.touches.length===2){I.current&&clearTimeout(I.current),S.current=!0,$.current=!0;const re=be.touches[1].clientX-be.touches[0].clientX,je=be.touches[1].clientY-be.touches[0].clientY;L.current=Math.sqrt(re*re+je*je),A.current=i.current,R.current={x:(be.touches[0].clientX+be.touches[1].clientX)/2,y:(be.touches[0].clientY+be.touches[1].clientY)/2}}},ve=be=>{const Ne=t.current;if(Ne&&be.target instanceof Node&&Ne.contains(be.target)&&be.preventDefault(),be.touches.length===1&&C.current){const re=be.touches[0],je=re.clientX-C.current.x,ce=re.clientY-C.current.y;if(!S.current&&x.current){const U=re.clientX-x.current.x,W=re.clientY-x.current.y;Math.sqrt(U*U+W*W)>8&&(S.current=!0,I.current&&clearTimeout(I.current))}if(S.current)if(X.current==="mouse"){const U=ue(je,ce),W=N.current||{nx:.5,ny:.5},Y=Math.max(0,Math.min(1,W.nx+U.dnx)),se=Math.max(0,Math.min(1,W.ny+U.dny));N.current={nx:Y,ny:se},k({nx:Y,ny:se}),y(`Cursor: ${Math.round(Y*100)}%, ${Math.round(se*100)}%`),O(Y,se,i.current);const ie=Date.now();ie-h.current>=30&&(h.current=ie,T.current("input_mouseMoved",{nx:Y,ny:se}).catch(()=>{}))}else if(i.current>1){const U=t.current;if(U){const W=U.clientWidth,Y=U.clientHeight,se=c.current+je/W*100,ie=d.current+ce/Y*100,ae=w(se,ie,i.current);p(ae.x),m(ae.y),c.current=ae.x,d.current=ae.y}}else{const U=xe(re);if(U){const W=Date.now();W-h.current>=40&&(h.current=W,y("Scroll"),T.current("input_wheel",{nx:U.nx,ny:U.ny,deltaX:Math.round(-je*2.5),deltaY:Math.round(-ce*2.5)}).catch(()=>{}))}}C.current={x:re.clientX,y:re.clientY};return}if(be.touches.length===2&&L.current!==null){const re=be.touches[1].clientX-be.touches[0].clientX,je=be.touches[1].clientY-be.touches[0].clientY,U=Math.sqrt(re*re+je*je)/L.current,W=(be.touches[0].clientX+be.touches[1].clientX)/2,Y=(be.touches[0].clientY+be.touches[1].clientY)/2,se=W-R.current.x,ie=Y-R.current.y,ae=Math.abs(U-1)>.03;if(X.current==="mouse"){if(ae){const D=Math.max(o,Math.min(5,A.current*U));u(D),i.current=D}else if(Math.abs(se)>2||Math.abs(ie)>2){const D=N.current||{nx:.5,ny:.5},oe=Date.now();oe-h.current>=30&&(h.current=oe,y("Scroll"),T.current("input_wheel",{nx:D.nx,ny:D.ny,deltaX:Math.round(-se*3),deltaY:Math.round(-ie*3)}).catch(()=>{}))}}else{const D=Math.max(o,Math.min(5,A.current*U));u(D),i.current=D;const oe=t.current;if(oe&&D>1){const ge=oe.clientWidth,pe=oe.clientHeight,te=c.current+se/ge*100,Me=d.current+ie/pe*100,_e=w(te,Me,D);p(_e.x),m(_e.y),c.current=_e.x,d.current=_e.y}}R.current={x:W,y:Y}}},we=be=>{var Ne;if(I.current&&clearTimeout(I.current),L.current=null,be.touches.length===1&&$.current){const re=be.touches[0];x.current={x:re.clientX,y:re.clientY,time:Date.now()},C.current={x:re.clientX,y:re.clientY},S.current=!0;return}if(be.touches.length===0){if($.current){$.current=!1,S.current=!1;return}if(be.changedTouches.length===1){const re=be.changedTouches[0],je=Date.now(),ce=je-(((Ne=x.current)==null?void 0:Ne.time)||0),U=x.current?re.clientX-x.current.x:0,W=x.current?re.clientY-x.current.y:0,Y=Math.sqrt(U*U+W*W);if(X.current==="mouse"){if(ce<M||ce>_||Y>B){S.current=!1;return}const se=N.current||xe(re);se&&(y(`Click: ${Math.round(se.nx*100)}%, ${Math.round(se.ny*100)}%`),f(se.nx,se.ny,"left"),T.current("input_click",{...se}).catch(()=>{}))}else{if(S.current){S.current=!1;return}if(ce<E||ce>F||Y>K){S.current=!1;return}const se=xe(re);if(!se)return;je-P.current<300?(y("Double tap"),f(se.nx,se.ny,"double"),T.current("input_click",{...se,clickCount:2}).catch(()=>{}),P.current=0):(y(`Tap: ${Math.round(se.nx*100)}%, ${Math.round(se.ny*100)}%`),f(se.nx,se.ny,"left"),T.current("input_click",{...se}).catch(()=>{}),P.current=je)}}S.current=!1}};return J.addEventListener("touchstart",H,{passive:!1}),J.addEventListener("touchmove",ve,{passive:!1}),J.addEventListener("touchend",we,{passive:!1}),()=>{J.removeEventListener("touchstart",H),J.removeEventListener("touchmove",ve),J.removeEventListener("touchend",we),I.current&&clearTimeout(I.current)}},[e,t,r,o,i,c,d,p,m,u,h,y,f,w]),{cursorPos:v,cursorPosRef:N,handleToggleInputMode:()=>{a(J=>{const xe=J==="touch"?"mouse":"touch";return xe==="mouse"&&z(),xe})},handleZoomReset:()=>{const J=j?g:1;u(J),i.current=J,p(0),m(0),c.current=0,d.current=0}}}function Ed({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:o}){const i=l.useRef(null),c=l.useRef(null),d=l.useRef(null),[p,m]=l.useState(null),[u,h]=l.useState(""),[,b]=l.useState(!1),[y,f]=l.useState([]),w=l.useRef(0),[j,g]=l.useState(!1),[v,k]=l.useState(!1),N=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[x,C]=l.useState(N?"mouse":"touch"),[S,I]=l.useState(1),P=l.useRef(!1),[L,A]=l.useState(1),[R,$]=l.useState(0),[X,T]=l.useState(0);Ur("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:x,zoom:L,panX:R,panY:X,isMenuOpen:j,isImeOpen:v});const M=l.useRef(0),_=l.useRef(L),B=l.useRef(R),E=l.useRef(X);l.useEffect(()=>{_.current=L},[L]),l.useEffect(()=>{B.current=R},[R]),l.useEffect(()=>{E.current=X},[X]),l.useEffect(()=>{var ce;(ce=i.current)==null||ce.focus()},[]);const F=r==="connected",K=n,z=F?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ne=F?"The remote stream is warming up":"Waiting for the remote stream to catch up";l.useEffect(()=>{if(!N||P.current||!K)return;const ce=d.current,U=c.current;if(!ce||!U)return;const W=()=>{const Y=U.clientWidth,se=U.clientHeight,ie=ce.naturalWidth,ae=ce.naturalHeight;if(!ie||!ae||!Y||!se)return;const D=Math.min(Y/ie,se/ae),ge=Math.max(Y/ie,se/ae)/D;ge>1.01&&(I(ge),A(ge),_.current=ge),P.current=!0};ce.complete&&ce.naturalWidth?W():ce.addEventListener("load",W,{once:!0})},[K,N]);const q=.5;l.useEffect(()=>{L<=q&&($(0),T(0))},[L,q]);const J=(ce,U,W)=>{if(W<=q)return{x:0,y:0};const Y=(W-1)/(2*W)*100,se=(W-1)/(2*W)*100;return{x:Math.max(-Y,Math.min(Y,ce)),y:Math.max(-se,Math.min(se,U))}},xe=(ce,U)=>{if(!d.current)return null;const W=d.current.getBoundingClientRect();return!W.width||!W.height?null:{nx:Math.max(0,Math.min(1,(ce-W.left)/W.width)),ny:Math.max(0,Math.min(1,(U-W.top)/W.height))}},ue=(ce,U,W)=>{const Y=c.current;if(!Y)return;const se=Y.getBoundingClientRect(),ie=++w.current;f(ae=>[...ae,{id:ie,x:ce-se.left,y:U-se.top,type:W}]),setTimeout(()=>f(ae=>ae.filter(D=>D.id!==ie)),600)},O=(ce,U,W)=>{const Y=d.current,se=c.current;if(!Y||!se)return;const ie=Y.getBoundingClientRect(),ae=se.getBoundingClientRect(),D=Y.naturalWidth||ie.width,oe=Y.naturalHeight||ie.height,ge=D/oe,pe=ie.width/ie.height;let te,Me,_e,Ce;ge>pe?(te=ie.width,Me=ie.width/ge,_e=0,Ce=(ie.height-Me)/2):(Me=ie.height,te=ie.height*ge,_e=(ie.width-te)/2,Ce=0);const Ke=ie.left-ae.left+_e+te*ce,Ze=ie.top-ae.top+Ce+Me*U,me=++w.current;f(De=>[...De,{id:me,x:Ke,y:Ze,type:W}]),setTimeout(()=>f(De=>De.filter($e=>$e.id!==me)),600)},H=async ce=>{var W;const U=xe(ce.clientX,ce.clientY);if(U){m(`Click: ${Math.round(U.nx*100)}%, ${Math.round(U.ny*100)}%`),ue(ce.clientX,ce.clientY,"left"),(W=i.current)==null||W.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(ce,U,W,Y=0)=>{try{await e("input_key",{type:W?"char":"keyDown",key:ce,code:U,text:W?ce:void 0,unmodifiedText:W?ce:void 0,modifiers:Y})}catch(se){t(`❌ Key error: ${se.message||se}`)}},we=async ce=>{if(ce.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ce.key)&&ce.preventDefault();let W=0;ce.altKey&&(W|=1),ce.ctrlKey&&(W|=2),ce.metaKey&&(W|=4),ce.shiftKey&&(W|=8),m(`Key: ${ce.key}`),await ve(ce.key,ce.code,ce.key.length===1,W)},be=async ce=>{if(ce.key==="Enter"){if(ce.nativeEvent.isComposing)return;if(u){const U=u;h(""),m(`IME Sent: ${U}`);try{const W=await e("input_type",{text:U});W!=null&&W.success||t(`❌ IME error: ${W==null?void 0:W.error}`)}catch(W){t(`❌ IME error: ${W.message}`)}}else m("Key: Enter"),await ve("Enter","Enter",!1)}};l.useEffect(()=>{const ce=i.current;if(!ce)return;const U=W=>{var Y;if((Y=d.current)!=null&&Y.contains(W.target)){W.preventDefault();const se=Date.now();if(se-M.current<40)return;M.current=se;const ie=xe(W.clientX,W.clientY);if(!ie)return;m(`Scroll: ${Math.round(W.deltaY)}`),e("input_wheel",{nx:ie.nx,ny:ie.ny,deltaX:Math.round(W.deltaX),deltaY:Math.round(W.deltaY)}).catch(()=>{})}};return ce.addEventListener("wheel",U,{passive:!1}),()=>ce.removeEventListener("wheel",U)},[e]);const{cursorPos:Ne,handleToggleInputMode:re,handleZoomReset:je}=Bf({containerRef:i,viewportRef:c,imgRef:d,inputMode:x,setInputMode:C,minZoom:q,zoomRef:_,panXRef:B,panYRef:E,setPanX:$,setPanY:T,setZoom:A,lastWheelTimeRef:M,onAction:e,setLastActionStatus:m,spawnRippleFromNormalized:O,clampPan:J,isMobile:N,mobileFillZoom:S});return s.jsxs("div",{ref:i,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:we,onContextMenu:ce=>ce.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(${R}%, ${X}%)`,transformOrigin:"center center",cursor:x==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:H,onContextMenu:ce=>ce.preventDefault(),onDragStart:ce=>ce.preventDefault()}):s.jsx($f,{waitingLabel:z,waitingHint:ne,transportType:o}),x==="mouse"&&K&&s.jsx(Pf,{cursorPos:Ne,viewportRef:c,imgRef:d}),y.map(ce=>{const W={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ce.type];return s.jsxs("div",{style:{position:"absolute",left:ce.x,top:ce.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${W}, 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(${W}, 0.9)`,boxShadow:`0 0 12px rgba(${W}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ce.id)})]}),s.jsx(Df,{inputMode:x,onToggleInputMode:re,isImeOpen:v,setIsImeOpen:k,isMenuOpen:j,setIsMenuOpen:g,imeText:u,setImeText:h,handleImeSubmit:be,isConnActive:F,zoom:L,isMobile:N,mobileFillZoom:S,onZoomOut:()=>A(ce=>Math.max(.5,ce-.25)),onZoomReset:je,onZoomIn:()=>A(ce=>Math.min(5,ce+.25)),transportType:o,screenshotUsage:a,lastActionStatus:p}),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 kl(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 Ff(e){var t;return kl(e.activeInteractivePrompt)||kl((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function Of(e){return e.sessionId||e.instanceId||e.id}function Hf(e,t){const r=typeof t=="string"?t.trim():"";for(const n of e){const a=Ff(n);if(!a)continue;const o=Of(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 Bd(e,t){var n;const r={};for(const a of e.questions){const o=t[a.questionId]||{},i=Array.from(new Set((o.selectedLabels||[]).map(d=>d.trim()).filter(Boolean))),c=(n=o.freeformText)==null?void 0:n.trim();r[a.questionId]={selectedLabels:i,...c?{freeformText:c}:{}}}return{promptId:e.promptId,answers:r}}function Nl(e){const t={};for(const r of(e==null?void 0:e.prompt.questions)||[])t[r.questionId]={selectedLabels:[],freeformText:""};return t}function Sl(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 zf({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(Md,{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 Fd({promptSession:e,isSubmitting:t=!1,error:r,onSubmit:n,onCancel:a}){var C;const[o,i]=l.useState(()=>Nl(e)),[c,d]=l.useState(0);l.useEffect(()=>{i(Nl(e)),d(0)},[e==null?void 0:e.prompt.promptId]);const p=(e==null?void 0:e.prompt.questions)||[],m=p.length,u=c===m-1,h=m===1,b=p[c],y=b?o[b.questionId]:void 0,f=b?Sl(b,y):!1,w=l.useMemo(()=>e?e.prompt.questions.every(S=>Sl(S,o[S.questionId])):!1,[e,o]);if(!e)return null;const j=(S,I)=>{i(P=>{const L=P[S.questionId]||{selectedLabels:[]},A=L.selectedLabels||[],R=S.multiSelect?A.includes(I)?A.filter($=>$!==I):[...A,I]:[I];return{...P,[S.questionId]:{...L,selectedLabels:R}}})},g=(S,I)=>{i(P=>({...P,[S]:{...P[S]||{selectedLabels:[]},freeformText:I}}))},v=()=>{c<m-1&&d(S=>S+1)},k=()=>{c>0&&d(S=>S-1)},N=()=>{!w||t||n(o)},x=Bd(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(Xs,{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," / ",m]}),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:p.map((S,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"}`},S.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(S=>{var I;return s.jsx(zf,{label:S.label,description:S.description||S.preview,selected:(((I=x.answers[b.questionId])==null?void 0:I.selectedLabels)||[]).includes(S.label),multiSelect:b.multiSelect,disabled:t,onClick:()=>j(b,S.label)},S.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:((C=o[b.questionId])==null?void 0:C.freeformText)||"",disabled:t,onChange:S=>g(b.questionId,S.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:k,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||u?s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:N,disabled:!w||t,children:t?"Submitting...":"Submit"}):s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:v,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 p=Math.floor(d/24);return p<7?`${p}d${r}`:new Date(e).toLocaleDateString()}const Od=e=>xa(e);function Wf(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 nr(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating"||e.status==="long_generating"||e.status==="streaming",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function Kf(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...Wf(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=nr(e),o=a.isReconnecting,i=a.isConnecting,c=a.isGenerating,d=a.isWaiting,p=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d,m=n.inboxBucket==="working"||c,h=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:h,requiresAction:p,isWorking:m,isReconnecting:o,isConnecting:i,isGenerating:c,isWaiting:d,inboxBucket:p?"needs_attention":m?"working":h?"task_complete":"idle"}}function Uf(e,t,r){return ba(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Hd({activeConv:e,onModalButton:t}){const[r,n]=l.useState(null);if(l.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!nr(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(Xs,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((c,d)=>{const p=i(c).toLowerCase(),m=/^(run|approve|accept|yes|allow|always)/.test(p),u=/^(reject|deny|delete|remove|abort)/.test(p),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 ${m?"font-extrabold":u?"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:m?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:u?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",Ro="adhdev:controlsbarvisibilitychange";function Da(e){if(!e)return!1;try{return e.getItem(di)==="1"}catch{return!1}}function Gf(e,t){if(t)try{t.setItem(di,e?"1":"0")}catch{}}function Vf(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Ro,{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"&&Gf(i,window.localStorage),c&&Vf(i)},[]);l.useEffect(()=>{const i=d=>{const p=d.detail,m=typeof(p==null?void 0:p.visible)=="boolean"?p.visible:Da(window.localStorage);r.current=m,t(m)},c=d=>{if(d.key!==di)return;const p=Da(window.localStorage);r.current=p,t(p)};return window.addEventListener(Ro,i),window.addEventListener("storage",c),()=>{window.removeEventListener(Ro,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 qf=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Yf(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function Bt(e,t){if(Yf(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":qf.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 Lo(e){return Bt(e)==="generating"}function Cl(e,t){return Bt(e,t)==="waiting_approval"}function It(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Jf(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 zd(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 Xf(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 Qf(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Zf(e){return Xf(e.trim().replace(/\.local$/i,""))}function ex(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function Wd(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&&!Qf(i));if(r&&r!=="Unknown")return Zf(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Ft(e,t={}){return ex(e)||Wd(e,t)}function Kd(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 Ud(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 Ts(e,t){return Kd(e).join(" · ")}function Er(e){return e.transport==="pty"}function Gs(e){return e.transport==="acp"}function tx(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:It(e)}function Il(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),i=It(r||"").trim().toLowerCase();return n===a||n===o||n===i}function sx(e,t=[],r=[]){var d,p,m,u;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=>Cl(h.status,{activeModal:h.activeModal})||Lo(h.status));if(a)return Bt(a.status,{activeModal:a.activeModal});const o=r.find(h=>Cl(h.status,{activeModal:h.activeModal})||Lo(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:(p=t[0])==null?void 0:p.activeModal});if(i!=="idle")return i;const c=Bt((m=r[0])==null?void 0:m.status,{activeModal:(u=r[0])==null?void 0:u.activeModal});return c!=="idle"?c:"idle"}function rx(e){return Bt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function nx(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 ax(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 ox(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&&ax(t.receivedAt)||0}function ix(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Po(e){return Math.max(ix(e),ox(e.activeChat))}function lx(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 lx(Po(e),Po(t),Ft(e,{fallbackId:e.id}),Ft(t,{fallbackId:t.id}),e.id,t.id)}const Gd="adhdev_notification_prefs",Ml={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function cx(){try{const e=localStorage.getItem(Gd);if(e){const t=JSON.parse(e);return{...Ml,...t}}}catch{}return{...Ml}}function dx(e){try{localStorage.setItem(Gd,JSON.stringify(e))}catch{}}let rs=cx(),_n=[];function ux(){_n.forEach(e=>e())}function px(e){rs={...rs,...e},dx(rs),ux()}function mx(){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=>{px(r)},[]);return[{...rs},t]}function Ir(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}}const hx={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Vd(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function qd(){return"Notification"in window&&Notification.permission==="granted"}let gs=null;function fx(e){return e!==!1}async function xx(){if(gs!==null)return gs;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return gs=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(gs=!!await e.pushManager.getSubscription(),gs):(gs=!1,!1)}catch{return gs=!1,!1}}function Do(e,t,r){if(qd())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={...hx,...t},n=l.useRef(new Map),a=l.useRef(0),[o,i]=l.useState(null);l.useEffect(()=>{let d=!1;return xx().then(p=>{d||i(p)}),()=>{d=!0}},[]);const c=l.useCallback((d,p,m)=>{const u=Date.now();u-a.current<r.throttleMs||(a.current=u,Do(d,p,m))},[r.throttleMs]);l.useEffect(()=>{var d;if(!(!r.enabled||!qd())&&Ir("browser")&&!fx(o)){if(document.hasFocus()){for(const p of e)n.current.set(p.id,Bt(p.status,{activeModal:p.activeModal}));return}for(const p of e){const m=n.current.get(p.id),u=Bt(p.status,{activeModal:p.activeModal}),h=p.name||p.id;if(r.onApproval&&Ir("approval")&&u==="waiting_approval"&&m!=="waiting_approval"){const b=((d=p.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${h} — Approval needed`,b.slice(0,120),`approval-${p.id}`)}r.onComplete&&Ir("completion")&&Lo(m)&&u==="idle"&&c(`✅ ${h} — Task complete`,"Agent has finished generating",`complete-${p.id}`),r.onError&&u==="error"&&m!=="error"&&c(`⚠️ ${h} — Error`,"Agent encountered an error",`error-${p.id}`),n.current.set(p.id,u)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,c])}const gx=/^(run|approve|accept|yes|allow|always)/,yx=/^(run|approve|accept|yes|allow|always|proceed|save)/,vx=/^(reject|deny|delete|remove|abort|cancel|no)/;function mi(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function wx(e){const t=mi(e).toLowerCase();return gx.test(t)?"primary":vx.test(t)?"danger":"default"}function jx(e){return yx.test(mi(e).toLowerCase())?"approve":"reject"}function kx(e){return e.map((t,r)=>({label:mi(t),variant:wx(t),action:jx(t),button:t,buttonIndex:r}))}function Nx(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Sx(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 Cx{constructor(){Qe(this,"dedupMap",new Map);Qe(this,"DEDUP_WINDOW_MS",5e3);Qe(this,"DEDUP_MAX_SIZE",50);Qe(this,"DEDUP_CLEANUP_AGE_MS",1e4);Qe(this,"toastCallbacks",[]);Qe(this,"statusEventCallbacks",[]);Qe(this,"resolveActionFn",null);Qe(this,"viewRequestRespondFn",null);Qe(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,o]of this.dedupMap)r-o>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(o=>o.id===t.daemonId&&o.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const o=this.ides.find(i=>i.id===a&&i.type==="adhdev-daemon");if(o)return o}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}handleRawEvent(t,r){var y;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 f of this.statusEventCallbacks)f(t);const d=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,p=(d==null?void 0:d.type)||"";let m=It(p);const u=this.resolveOwningDaemon(t);if(u){const f=Ft(u,{fallbackId:u.id});f&&(m=!p||p==="adhdev-daemon"?f:`${f}/${m}`)}let h="",b="info";if(t.event==="agent:generating_completed"){const f=t.duration?` (${t.duration}s)`:"";h=`✅ ${m} agent task completed${f}`,b="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started")if(t.event==="agent:waiting_approval"){if(h=`⚡ ${m} approval needed`,b="warning",(y=t.modalButtons)!=null&&y.length&&this.resolveActionFn){const f=this.resolveActionRouteTarget(t);if(!f)return;const w=this.resolveActionFn,j=kx(t.modalButtons).map(k=>({label:k.label,variant:k.variant,onClick:()=>{w(f,"resolve_action",{action:k.action,button:k.button,buttonIndex:k.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),g=Nx(m,t.modalMessage,h),v=Date.now();this.emitToast({id:v,message:g,type:b,timestamp:v,targetKey:n||f,actions:j,duration:15e3}),h=""}}else if(t.event==="monitor:long_generating"){const f=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";h=`⚠️ ${m} agent is taking a long time${f}`,b="warning",Ir("browser")&&!document.hasFocus()&&Do(`⚠️ ${m} — Long Running`,`Agent has been generating for over ${f.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const f=t.requesterName||"A team member",w=t.requestId,j=t.orgId;if(h=`👁️ ${f} wants to view your session`,b="warning",w&&j&&this.viewRequestRespondFn){const g=Date.now(),v=Sx(j,w,this.viewRequestRespondFn,(k,N)=>console.error(`[EventManager] ${k} view request failed:`,N));this.emitToast({id:g,message:h,type:b,timestamp:g,actions:v,duration:3e4}),h=""}Ir("browser")&&!document.hasFocus()&&Do("👁️ View Request",`${f} wants to view your session`,`view-request-${w}`)}else t.event==="team:view_request_approved"?(h="✅ View request approved",b="success"):t.event==="team:view_request_rejected"&&(h=`❌ ${t.targetName||"Team member"} declined your view request`,b="warning");if(h){const f=Date.now();this.emitToast({id:f,message:h,type:b,timestamp:f,targetKey:n||t.daemonId,duration:5e3})}}}const it=new Cx,Al=new Map;function Yn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Vs(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function ga(e){return Yn(e)?Yn(e.result)?e.result:e:null}function Ix(e){const t=ga(e);return!t||!Yn(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function pn(e){const t=ga(e);return!t||!Yn(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function dr(e){const t=ga(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function mn(e){const t=ga(e);return!!t&&t.success===!1}function Mx(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";it.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";it.showToast(n.notification.body,a)}}}function Ax(e,t){return e&&Vs(e.currentValue)?e.currentValue:t}function Tx(e,t){return Vs(t)?Vs(e)?typeof e=="string"&&e.trim()==="":!0:!1}function _x(e,t){var o,i;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if(Vs(c))return c}const n=(o=t.controlValues)==null?void 0:o[e];if(Vs(n))return n;const a=(i=t.defaultValues)==null?void 0:i[e];return Vs(a)?a:void 0}function Rn(e,t){return e.options||t[e.id]||[]}const Rx={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 Lx(e,t,r){var n;return((n=Rx[t])==null?void 0:n.has(r.id))===!0}function hi(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Lx(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function Ea(e,t){return{value:t}}function Px(e,t,r){var a;return r?((a=Rn(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const Dx={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function $x({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:i}){const{sendCommand:c}=mt(),d=`${e}:${t||n}`,p=Dx[n]||"#94a3b8",[m,u]=l.useState({}),h=l.useRef({}),b=l.useRef(i);h.current=m,b.current=i;const y=l.useRef(0),f={};for(const M of o||[])M.defaultValue!==void 0&&(f[M.id]=M.defaultValue);const w={...f,...i||{},...Date.now()<y.current?m:{}};l.useEffect(()=>{i&&Date.now()>y.current&&u({})},[i]);const[j,g]=l.useState(Al.get(d)||{}),[v,k]=l.useState(null),[N,x]=l.useState(null),C=l.useCallback(async(M,_={})=>{const B={..._,...t&&{targetSessionId:t}};return await c(e,M,B)},[e,t,c]),S=l.useCallback(async(M,_={})=>{const B=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await C("invoke_provider_script",{...B,scriptName:M,..._})},[C,n,r,t]),I=l.useCallback((M,_,B)=>{const E=Ax(B,_);u(F=>({...F,[M.id]:E})),Mx(B==null?void 0:B.effects)},[]),P=l.useCallback((M,_)=>{u(B=>{const E={...B};return _===void 0?delete E[M.id]:E[M.id]=_,E}),y.current=0},[]);if(!o||o.length===0)return null;const L=hi(o,{hostIdeType:r,providerType:n});if(L.length===0)return null;const A=async M=>{if(v===M.id){k(null);return}if(Rn(M,j).length>0){k(M.id);return}if(M.dynamic&&M.listScript){x(M.id);try{const B=await S(M.listScript,{}),E=Ix(B);if(!E){const z=dr(B);z&&it.showToast(z,"warning");return}const F=E.options;g(z=>{const ne={...z,[M.id]:F};return Al.set(d,ne),ne});const K=_x(M.id,{localOverrideUntil:y.current,localValues:h.current,controlValues:b.current,defaultValues:f});if(Tx(K,E.currentValue)){const z=E.currentValue;u(ne=>({...ne,[M.id]:z}))}k(M.id)}catch(B){const E=B instanceof Error?B.message:`Could not load ${M.label}`;it.showToast(E,"warning")}finally{x(null)}}},R=async(M,_)=>{k(null);const B=(i==null?void 0:i[M.id])??f[M.id];u(E=>({...E,[M.id]:_})),y.current=Date.now()+5e3;try{if(!M.setScript)return;const E=await S(M.setScript,Ea(M,_)),F=pn(E);if(F&&!F.ok||mn(E))throw new Error((F==null?void 0:F.error)||dr(E)||`Could not update ${M.label}`);I(M,_,F)}catch(E){P(M,B);const F=E instanceof Error?E.message:`Could not update ${M.label}`;it.showToast(F,"warning")}},$=async M=>{const _=Rn(M,j).map(ne=>ne.value);if(_.length===0)return;const B=String(w[M.id]||""),F=(_.indexOf(B)+1)%_.length,K=_[F];if(typeof K!="string")return;const z=(i==null?void 0:i[M.id])??f[M.id];u(ne=>({...ne,[M.id]:K})),y.current=Date.now()+5e3;try{if(!M.setScript)return;const ne=await S(M.setScript,Ea(M,K)),q=pn(ne);if(q&&!q.ok||mn(ne))throw new Error((q==null?void 0:q.error)||dr(ne)||`Could not update ${M.label}`);I(M,K,q)}catch(ne){P(M,z);const q=ne instanceof Error?ne.message:`Could not update ${M.label}`;it.showToast(q,"warning")}},X=async M=>{const B=!w[M.id],E=(i==null?void 0:i[M.id])??f[M.id];u(F=>({...F,[M.id]:B})),y.current=Date.now()+5e3;try{if(!M.setScript)return;const F=await S(M.setScript,Ea(M,B)),K=pn(F);if(K&&!K.ok||mn(F))throw new Error((K==null?void 0:K.error)||dr(F)||`Could not update ${M.label}`);I(M,B,K)}catch(F){P(M,E);const K=F instanceof Error?F.message:`Could not update ${M.label}`;it.showToast(K,"warning")}},T=async M=>{if(!M.invokeScript)return;if(M.confirmMessage){const B=[M.confirmTitle,M.confirmMessage,M.confirmLabel].filter(F=>typeof F=="string"&&F.trim().length>0);if(!window.confirm(B.join(`
|
|
30
|
+
|
|
31
|
+
`)))return}const _=(i==null?void 0:i[M.id])??f[M.id];try{const B=await S(M.invokeScript),E=pn(B);if(E&&!E.ok||mn(B))throw new Error((E==null?void 0:E.error)||dr(B)||`Could not run ${M.label}`);E&&I(M,_??!0,E)}catch(B){P(M,_);const E=B instanceof Error?B.message:`Could not run ${M.label}`;it.showToast(E,"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:`${p}33`,background:`${p}12`,color:p},children:a}),L.map(M=>{const _=String(w[M.id]||""),B=Px(M,j,_),E=v===M.id,F=N===M.id,K=Rn(M,j),z="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium transition-colors whitespace-nowrap";switch(M.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${z} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:E?`${p}55`:"var(--border-default)",background:E?`${p}10`:"var(--surface-tertiary)",color:_?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void A(M),title:M.label,children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:F?"Loading…":B||M.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),E&&K.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>k(null)}),s.jsxs("div",{className:"absolute bottom-full left-0 z-[60] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[s.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:M.label}),K.map(ne=>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:ne.value===_?`${p}14`:"transparent",color:ne.value===_?"var(--text-primary)":"var(--text-secondary)",borderLeft:ne.value===_?`2px solid ${p}`:"2px solid transparent"},title:ne.description||ne.label,onMouseEnter:q=>{q.currentTarget.style.background=`${p}10`},onMouseLeave:q=>{q.currentTarget.style.background=ne.value===_?`${p}14`:"transparent"},onClick:()=>void R(M,ne.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ne.label}),ne.value===_&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:p},children:"✓"})]},ne.value))]})]})]},M.id);case"cycle":return s.jsxs("button",{type:"button",className:`${z} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:_?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void $(M),title:`Click to cycle: ${K.map(ne=>ne.label).join(" → ")}`,children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:B||M.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},M.id);case"toggle":return s.jsxs("button",{type:"button",className:`${z} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:_?`${p}44`:"var(--border-default)",background:_?`${p}14`:"var(--surface-tertiary)",color:_?p:"var(--text-muted)"},onClick:()=>void X(M),"aria-pressed":!!_,children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),M.label]},M.id);case"action":return s.jsxs("button",{type:"button",className:`${z} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void T(M),children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:M.resultDisplay==="inline"&&_?`${M.label}: ${_}`:M.label})]},M.id);case"display":return s.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:_?"var(--text-primary)":"var(--text-muted)"},children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:_?`${M.label}: ${_}`:M.label})]},M.id);default:return null}})]})})}function Ex({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:c,controlValues:d}){const{isVisible:p}=ui(),m=hi(c,{hostIdeType:a,providerType:o});return!e||t||m.length===0||!p?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx($x,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:i,controls:m,controlValues:d})})}const ur=5,Yd=10*1024*1024;function Bx({hasDraft:e,isBusy:t=!1}){return!e||t}function Fx(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 Ox(e){if(e.size>Yd)return null;const t=await Fx(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 Hx(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const Jd=l.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,onSend:i,onForceSend:c,canForceSend:d=!1,isActive:p=!0,showControlsToggle:m=!1,animateVisibility:u=!0,onControlsToggle:h,messageInput:b}){const y=l.useRef(null),f=l.useRef(null),[w,j]=l.useState(""),[g,v]=l.useState([]),[k,N]=l.useState(null),[x,C]=l.useState(!1),S=l.useRef(!1),{isVisible:I,toggleVisibility:P}=ui(),L=Hx(b),A=!!w.trim()||g.length>0;l.useEffect(()=>{j(""),v([]),N(null)},[t]),l.useEffect(()=>{var E;p&&((E=y.current)==null||E.focus({preventScroll:!0}))},[t,p]),l.useEffect(()=>{const E=y.current;E&&(E.style.height="auto",E.style.height=`${Math.min(E.scrollHeight,160)}px`)},[w]);const R=l.useCallback(async E=>{N(null);const F=Array.from(E).filter(xe=>xe.type.startsWith("image/"));if(F.length===0)return;const K=ur-g.length;if(K<=0){N(`Max ${ur} images`);return}const z=F.slice(0,K);if(z.filter(xe=>xe.size>Yd).length>0){N("Image too large (max 10 MB)");return}const J=(await Promise.all(z.map(Ox))).filter(xe=>xe!==null);v(xe=>[...xe,...J])},[g.length]),$=l.useCallback(E=>{v(F=>F.filter((K,z)=>z!==E))},[]),X=l.useCallback(async()=>{const E=w.trim();if(!E&&g.length===0||a||S.current)return;S.current=!0;const F=g.length>0?[...g]:void 0;try{await i(E,F)!==!1&&(j(""),v([]),N(null))}finally{S.current=!1}},[w,g,a,i]),T=l.useCallback(async()=>{if(!d||!c)return;const E=w.trim();if(!E&&g.length===0||S.current)return;S.current=!0;const F=g.length>0?[...g]:void 0;try{await c(E,F)!==!1&&(j(""),v([]),N(null))}finally{S.current=!1}},[g,d,w,c]),M=l.useCallback(E=>{L&&(E.preventDefault(),C(!0))},[L]),_=l.useCallback(()=>C(!1),[]),B=l.useCallback(E=>{L&&(E.preventDefault(),C(!1),E.dataTransfer.files.length>0&&R(E.dataTransfer.files))},[L,R]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",u?"transition-all duration-200 ease-out":"",x?"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:M,onDragLeave:_,onDrop:B,children:[g.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:g.map((E,F)=>s.jsxs("div",{className:"relative group w-14 h-14 rounded-lg overflow-hidden border border-border-subtle shrink-0",style:{background:"var(--surface-secondary)"},children:[s.jsx("img",{src:E.previewUrl,alt:E.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>$(F),className:"absolute top-0.5 right-0.5 w-4 h-4 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-[10px] leading-none","aria-label":`Remove ${E.name}`,children:"✕"})]},F))}),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:()=>{P(),h==null||h()},"aria-label":I?"Hide controls":"Show controls","aria-pressed":I,title:I?"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"})]})}),L&&s.jsxs(s.Fragment,{children:[s.jsx("input",{ref:f,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:E=>{E.target.files&&R(E.target.files),E.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var E;return(E=f.current)==null?void 0:E.click()},disabled:g.length>=ur,title:g.length>=ur?`Max ${ur} 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:y,rows:1,placeholder:o||(L&&g.length>0?"Add a message (optional)...":`Send message to ${r}... (Shift+Enter for newline)`),value:w,onChange:E=>j(E.target.value),onPaste:E=>{L&&E.clipboardData.files.length>0&&Array.from(E.clipboardData.files).some(K=>K.type.startsWith("image/"))&&(E.preventDefault(),R(E.clipboardData.files))},onKeyDown:E=>{E.key==="Enter"&&(E.nativeEvent.isComposing||E.shiftKey||(E.preventDefault(),X()))},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:()=>{X()},disabled:Bx({hasDraft:A,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${A&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:A&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":"Send message",children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:A?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})}),d&&s.jsx("button",{type:"button",onClick:()=>{T()},disabled:!A,className:`h-10 px-3 rounded-full text-[11px] font-medium border border-border-subtle shrink-0 transition-colors ${A?"bg-bg-secondary text-text-primary hover:bg-[var(--surface-tertiary)]":"bg-bg-secondary text-text-muted cursor-default opacity-60"}`,"aria-label":"Force send message now",title:"Force send message now",children:"Force"})]}),(k||L&&x)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${k?"text-red-400":"text-[var(--accent-primary)]"}`,children:k||"Drop image here"}),o&&!k&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:o})]})}),zx=l.createContext(null);function fi(){return l.useContext(zx)}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 Wx(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 xi(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 Kx(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)??Wx(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 p=Se(a.error);return p&&(d.error=p),d}).filter(n=>n!==null);return r.length>0?r:void 0}function Ux(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 Ln(e,t,r){const n=Rt(e.isGitRepo);if(!Object.keys(e).length||!Ux(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(v=>typeof v=="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,p=Kx(e.submodules,d),m=Se(e.upstreamStatus,e.upstream_status),u=Dt(e.upstreamFetchedAt,e.upstream_fetched_at),h=Se(e.upstreamFetchError,e.upstream_fetch_error),b=Se(e.error),y=Dt(e.staged)??0,f=Dt(e.modified)??0,w=Dt(e.untracked)??0,j=Dt(e.deleted)??0,g=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:m??"unchecked",...u!==void 0?{upstreamFetchedAt:u}:{},...h?{upstreamFetchError:h}:{},ahead:Dt(e.ahead)??0,behind:Dt(e.behind)??0,staged:y,modified:f,untracked:w,deleted:j,renamed:g,dirty:Rt(e.dirty,e.isDirty,e.is_dirty)??(y+f+w+j+g>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(),...p?{submodules:p}:{},...b?{error:b}:{}}}function Gx(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+=xi(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 Vx(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),p=ct(c.status),m=ct(d.status),u=t==null?void 0:t.lastCheckedAt;let h=null;for(const b of[a,o,p,m]){const y=Ln(b,e,{lastCheckedAt:u??Date.now()});if(!y)continue;const f=Gx(y);(!h||f>h.score)&&(h={git:y,score:f})}return h==null?void 0:h.git}function qx(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 $o(e){const t=ct(e),r=Se(t.sessionId,t.session_id,t.id)??qx(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 Yx(e){const t=e&&typeof e=="object"?e:{};return Se(t.id,t.nodeId,t.node_id)}function Jx(e,t){if(!t)return!1;const r=t.trim();return r?Yx(e)===r:!1}function Xx(e){return Vx(e,{lastCheckedAt:Date.now()})}function Qx(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 Zx(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=Qx(e);return t.outOfSync?"degraded":t.dirty||Zx(e)?"dirty":"online"}function eb(e,t){const r=t?Jn(t):void 0;return!e||e==="unknown"?r:e}function tb(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($o).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=$o(n);return a?[a]:void 0}function sb(e){const t=ct(e.connection);return Object.keys(t).length>0?t:void 0}function rb(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 bi(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 Tl(e){var n,a,o,i,c,d;let t=0;const r=e.git;return bi(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+=xi(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 nb(e,t){var y,f,w,j;const r=Tl(e),a=Tl(t)>r?t:e,o=a===t?e:t,i=a.git??o.git,c=(((y=a.providers)==null?void 0:y.length)??0)>0?a.providers:o.providers,d=(((f=a.activeSessions)==null?void 0:f.length)??0)>0?a.activeSessions:o.activeSessions,p=(((w=a.activeSessionDetails)==null?void 0:w.length)??0)>0?a.activeSessionDetails:o.activeSessionDetails,m=(((j=a.providerPriority)==null?void 0:j.length)??0)>0?a.providerPriority:o.providerPriority,u=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??[],...p&&p.length>0?{activeSessionDetails:p}:{},...m&&m.length>0?{providerPriority:m}:{},...u?{connection:u}:{},...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 Xd(e){const t=ct(e),r=Se(t.nodeId,t.id);if(!r)return null;const n=ct(t.cachedStatus),a=Xx(t),o=a?void 0:Ln(ct(t.git),t)??Ln(t,t),i=a??o,c=i?void 0:Ln(ct(n.git),t),d=i??c,p=Se(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),m=Se(t.health),u=a?Jn(d):eb(m,i)||(d?Jn(d):void 0)||Se(n.health)||p||Se(t.status)||"unknown",b=(a?void 0:Se(t.error))??(i?void 0:Se(n.error)),y=tb(t),f=Ba(t.activeSessions),w=(y==null?void 0:y.map(S=>S.sessionId))??[],j=Ba(t.providerPriority),g=Rt(t.gitProbePending,t.git_probe_pending),v=i?void 0:g,k=sb(t),N=ct(t.branchConvergence??t.branch_convergence),x=k==null?void 0:k.state,C=a&&(!(k!=null&&k.reported)||x==="unknown")?rb(k):k;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)}:{},...p?{machineStatus:p}:{},...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:u,...d?{git:d}:{},...v!==void 0?{gitProbePending:v}:{},providers:Ba(t.providers),activeSessions:f.length>0?f:w,...y&&y.length>0?{activeSessionDetails:y}:{},...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)}:{},...C?{connection:C}:{},...Object.keys(N).length>0?{branchConvergence:N}:{},...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 Qd(e,t){const r=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],n=r.map($o).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})),p=Se(d.nodeId,d.node_id),m=Se(d.daemonId,d.daemon_id),u=Se(d.workspace);return p&&p===a.nodeId?!0:m&&a.daemonId&&m===a.daemonId?!u||!a.workspace||u===a.workspace:!!(u&&a.workspace&&u===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 ab(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 Zd(e){const t=new Map,r=[];for(const n of e){const a=ab(n)?Xd(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=nb(o,a);t.set(a.nodeId,i);const c=r.findIndex(d=>d.nodeId===a.nodeId);c>=0&&(r[c]=i)}return r}function gi(e){const t=Zd(e.nodes??[]);return{...e,nodes:Qd(e,t)}}function ob(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:bi(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 ib(e){const t=Se(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(d=>Xd(d)).filter(d=>d!==null):null;if(!t||!n)return null;const a=Qd(e,Zd(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 lb(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+=xi(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 cb(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 db=20;function Rl(e){let t=null;for(const r of e){const n=ib(ct(r));if(!n)continue;const a=lb(n),o=cb(n);if(!t){t={status:n,score:a,refreshedAt:o};continue}(Math.abs(a-t.score)<=db?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 yi(e){const r=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,n=Rl([r==null?void 0:r.status,r]);return n||Rl([e==null?void 0:e.status,e])}function ub(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 mb(e,t){var a;if(!t)return null;const r=yi(e),n=(a=r==null?void 0:r.nodes)==null?void 0:a.find(o=>Jx(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 Ll(e){if(!e||!Number.isFinite(e))return"—";try{return`${new Date(e).toLocaleString()} (${e})`}catch{return String(e)}}function Pl(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 hb({sessionId:e,daemonId:t,conv:r,onClose:n}){var k,N;const{sendCommand:a}=mt(),o=fi(),[i,c]=l.useState(!0),[d,p]=l.useState(null),[m,u]=l.useState(null),[h,b]=l.useState(null),[y,f]=l.useState(null),w=l.useMemo(()=>ub(r),[r]),j=l.useMemo(()=>pb(r),[r]),g=l.useCallback(async()=>{c(!0),u(null);try{const x=await a(t,"get_session_info",{targetSessionId:e}),C=x&&typeof x=="object"?x:{},S=C.result&&typeof C.result=="object"?C.result:C;S!=null&&S.success?p(S):(u((S==null?void 0:S.error)||"Failed to load session info"),p(null))}catch(x){u((x==null?void 0:x.message)||String(x)),p(null)}finally{c(!1)}},[a,t,e]);l.useEffect(()=>{g()},[g]);const v=l.useCallback(async()=>{if(b(null),f(null),!(!w||!j||!(o!=null&&o.loadMeshStatus)))try{const x=await o.loadMeshStatus(t,w,{refresh:!1}),C=mb(x,j);if(!C){f("This session is stamped to a mesh node that the coordinator no longer reports.");return}b(C)}catch(x){f((x==null?void 0:x.message)||"Failed to load mesh node info")}},[o,t,w,j]);return l.useEffect(()=>{v()},[v]),l.useEffect(()=>{const x=C=>{C.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…"}),m&&s.jsx("div",{className:"text-red-500",children:m}),(d==null?void 0:d.session)&&s.jsxs(Hs,{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:[Ll(d.session.spawnedAtMs),d.session.spawnedAtMs?s.jsx("span",{className:"text-text-secondary ml-2",children:Pl(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"]})})]}),((k=d==null?void 0:d.session)==null?void 0:k.launch)&&s.jsxs(Hs,{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(Hs,{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&&y&&(w||j)&&s.jsx(Hs,{title:"Mesh node",children:s.jsx("div",{className:"text-text-secondary italic",children:y})}),(d==null?void 0:d.coordinator)&&s.jsxs(Hs,{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:[Ll(d.coordinator.startedAt),d.coordinator.startedAt?s.jsx("span",{className:"text-text-secondary ml-2",children:Pl(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(Eo,{title:"Per-launch extra prompt",body:d.coordinator.extraSystemPrompt,defaultOpen:!0}),d.coordinator.systemPrompt&&s.jsx(Eo,{title:"Final system prompt (click to expand)",body:d.coordinator.systemPrompt})]}),((N=d==null?void 0:d.session)==null?void 0:N.runtimeMetadata)!=null&&s.jsx(fb,{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 g(),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 Hs({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 fb({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(Hs,{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(Eo,{title:"Raw runtime metadata (click to expand)",body:xb(e)})]})}function xb(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Eo({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(hb,{sessionId:e,daemonId:t,conv:r,onClose:()=>a(!1)})]})}const nt=e=>e.transport==="pty",ar=(e,t)=>nt(e)?e.mode||"terminal":"chat",eu=(e,t)=>nt(e)&&ar(e)==="terminal",rt=e=>e.transport==="acp",gb=180;function xs(e){return e.streamSource!=="agent-stream"}function Ds(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function tu(e){return e.machineName||""}function Gr(e){return Ds(e)}function es(e){return e.agentType||""}function Xn(e){return e.hostIdeType||""}function vi(e){return e.displayPrimary||e.agentName||"Agent"}function su(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function yb(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function ru(e){const t=yb(e),r=Ys(t==null?void 0:t.content),n=Ys(e.lastMessagePreview);return r||n||""}function vb(e,t=gb){const r=Ys(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 wb(e){return vb(ru(e)||e.displaySecondary||"")}function nu(e){return[e.displaySecondary,tu(e)].filter(Boolean)}function Zs(e){return e.agentName||It(es(e))}function jb(e){var t,r;if(!xs(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return It(Xn(e)||es(e))}function au(e){return xs(e)?e.sessionId:e.nativeSessionId}function Dl(e){return xs(e)?"native":e.tabKey}function kb(e){return e.sessionId}function Nb(e,t){if(t)return xs(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function Sb(e,t){const r=es(e),n=xs(e),a=nt(e)||rt(e),o=n?a?Zs(e)||(t==null?void 0:t.cliName)||It(Xn(e)||r):t!=null&&t.type?It(t.type):It(Xn(e)||r):Zs(e);return{isNativeConversation:n,isCli:nt(e),isAcp:rt(e),isCliTerminal:eu(e),providerType:r,displayLabel:o,targetEntry:Nb(e,t)}}function ks(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 Ns(e){return e?Gr(e):""}function pr(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function wi(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function $l(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 ou(){return"select_session"}function Cb(){return"open_panel"}function Ib({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function El(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function hn(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function Mr(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function ji(e){return e instanceof Error?e.message:String(e||"")}function Bl(e){const t=ji(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Fl(e,t){const r=ji(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function Ol(e,t,r,n={}){const a=ks(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 ya({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,o]=l.useState(!1),[i,c]=l.useState(!1),[d,p]=l.useState(null),m=l.useRef(!1),u=l.useRef(null);l.useEffect(()=>{p(null)},[t==null?void 0:t.tabKey]);const h=l.useCallback(async(j,g)=>{if(!t||m.current)return!1;const v=j.trim(),k=wi(t);if(Ib({hasMessage:!!v,blockedMessage:k,sendInFlight:m.current}))return k&&p(k),!1;const N=Date.now(),x={tabKey:t.tabKey,message:v,timestamp:N};if(El(u.current,x))return p(null),!0;m.current=!0,c(!0),p(null),u.current=x;try{const C=Ns(t);if(!C)return u.current=hn(u.current,x),p("Unable to send message right now."),!1;const S=await e(C,"send_chat",Ol(v,g,t)),I=Mr(S);if(I!=null&&I.deduplicated)return p(null),!0;if((I==null?void 0:I.sent)===!1)throw new Error((I==null?void 0:I.error)||"Send failed");if((I==null?void 0:I.success)===!1)throw new Error((I==null?void 0:I.error)||"Send failed");return p(null),!0}catch(C){const S=ji(C);return S.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",S):console.warn("Send blocked/failed",C),u.current=hn(u.current,x),p($l(C)),!1}finally{m.current=!1,c(!1)}},[t,e]),b=l.useCallback(async(j,g)=>{if(!t||m.current)return!1;const v=j.trim();if(!v&&(!g||g.length===0))return!1;const k=Date.now(),N={tabKey:t.tabKey,message:`force:${v}`,timestamp:k};if(El(u.current,N))return p(null),!0;m.current=!0,c(!0),p(null),u.current=N;try{const x=Ns(t);if(!x)return u.current=hn(u.current,N),p("Unable to send message right now."),!1;const C=await e(x,"send_chat",Ol(v,g,t,{force:!0})),S=Mr(C);if((S==null?void 0:S.success)===!1||(S==null?void 0:S.sent)===!1)throw new Error((S==null?void 0:S.error)||"Send failed");return p(null),!0}catch(x){return console.warn("Force send blocked/failed",x),u.current=hn(u.current,N),p($l(x)),!1}finally{m.current=!1,c(!1)}},[t,e]),y=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 v=(t.modalButtons||[]).indexOf(j),k=j.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),N=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(k),x=Ns(t);if(!x)return;const C=await e(x,"resolve_action",{button:j,action:N?"approve":"reject",...v>=0&&{buttonIndex:v},...ks(t)}),S=Mr(C);S.success||r(I=>[...I,{routeId:t.tabKey,text:Fl(j,S==null?void 0:S.error),timestamp:Date.now()}])}catch(g){Bl(g)||console.error("[ModalButton] Error:",g),r(v=>[...v,{routeId:t.tabKey,text:Bl(g)?Fl(j,g):`❌ **${j}** error`,timestamp:Date.now()}])}},[t,e,r]),w=l.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,Cb(),{...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:y,handleModalButton:f,handleFocusAgent:w}}const Mb=10,Ab=8e3,Tb=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function _b(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 Bo(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(Tb.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=_b(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=>Bo(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,Bo(a,n,r+1)]))}function mr(e,t){return Array.isArray(e)?e.slice(-t):[]}function Rb(e,t=Date.now()){const r=e&&t-e.firstAt<=Ab,n=r?e.count+1:1;return n>=Mb?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function iu(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:mr(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:mr(t.messages,10),visibleMessagesTail:mr(e.visibleMessages,5),historyMessagesTail:mr(e.chatTailState.historyMessages,5),actionLogsTail:mr(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 Bo(r)}function lu(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 cu(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 du(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 Lb(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function Pb(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Bs(e,t){Pb()&&console.debug(`[subscription-manager] ${e}`,t)}class Db{constructor(){Qe(this,"active",new Map);Qe(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var m,u;const i=Fa(n.topic,n.key),c=this.active.get(i);let d=!0;if(c)c.handlers.add(a),(!Lb(c.request,n)||c.daemonId!==r)&&(c.daemonId=r,c.request=n,d=((m=t.sendData)==null?void 0:m.call(t,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)?this.scheduleRetry(i,t,o.retryIntervalMs):d&&this.clearRetry(i),Bs("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),Bs("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((u=t.sendData)==null?void 0:u.call(t,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(i,t,o.retryIntervalMs)}const p=()=>{var y;this.clearRetry(i);const h=this.active.get(i);if(!h||(h.handlers.delete(a),h.handlers.size>0))return;this.active.delete(i);const b={type:"unsubscribe",topic:n.topic,key:n.key};Bs("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(y=t.sendData)==null||y.call(t,r,b)};return p.initialSendAccepted=d,p}publish(t){const r=Fa(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,qs.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),qs.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;Bs("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);Bs("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;Bs("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 Db;function $b(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 Eb(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 Bb(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function Fb(e){Bb()&&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:p,childrenByParent:m}=Eb(d),u=$b(o,n),h=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,b=p.filter(w=>w.kind==="workspace"&&w.transport==="cdp-page"),y=p.filter(w=>w.kind==="agent"&&w.transport==="pty"),f=p.filter(w=>w.kind==="agent"&&w.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(w=>!!w.cdpConnected)});for(const w of b){const j=u.get(w.id),g=jr(w,j),v=(m.get(w.id)||[]).map(k=>jr(k,u.get(k.id)));r.push({id:`${n}:ide:${w.id}`,sessionId:w.id,providerSessionId:w.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:g.parentId,sessionKind:g.kind,transport:g.transport,sessionCapabilities:g.capabilities,type:g.providerType,status:g.cdpConnected?"online":"detected",daemonId:n,instanceId:Oa(n,w.id),workspace:g.workspace,terminals:0,childSessions:v,agents:v.map(k=>({id:k.id,name:k.providerName||k.providerType,type:k.providerType,status:k.status})),activeChat:g.activeChat,...g.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:g.activeInteractivePrompt},chats:[],cdpConnected:g.cdpConnected,...g.lastMessagePreview!==void 0&&{lastMessagePreview:g.lastMessagePreview},...g.lastMessageRole!==void 0&&{lastMessageRole:g.lastMessageRole},...g.lastMessageAt!==void 0&&{lastMessageAt:g.lastMessageAt},...g.lastMessageHash!==void 0&&{lastMessageHash:g.lastMessageHash},lastUpdated:g.lastUpdated,unread:g.unread,lastSeenAt:g.lastSeenAt,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,seenCompletionMarker:g.seenCompletionMarker,surfaceHidden:g.surfaceHidden,...g.controlValues!==void 0&&{controlValues:g.controlValues},...g.providerControls!==void 0&&{providerControls:g.providerControls},...g.summaryMetadata!==void 0&&{summaryMetadata:g.summaryMetadata},...g.settings!==void 0&&{settings:g.settings},...g.messageInput!==void 0&&{messageInput:g.messageInput},timestamp:c})}for(const w of y){const j=u.get(w.id),g=jr(w,j);r.push({id:`${n}:cli:${w.id}`,sessionId:w.id,providerSessionId:w.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:g.parentId,sessionKind:g.kind,transport:g.transport,sessionCapabilities:g.capabilities,type:g.providerType,agentType:g.providerType,status:g.status||"running",daemonId:n,instanceId:Oa(n,w.id),cliName:g.providerName||g.providerType,mode:g.mode||(j==null?void 0:j.mode)||"terminal",workspace:g.workspace||"",...w.ownerDaemonId&&{ownerDaemonId:w.ownerDaemonId},...w.ownerMachineName&&{ownerMachineName:w.ownerMachineName},activeChat:g.activeChat,...g.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:g.activeInteractivePrompt},...g.resume!==void 0&&{resume:g.resume},...g.runtimeKey!==void 0&&{runtimeKey:g.runtimeKey},...g.runtimeDisplayName!==void 0&&{runtimeDisplayName:g.runtimeDisplayName},...g.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:g.runtimeWorkspaceLabel},...g.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:g.runtimeWriteOwner},...g.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:g.runtimeAttachedClients},...g.lastMessagePreview!==void 0&&{lastMessagePreview:g.lastMessagePreview},...g.lastMessageRole!==void 0&&{lastMessageRole:g.lastMessageRole},...g.lastMessageAt!==void 0&&{lastMessageAt:g.lastMessageAt},...g.lastMessageHash!==void 0&&{lastMessageHash:g.lastMessageHash},lastUpdated:g.lastUpdated,unread:g.unread,lastSeenAt:g.lastSeenAt,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,seenCompletionMarker:g.seenCompletionMarker,surfaceHidden:g.surfaceHidden,...g.controlValues!==void 0&&{controlValues:g.controlValues},...g.providerControls!==void 0&&{providerControls:g.providerControls},...g.summaryMetadata!==void 0&&{summaryMetadata:g.summaryMetadata},...g.settings!==void 0&&{settings:g.settings},...g.messageInput!==void 0&&{messageInput:g.messageInput},timestamp:c,_isCli:!0})}for(const w of f){const j=u.get(w.id),g=jr(w,j);r.push({id:`${n}:acp:${w.id}`,sessionId:w.id,providerSessionId:w.providerSessionId??(j==null?void 0:j.providerSessionId),parentSessionId:g.parentId,sessionKind:g.kind,transport:g.transport,sessionCapabilities:g.capabilities,type:g.providerType,agentType:g.providerType,status:g.status||"running",daemonId:n,instanceId:Oa(n,w.id),cliName:g.providerName||g.providerType,mode:"chat",workspace:g.workspace||"",...w.ownerDaemonId&&{ownerDaemonId:w.ownerDaemonId},...w.ownerMachineName&&{ownerMachineName:w.ownerMachineName},activeChat:g.activeChat,...g.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:g.activeInteractivePrompt},...g.runtimeKey!==void 0&&{runtimeKey:g.runtimeKey},...g.runtimeDisplayName!==void 0&&{runtimeDisplayName:g.runtimeDisplayName},...g.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:g.runtimeWorkspaceLabel},...g.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:g.runtimeWriteOwner},...g.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:g.runtimeAttachedClients},...g.lastMessagePreview!==void 0&&{lastMessagePreview:g.lastMessagePreview},...g.lastMessageRole!==void 0&&{lastMessageRole:g.lastMessageRole},...g.lastMessageAt!==void 0&&{lastMessageAt:g.lastMessageAt},...g.lastMessageHash!==void 0&&{lastMessageHash:g.lastMessageHash},lastUpdated:g.lastUpdated,unread:g.unread,lastSeenAt:g.lastSeenAt,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,seenCompletionMarker:g.seenCompletionMarker,surfaceHidden:g.surfaceHidden,...g.controlValues!==void 0&&{controlValues:g.controlValues},...g.providerControls!==void 0&&{providerControls:g.providerControls},...g.summaryMetadata!==void 0&&{summaryMetadata:g.summaryMetadata},...g.settings!==void 0&&{settings:g.settings},...g.messageInput!==void 0&&{messageInput:g.messageInput},timestamp:c,_isAcp:!0})}return Fb(r),r}const Ob=15e3,Hb=15e3,zb=6e4,Wb=1200,Hl=12,Kb=8e3,Ub=4e3,Ha=new Map,za=new Map,fn=new Set,Ar=new Map;function Gb(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 zl(e,t){const r=Ar.get(e);!r||r.size===0||(Ar.delete(e),r.forEach(n=>n(t)))}function Vb(e,t){return new Promise(r=>{const n=Ar.get(e)||new Set;Ar.set(e,n);const a=i=>{clearTimeout(o),n.delete(a),n.size===0&&Ar.delete(e),r(i)},o=setTimeout(()=>a(!1),t);n.add(a)})}function Vr(){const{sendCommand:e,sendData:t}=mt(),{injectEntries:r,getIdes:n}=$r();return l.useCallback(async(a,o)=>{if(!a)return;const i=(o==null?void 0:o.minFreshMs)??zb,c=za.get(a)||0;if(!(o!=null&&o.force)&&fn.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 p=(async()=>{if(t&&!fn.has(a)){const f=ts.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},w=>{const j=n(),g=j.find(k=>k.id===a),v=Qn(w.status,{daemonId:a,existingDaemon:g,existingEntries:j,timestamp:w.timestamp});v.length>0&&r(v),za.set(a,Date.now()),zl(a,!0)});if(f.initialSendAccepted?fn.add(a):fn.delete(a),!(o!=null&&o.force)&&f.initialSendAccepted&&await Vb(a,Wb))return}const m=await e(a,"get_status_metadata"),u=Gb(m);if(!u)return;const h=n(),b=h.find(f=>f.id===a),y=Qn(u,{daemonId:a,existingDaemon:b,existingEntries:h,timestamp:u.timestamp||Date.now()});y.length>0&&r(y,{authoritativeDaemonIds:[a]}),za.set(a,Date.now()),zl(a,!0)})().finally(()=>{Ha.delete(a)});return Ha.set(a,p),p},[n,r,e,t])}function qb(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const Yb=60,Jb=50;function uu(e={}){return e.isCliLike?Jb:Yb}function Xb(e={}){return uu(e)}function Mt(e){return(typeof e=="string"?e.trim():"")||void 0}function ns(e,t){const r=Mt(t);return r?`${e}:${r}`:void 0}function ps(e,t,r){const n=ns(t,r),a=Mt(r);n&&e.push(n),a&&e.push(a)}function Us(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function pu(e){return Mt(e.providerSessionId)||Mt(e.sessionId)||Mt(e.tabKey)||Mt(e.routeId)}function va(e){return Us([Mt(e.historySessionId),Mt(e.providerSessionId),Mt(e.sessionId)])}function os(e){const t=[];return ps(t,"provider",e.providerSessionId),ps(t,"session",e.sessionId),ps(t,"tab",e.tabKey),ps(t,"route",e.routeId),Us(t)}function Qb(e){const t=[];return Mt(e.providerSessionId)?(ps(t,"provider",e.providerSessionId),Us(t)):Mt(e.sessionId)?(ps(t,"session",e.sessionId),Us(t)):Mt(e.tabKey)?(ps(t,"tab",e.tabKey),Us(t)):Mt(e.routeId)?(ps(t,"route",e.routeId),Us(t)):[]}function Br(e){return ns("provider",e.providerSessionId)||ns("session",e.sessionId)||ns("tab",e.tabKey)||ns("route",e.routeId)||"unknown:"}function qr(e){return va(e)[0]}function Zb(e){const t=Mt(e.providerSessionId),r=Mt(e.sessionId),n=Mt(e.tabKey),a=Mt(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=Br({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:c,targetKey:c,targetValue:pu({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:qr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:i}}function Fo(e,t){const r=Zb(e);return Qb(t).some(n=>r.lookupKeys.includes(n))}const Yr=60,eg=1e3,Wl=500,ki=12e4,tg=new Set(["generating","waiting_approval","starting","streaming","working"]),Oo=new Map;function Ni(e,t,r){return`${e}::${t}::${r||t}`}function Zn(e=Yr){return{liveMessages:[],hasLiveSnapshot:!1,cursor:sg([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function sg(e,t=Yr){return{tailLimit:t}}function Kl(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 rg(e){return Ho(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function ng(e){return e.length===0||e.every(rg)}function ag(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="generating"||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 og(e,t,r,n,a){if(!ag(n))return!1;const o=mu(e,t);if(o<=0)return!1;if(ng(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 ig(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 lg(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}function Ul(e,t){const r=e[t];return typeof r=="string"?r:""}class cg{constructor(t){Qe(this,"manager");Qe(this,"sendData");Qe(this,"daemonId");Qe(this,"sessionId");Qe(this,"historySessionId");Qe(this,"subscriptionKey");Qe(this,"fallbackRecentCount");Qe(this,"snapshot");Qe(this,"transportSubscription",null);Qe(this,"listeners",new Set);Qe(this,"retainCount",0);Qe(this,"loadHistoryPromise",null);Qe(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??Yr))}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],p=d.length>Wl?d.slice(d.length-Wl):d;this.snapshot={...this.snapshot,historyMessages:p,historyOffset:this.snapshot.historyOffset+i.length,hasMoreHistory:c?!0:o.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}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:eg}))}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=Ul(t,"sessionId");if(r&&r!==this.sessionId)return;const n=Ul(t,"historySessionId");if(n&&this.historySessionId&&n!==this.historySessionId)return;const a=lg(t),o=t.messageSource;if(og(this.snapshot,this.fallbackRecentCount,a,t.status,o)||ig(this.snapshot,this.fallbackRecentCount,a,o))return;const i={tailLimit:this.snapshot.cursor.tailLimit};Kl(this.snapshot.liveMessages)===Kl(a)&&this.snapshot.cursor.tailLimit===i.tailLimit||(this.snapshot={...this.snapshot,liveMessages:a,hasLiveSnapshot:!0,cursor:i,messageSource:o},this.emit())}}function hu(e){const t=Ni(e.daemonId,e.sessionId,e.historySessionId),r=Oo.get(t);if(r)return r.updateOptions(e),r;const n=new cg(e);return Oo.set(t,n),n}function dg(e,t,r){if(!e||!t)return;const n=`${e}::${t}::`,a=Ni(e,t,r);for(const[o,i]of Oo.entries())(o===a||o.startsWith(n))&&i.clearLiveSnapshot()}function ug(e,t){return{...e,loadHistoryPage:t}}function pg(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function mg(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(tg.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??ki)),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 hg(e=ki){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function fg(e,t={}){const r=new Set,n=[];for(const a of e){if(!mg(a,t))continue;const o=Gr(a),i=a.sessionId||"";if(!o||!i)continue;const c=qr(a),d=Ni(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(pg),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function xg(e,t){const{sendData:r,sendCommand:n}=mt(),a=(t==null?void 0:t.enabled)!==!1,o=Gr(e),i=e.sessionId||"",c=qr(e)||i,d=`daemon:${o}:session:${i}`,p=Math.max(0,(t==null?void 0:t.tailLimit)??Yr),m=e.messages.length,u=l.useMemo(()=>!a||!o||!i?null:hu({daemonId:o,sessionId:i,historySessionId:c,subscriptionKey:d,sendData:r,tailLimit:p,fallbackRecentCount:m}),[o,a,c,r,i,d,p]);l.useEffect(()=>{u==null||u.updateOptions({fallbackRecentCount:m})},[u,m]);const[h,b]=l.useState(()=>(u==null?void 0:u.getSnapshot())||Zn(p));l.useEffect(()=>{if(!u){b(Zn(p));return}u.retain(),b(u.getSnapshot());const f=u.subscribe(w=>{b(w)});return()=>{f(),u.release()}},[u,p]);const y=l.useCallback(async()=>{!u||!o||!i||await u.loadHistoryPage(async({offset:f,excludeRecentCount:w})=>{const j=e.agentType,g=await n(o,"chat_history",{agentType:j,offset:f,limit:30,targetSessionId:i,historySessionId:c,excludeRecentCount:w}),v=g&&typeof g=="object"&&"result"in g?g.result||{}:g||{};return{messages:Array.isArray(v.messages)?v.messages:[],hasMore:v.hasMore===!0}})},[e.agentType,u,o,c,n,i]);return l.useMemo(()=>ug(h,y),[y,h])}function bg(e,t){const{sendData:r}=mt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??Yr),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??ki)),i=hg(o),[c,d]=l.useState(0);l.useEffect(()=>{if(!n||e.length===0)return;const m=setInterval(()=>{d(u=>u+1)},i);return()=>{clearInterval(m)}},[e.length,n,i]);const p=l.useMemo(()=>fg(e,{recentActivityMs:o}),[e,o,c]);l.useEffect(()=>{if(!n||!r||p.descriptors.length===0)return;const m=p.descriptors.map(u=>hu({...u,sendData:r,tailLimit:a}));return m.forEach(u=>{u.retain()}),()=>{m.forEach(u=>u.release())}},[p.signature,n,r,a])}function gg(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function Gl(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 yg(e,t){if(e.length===0)return[];if(t.some(Gl))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||!Gl(o))continue;const i=String(o.role||"").toLowerCase();n.has(i)||(n.add(i),r.unshift(o))}return r}function vg(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=yg(o,i),d=c.length>0?[...c,...i]:i;return t.length===0?d:[...t,...d]}function wg(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function jg(e){return wg(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Pn=new Map,zo=new Set;function Vl(e,t){!e||Pn.get(e)===t||(t?Pn.set(e,!0):Pn.delete(e),zo.forEach(n=>n(e,t)))}function kg(e){return e?Pn.get(e)===!0:!1}function Ng(e){return zo.add(e),()=>{zo.delete(e)}}function Sg(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function Cg(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function Ig(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function fu(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function xu(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 Mg(e){return fu(e)?!1:e.inboxBucket==="task_complete"&&xu(e).length>0}function ql(e){return e.branch||"detached HEAD"}function Ag(e){if(e.error)return`${ql(e)} · Git error: ${e.error}`;const t=[ql(e)];return e.changedFiles>0?t.push(Sg(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 Tg(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${Ag(t)}`}function _g(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function Rg(e,t={}){if(t.enabled===!1)return[];if(!Ig(e))return[];const r=fu(e)?"working":Mg(e)?"complete":null;if(!r)return[];const n=r==="complete"?xu(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${Cg(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:Tg(r,e.git),timestamp:_g(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 Lg=60;function Pg(e){return e.status==="long_generating"?"Agent has been generating for a long time. Send queues your message; Force sends it immediately.":e.status==="generating"||e.status==="streaming"?"Agent is generating. Send queues your message; Force sends it immediately.":e.status==="waiting_approval"&&(!e.modalButtons||e.modalButtons.length===0)?"Agent is waiting for approval. Approval controls will appear when available.":null}function Wo({activeConv:e,ideEntry:t,handleSendChat:r,handleForceSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:d,userName:p,scrollToBottomRequestNonce:m,isInputActive:u=!0,isVisible:h=!0}){var re,je,ce,U,W,Y,se;const b=l.useRef(new Map),y=l.useRef(void 0),f=Vr(),{sendCommand:w}=mt(),{isVisible:j}=ui();Ur("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:d.length,isSendingChat:a});const g=St.useMemo(()=>nr(e),[e.status,e.connectionState]);St.useEffect(()=>{const ie=e.sessionId;if(ie)return Vl(ie,g.isGenerating),()=>{Vl(ie,!1)}},[e.sessionId,g.isGenerating]);const v=l.useMemo(()=>Sb(e,t),[e,t]),k=l.useMemo(()=>{var ie;return hi((ie=v.targetEntry)==null?void 0:ie.providerControls,{hostIdeType:e.hostIdeType,providerType:v.providerType})},[e.hostIdeType,v.providerType,(re=v.targetEntry)==null?void 0:re.providerControls]),N=uu({isCliLike:v.isCli||v.isAcp}),x=Xb({isCliLike:v.isCli||v.isAcp}),C=xg(e,{enabled:h&&!!e.sessionId,tailLimit:x}),[S,I]=l.useState(N),[P,L]=l.useState(()=>fl()),A=e.tabKey,R=C.historyMessages,$=C.hasMoreHistory,X=C.historyError,T=gg(e,C),M=_d(T).length;l.useEffect(()=>{I(N)},[N,A]);const _=Math.max(0,T.length-S),B=vi(e),E=Gr(e),F=jg(e),K=wi(e),z=Pg(e),ne=o||K||z,q=!!K,[J,xe]=l.useState(!1);l.useEffect(()=>{const ie=v.targetEntry;E&&(!ie||ie.providerControls===void 0||ie.controlValues===void 0)&&f(E,{minFreshMs:3e4}).catch(()=>{})},[E,v.isAcp,(je=v.targetEntry)==null?void 0:je.providerControls,(ce=v.targetEntry)==null?void 0:ce.controlValues,f]);const ue=l.useCallback(async()=>{if(!J){if(T.length>S){I(ie=>Math.min(T.length,ie+Lg));return}xe(!0);try{await C.loadHistoryPage()}finally{xe(!1)}}},[C,J,T.length,S]),{allMessages:O,receivedAtMap:H}=l.useMemo(()=>{const ie=vg({historyMessages:R,liveMessages:T,visibleLiveCount:S}),ae=Rg(e),D=ae.length>0?[...ie,...ae]:ie,oe={};return D.forEach((ge,pe)=>{const te=`${e.tabKey}:${Vn(ge,pe)}`;let Me=qb(ge)||b.current.get(te)||0;Me||(Me=Date.now(),b.current.set(te,Me)),oe[Vn(ge,pe)]=Me}),{allMessages:D,receivedAtMap:oe}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,_,R,T,S]),ve=l.useMemo(()=>d.filter(ie=>ie.routeId===e.tabKey).sort((ie,ae)=>ie.timestamp-ae.timestamp),[d,e.tabKey]),we=l.useCallback(async()=>{var pe,te;if(!E)return;const ie=iu({activeConv:e,visibleMessages:O,actionLogs:d,controls:(pe=v.targetEntry)==null?void 0:pe.providerControls,controlValues:(te=v.targetEntry)==null?void 0:te.controlValues,visibleBarControlCount:k.length,chatTailState:{liveMessages:C.liveMessages,hasLiveSnapshot:C.hasLiveSnapshot,hasMoreHistory:$,historyError:X,historyMessages:R},ui:{controlsVisible:j,visibleLiveCount:S,activityVisible:P,activityCount:M,hiddenLiveCount:_,isInputActive:u,isVisible:h}}),ae=await w(E,"get_chat_debug_bundle",{agentType:v.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:ie}),D=Mr(ae),oe=du(D),ge=await cu(oe);ge==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),it.showToast(lu(D,{locatorCopyStatus:ge}),ge==="failed"?"warning":"success")},[e,d,M,O,j,C.hasLiveSnapshot,C.liveMessages,v.providerType,(U=v.targetEntry)==null?void 0:U.controlValues,(W=v.targetEntry)==null?void 0:W.providerControls,E,$,_,R,u,h,X,w,P,k.length,S]);l.useEffect(()=>{const ie=ae=>{ae.key===Ad&&L(fl())};return window.addEventListener("storage",ie),()=>window.removeEventListener("storage",ie)},[]);const be=l.useCallback(()=>{const ie=Rb(y.current);y.current=ie.state,ie.shouldCollect&&we().catch(ae=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",ae),it.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[we]),Ne=l.useMemo(()=>{if(T.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((g.isGenerating||e.status==="streaming")&&xe(!1),e.status==="not_monitored"&&F)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Qs,{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(Js,{size:14})," Open ",B," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&F)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Nd,{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(Js,{size:14})," Open ",B," 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"&&!J)return!$&&R.length===0?s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"No messages yet"})]}):s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,F,i,$,R.length,c,J,T.length,B,g.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(Tf,{messages:O,actionLogs:ve,agentName:Zs(e)||B||"Agent",userName:p,isCliMode:v.isCli||v.isAcp,isWorking:g.isGenerating,contextKey:e.tabKey,receivedAtMap:H,lastMessageHash:e.lastMessageHash,showActivityMessages:P,onLoadMore:ue,isLoadingMore:J,hasMoreHistory:$,hiddenLiveCount:_,loadError:X??void 0,emptyState:Ne,scrollToBottomRequestNonce:m,isVisible:h}),s.jsx(Ex,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:v.providerType,displayLabel:v.displayLabel,controls:(Y=v.targetEntry)==null?void 0:Y.providerControls,controlValues:(se=v.targetEntry)==null?void 0:se.controlValues,isActive:u,isCliTerminal:v.isCliTerminal}),!v.isCliTerminal&&s.jsx(Jd,{contextKey:e.tabKey,panelLabel:B,isSending:a,isBusy:q,statusMessage:ne,onSend:r,onForceSend:n,canForceSend:!!n&&g.isGenerating&&!q,isActive:u,showControlsToggle:k.length>0,onControlsToggle:be,messageInput:e.messageInput})]})}let bu=ss;function gu(){return bu()}class Dg{constructor(){Qe(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 yu=new Dg;class $g{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 xt=new $g;function Eg(e){e.dashboardWS&&(yu=e.dashboardWS),e.connectionManager&&(xt=e.connectionManager),e.useDaemonsHook&&(bu=e.useDaemonsHook)}const Bg=.5,Fg=1.25;function pt(e){return vi(e)}function _s(e){return nu(e).join(" · ")}function Og(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 Hg(e){var i,c,d;const t=[],r=typeof((i=e.settings)==null?void 0:i.meshNodeFor)=="string"?e.settings.meshNodeFor.trim():"",n=typeof((c=e.coordinator)==null?void 0:c.meshId)=="string"?e.coordinator.meshId.trim():"",a=typeof((d=e.settings)==null?void 0:d.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor.trim():"",o=n||a;if(r&&t.push(`Mesh node: ${r}`),o&&t.push(`Coordinator: ${o}`),e.meshQueueStats){const{pending:p,assigned:m,completed:u,failed:h}=e.meshQueueStats;t.push(`Queue: ${p} pending, ${m} assigned, ${u} completed, ${h} failed`)}return t.join(" · ")}function vu(e){const t=ru(e);return t||(e.title?e.title:_s(e)||"No messages yet")}function wu(e,t){const{isReconnecting:r,isConnecting:n}=nr(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function zg(e,t){const r=["Chat",...nu(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function Ss(e){return wu(e)||_s(e)}function Wg(e){return`${pt(e)} · ${vu(e)}`}function Kg(e){const t=Xn(e),r=t?It(t):Zs(e);return`${pt(e)} — ${r||"Agent"}`}function Ug(e){return Zs(e)||"CLI"}function ju(e){return su(e)}function ku(e){return e?`Remote · ${pt(e)||e.workspaceName||"Session"}`:"Remote"}const Yl=[{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:""}})}],Gg=[{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 Vg(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 Si({cond:e,path:t,sections:r,onChange:n,onRemove:a,onPreview:o,preview:i}){const c=Vg(e),d=i[t],p=m=>{const u=Yl.find(h=>h.kind===m);u&&n(u.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:m=>p(m.target.value),className:"bg-zinc-900 text-zinc-200 text-[10px] font-mono rounded border border-zinc-700 px-1 py-0.5",children:Yl.map(m=>s.jsx("option",{value:m.kind,children:m.label},m.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:m=>n({...e,section:m.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(m=>s.jsx("option",{value:m,children:m},m))]}),s.jsx("input",{value:e.matches??"",onChange:m=>n({...e,matches:m.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(ms,{label:"elapsed_ms",value:e.elapsed_ms,onChange:m=>n({elapsed_ms:m})}),c==="stable"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ms,{label:"stable_ms",value:e.stable_ms,onChange:m=>n({...e,stable_ms:m})}),s.jsx(ms,{label:"cursor_above",value:e.cursor_above??0,onChange:m=>n({...e,cursor_above:m||void 0})})]}),c==="changed"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ms,{label:"cursor_above",value:e.cursor_above,onChange:m=>n({...e,cursor_above:m})}),s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-zinc-400",children:[s.jsx("input",{type:"checkbox",checked:!!e.changed,onChange:m=>n({...e,changed:m.target.checked}),className:"accent-sky-500"}),"changed"]})]}),(c==="all"||c==="any")&&s.jsx(qg,{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(Si,{cond:e.not,path:`${t}.not`,sections:r,onChange:m=>n({not:m}),onPreview:o,preview:i})})]})}function qg({kind:e,cond:t,path:r,sections:n,onChange:a,onPreview:o,preview:i}){const c=(e==="all"?t.all:t.any)??[],d=p=>a(e==="all"?{all:p}:{any:p});return s.jsxs("div",{className:"pl-2 border-l border-zinc-700 space-y-1",children:[c.map((p,m)=>s.jsx(Si,{cond:p,path:`${r}.${e}[${m}]`,sections:n,onChange:u=>d(c.map((h,b)=>b===m?u:h)),onRemove:()=>d(c.filter((u,h)=>h!==m)),onPreview:o,preview:i},m)),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"}),Gg.map(p=>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(p.cond))]),title:"insert verified pattern",children:["+ ",p.label]},p.label))]})]})}function ms({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 Yg({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(u=>[u.id,u])):{},c=(u,h)=>{if(!h||h===u||e[h])return;const b={};for(const[y,f]of Object.entries(e))b[y===u?h:y]=f;r(b)},d=(u,h)=>r({...e,[u]:h}),p=u=>{const h={...e};delete h[u],r(h)},m=()=>{let u="section",h=1;for(;e[u];)u=`section${h++}`;r({...e,[u]:{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:m,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(u=>{var f;const h=e[u],b=h.anchor!=null?"anchor":"positional",y=w=>{w==="anchor"?d(u,{anchor:h.anchor??"^",anchor_last:h.anchor_last,until:h.until}):d(u,{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:u,onChange:w=>c(u,w.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:()=>y("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:()=>y("anchor"),children:"anchor"})]}),s.jsx("button",{type:"button",className:"ml-auto text-zinc-500 hover:text-red-300 text-sm px-1",onClick:()=>p(u),children:"×"})]}),b==="positional"?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx(ms,{label:"from_top",value:typeof h.from_top=="number"?h.from_top:0,onChange:w=>d(u,{...h,from_top:w,from_bottom:void 0})}),s.jsx(ms,{label:"from_bottom",value:typeof h.from_bottom=="number"?h.from_bottom:0,onChange:w=>d(u,{...h,from_bottom:w||void 0})}),s.jsx(Jl,{def:h,otherIds:t(u),onChange:w=>d(u,w)})]}):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:w=>d(u,{...h,anchor:w.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:w=>d(u,{...h,anchor_last:w.target.checked||void 0}),className:"accent-sky-500"}),"last"]})]}),s.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s.jsx(Jl,{def:h,otherIds:t(u),onChange:w=>d(u,w)})}),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:w=>d(u,{...h,anchor_context:{...h.anchor_context,next:w.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[u]&&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[u].fromLine,"–",i[u].toLine,i[u].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[u].text||"(empty)"})]})]},u)})})]})}function Jl({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 Jg({model:e,onChange:t,onPreview:r,preview:n,onTestSections:a,sectionPreview:o}){const i=e.states.map(u=>u.id),c=Object.keys(e.sections??{}),d=l.useCallback(u=>t({...e,...u}),[e,t]),p=(u,h)=>d({states:e.states.map((b,y)=>y===u?{...b,...h}:b)}),m=(u,h)=>d({transitions:e.transitions.map((b,y)=>y===u?{...b,...h}:b)});return s.jsxs("div",{className:"space-y-3",children:[s.jsx(Yg,{sections:e.sections??{},otherSectionIds:u=>c.filter(h=>h!==u),onChange:u=>d({sections:u}),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((u,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:u.id,onChange:b=>p(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:u.label,onChange:b=>p(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,y)=>y!==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:!!u.initial,onChange:()=>d({states:e.states.map((b,y)=>({...b,initial:y===h}))}),className:"accent-sky-500"}),"initial"]}),s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"checkbox",checked:!!u.modal,onChange:b=>p(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:u.status??"",onChange:b=>p(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((u,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(Xg,{value:u.from,states:i,onChange:b=>m(h,{from:b})}),s.jsx("span",{className:"text-[10px] text-zinc-500",children:"→"}),s.jsx("select",{value:u.to,onChange:b=>m(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:u.label??"",onChange:b=>m(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,y)=>y!==h)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(ms,{label:"min_hold_ms",value:u.min_hold_ms??0,onChange:b=>m(h,{min_hold_ms:b||void 0})}),s.jsx(ms,{label:"priority",value:u.priority??0,onChange:b=>m(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"}),!u.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:()=>m(h,{when:{section:c[0],matches:""}}),children:"+ guard condition"}),u.when&&s.jsx("button",{type:"button",className:"text-[10px] text-zinc-500 hover:text-red-300",onClick:()=>m(h,{when:void 0}),children:"remove guard"})]}),u.when&&s.jsx(Si,{cond:u.when,path:`t${h}`,sections:c,onChange:b=>m(h,{when:b}),onPreview:r,preview:n})]})]},h))})]})]})}function Xg({value:e,states:t,onChange:r}){const n=new Set(Array.isArray(e)?e:e==="*"?t:[e]),a=e==="*",o=i=>{const c=new Set(n);c.has(i)?c.delete(i):c.add(i);const d=t.filter(p=>c.has(p));r(d.length===1?d[0]:d)};return s.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.map(i=>s.jsx("button",{type:"button",onClick:()=>o(i),className:`font-mono text-[10px] px-1 py-0.5 rounded border ${a||n.has(i)?"text-sky-200 bg-sky-600/25 border-sky-500/40":"text-zinc-500 border-zinc-700 hover:border-zinc-500"}`,children:i},i))})}function hr(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 Xl(e){return e<=0?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}const Qg={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"},Zg={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 Zg[e]??"text-zinc-200 bg-zinc-600/20 border border-zinc-500/30"}function xn({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 bn(){return s.jsx("div",{className:"border-t border-white/8 my-2"})}function Nu({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(Nu,{node:o,depth:t+1},i))]})}function e0({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(Nu,{node:e.cond})})]})}function t0({activeConv:e,onClose:t}){var be,Ne,re,je,ce;const{sendCommand:r}=mt(),[n,a]=l.useState(!0),[o,i]=l.useState(null),[c,d]=l.useState(null),[p,m]=l.useState(!1),[u,h]=l.useState(new Set(["footer"])),[b,y]=l.useState("Snapshot"),[f,w]=l.useState(!1),[j,g]=l.useState(null),[v,k]=l.useState(!1),[N,x]=l.useState(""),[C,S]=l.useState(!1),[I,P]=l.useState("idle"),[L,A]=l.useState(null),[R,$]=l.useState([]),[X,T]=l.useState({}),[M,_]=l.useState(null),[B,E]=l.useState(!1),F=e.daemonId||((be=e.routeId)==null?void 0:be.split(":")[0])||e.routeId||"",K=e.sessionId||"",z=l.useCallback(async()=>{a(!0),d(null);try{const U=await r(F,"get_spec_debug",{targetSessionId:K}),W=U&&typeof U=="object"?U:{},Y=W.result&&typeof W.result=="object"?W.result:W;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,F,K]);l.useEffect(()=>{z()},[z]),l.useEffect(()=>{if(!B)return;const U=setInterval(()=>{z()},1e3);return()=>clearInterval(U)},[B,z]),l.useEffect(()=>{const U=W=>{W.key==="Escape"&&!f&&t()};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[t,f]);const ne=l.useCallback(async U=>{try{const W=await r(F,"validate_spec",{content:JSON.stringify(U)}),Y=W&&typeof W=="object"?W:{},se=Y.result&&typeof Y.result=="object"?Y.result:Y;$(se!=null&&se.valid?[]:(se==null?void 0:se.errors)??["validation failed"])}catch(W){$([(W==null?void 0:W.message)||String(W)])}},[r,F]),q=l.useCallback(async()=>{A(null),P("idle"),T({});try{const U=await r(F,"get_spec_source",{targetSessionId:K}),W=U&&typeof U=="object"?U:{},Y=W.result&&typeof W.result=="object"?W.result:W;if(!(Y!=null&&Y.success)||typeof Y.content!="string"){A((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"?(g(se),k(!1),ne(se)):(g(null),k(!0)),S(!1),w(!0)}catch(U){A((U==null?void 0:U.message)||String(U))}},[r,F,K,ne]),J=l.useCallback(U=>{g(U),x(JSON.stringify(U,null,2)),S(!0),P("idle"),ne(U)},[ne]),xe=l.useCallback(async(U,W)=>{T(Y=>({...Y,[U]:"loading"}));try{const Y=await r(F,"eval_condition_preview",{targetSessionId:K,condition:W}),se=Y&&typeof Y=="object"?Y:{},ie=se.result&&typeof se.result=="object"?se.result:se;!(ie!=null&&ie.success)||!ie.result?T(ae=>({...ae,[U]:{result:!1,detail:ie==null?void 0:ie.error}})):T(ae=>({...ae,[U]:{result:ie.result.result,detail:ie.result.detail}}))}catch(Y){T(se=>({...se,[U]:{result:!1,detail:Y==null?void 0:Y.message}}))}},[r,F,K]),ue=l.useCallback(async U=>{_("loading");try{const W=await r(F,"resolve_section_preview",{targetSessionId:K,sections:U}),Y=W&&typeof W=="object"?W:{},se=Y.result&&typeof Y.result=="object"?Y.result:Y;!(se!=null&&se.success)||!Array.isArray(se.sections)?_({error:(se==null?void 0:se.error)||"resolve failed"}):_({sections:se.sections,screenLineCount:se.screenLineCount??0})}catch(W){_({error:(W==null?void 0:W.message)||String(W)})}},[r,F,K]),O=l.useCallback(async()=>{var Y,se;const U=(Y=o==null?void 0:o.snapshot)==null?void 0:Y.specPath;if(!U){A("No spec path on this session");return}if(!v&&R.length>0){A("Fix validation errors before saving");return}const W=!v&&j?JSON.stringify(j,null,2):N;P("saving"),A(null);try{const ie=await r(F,"write_spec_source",{specPath:U,content:W}),ae=ie&&typeof ie=="object"?ie:{},D=ae.result&&typeof ae.result=="object"?ae.result:ae;if(!(D!=null&&D.success)){P("error"),A(((se=D==null?void 0:D.validationErrors)==null?void 0:se.join(`
|
|
42
|
+
`))||(D==null?void 0:D.error)||"Save failed");return}P("saved"),S(!1),setTimeout(()=>{z()},400),setTimeout(()=>P("idle"),1500)}catch(ie){P("error"),A((ie==null?void 0:ie.message)||String(ie))}},[r,F,(Ne=o==null?void 0:o.snapshot)==null?void 0:Ne.specPath,N,j,v,R,z]),H=o==null?void 0:o.snapshot,ve=async()=>{var D,oe,ge;let U=o;U||(await z(),U=o);const W=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: ${(W==null?void 0:W.spec_id)??""} (${(W==null?void 0:W.specPath)??""})`),Y.push(`Provider: ${(W==null?void 0:W.name)??""} (${(W==null?void 0:W.cliType)??""})`),Y.push(`Working dir: ${(W==null?void 0:W.workingDir)??""}`),Y.push(`Spawned: ${W!=null&&W.spawnedAtMs?new Date(W.spawnedAtMs).toISOString():""}`),Y.push(""),Y.push("## Current State"),Y.push(`State: ${((D=W==null?void 0:W.current_state)==null?void 0:D.id)??"none"} (${((oe=W==null?void 0:W.current_state)==null?void 0:oe.label)??""})`),Y.push(`Status: ${(W==null?void 0:W.status)??""}`),Y.push(`Idle hold pending: ${(W==null?void 0:W.idleHoldPending)??!1}`),Y.push(`Exited: ${(W==null?void 0:W.exited)??!1}`),Y.push(`Last busy: ${W!=null&&W.lastBusyAt?hr(W.lastBusyAt):""}`),Y.push(`Cursor: ${(W==null?void 0:W.cursorPosition)!=null?`(${W.cursorPosition.row},${W.cursorPosition.col})`:"n/a"}`),(ge=W==null?void 0:W.completionIdleDebounce)!=null&&ge.active){const pe=W.completionIdleDebounce;Y.push(`completion_idle_after: age=${pe.ageMs}ms hold=${pe.holdMs}ms force=${pe.forceAfterMs}ms remaining=${Math.max(0,pe.holdMs-pe.ageMs)}ms`)}if(Y.push(""),Y.push("## Modal"),W!=null&&W.current_modal){const pe=W.current_modal.buttons.map(te=>te.label).join(" / ");Y.push(`${W.current_modal.title??""} [${pe}]`)}else Y.push("none");Y.push(""),Y.push("## State History (last 20)");const se=W!=null&&W.stateHistory?[...W.stateHistory].reverse().slice(0,20):[];for(const pe of se){const te=pe.reason!=null?typeof pe.reason=="string"?pe.reason:JSON.stringify(pe.reason):"",Me=pe.debounceKind!=null?typeof pe.debounceKind=="string"?pe.debounceKind:JSON.stringify(pe.debounceKind):"",_e=pe.matchedStateId!=null?String(pe.matchedStateId):"",Ce=(pe.matchedRules??[]).map(Ke=>typeof Ke=="string"?Ke:JSON.stringify(Ke)).join(", ");Y.push(`- ${pe.stateId} @ ${new Date(pe.at).toISOString()} held ${pe.durationMs}ms | reason: ${te} | debounce: ${Me} | eval→${_e} | rules: ${Ce}`)}if(Y.push(""),Y.push("## Sections"),W!=null&&W.sections)for(const[pe,te]of Object.entries(W.sections)){const Me=te.split(`
|
|
43
|
+
`).slice(0,3).join(`
|
|
44
|
+
`);Y.push(`${pe}: ${Me}`)}Y.push(""),Y.push("## Last Assistant Message");const ae=[...(W==null?void 0:W.messages)??(W==null?void 0:W.committedMessages)??[]].reverse().find(pe=>pe.role==="assistant");Y.push(ae?ae.content.slice(0,400):""),Y.push(""),Y.push("## Screen (first 50 lines)"),Y.push(W!=null&&W.screen?W.screen.split(`
|
|
45
|
+
`).slice(0,50).join(`
|
|
46
|
+
`):"");try{await navigator.clipboard.writeText(Y.join(`
|
|
47
|
+
`)),y("Copied!"),setTimeout(()=>y("Snapshot"),1500)}catch(pe){console.error("[SpecDebugPanel] clipboard write failed",pe)}},we=U=>{h(W=>{const Y=new Set(W);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"}),H&&s.jsx("span",{className:"text-[11px] text-zinc-400 font-mono bg-zinc-800 px-1.5 py-0.5 rounded truncate",children:H.spec_id})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(H==null?void 0:H.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?w(!1):q()},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:()=>{z()},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 ${v?"text-zinc-400 hover:bg-zinc-700/40":"bg-sky-600/30 text-sky-100"}`,onClick:()=>{if(v)try{const U=JSON.parse(N);g(U),ne(U)}catch{return}k(!1)},disabled:!j&&v,children:"Form"}),s.jsx("button",{type:"button",className:`px-2 py-0.5 ${v?"bg-sky-600/30 text-sky-100":"text-zinc-400 hover:bg-zinc-700/40"}`,onClick:()=>{j&&x(JSON.stringify(j,null,2)),k(!0)},children:"JSON"})]}),s.jsx("span",{className:"text-[10px] text-zinc-500 font-mono truncate flex-1",title:H==null?void 0:H.specPath,children:((H==null?void 0:H.specPath)??"").split("/").slice(-3).join("/")}),C&&s.jsx("span",{className:"text-amber-300 text-[10px]",children:"unsaved"}),!v&&R.length>0&&s.jsxs("span",{className:"text-red-300 text-[10px]",children:[R.length," error",R.length>1?"s":""]}),s.jsx("button",{type:"button",className:`text-[11px] px-2.5 py-1 rounded border transition-colors ${I==="saving"||!v&&R.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:()=>{O()},disabled:I==="saving"||!v&&R.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}),!v&&R.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:R.map((U,W)=>s.jsx("div",{className:"font-mono",children:U},W))}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:v||!j?s.jsx("textarea",{value:N,onChange:U=>{x(U.target.value),S(!0),P("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(Jg,{model:j,onChange:J,onPreview:xe,preview:X,onTestSections:ue,sectionPreview:M})}),s.jsx("div",{className:"text-[10px] text-zinc-500 shrink-0",children:v?"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",")."]}),H&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-[11px] bg-zinc-800/60 rounded-md px-3 py-2 border border-zinc-700/50",children:[H.name&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Provider"}),s.jsxs("span",{className:"font-mono text-zinc-200",children:[H.name," ",s.jsxs("span",{className:"text-zinc-500",children:["(",H.cliType,")"]})]})]}),H.workingDir&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Dir"}),s.jsx("span",{className:"font-mono text-zinc-300 truncate",title:H.workingDir,children:H.workingDir})]}),H.spawnedAtMs?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Spawned"}),s.jsx("span",{className:"text-zinc-400",children:hr(H.spawnedAtMs)})]}):null,H.providerSessionId&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-zinc-500",children:"Session"}),s.jsx("span",{className:"font-mono text-zinc-500 text-[10px] truncate",title:H.providerSessionId,children:H.providerSessionId})]})]}),s.jsxs("div",{className:"flex items-center gap-2 flex-wrap bg-zinc-800/40 rounded-md px-3 py-2 border border-zinc-700/50",children:[s.jsx("span",{className:`font-semibold font-mono text-[12px] px-2 py-0.5 rounded ${H.current_state?Wa(H.current_state.id):"text-zinc-500"}`,children:H.current_state?H.current_state.id:"none"}),((re=H.current_state)==null?void 0:re.label)&&H.current_state.label!==H.current_state.id&&s.jsx("span",{className:"text-zinc-400 text-[11px]",children:H.current_state.label}),H.status&&H.status!==((je=H.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(H.status)} px-1 py-0.5 rounded text-[10px]`,children:H.status})]}),H.idleHoldPending&&s.jsx("span",{className:"text-yellow-200 text-[10px] bg-yellow-600/25 border border-yellow-500/35 px-1.5 py-0.5 rounded font-mono",children:"idle hold pending"}),H.exited&&s.jsx("span",{className:"text-red-200 text-[10px] bg-red-600/25 border border-red-500/35 px-1.5 py-0.5 rounded font-mono",children:"exited"}),H.cursorPosition!=null&&s.jsxs("span",{className:"text-zinc-500 text-[11px] font-mono",children:["cursor: ",s.jsxs("span",{className:"text-zinc-300",children:[H.cursorPosition.row,",",H.cursorPosition.col]})]}),H.lastBusyAt>0&&s.jsxs("span",{className:"text-zinc-500 text-[11px] ml-auto",children:["last busy: ",s.jsx("span",{className:"text-zinc-400",children:hr(H.lastBusyAt)})]})]}),((ce=H.completionIdleDebounce)==null?void 0:ce.active)&&s.jsxs("div",{className:"flex items-center gap-2 text-[11px] bg-sky-900/20 border border-sky-700/30 rounded-md px-3 py-1.5 font-mono",children:[s.jsx("span",{className:"text-sky-400",children:"completion_idle_after"}),s.jsxs("span",{className:"text-zinc-400",children:["age: ",s.jsxs("span",{className:"text-sky-200",children:[H.completionIdleDebounce.ageMs,"ms"]})]}),s.jsx("span",{className:"text-zinc-500",children:"/"}),s.jsxs("span",{className:"text-zinc-400",children:["hold: ",s.jsxs("span",{className:"text-zinc-300",children:[H.completionIdleDebounce.holdMs,"ms"]})]}),s.jsxs("span",{className:"text-zinc-400",children:["force: ",s.jsxs("span",{className:"text-zinc-300",children:[H.completionIdleDebounce.forceAfterMs,"ms"]})]}),s.jsx("span",{className:"text-zinc-500 ml-auto",children:H.completionIdleDebounce.ageMs<H.completionIdleDebounce.holdMs?s.jsxs("span",{className:"text-amber-300",children:["hold remaining: ",H.completionIdleDebounce.holdMs-H.completionIdleDebounce.ageMs,"ms"]}):H.completionIdleDebounce.ageMs<H.completionIdleDebounce.forceAfterMs?s.jsxs("span",{className:"text-orange-300",children:["force in: ",H.completionIdleDebounce.forceAfterMs-H.completionIdleDebounce.ageMs,"ms"]}):s.jsx("span",{className:"text-red-300",children:"overdue"})})]}),H.current_modal&&s.jsxs("div",{className:"bg-orange-900/30 border border-orange-600/40 rounded-md p-2.5",children:[s.jsx("span",{className:"text-orange-200 font-semibold",children:"Modal: "}),s.jsx("span",{className:"text-zinc-300",children:H.current_modal.title||""}),H.current_modal.buttons.length>0&&s.jsxs("span",{className:"text-zinc-400 ml-2",children:["[",H.current_modal.buttons.map(U=>U.label).join(" / "),"]"]})]}),H.fsm&&s.jsxs(s.Fragment,{children:[s.jsx(bn,{}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsxs(xn,{children:["FSM — outgoing from ",s.jsx("span",{className:"text-sky-300 font-mono normal-case",children:H.fsm.currentState})," (held ",Xl(H.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:B,onChange:U=>E(U.target.checked),className:"accent-sky-500"}),"live"]})]}),s.jsxs("div",{className:"space-y-1",children:[H.fsm.transitions.length===0&&s.jsx("div",{className:"text-zinc-600 text-[11px] italic px-1",children:"no outgoing transitions (terminal state)"}),H.fsm.transitions.map((U,W)=>s.jsx(e0,{t:U},W))]})]})]}),s.jsx(bn,{}),H.sections&&Object.keys(H.sections).length>0&&s.jsxs("div",{children:[s.jsx(xn,{children:"Sections"}),s.jsx("div",{className:"space-y-1",children:Object.entries(H.sections).map(([U,W])=>{var ae;const Y=u.has(U),se=W.split(`
|
|
48
|
+
`),ie=((ae=se[0])==null?void 0:ae.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:ie}),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:W||"(empty)"})]},U)})})]}),s.jsx(bn,{}),H.stateHistory&&H.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs(xn,{children:["State History (",H.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...H.stateHistory].reverse().slice(0,20).map((U,W)=>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:hr(U.at)}),U.durationMs>0&&s.jsxs("span",{className:"text-zinc-500 text-[11px]",children:["held ",s.jsx("span",{className:"text-zinc-400",children:Xl(U.durationMs)})]}),U.reason&&s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${Qg[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"]})]})]},W))})]}),s.jsx(bn,{}),(()=>{const U=H.messages??H.committedMessages??[];if(U.length===0)return null;const W=U.filter(ie=>ie.role==="user").length,Y=U.filter(ie=>ie.role==="assistant").length,se=[...U].reverse().find(ie=>ie.role==="assistant");return s.jsxs("div",{children:[s.jsxs(xn,{children:["Transcript (",U.length," — ",W,"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?hr(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?"…":""]})]})]})})(),H.specPath&&s.jsx("div",{className:"text-[10px] text-zinc-600 font-mono truncate border-t border-zinc-800 pt-2 mt-1",title:H.specPath,children:H.specPath}),s.jsxs("div",{children:[s.jsxs("button",{type:"button",className:"text-[11px] text-zinc-400 hover:text-zinc-200 transition-colors flex items-center gap-1.5",onClick:()=>m(U=>!U),children:[s.jsx("span",{className:"text-zinc-600",children:p?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",H.screen?H.screen.split(`
|
|
49
|
+
`).length:0," lines)"]})]}),p&&s.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-[11px] text-zinc-300 whitespace-pre bg-black/40 rounded-md border border-zinc-700 max-h-64 overflow-auto",children:H.screen||"(empty)"})]})]})]})]})})}function s0({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(),[p,m]=l.useState(!1),u=l.useRef(!1);u.current=p;const[h,b]=l.useState("Runtime terminal unavailable"),[y,f]=l.useState(!1),[w,j]=l.useState(null),[g,v]=l.useState(!1),[k,N]=l.useState(!1),[x,C]=l.useState(1),[S,I]=l.useState(!1),[P,L]=l.useState(!1),[A,R]=l.useState({width:0,height:0}),[$,X]=l.useState({width:0,height:0}),[T,M]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[_,B]=l.useState(null),E=l.useRef(null),F=l.useRef(null),K=l.useRef(!1),z=l.useRef(!1),ne=l.useRef(i),q=l.useRef(0),J=l.useRef(!1),xe=l.useRef(""),ue=l.useRef(null),O=l.useRef(!1),H=l.useRef(!1),ve=l.useRef(null),we=l.useRef(null),be=l.useRef(null),Ne=32*1024,re=()=>{var Q,Z,fe,Ie;return((Z=(Q=E.current)==null?void 0:Q.ownerDocument)==null?void 0:Z.defaultView)||((Ie=(fe=F.current)==null?void 0:fe.ownerDocument)==null?void 0:Ie.defaultView)||window},je=Q=>{const Z=re();return{ownerWindow:Z,frameId:Z.requestAnimationFrame(Q)}},ce=()=>{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}},W=()=>{const Q=be.current;if(Q){try{Q.ownerWindow.clearTimeout(Q.timeoutId)}catch{}be.current=null}},Y=()=>{i&&ve.current===null&&(ve.current=je(()=>{Ue()}))},se=e.tabKey,ie=e.sessionId||"",ae=e.daemonId||((ke=e.routeId)==null?void 0:ke.split(":")[0])||e.routeId||"",D=wi(e),oe=p?o||D:h,ge=Bg,pe=Fg,te=.05,Me=()=>{const Q=$.width,Z=$.height;if(!Number.isFinite(A.width)||A.width<=0||!Number.isFinite(A.height)||A.height<=0||!Number.isFinite(Q)||Q<=0||!Number.isFinite(Z)||Z<=0)return 1;const fe=A.width/Q,Ie=A.height/Z;return Number(Math.min(pe,Math.max(ge,Math.min(fe,Ie))).toFixed(2))},_e=Me(),Ce=K.current&&x>_e,Ke=Number.isFinite($.width)&&$.width>0?Math.max(A.width,Math.round($.width*x)):A.width,Ze=Number.isFinite($.height)&&$.height>0?Math.max(A.height,Math.round($.height*x)):A.height,me=()=>{je(()=>{const Q=F.current;Q&&(Q.scrollLeft=0,Q.scrollTop=Q.scrollHeight-Q.clientHeight)})},De=()=>{var Q,Z;q.current=0,J.current=!1,xe.current="",ue.current=null,O.current=!1,H.current=!1,K.current||(z.current=!1,C(1)),ve.current!==null&&ce(),m(!1),b("Runtime terminal unavailable"),W(),U(),j(null),B(null),I(!1),f(!1),v(!1),N(!1),(Z=(Q=r.current)==null?void 0:Q.reset)==null||Z.call(Q)},$e=()=>{var Q,Z;q.current=0,J.current=!1,xe.current="",ue.current=null,O.current=!1,H.current=!1,ve.current!==null&&ce(),m(!0),b(""),W(),U(),j(null),B(null),I(!1),f(!1),v(!1),N(!1),(Z=(Q=r.current)==null?void 0:Q.reset)==null||Z.call(Q)},tt=()=>{H.current&&(H.current=!1,je(()=>{var Q,Z;(Z=(Q=r.current)==null?void 0:Q.scrollToTop)==null||Z.call(Q)}))},Ue=()=>{if(ve.current=null,!i)return;const Q=xe.current;if(!Q)return;const Z=Q.slice(0,Ne);xe.current=Q.slice(Z.length);const fe=r.current;if(!fe){xe.current=Z+xe.current,Y();return}fe.write(Z,()=>{if(xe.current.length>0){Y();return}tt()})},Ve=Q=>{Q&&(xe.current+=Q,Y())},Te=(Q,Z=0,fe,Ie,Pe={})=>{var Ee,He,Le,Ye;const Ae=!!Pe.force;!Ae&&Z>0&&q.current>=Z||!Ae&&Z===0&&J.current||(q.current=Z,Z>0&&v(!0),m(!0),b(""),typeof fe=="number"&&typeof Ie=="number"&&fe>0&&Ie>0&&((He=(Ee=r.current)==null?void 0:Ee.resize)==null||He.call(Ee,fe,Ie)),xe.current="",(Ye=(Le=r.current)==null?void 0:Le.reset)==null||Ye.call(Le),Q?Ve(Q):tt())};l.useEffect(()=>{De()},[ie]),l.useEffect(()=>{var Z;if(!ie)return;const Q=((Z=xt.onRuntimeEvent)==null?void 0:Z.call(xt,ie,fe=>{if(!(!fe||fe.sessionId!==ie)){if(fe.type==="runtime_snapshot"){if(!i){ue.current={text:fe.text||"",seq:fe.seq||0,cols:fe.cols,rows:fe.rows,force:!!fe.force};return}Te(fe.text||"",fe.seq||0,fe.cols,fe.rows,{force:!!fe.force});return}if(fe.type==="session_output"){J.current=!0,typeof fe.seq=="number"&&(q.current=Math.max(q.current,fe.seq),fe.seq>0&&v(!0)),u.current||m(!0),u.current||b(""),typeof fe.data=="string"&&Ve(fe.data);return}if(fe.type==="session_cleared"){if(!i){O.current=!0,xe.current="",ue.current=null;return}$e();return}if(fe.type==="session_io_error"){const Ie=typeof fe.error=="string"&&fe.error?fe.error:typeof fe.reason=="string"&&fe.reason?fe.reason:"unknown error";m(!1),b(`Runtime input failed: ${Ie}`);return}}},ae))||(()=>{});return()=>{Q()}},[ae,ie,r,i]);const ze=async(Q={})=>{var Z;if(!ae||!ie)return{success:!1,error:"daemonId and sessionId are required"};Q.preserveStatus||b(Q.loadingMessage||"Loading runtime terminal...");try{const fe=await((Z=xt.requestRuntimeSnapshot)==null?void 0:Z.call(xt,ae,ie,{sinceSeq:Q.sinceSeq,force:Q.force}));return fe&&fe.success===!1?(Q.preserveStatus||(m(!1),b(`Runtime terminal unavailable: ${fe.error}`)),fe):fe||{success:!0}}catch(fe){const Ie=(fe==null?void 0:fe.message)||String(fe);return Q.preserveStatus||(m(!1),b(`Runtime terminal unavailable: ${Ie}`)),{success:!1,error:Ie}}},ot=async Q=>{var Ae,Ee;const Z=((Ae=E.current)==null?void 0:Ae.ownerDocument)||document,fe=Z.defaultView||window,Ie=(Ee=fe.navigator)==null?void 0:Ee.clipboard;if(Ie!=null&&Ie.writeText&&fe.isSecureContext)try{return await Ie.writeText(Q),!0}catch{}let Pe=null;try{return Pe=Z.createElement("textarea"),Pe.value=Q,Pe.setAttribute("readonly","true"),Pe.style.position="fixed",Pe.style.left="-9999px",Pe.style.top="0",Z.body.appendChild(Pe),Pe.focus(),Pe.select(),Z.execCommand("copy")}catch{return!1}finally{Pe==null||Pe.remove()}},Je=Q=>{U(),B(Q);const Z=re();we.current={ownerWindow:Z,timeoutId:Z.setTimeout(()=>{we.current=null,B(fe=>fe===Q?null:fe)},2200)}},Re=Q=>{W(),j(Q);const Z=re();be.current={ownerWindow:Z,timeoutId:Z.setTimeout(()=>{be.current=null,j(fe=>fe===Q?null:fe)},2200)}},G=async()=>{var Pe,Ae,Ee,He;const Q=((Ae=(Pe=r.current)==null?void 0:Pe.getSelection)==null?void 0:Ae.call(Pe))||"",Z=((He=(Ee=r.current)==null?void 0:Ee.getVisibleText)==null?void 0:He.call(Ee))||"",fe=Q.trimEnd()||Z.trimEnd();if(!fe){Je("Nothing to copy");return}if(!await ot(fe)){Je("Copy failed");return}Je(Q.trimEnd()?"Copied selection":"Copied visible terminal")},V=Q=>{if(!p||!i)return;((d==null?void 0:d(ae,ie,Q))??!1)||Je("Terminal input failed")},ee=async()=>{if(y)return;f(!0),j("Loading older terminal output..."),H.current=!0;const Q=await ze({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:p});if(f(!1),(Q==null?void 0:Q.success)===!1){H.current=!1,j(`Older terminal output unavailable: ${Q.error}`);return}N(!0),Re("Older terminal output loaded"),je(()=>{var Z;(Z=r.current)==null||Z.bumpResize()})};l.useEffect(()=>{var Z,fe;if(!ie)return;ae&&((Z=xt.getState)==null?void 0:Z.call(xt,ae))==="connected"&&ze();const Q=(fe=xt.onStateChange)==null?void 0:fe.call(xt,(Ie,Pe)=>{Ie!==ae||Pe!=="connected"||ze()});return()=>{Q==null||Q()}},[ae,ie,r]),l.useEffect(()=>{t&&De()},[t,se,r]),l.useEffect(()=>{var Ie,Pe;const Q=E.current,Z=(Pe=(Ie=Q==null?void 0:Q.ownerDocument)==null?void 0:Ie.defaultView)==null?void 0:Pe.ResizeObserver;if(!Q||!Z)return;const fe=new Z(Ae=>{const Ee=Ae[0];if(!Ee)return;const{width:He,height:Le}=Ee.contentRect;R(Ye=>{const st=Math.round(He),ht=Math.round(Le);return Ye.width===st&&Ye.height===ht?Ye:{width:st,height:ht}})});return fe.observe(Q),()=>fe.disconnect()},[]),l.useEffect(()=>{if(K.current)return;const Q=Me();!Number.isFinite(Q)||Q<=0||C(Z=>z.current?Q<Z-te?Q:Z:(z.current=!0,Q))},[$.height,$.width,A.height,A.width]),l.useEffect(()=>{Ce&&me()},[Ce,Ze,Ke]),l.useEffect(()=>{var fe;const Q=ne.current;if(ne.current=i,!i)return;Q||N(!1),O.current&&(O.current=!1,$e());const Z=ue.current;Z&&(ue.current=null,Te(Z.text,Z.seq,Z.cols,Z.rows,{force:!!Z.force})),ae&&ie&&((fe=xt.getState)==null?void 0:fe.call(xt,ae))==="connected"&&ze(),xe.current&&ve.current===null&&Y(),je(()=>{var Ie;(Ie=r.current)==null||Ie.bumpResize()})},[ae,i,ie]),l.useEffect(()=>()=>{ve.current!==null&&ce(),U(),W()},[]),l.useEffect(()=>{const Q=Ie=>{var Ae;const Pe=Ie.detail;Pe!=null&&Pe.sessionId&&Pe.sessionId!==ie||p&&((Ae=r.current)==null||Ae.bumpResize())},Z=re(),fe=Z===window?[window]:[window,Z];for(const Ie of fe)Ie.addEventListener("adhdev:fit-cli-terminal",Q);return()=>{for(const Ie of fe)Ie.removeEventListener("adhdev:fit-cli-terminal",Q)}},[p,ie,r]);const ye=p&&g&&!k&&(T.atTop||!T.canScroll)||y||!!w;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:E,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[ye&&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:()=>{ee()},disabled:!ie||y,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:y?"Loading older...":"Load older terminal output"}),w&&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:w})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[_&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:_}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",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:!p,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>I(Q=>!Q),disabled:!p,"aria-label":"Open terminal control keys","aria-expanded":S,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),S&&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,C(Q=>{const Z=Math.max(_e,Number((Q-.1).toFixed(2)));return Z>_e&&me(),Z})},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,C(Q=>{const Z=Math.min(pe,Number((Q+.1).toFixed(2)));return Z>_e&&me(),Z})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:F,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:Ke>0?`${Ke}px`:"100%",height:Ze>0?`${Ze}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($d,{ref:r,readOnly:!p||!i,sizingMode:"measured",onViewportMetrics:X,onScrollMetrics:M,onInput:Q=>{!p||(d==null||d(ae,ie,Q))}})})})}),!p&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:h})]}),s.jsx(Jd,{contextKey:e.tabKey,panelLabel:pt(e),isSending:a,isBusy:!!D,statusMessage:oe,onSend:async Q=>D?!1:n(Q),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),P&&s.jsx(t0,{activeConv:e,onClose:()=>L(!1)})]})}const r0=5e3,n0=12e3;function a0(e){return e==="disconnected"||e==="reconnecting"}function o0({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=r0,reconnectActionDelayMs:o=n0}){const i=a0(e),[c,d]=l.useState(()=>!i||a<=0),[p,m]=l.useState(()=>!i||o<=0),u=l.useRef(!1);l.useEffect(()=>{if(!i){d(!1);return}if(u.current=!1,a<=0){u.current=!0,d(!0);return}d(!1);const N=setTimeout(()=>{u.current=!0,d(!0)},a);return()=>clearTimeout(N)},[a,i]),l.useEffect(()=>{if(!i){m(!1);return}if(o<=0){m(!0);return}m(!1);const N=setTimeout(()=>{m(!0)},o);return()=>clearTimeout(N)},[o,i]);const h=i?c:e==="offline"||e==="auth_failed",b=!!(n&&e!=="auth_failed"&&(!i||p)),y=l.useMemo(()=>!t||e!=="connected"?!1:a<=0||u.current,[a,t,e]),f=e==="auth_failed"?"red":e==="offline"?"orange":"accent",w={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)"},g={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},v="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",k={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[h&&s.jsx("div",{className:v,style:k,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:w[f],border:j[f],color:g[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"})]})}),y&&s.jsx("div",{className:v,style:k,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 Su({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(Ps,{size:n})})}const Qt="New session",Cu="A connected machine is ready. Start a new session with any installed provider — CLI, ACP, or IDE.";function i0(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 l0(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 c0(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=i0(e),a=l0(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 ${c0(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 d0({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 Ql({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Zl({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 u0({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:p,hiddenConversations:m=[],onShowConversation:u,onShowAllHidden:h,onResetPanelsToMain:b,inboxOpen:y,onInboxOpenChange:f,hiddenOpen:w,onHiddenOpenChange:j,onOpenNewSession:g,onOpenDashboardGuide:v,guideNudgeVisible:k=!1,actionShortcuts:N,notifications:x,notificationUnreadCount:C,onOpenNotification:S,onMarkNotificationRead:I,onMarkNotificationUnread:P,onDeleteNotification:L,onOpenGitDialog:A,onOpenMeshGraph:R}){var Ne;const{ides:$,p2pStates:X={}}=ss(),T=!!e&&nt(e)&&!rt(e),M=!!e&&rt(e),_=!!(e!=null&&e.daemonId)&&!!((Ne=e==null?void 0:e.coordinator)!=null&&Ne.meshId),B=c||(e?eu(e)?"terminal":"chat":null),[E,F]=l.useState(!1),K=l.useRef(null),z=l.useRef(null),ne=$.filter(re=>re.type==="adhdev-daemon"),q=d0({wsStatus:t,isConnected:r,daemonCount:ne.length,p2pStates:X}),J=q.subtitle,xe=q.tone==="connected"?"#22c55e":q.tone==="limited"?"#eab308":"#ef4444",ue=q.tone==="connected"?"0 0 4px #22c55e80":q.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",O=l.useMemo(()=>x.filter(re=>!re.readAt),[x]),H=l.useMemo(()=>x.filter(re=>!!re.readAt),[x]),ve=l.useMemo(()=>O.slice(0,9),[O]),we=C;l.useEffect(()=>{if(!y)return;const re=je=>{var ce;(ce=K.current)!=null&&ce.contains(je.target)||f(!1)};return document.addEventListener("mousedown",re),()=>document.removeEventListener("mousedown",re)},[y,f]),l.useEffect(()=>{if(!w)return;const re=je=>{var ce;(ce=z.current)!=null&&ce.contains(je.target)||j(!1)};return document.addEventListener("mousedown",re),()=>document.removeEventListener("mousedown",re)},[w,j]),l.useEffect(()=>{if(!w&&!y)return;const re=je=>{if(!je.altKey)return;const ce=je.code.match(/^Digit([1-9])$/);if(!ce)return;const U=Number(ce[1])-1,W=w?m[U]:void 0,Y=y?ve[U]:void 0;if(!(!W&&!Y)){if(je.preventDefault(),je.stopPropagation(),W){u==null||u(W),j(!1);return}Y&&(S(Y),f(!1))}};return window.addEventListener("keydown",re,!0),()=>window.removeEventListener("keydown",re,!0)},[m,w,y,ve,j,f,S,u]);const be=re=>{if(!re)return;const je=n.find(ce=>ce.tabKey===re);je&&(p==null||p(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(Ps,{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:q.title,"aria-label":q.title,className:"header-title-status-dot",style:{background:xe,boxShadow:ue}}),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:xe,boxShadow:ue}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[J&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",J]}),g&&s.jsx("button",{type:"button",onClick:g,className:"btn btn-secondary btn-sm ml-2",title:`${Qt}${N!=null&&N.openNewSession?` (${N.openNewSession})`:""}`,"aria-label":Qt,children:s.jsx(Id,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[v&&s.jsxs("button",{type:"button",onClick:v,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:"Dashboard guide","aria-label":"Open dashboard guide",children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),k&&s.jsx("span",{children:"Guide"})]}),e&&(T||M||!rt(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:_s(e)||pt(e),children:pt(e)}),A&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:()=>A(e.daemonId,e.workspacePath),children:s.jsx(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"}),_&&R&&s.jsxs("button",{type:"button",onClick:()=>R(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"})]}),(T||M)&&i&&s.jsxs(s.Fragment,{children:[T&&d&&B&&s.jsx(Su,{mode:B,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:M?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(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})}),!T&&!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${E?" is-drop-target":""}`,ref:z,onDragEnter:re=>{re.dataTransfer.types.includes("text/tab-key")&&(re.preventDefault(),F(!0))},onDragOver:re=>{re.dataTransfer.types.includes("text/tab-key")&&(re.preventDefault(),re.dataTransfer.dropEffect="move",F(!0))},onDragLeave:re=>{re.currentTarget.contains(re.relatedTarget)||F(!1)},onDrop:re=>{const je=re.dataTransfer.getData("text/tab-key");re.preventDefault(),F(!1),be(je)},children:[s.jsxs("button",{type:"button",onClick:()=>j(!w),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${N!=null&&N.toggleHiddenTabs?` (${N.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(oi,{size:16}),m.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:m.length})]}),w&&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(Ql,{value:N==null?void 0:N.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"}),m.length>0&&h&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{h(),j(!1)},children:"Restore all"})]})]}),e&&p&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>p(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),s.jsx(Ql,{value:N==null?void 0:N.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:pt(e)})]}),m.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:m.map(re=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{u==null||u(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:[m.indexOf(re)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",m.indexOf(re)+1]}):null,_s(re)]})]},re.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>f(!y),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Kr,{size:16}),we>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:we})]}),y&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[O.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),O.map(re=>s.jsx(Zl,{notification:re,shortcutIndex:ve.indexOf(re)>=0?ve.indexOf(re)+1:void 0,onOpen:()=>S(re),onMarkRead:()=>I(re.id),onMarkUnread:()=>P(re.id),onDelete:()=>L(re.id)},re.id))]}),H.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),H.map(re=>s.jsx(Zl,{notification:re,onOpen:()=>S(re),onMarkRead:()=>I(re.id),onMarkUnread:()=>P(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 p0(e,t){return String(e||"")!==String(t||"")}function m0(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&&!Kd(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
51
|
+
`).includes(a)))}function h0(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 Iu(e,t={}){return h0(m0(e,t),t.sortMode||"recent")}function ta(e){return e?"Resume saved history":"Start fresh"}function Ci(e){return e?"Resuming saved history…":"Starting fresh…"}function f0(){return"Start fresh"}function x0(e,t=!1){return e==="cli"?ta(t):e==="ide"?"Start IDE":"Start ACP session"}function b0(e,t=!1){return e==="cli"?Ci(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function g0(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function y0(){return"Open saved history"}function v0(){return"Saved History"}function Ii(){return"Use saved history when you want continuity in the same provider conversation."}function w0(){return"No saved history found yet."}function j0(){return"Refresh saved history"}function k0(){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 Mu(e){return`Resume saved history with ${e}?`}function Au(){return"Review or change the target workspace before resuming saved history."}function N0(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 Tu({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:p,onClose:m,onNewChat:u,onSwitchSession:h,onRefreshHistory:b,onResumeSavedSession:y}){var L;const f=t.find(A=>A.id===e.routeId),w=(f==null?void 0:f.chats)||[],j=(L=f==null?void 0:f.activeChat)==null?void 0:L.id,g=nt(e)&&!rt(e),[v,k]=l.useState(()=>_t()),N=c||v,x=String(d||"").trim(),C=A=>{if(p){p(A);return}k(A)},S=l.useMemo(()=>a.map(A=>{const R=String(A.workspace||"").trim();return A.canResume||R||!x?A:{...A,workspace:x,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[x,a]),I=l.useMemo(()=>Iu(S,{textQuery:N.textQuery,workspaceQuery:N.workspaceQuery,modelQuery:N.modelQuery,resumableOnly:N.resumableOnly,sortMode:N.sortMode}),[S,N.modelQuery,N.resumableOnly,N.sortMode,N.textQuery,N.workspaceQuery]),P=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:m,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:g?v0():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Kg(e)}),g&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Ii()})]}),s.jsx("button",{onClick:m,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:[!g&&s.jsx("button",{onClick:u,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"}),g?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:N.textQuery,onChange:A=>C({...N,textQuery:A.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:N.workspaceQuery,onChange:A=>C({...N,workspaceQuery:A.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:N.modelQuery,onChange:A=>C({...N,modelQuery:A.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:N.sortMode,onChange:A=>C({...N,sortMode:A.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:N.resumableOnly,onChange:A=>C({...N,resumableOnly:A.target.checked})}),"Resume-ready only"]})]}),I.map(A=>{const R=e.providerSessionId===A.providerSessionId,$=R||!A.canResume||!!i,X=A.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{$||!y||y(A)},disabled:$,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${R?"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 ${R?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:A.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:A.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:N0(A.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:A.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[A.workspace||"Workspace unknown",X?" · selected workspace":"",Ts(A.summaryMetadata)?` · ${Ts(A.summaryMetadata)}`:"",A.messageCount>0?` · ${A.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:R?"ACTIVE":A.canResume?X?"RESUME IN SELECTED WORKSPACE":i===A.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},A.id)})]}):w.map(A=>s.jsxs("div",{onClick:()=>{h(e.routeId,A.id),m()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${j===A.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${j===A.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:A.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[A.id.substring(0,12),"..."]}),j===A.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},A.id)),(g&&!o&&I.length===0||!g&&w.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(qh,{size:32})}),s.jsx("div",{className:"text-[13px]",children:g?a.length>0?"No saved history matches these filters.":w0():"No recent chat sessions found."})]}),g&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:k0()})})]}),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})," ",g?j0():"Refresh History"]})})})]})]});return typeof document>"u"?P:Dr.createPortal(P,document.body)}const ec={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 _u({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=ec[n.type]||ec.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 S0=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function C0(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function I0(e){return e.sessionId||e.instanceId||e.agentType}function Ka(e,t){return t||e||"unknown"}function Ru(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Ft(r,{fallbackId:r.id}));return t}function Lu(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 Mi(e,t={}){return M0(e,Lu(e,t))}function M0(e,t={}){var u,h,b,y,f,w,j,g,v;const r=[],n=t.machineName,a=t.connectionState,o=C0(e),i=e.workspace||"",c=tx(e.type,{agentName:e.cliName}),d=nt(e)||rt(e)?c:It(e.type),p=Array.isArray(e.childSessions)?e.childSessions.map(k=>{var N,x,C;return{sessionId:k.id,instanceId:k.id,providerSessionId:k.providerSessionId,activeChatId:(N=k.activeChat)==null?void 0:N.id,transport:k.transport,sessionCapabilities:k.capabilities,agentType:k.providerType,agentName:k.providerName||It(k.providerType),status:k.status,title:k.title,lastMessagePreview:k.lastMessagePreview,lastMessageRole:k.lastMessageRole,lastMessageAt:k.lastMessageAt,lastMessageHash:k.lastMessageHash,messages:((x=k.activeChat)==null?void 0:x.messages)||[],activeModal:((C=k.activeChat)==null?void 0:C.activeModal)||void 0,unread:k.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,inboxBucket:k.inboxBucket,completionMarker:k.completionMarker,surfaceHidden:k.surfaceHidden,git:k.git,settings:k.settings,coordinator:k.coordinator,messageInput:k.messageInput}}):[],m=S0(e);if(m){const k=e.sessionId||e.instanceId,N=(u=e.settings)==null?void 0:u.meshCoordinatorFor,x=((h=e.settings)==null?void 0:h.meshNodeFor)||!((b=e.settings)!=null&&b.meshCoordinatorFor)&&((y=e.settings)==null?void 0:y.launchedByCoordinator),C=N?" (Coordinator)":x?" (Mesh Node)":"",S=c+C,I=(f=e.activeChat)==null?void 0:f.activeModal,P=I&&Array.isArray(I.buttons)&&I.buttons.length>0,L=sx(e.activeChat,[{status:e.status,activeModal:(w=e.activeChat)==null?void 0:w.activeModal}],e.agents||[]),A=e.activeChat||{title:"",messages:[]};let R=A.title&&String(A.title).trim()?String(A.title).trim():"";const $=(j=e.activeChat)==null?void 0:j.id,X=e.chats;if($&&Array.isArray(X)&&X.length>0){const z=X.find(ne=>ne.id===$||ne.id&&String(ne.id)===String($));z!=null&&z.title&&String(z.title).trim()&&(R=String(z.title).trim())}const T=(nt(e)||rt(e),e.type),M=(nt(e)||rt(e))&&Il(R,S,T)?"":R,_=A.messages||[],B=typeof $=="string"?$.trim():"",E=(nt(e)||rt(e))&&B===String(e.type||"").trim(),F=B&&!E?B:e.providerSessionId,K=e.coordinator||(typeof((g=e.settings)==null?void 0:g.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:k,providerSessionId:e.providerSessionId,historySessionId:F,nativeSessionId:k,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:nt(e)?e.mode||"terminal":"chat",agentName:S,agentType:T,status:L,title:M,messages:_,resume:e.resume,hostIdeType:!nt(e)&&!rt(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:M||o||(nt(e)?e.mode==="chat"?S:`Terminal${C}`:S),displaySecondary:nt(e)&&o?S: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:P?I.buttons:void 0,modalMessage:P?I.message:void 0,streamSource:"native",tabKey:Ka(k,e.id),machineName:n,connectionState:a,settings:e.settings,coordinator:K,messageInput:e.messageInput})}if(m&&(nt(e)||rt(e)))return r;for(const k of p){const N=k.activeModal&&Array.isArray(k.activeModal.buttons)&&k.activeModal.buttons.length>0,x=rx(k),C=I0(k),S=`${e.id}:${C}`,I=k.title&&String(k.title).trim()||"",P=Il(I,k.agentName,k.agentType)?"":I,L=k.messages||[];if(!(k.transport==="cdp-webview"||!!k.sessionId||!!k.providerSessionId||L.length>0||N||!!P||!["idle","panel_hidden","disconnected","not_monitored"].includes(x)))continue;const R=k.coordinator||(typeof((v=k.settings)==null?void 0:v.meshCoordinatorFor)=="string"&&k.settings.meshCoordinatorFor?{meshId:k.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:k.sessionId||k.instanceId,providerSessionId:k.providerSessionId,historySessionId:k.activeChatId||k.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:k.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:k.sessionCapabilities,mode:"chat",agentName:k.agentName,agentType:k.agentType,status:x,title:P,messages:L,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:k.git||e.git,displayPrimary:P||o||k.agentName||d,displaySecondary:`${d} · ${k.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:k.lastMessagePreview,lastMessageRole:k.lastMessageRole,lastMessageAt:k.lastMessageAt,lastMessageHash:k.lastMessageHash,lastUpdated:k.lastUpdated||e.lastUpdated,inboxBucket:k.inboxBucket,completionMarker:k.completionMarker,modalButtons:N?k.activeModal.buttons:void 0,modalMessage:N?k.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Ka(k.sessionId||k.instanceId,S),machineName:n,connectionState:a,settings:k.settings,coordinator:R,messageInput:k.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 Pu(e){return String(e.type||e.id||"").trim()}function A0(e){var t;return e.category!=="cli"||!Pu(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 er(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!A0(a))continue;const o=Pu(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 Jr(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 Jr(e).filter(n=>r.has(n))}function Fr(e){return e.map(t=>t.type)}function T0(e,t){const r=Jr(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function _0(e,t){return Jr(e).filter(r=>r!==t)}function tc(e,t,r){const n=Jr(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 sc({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 rc({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]),p=e.length-d.length,m=t.filter(h=>!d.includes(h.type)),u=()=>{o&&(r(T0(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 y=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]}),(y==null?void 0:y.icon)&&s.jsx("span",{"aria-hidden":"true",children:y.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:y?`${y.label} · ${y.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(tc(d,h,"up")),children:s.jsx(sc,{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(tc(d,h,"down")),children:s.jsx(sc,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(_0(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||m.length===0,children:[s.jsx("option",{value:"",children:m.length?"Select provider…":"No additional detected CLI providers"}),m.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:u,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.",p>0?` ${p} provider${p===1?"":"s"} from the saved policy are not detected now and will be omitted when saved.`:""]})]})}function R0(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 Du(e,t){const r=R0(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const $u=[{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:"🏄"}],Eu=[{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:"🧩"}],Bu=[{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:"🟠"}],L0=$u,P0=Eu,D0=Bu;function Ut(...e){return Km(Um(e))}function $0({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 Xr({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($0,{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 E0(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function zs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Ws(e){return e==="system"?E0():e}function Fu(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 B0(){const e=zs(),t=Ws(e);Fu(t),$n(e,t)}function $s(){const[e,t]=l.useState(zs),[r,n]=l.useState(()=>Ws(zs()));l.useEffect(()=>{Fu(r)},[r]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const p=d.matches?"light":"dark";n(p),$n("system",p)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=d=>{const p=d.detail||{},m=p.preference,u=p.theme;t(m==="dark"||m==="light"||m==="system"?m:zs()),n(u==="dark"||u==="light"?u:Ws(zs()))},c=d=>{if(d.key!=="theme")return;const p=zs(),m=Ws(p);t(p),n(m)};return window.addEventListener(Ko,i),window.addEventListener("storage",c),()=>{window.removeEventListener(Ko,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=Ws(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=Ws(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 nc={dark:"Dark",light:"Light",system:"System"};function F0({collapsed:e}){const{preference:t,cycleTheme:r}=$s(),n=t==="dark"?s.jsx(Jh,{size:16}):t==="light"?s.jsx(Yh,{size:16}):s.jsx(Xh,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${nc[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:nc[t]})]})}function Ua(e,t){return e?typeof e=="function"?e(t):e:null}function O0({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const[p,m]=l.useState(!1),[u,h]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),b=()=>m(!0),y=()=>m(!1),f=()=>{h(v=>{const k=!v;try{localStorage.setItem(d,k?"1":"0")}catch{}return k})},w=l.useMemo(()=>({collapsed:u,mobileMenuOpen:p,openMobileMenu:b,closeMobileMenu:y,toggleCollapsed:f}),[u,p]),j=v=>`nav-item${v.active?" active":""} cursor-pointer ${u?"justify-center py-2.5 px-0":""}${v.className?` ${v.className}`:""}`,g=v=>s.jsxs("div",{className:j(v),id:`nav-${v.id}`,onClick:()=>{v.onSelect(),y()},title:u?v.title??(typeof v.label=="string"?v.label:void 0):v.title,children:[s.jsx("span",{className:"nav-icon",children:v.icon}),!u&&v.label]},v.id);return s.jsxs("div",{className:`app-layout${p?" mobile-menu-open":""}${u?" 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"})]}),p&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:y,onKeyDown:v=>v.key==="Escape"&&y()}),s.jsxs("aside",{className:`sidebar ${p?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${u?"justify-center gap-0":""}`,children:Ua(t,w)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:y,children:s.jsx(vt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(g)}),n.map(v=>s.jsxs("div",{className:v.className??"border-t border-border-subtle pt-2 mt-2",children:[!u&&v.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:v.title}):null,v.items.map(g)]},v.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(g),Ua(o,w),s.jsx(F0,{collapsed:u}),Ua(i,w)]})]}),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[p,m]=l.useState(i),u=o?p:!0,h=(e||r)&&s.jsxs("div",{className:Ut("flex items-start justify-between gap-3",u&&"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",u?"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:()=>m(b=>!b),"aria-expanded":u,children:h}):h,u&&d]})}function wa({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 H0={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"},z0={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function hs({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]",H0[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:z0[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 Tr(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 W0={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"},K0={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function U0({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",W0[e],r),children:[s.jsx("span",{className:Ut("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",K0[e])}),n]})}function ws({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 G0({onPrefChange:e}){const[t,r]=mx(),[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(ws,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Kr,{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(ws,{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:()=>{Vd().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(ws,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Md,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:i=>o("completionAlert",i)}),s.jsx(ws,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Qh,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:i=>o("approvalAlert",i)}),s.jsx(ws,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Qs,{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 V0(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 Ai(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function _r(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||V0(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 q0(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 Y0({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(wa,{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(X0,{ide:i,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},i.id))})}function ac({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 Dr.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 J0(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...L0,...P0,...D0].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 X0({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var $,X;const[o,i]=l.useState("idle"),[c,d]=l.useState(""),[p,m]=l.useState(null),[u,h]=l.useState("idle"),[b,y]=l.useState(""),f=e.version||null,w=(($=e.machine)==null?void 0:$.platform)||((X=e.system)==null?void 0:X.platform)||"",j=Ft(e,{fallbackId:e.id}),g=w==="win32"?"🪟":w==="darwin"?"🍎":"🐧",v=t.filter(T=>T.daemonId===e.id&&T.transport==="cdp-page"),k=t.filter(T=>T.daemonId===e.id&&T.transport==="pty"),N=t.filter(T=>T.daemonId===e.id&&T.transport==="acp"),x=e.p2p,C=async()=>{if(r){i("upgrading"),d("Starting upgrade...");try{const T=q0(await r(e.id,"daemon_upgrade",{}));T.alreadyLatest?(i("done"),d(`Already on v${T.version||"latest"}.`)):T.upgraded||T.success?(i("done"),d(`Upgrade to v${T.version||"latest"} started. Daemon is restarting...`)):(i("error"),d(T.error||"Upgrade failed"))}catch(T){i("error"),d(Ga(T,"Connection lost during upgrade"))}}},S=async()=>{if(m(null),!!n){h("loading");try{await n(e.id),h("done"),y("Machine disconnected.")}catch(T){h("error"),y(Ga(T,"Failed to disconnect"))}}},I=async()=>{if(m(null),!!a){h("loading");try{await a(e.id),h("done"),y("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(T){h("error"),y(Ga(T,"Failed to revoke token"))}}},P="0.9.82",L=Ai(e,P),A=_r(e,P),R=v.length+k.length+N.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:g}),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:C,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${P}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${A?"↑ Update now":`↑ Update${` to v${P}`}`}`}),n&&s.jsx("button",{onClick:()=>m("disconnect"),disabled:u==="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:()=>m("revoke"),disabled:u==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(U0,{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&&R>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),R>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[v.map(T=>{const M=J0(T.type),_=T.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:M.icon}),s.jsx("span",{children:M.name}),_!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${_?"bg-green-400":"animate-pulse"}`,style:_?void 0:{background:"var(--status-warning)"},title:_?"CDP connected":"CDP connecting..."})]},T.id)}),k.map(T=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:T.cliName||"CLI"})]},T.id)),N.map(T=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:T.cliName||"ACP"})]},T.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(c||b)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||u==="error"?"text-red-400":o==="done"||u==="done"?"text-green-400":"text-text-muted"}`,children:b||c})]}),p==="disconnect"&&s.jsx(ac,{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:S,onCancel:()=>m(null)}),p==="revoke"&&s.jsx(ac,{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:()=>m(null)})]})}const Q0=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function Z0({daemonId:e,knownCliTypes:t=Q0}){const{sendCommand:r}=mt(),[n,a]=l.useState({}),[o,i]=l.useState({}),[c,d]=l.useState(!0),[p,m]=l.useState(null),[u,h]=l.useState(null),[b,y]=l.useState(""),f=l.useCallback(async()=>{if(e){d(!0),h(null);try{const g=await r(e,"list_coordinator_prompts",{}),v=g!=null&&g.result&&typeof g.result=="object"?g.result:g;if(!(v!=null&&v.success)){h((v==null?void 0:v.error)||"Failed to load");return}const k=v.entries||{};y(v.dir||"");const N={};for(const x of t)N[x]=k[x]||{override:"",append:""};for(const x of Object.keys(k))N[x]||(N[x]=k[x]);a(N),i(JSON.parse(JSON.stringify(N)))}catch(g){h((g==null?void 0:g.message)||String(g))}finally{d(!1)}}},[r,e,t]);l.useEffect(()=>{f()},[f]);const w=l.useCallback(async(g,v)=>{var k;if(e){m(`${g}:${v}`),h(null);try{const N=((k=n[g])==null?void 0:k[v])||"",x=await r(e,"write_coordinator_prompt",{key:g,kind:v,content:N}),C=x!=null&&x.result&&typeof x.result=="object"?x.result:x;if(!(C!=null&&C.success)){h((C==null?void 0:C.error)||"Save failed");return}i(S=>({...S,[g]:{...S[g]||{override:"",append:""},[v]:N}}))}catch(N){h((N==null?void 0:N.message)||String(N))}finally{m(null)}}},[r,e,n]),j=l.useMemo(()=>(g,v)=>{var k,N;return(((k=n[g])==null?void 0:k[v])||"")!==(((N=o[g])==null?void 0:N[v])||"")},[n,o]);return e?s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",children:[s.jsxs("p",{children:["Customize the coordinator prompt this daemon's mesh coordinator sessions get. ",s.jsx("span",{className:"font-mono text-[11px]",children: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."]})]}),u&&s.jsx("div",{className:"text-[12px] text-red-400 bg-red-500/10 border border-red-500/20 rounded px-3 py-2",children:u}),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(([g,v])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-2",children:g}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Override"}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:4,value:v.override,onChange:k=>a(N=>({...N,[g]:{...N[g],override:k.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:p===`${g}: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 w(g,"override"),disabled:p===`${g}:override`||!j(g,"override"),children:p===`${g}:override`?"Saving…":j(g,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Append"}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:3,value:v.append,onChange:k=>a(N=>({...N,[g]:{...N[g],append:k.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:p===`${g}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void w(g,"append"),disabled:p===`${g}:append`||!j(g,"append"),children:p===`${g}:append`?"Saving…":j(g,"append")?"Save append":"Saved"})})]},g))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const ey=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function ty(){const{preference:e,setPreference:t}=$s();return s.jsx("div",{className:"flex gap-2",children:ey.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 sy(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 ry(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 oc(e){const{r:t,g:r,b:n}=ry(e);return .2126*Va(t)+.7152*Va(r)+.0722*Va(n)}function ic(e,t){const r=oc(e),n=oc(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function Ou(e){const t=sy(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return ic(t,r)>=ic(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},ny=[{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"}}}],Hu="adhdev-chat-theme",zu="adhdev-chat-theme-custom";function En(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Hu)||"ember"}catch{return"ember"}}function Kt(e){try{const t=localStorage.getItem(zu);if(t){const r=JSON.parse(t);return{...e==="dark"?Uo:Go,...r[e]}}}catch{}return e==="dark"?Uo:Go}function gn(e,t){try{localStorage.setItem(zu,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 ay={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Rr(e,t){var a;const r=(a=ay[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",Ou(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 Cs(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",Ou(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 Ti(){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 oy(e){try{localStorage.setItem(Hu,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Is()?"dark":"light";Cs(Kt(t))}else Ti(),Rr(e,Is()?"dark":"light")}function iy(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=En();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Is()?"dark":"light";Cs(Kt(t))}else Ti(),Rr(e,Is()?"dark":"light")}function Is(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function At({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 fr({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 ly({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 p={...d,[i]:c},u=Kt(r==="dark"?"light":"dark");return r==="dark"?gn(p,u):gn(u,p),Cs(p),t(p),p})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",s.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(fr,{title:"App Background",children:[s.jsx(At,{label:"Background",value:n.bgPrimary,onChange:i=>o("bgPrimary",i)}),s.jsx(At,{label:"Surface",value:n.bgSecondary,onChange:i=>o("bgSecondary",i)}),s.jsx(At,{label:"Card",value:n.surfacePrimary,onChange:i=>o("surfacePrimary",i)})]}),s.jsxs(fr,{title:"App Text",children:[s.jsx(At,{label:"Primary",value:n.textPrimary,onChange:i=>o("textPrimary",i)}),s.jsx(At,{label:"Secondary",value:n.textSecondary,onChange:i=>o("textSecondary",i)}),s.jsx(At,{label:"Muted",value:n.textMuted,onChange:i=>o("textMuted",i)})]}),s.jsxs(fr,{title:"Borders & Accent",children:[s.jsx(At,{label:"Border subtle",value:n.borderSubtle,onChange:i=>o("borderSubtle",i)}),s.jsx(At,{label:"Border default",value:n.borderDefault,onChange:i=>o("borderDefault",i)}),s.jsx(At,{label:"Accent",value:n.accentColor,onChange:i=>o("accentColor",i)})]})]}),s.jsxs("div",{children:[s.jsxs(fr,{title:"Chat Bubbles",children:[s.jsx(At,{label:"User bubble",value:n.userBubble,onChange:i=>o("userBubble",i)}),s.jsx(At,{label:"User text",value:n.userText,onChange:i=>o("userText",i)}),s.jsx(At,{label:"Agent bubble",value:n.assistantBubble,onChange:i=>o("assistantBubble",i)}),s.jsx(At,{label:"Agent text",value:n.assistantText,onChange:i=>o("assistantText",i)})]}),s.jsxs(fr,{title:"Chat Layout",children:[s.jsx(At,{label:"Chat BG",value:n.containerBg,onChange:i=>o("containerBg",i)}),s.jsx(At,{label:"Send button",value:n.sendButton,onChange:i=>o("sendButton",i)}),s.jsx(At,{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?gn(i,d):gn(d,i),a(i),Cs(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 cy(){const[e,t]=l.useState(En),[r,n]=l.useState(!0),[a,o]=l.useState(()=>Kt("dark"));l.useEffect(()=>{n(Is());const d=new MutationObserver(()=>{const u=Is();n(u);const h=En();h==="custom"?Cs(Kt(u?"dark":"light")):Rr(h,u?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const u=Is();n(u);const h=En();h==="custom"?Cs(Kt(u?"dark":"light")):Rr(h,u?"dark":"light")};return p.addEventListener("change",m),()=>{d.disconnect(),p.removeEventListener("change",m)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?Cs(Kt(r?"dark":"light")):(Ti(),Rr(e,r?"dark":"light"))},[e,r]),l.useEffect(()=>{o(Kt(r?"dark":"light"))},[r]);const i=d=>{t(d),oy(d)},c=[...ny,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:c.map(d=>{const p=e===d.id,m=r?d.preview.dark:d.preview.light,u=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>i(d.id),className:"text-left rounded-xl p-3 transition-all",style:{background:p?"var(--bg-glass-hover)":"var(--bg-glass)",border:p?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:p?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.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:m.userBubble,color:u},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:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[p&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:d.id==="custom"?"🎨 Custom":d.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:d.description})]})]})]},d.id)})}),e==="custom"&&s.jsx(ly,{dark:r,onColorsChange:d=>o(d)})]})}const _i="adhdev_mobileDashboardMode_v1",Vo="adhdev:mobile-dashboard-mode-change";function Ri(){try{return localStorage.getItem(_i)==="workspace"?"workspace":"chat"}catch{return"chat"}}function dy(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Ri())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==_i||t()};return window.addEventListener(Vo,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Vo,r),window.removeEventListener("storage",n)}}function uy(e){try{localStorage.setItem(_i,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Vo,{detail:e}))}function py(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(Ri()==="chat")},[]),s.jsx(ws,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ps,{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),uy(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const qa=new Map,lc=new Map;function my(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 hy(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 Wu(){const{sendCommand:e}=mt(),{injectEntries:t,getIdes:r}=$r();return l.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??Hb,i=lc.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 p=await e(n,"get_machine_runtime_stats"),m=my(p);if(!m)return;const u=r().find(b=>b.id===n),h=hy(u,n,m.machine,m.timestamp||Date.now());t([h]),lc.set(n,Date.now())})().finally(()=>{qa.delete(n)});return qa.set(n,d),d},[r,t,e])}function fy(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 xy(e,t){const{sendData:r}=mt(),{injectEntries:n,getIdes:a}=$r(),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}},m=>{const u=a().find(b=>b.id===d),h=fy(u,d,m);n([h])}));return()=>{c.forEach(d=>d())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function by(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}:{}}},p=>{c&&(clearTimeout(c),c=null),a(p.diagnostics),i(!1)});return d.initialSendAccepted?c=setTimeout(()=>{i(!1)},Ub):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 gy(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Ku(e){const{sendData:t}=mt(),[r,n]=l.useState({});return l.useEffect(()=>{const a=gy(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}),qs.record({interactionId:i.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:i.status,modalButtonCount:Array.isArray(i.modalButtons)?i.modalButtons.length:0}})});return o.initialSendAccepted||n({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),r}const Uu="adhdev_hiddenTabs",Gu="adhdev_autoHiddenMeshTabs";function yy(){try{const e=localStorage.getItem(Uu);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ys(e){try{localStorage.setItem(Uu,JSON.stringify([...e]))}catch{}}function vy(){try{const e=localStorage.getItem(Gu);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function cc(e){try{localStorage.setItem(Gu,JSON.stringify([...e]))}catch{}}function Nr(e){return Br(e)}function ja(e,t){return os(t).some(r=>e.has(r))}function Vu(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 wy(e,t,r=new Set){return e.filter(n=>{if(!Vu(n))return!1;const a=Nr(n);return r.has(a)?!1:!ja(t,n)})}function jy(){const[e,t]=l.useState(yy),[r,n]=l.useState(vy),a=l.useCallback(h=>{const b=Nr(h);t(y=>{const f=new Set(y);return f.has(b)?f.delete(b):f.add(b),ys(f),f})},[]),o=l.useCallback(h=>{const b=Nr(h);t(y=>{if(y.has(b))return y;const f=new Set(y);return f.add(b),ys(f),f})},[]),i=l.useCallback(h=>{const b=Nr(h);t(y=>{if(y.has(b))return y;const f=new Set(y);return f.add(b),ys(f),f}),n(y=>{if(y.has(b))return y;const f=new Set(y);return f.add(b),cc(f),f})},[]),c=l.useCallback(h=>{const b=Nr(h);t(y=>{if(!y.has(b))return y;const f=new Set(y);return f.delete(b),ys(f),f}),n(y=>{if(y.has(b))return y;const f=new Set(y);return f.add(b),cc(f),f})},[]),d=l.useCallback(()=>{t(h=>{if(h.size===0)return h;const b=new Set;return ys(b),b})},[]),p=l.useCallback((h,b)=>{t(y=>{const f=new Set(y);for(const w of b)f.add(w);return ys(f),f})},[]),m=l.useCallback((h,b)=>{t(y=>{const f=new Set(y);for(const w of b)f.delete(w);return ys(f),f})},[]),u=l.useCallback(h=>ja(e,h),[e]);return{hiddenTabs:e,autoHiddenTabs:r,toggleTarget:a,hideTarget:o,autoHideTarget:i,showTarget:c,showAllTabs:d,hideAllForDaemon:p,showAllForDaemon:m,isHidden:u}}const yn="adhdev_mutedConversations",Ya="adhdev_autoMutedMeshConversations";function dc(e){try{const t=localStorage.getItem(e);if(t)return new Set(JSON.parse(t))}catch{}return new Set}function xr(e,t){try{localStorage.setItem(e,JSON.stringify([...t]))}catch{}}function ky(e,t){return os(t).some(r=>e.has(r))}function Ny(){const[e,t]=l.useState(()=>dc(yn)),[r,n]=l.useState(()=>dc(Ya)),a=l.useCallback(p=>{const m=Br(p);t(u=>{if(u.has(m))return u;const h=new Set(u);return h.add(m),xr(yn,h),h})},[]),o=l.useCallback(p=>{const m=os(p);t(u=>{let h=!1;const b=new Set(u);for(const y of m)b.delete(y)&&(h=!0);return h?(xr(yn,b),b):u}),n(u=>{let h=!1;const b=new Set(u);for(const y of m)b.delete(y)&&(h=!0);return h?(xr(Ya,b),b):u})},[]),i=l.useCallback(p=>{os(p).some(h=>e.has(h))?o(p):a(p)},[e,a,o]),c=l.useCallback(p=>{if(!Vu(p))return;const m=Br(p);r.has(m)||(n(u=>{if(u.has(m))return u;const h=new Set(u);return h.add(m),xr(Ya,h),h}),t(u=>{if(u.has(m))return u;const h=new Set(u);return h.add(m),xr(yn,h),h}))},[r]),d=l.useCallback(p=>ky(e,p),[e]);return{mutedTargets:e,autoMutedTargets:r,muteTarget:a,unmuteTarget:o,toggleTarget:i,autoMuteIfCoordinator:c,isMuted:d}}function Sy(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function Cy(e){const t=(e==null?void 0:e.result)??e;return typeof(t==null?void 0:t.error)=="string"?t.error:"Interactive prompt response failed"}async function Iy(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 My({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(!Sy(o))throw new Error(Cy(o));return}await Iy(e.sessionId,t,a)}function qu(e){const{ides:t,isP2PActive:r,p2pStates:n}=ss(),{sendCommand:a}=mt(),[o,i]=l.useState(null),[c,d]=l.useState(!1),[p,m]=l.useState(null),u=l.useMemo(()=>Hf(t,e),[t,e]),h=!!u,b=l.useMemo(()=>u?u.prompt.promptId===o?null:u:null,[o,u]),y=l.useCallback(async j=>{if(!b)return;const g=Bd(b.prompt,j);d(!0),m(null);try{const v=(n==null?void 0:n[b.daemonId])==="connected"||r===!0;await My({promptSession:b,response:g,useP2PCommand:v,sendCommand:a}),i(b.prompt.promptId)}catch(v){throw m(v instanceof Error?v.message:String(v)),v}finally{d(!1)}},[r,n,b,a]),f=l.useCallback(()=>{b&&i(b.prompt.promptId)},[b]),w=l.useCallback(()=>{i(null),m(null)},[]);return{promptSession:b,hasActivePrompt:h,responseError:p,isSubmitting:c,submit:y,cancel:f,reopen:w}}function Yu(e){return e instanceof Error?e.message:String(e||"")}function Ay(e){const t=Yu(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function Ty(e){const t=Yu(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Ju({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!nt(e)||rt(e))return;const o=ar(e);if(o===t)return;const i=e.sessionId;i&&a(c=>({...c,[i]:t}));try{await n(Ds(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:es(e),mode:t})}catch(c){const d=Ty(c);i&&!d&&a(p=>{const m={...p};return o===Xu(r,i)?delete m[i]:m[i]=o,m}),Ay(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 uc(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 _y(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=uc(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(d=>uc(d,t)):a.childSessions,c=i!==a.childSessions;return o!==a||c?(r=!0,{...o,...c?{childSessions:i}:{}}):a});return r?n:e}function Xu(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 Ry(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))Xu(t,a)===o&&(delete n[a],r=!0);return r?n:e}function Ly({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){l.useEffect(()=>{Vd()},[]);const a=l.useMemo(()=>e.map(o=>({id:o.tabKey,name:ju(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return bx(a),l.useEffect(()=>{if(Object.keys(t).length===0)return;const i=setTimeout(()=>{r(c=>{const d=Date.now(),p={};for(const[m,u]of Object.entries(c))d-u<5e3&&(p[m]=u);return Object.keys(p).length===Object.keys(c).length?c:p})},5500);return()=>clearTimeout(i)},[t,r]),l.useEffect(()=>{const o=setInterval(()=>{const i=Date.now()-3e5;n(c=>{const d=c.filter(p=>p.timestamp>i).slice(-100);return d.length===c.length?c:d})},6e4);return()=>clearInterval(o)},[n]),null}function pc(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 Ms(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=pc(t==null?void 0:t.receivedAt)||pc(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function qo(e,t=0){return Ms(e)||e.lastUpdated||t||0}function Qu(e){return Ms(e)||e.lastUpdated||0}function Zu(e,t,r=Qu){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 Py(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Yo(e)&&!e.title.trim()}function Dy(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:Zu(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=Dy(a);return n?o&&Py(n)?o:n:o||r[0]||null}function $y(e){const t=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return!t||r.startsWith(`${t}:`)?r:`${t}:${r}`}function Ey(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=$y(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 Ja(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 By(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 mc(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?By(Ys(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 Fy(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||""),mc(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||""),mc(r.activeChat)].join(":"))].join("|")}function Oy(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 Hy(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 zy(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Wy(e){const t=zy(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=Ys(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Ky({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=l.useMemo(()=>Ey(e),[e]),o=l.useMemo(()=>Ru(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),p=l.useRef(new Map),m=l.useRef(new Map),u=l.useMemo(()=>{const k=new Map,N=[];for(const I of a){const{connectionState:P="new",machineName:L}=Lu(I,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),A=Fy(I),R=p.current.get(I.id);if(R&&R.ide===I&&R.sourceSignature===A&&R.connectionState===P&&R.machineName===L){k.set(I.id,R),N.push(...R.conversations);continue}const $=Mi(I,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),X={ide:I,sourceSignature:A,connectionState:P,machineName:L,conversations:$};k.set(I.id,X),N.push(...$)}p.current=k;const x=new Map,C=I=>{const P=Wy(I),L=m.current.get(I.tabKey);if(L&&L.signature===P)return x.set(I.tabKey,L),L.timestamp;const A={signature:P,timestamp:Qu(I)||(L==null?void 0:L.timestamp)||0};return x.set(I.tabKey,A),A.timestamp},S=[...N].sort((I,P)=>Zu(I,P,C));return m.current=x,S},[a,t,o]),h=l.useMemo(()=>{const k=Oy(u,r);return Ja(i.current,k)?i.current:(i.current=k,k)},[u,r]),b=l.useMemo(()=>{const k=new Map,N=Array.from(new Set(h.map(x=>x.routeId)));for(const x of N){const C=Gt(h,x);C&&k.set(x,C)}return k},[h]),y=l.useMemo(()=>{const k=new Map;for(const N of h){const x=b.get(N.routeId),C=N.streamSource==="native"&&x?x:N;for(const S of os({providerSessionId:N.providerSessionId,sessionId:N.sessionId,tabKey:N.tabKey}))k.set(S,C)}return k},[h,b]),f=l.useMemo(()=>Hy(h,b),[h,b]),w=l.useCallback(k=>{if(k)return y.get(k)},[y]),j=l.useCallback(k=>{if(k)return f.get(k)},[f]),g=l.useMemo(()=>{const k=h.filter(N=>!ja(n,N));return Ja(c.current,k)?c.current:(c.current=k,k)},[h,n]),v=l.useMemo(()=>{const k=g.map(N=>N.tabKey);return Ja(d.current,k)?d.current:(d.current=k,k)},[g]);return{chatIdes:a,conversations:h,visibleConversations:g,visibleTabKeys:v,resolveConversationBySessionId:w,resolveConversationByTarget:j}}function Uy({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 Gy({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){l.useEffect(()=>{it.setIdes(e)},[e]),l.useEffect(()=>{it.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=it.onToast(o=>{r(c=>c.some(p=>p.message===o.message&&o.timestamp-p.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>r(c=>c.filter(d=>d.id!==o.id)),i)});return()=>{a()}},[r]),l.useEffect(()=>{const a=yu.on("status_event",o=>{it.handleRawEvent(o,"ws")});return()=>{a()}},[]),l.useEffect(()=>{var o;const a=i=>{var f;const c=i.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,p=n(d),m=(p==null?void 0:p.routeId)||c.daemonId;if(!m)return;const u=Number(c.buttonIndex),h=c.button||((f=p==null?void 0:p.modalButtons)==null?void 0:f[u])||"Approve",b=String(h).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),y=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(b);t(m,"resolve_action",{action:y?"approve":"reject",button:h,...Number.isFinite(u)&&{buttonIndex:u},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(w=>console.error("[SW Action] approval failed:",w))};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 Vy="adhdev_dashboardLayout_v1",qy="adhdev_dashboardDockview_v1",Yy="adhdev_dashboardDockviewHiddenRestore_v1",br={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 Jy(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function ep(e){return`${Vy}:${e}`}function Xy(e){const t=ep(e);return Li(t,null)}function Qy(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=ep(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function tp(e){return`${qy}:${e}`}function Zy(e){const t=tp(e);return Li(t,null)}function ev(e,t){try{const r=tp(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function sp(e){return`${Yy}:${e}`}function tv(e){const t=sp(e);return Li(t,{})}function sv(e,t){try{const r=sp(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function rv(){return{groupAssignments:[...br.groupAssignments],focusedGroup:br.focusedGroup,groupActiveTabIds:{...br.groupActiveTabIds},groupTabOrders:{...br.groupTabOrders},groupSizes:[...br.groupSizes]}}function nv(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function av(){const[e]=l.useState(()=>Jy(typeof window<"u"?window.innerWidth:1280)),[t,r]=l.useState(()=>new Map),[n,a]=l.useState(0),[o,i]=l.useState({}),[c,d]=l.useState({}),[p,m]=l.useState([]),[u,h]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[b,y]=l.useState(!1),f=l.useCallback(()=>{if(b)return;const I=Xy(e)??rv();r(new Map(I.groupAssignments)),a(I.focusedGroup),i(I.groupActiveTabIds),d(I.groupTabOrders),m(I.groupSizes),y(!0)},[b,e]);l.useEffect(()=>{b&&Qy(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[b,e,t,n,o,c,p]),l.useEffect(()=>{const I=window.matchMedia("(max-width: 767px)"),P=L=>h(L.matches);return I.addEventListener("change",P),()=>I.removeEventListener("change",P)},[]);const w=l.useCallback(I=>{r(I)},[]),j=l.useCallback(I=>{a(I)},[]),g=l.useCallback(I=>{i(I)},[]),v=l.useCallback(I=>{d(I)},[]),k=l.useCallback(I=>{m(I)},[]),N=l.useCallback(I=>{j(I)},[j]),x=l.useCallback((I,P)=>{i(L=>(L[I]??null)===(P??null)?L:{...L,[I]:P})},[]),C=l.useCallback((I,P)=>{d(L=>{const A=L[I];return nv(A,P)?L:{...L,[I]:P}})},[]),S=l.useCallback((I,P)=>{const L=P.get(I)??0;return x(L,I),N(L),L},[N,x]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:w,focusedGroup:n,updateFocusedGroup:j,focusGroup:N,groupActiveTabIds:o,updateGroupActiveTabIds:g,setGroupActiveTab:x,groupTabOrders:c,updateGroupTabOrders:v,setGroupTabOrder:C,groupSizes:p,updateGroupSizes:k,isMobile:u,hasHydratedStoredLayout:b,hydrateStoredLayout:f,focusConversationTab:S}}function ov(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=va(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function iv({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:p,isRefreshingHistory:m,ides:u,handleRefreshHistory:h}){const b=l.useRef(!1),y=l.useRef(!1),f=l.useRef(null),w=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,y.current=!0,f.current!=null&&(window.clearTimeout(f.current),f.current=null),c(g=>{const v=new URLSearchParams(g);return v.delete("activeTab"),v},{replace:!0}))},[e,t,r,n,a,o,i,c]),l.useEffect(()=>{if(!(y.current||a)&&t.length!==0){if(!e){o(),y.current=!0;return}if(b.current){y.current=!0;return}if(f.current==null)return f.current=window.setTimeout(()=>{f.current=null,!(y.current||a)&&(o(),y.current=!0)},1500),()=>{f.current!=null&&(window.clearTimeout(f.current),f.current=null)}}},[e,t.length,a,o]),l.useEffect(()=>{if(!d){w.current=!1;return}if(!p||w.current||m)return;const j=u.find(g=>g.id===p.routeId);j&&(!j.chats||j.chats.length===0||ov(j.chats,p))&&(w.current=!0,h())},[d,p,m,u,h])}function Xa(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=va(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function rp({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[i,c]=l.useState(!1),[d,p]=l.useState(!1),m=l.useCallback(async y=>{try{await e("standalone","launch_ide",{ideType:y,enableCdp:!0})}catch(f){console.error("Launch failed",f)}},[e]),u=l.useCallback(async(y,f)=>{try{const w=y||(t==null?void 0:t.daemonId)||"",j=await e(w,"switch_chat",{id:f,sessionId:f,...ks(t)}),g=j==null?void 0:j.result;if((j==null?void 0:j.success)===!0||g==="switched"||g==="switched-by-title")return;g===!1||g==="not_found"?pr(a,"⚠️ Session tab not found — try refreshing history"):typeof g=="string"&&g.startsWith("error:")?pr(a,`⚠️ Switch error: ${g}`):pr(a,"⚠️ Session switch failed")}catch(w){console.error("Switch failed",w),pr(a,`❌ Switch failed: ${w.message||"connection error"}`)}},[t,e,a]),h=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const y=Ns(t);await e(y,"new_chat",{...ks(t)}),dg(y,t.sessionId,va(t)[0]),o(f=>({...f,[t.tabKey]:Date.now()}))}catch(y){console.error("New chat failed",y)}finally{c(!1)}}},[t,i,e,o]),b=l.useCallback(async()=>{var y,f;if(!(!t||d)){p(!0);try{const w=Ns(t),j=async()=>e(w,"list_chats",{forceExpand:!0,...ks(t)});let g=await j(),v=(g==null?void 0:g.chats)||((y=g==null?void 0:g.result)==null?void 0:y.chats);Xa(v,t)&&(await new Promise(k=>setTimeout(k,450)),g=await j(),v=(g==null?void 0:g.chats)||((f=g==null?void 0:g.result)==null?void 0:f.chats)),g!=null&&g.success&&Array.isArray(v)&&(n(t.routeId,v),Xa(v,t)&&!Xa(r,t)&&pr(a,"⚠️ History dialog did not fully open — try once more"))}catch(w){console.error("Refresh history failed",w)}finally{p(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:m,handleSwitchSession:u,handleNewChat:h,handleRefreshHistory:b}}function lv(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 cv(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function hc(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 fc(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 dv(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 uv(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 xc(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 bc(e){return Array(e).fill(100/e)}function pv({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:p}){const m=l.useRef(null),u=l.useMemo(()=>vn(e,p),[e,p]),h=u.assignments,b=l.useMemo(()=>c?1:u.groupCount,[u.groupCount,c]),y=b>1,f=l.useCallback((N,x)=>{t(C=>{const S=new Map(vn(C,p).assignments);return x===0?S.delete(N):S.set(N,x),S}),n(C=>({...C,[x]:N})),r(x)},[t,p,n,r]),w=l.useCallback(N=>{t(x=>{const C=vn(x,p).assignments,S=new Map;for(const[I,P]of C)P!==N&&(P>N?S.set(I,P-1):S.set(I,P));return S}),i(x=>{if(x.length<=1)return[];const C=[...x];C.splice(N,1);const S=C.reduce((I,P)=>I+P,0);return S>0?C.map(I=>I/S*100):[]}),r(0)},[t,p,i,r]),j=l.useCallback((N,x)=>{x.preventDefault();const C=m.current;if(!C)return;const S=x.clientX,I=C.offsetWidth,P=o.length===b?[...o]:bc(b),L=R=>{const X=(R.clientX-S)/I*100,T=[...P];T[N]=Math.max(15,P[N]+X),T[N+1]=Math.max(15,P[N+1]-X),i(T)},A=()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",A),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",L),document.addEventListener("mouseup",A)},[o,b,i]),g=l.useCallback((N,x,C)=>{if(b>=4)return;const S=C==="left"?x:x+1;t(I=>{const P=vn(I,p).assignments,L=new Map;for(const A of d){const R=P.get(A.tabKey)??0,$=R>=S?R+1:R;$>0&&L.set(A.tabKey,$)}return S>0&&L.set(N,S),L}),i(I=>{const P=I.length===b?[...I]:bc(b),L=P[x]??100/b,A=Math.max(15,L/2),R=Math.max(15,L/2),$=[...P];$[x]=A,$.splice(S,0,R);const X=$.reduce((T,M)=>T+M,0);return $.map(T=>T/X*100)}),n(I=>{const P=xc(I,S);return P[S]=N,P}),a(I=>{const P=xc(I,S);return P[S]=[N],P}),r(S)},[b,t,p,d,i,n,a,r]);l.useEffect(()=>{lv(e,h)||t(h)},[e,h,t]),l.useEffect(()=>{const{mapping:N,usedGroups:x}=u;n(C=>{const S=fc(C,N);return hc(C,S)?C:S}),a(C=>{const S=fc(C,N);return hc(C,S)?C:S}),r(C=>{const S=c?0:dv(C,x,N);return C===S?C:S}),i(C=>{const S=c?[]:uv(C,x,u.groupCount);return cv(C,S)?C:S})},[u,c,n,a,r,i]);const v=l.useMemo(()=>{const N=Array.from({length:b},()=>[]);for(const x of d){const C=h.get(x.tabKey)??0,S=Math.min(C,b-1);N[S].push(x)}return N},[d,h,b]),k=l.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:m,normalizedGroupAssignments:h,numGroups:b,isSplitMode:y,groupedConvs:v,moveTabToGroup:f,closeGroup:w,handleResizeStart:j,splitTabRelative:g,clearAllSplits:k}}function Qa(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 mv(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 Pi(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=Qa(t.channel)||Qa(e.updateChannel)||Qa(e.releaseChannel)||void 0,n=mv(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 Ks(e,t=null){return Pi(e).targetVersion||t}function np(e){return Pi(e).channel||null}function ap(e){const t=Pi(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 hv({ides:e,sendDaemonCommand:t}){const r="0.9.82",n=l.useMemo(()=>e.filter(u=>u.type!=="adhdev-daemon"?!1:Ai(u,Ks(u,r))).sort((u,h)=>Number(_r(h,Ks(h,r)))-Number(_r(u,Ks(u,r)))),[r,e]),a=l.useMemo(()=>n.some(u=>_r(u,Ks(u,r))),[r,n]),o=l.useMemo(()=>n.map(u=>Ks(u,r)).find(u=>typeof u=="string"&&u.trim().length>0)||r,[r,n]),[i,c]=l.useState(!1),[d,p]=l.useState({}),m=l.useCallback(async u=>{var b,y;const h=e.find(f=>f.id===u);if(h){p(f=>({...f,[u]:"upgrading"}));try{const f=await t(u,"daemon_upgrade",ap(h));(b=f==null?void 0:f.result)!=null&&b.upgraded||(y=f==null?void 0:f.result)!=null&&y.success?p(w=>({...w,[u]:"done"})):p(w=>({...w,[u]:"error"}))}catch{p(f=>({...f,[u]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:m}}const op=80;function Bn(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function fv(e){return{...e,createdAt:Bn(e.createdAt),updatedAt:Bn(e.updatedAt,e.createdAt),lastEventAt:Bn(e.lastEventAt,e.updatedAt||e.createdAt)}}function xv(e){const t=Br(e);return t==="unknown:"?e.id:t}function bv(e){return[e.type,pu(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function gv(e,t=op){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=xv(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 yv(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),p=bv({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(fv({id:p,dedupKey:p,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:su(a),preview:wb(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return gv(n)}function vv(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function wv(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=op}=e,a=l.useMemo(()=>yv(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=l.useMemo(()=>vv(a),[a]);return{notifications:a,unreadCount:o}}function jv({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 Di(...e){const t=new Set,r=[],n=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),r.push(o))};for(const a of e){if(Array.isArray(a)){for(const o of a)n(o);continue}n(a)}return r}function kv(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 $i(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=kv(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 Nv(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 Sv(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Ei(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=Sv(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const o=typeof(a==null?void 0:a.path)=="string"?a.path:r,i=o.includes("\\")?"\\":"/",c=(p,m)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${m}`:p==="/"||p==="\\"?`${i}${m}`:`${p.replace(/[\\/]+$/,"")}${i}${m}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:c(o,p.name)})).sort((p,m)=>p.name.localeCompare(m.name)):[];return{path:o,directories:d}}function Cv(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 ip(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:Cv(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function Iv(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 Or(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function lp(e){return qr(e)||e.tabKey||e.routeId||null}function cp(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 us(e){return String(e||"").trim()}function dp(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 Mv(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Av(e,t){const r=us(e.providerSessionId),n=us(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(us).filter(Boolean);return!!(r&&i.includes(r)||n&&i.includes(n))});return a?a.tabKey:n||r||null}function Tv(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=dp(t.daemonId);if(n&&n!==e.machineId)return null;const a=us(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=us(e.resumeSessionId),i=us(e.launchedSessionId),c=us(t.providerSessionId),d=us(t.targetSessionId);if(o&&o!==c&&o!==d||i&&i!==c&&i!==d)return null;const p=la(e.workspacePath);if(p){const m=la(t.workspaceName);if(m&&!Mv(m,p))return null}return Av(t,r)}function gc(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function _v({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),p=e.find(u=>{var w,j,g,v;if(!u||u.type==="adhdev-daemon"||dp(u.daemonId||u.id)!==n.machineId||(Er(u)?"cli":Gs(u)?"acp":"ide")!==n.kind)return!1;const y=String(u.agentType||u.type||"");if(n.providerType&&y!==n.providerType)return!1;if(n.resumeSessionId)return String(u.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const k=String(n.launchedSessionId||"");return[u.providerSessionId,u.sessionId,u.instanceId,u.id].map(x=>String(x||"")).filter(Boolean).includes(k)}if(d){const k=la(u.workspace||u.runtimeWorkspaceLabel);return k?k===d:!1}return Number(u.lastUpdated||u._lastUpdate||u.timestamp||((v=(g=(j=(w=u.activeChat)==null?void 0:w.messages)==null?void 0:j.at)==null?void 0:g.call(j,-1))==null?void 0:v.timestamp)||0)>=n.startedAt-5e3});if(!p)return;const m=cp({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});m&&(i(),r(m))},[i,t,e,r,n]),l.useEffect(()=>it.onStatusEvent(d=>{const p=o.current;if(!p)return;const m=Tv(p,d,t);m&&(i(),r(m))}),[i,t,r]),l.useEffect(()=>{if(!n)return;const d=window.setTimeout(()=>{a(p=>!p||p.startedAt!==n.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[n]),{trackPendingLaunch:c}}function Rv({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const i=fi(),{launchCli:c}=ma(),d=l.useCallback(async(w,j)=>Ei(e,w,j),[e]),p=l.useCallback(async(w,j)=>{if(!j.trim())return{ok:!1,error:"Choose a workspace path first."};try{const g=await e(w,"workspace_add",{path:j.trim()});return g!=null&&g.success?{ok:!0}:{ok:!1,error:(g==null?void 0:g.error)||"Could not save workspace"}}catch(g){return{ok:!1,error:g instanceof Error?g.message:"Could not save workspace"}}},[e]),m=l.useCallback(async(w,j,g)=>{var v;try{const k={ideType:j,enableCdp:!0};(v=g==null?void 0:g.workspacePath)!=null&&v.trim()&&(k.workspace=g.workspacePath.trim());const N=await e(w,"launch_ide",k);return!(N!=null&&N.success)&&(N==null?void 0:N.success)!==void 0?{ok:!1,error:(N==null?void 0:N.error)||"Could not launch IDE"}:(t({machineId:w,kind:"ide",providerType:j,workspacePath:(g==null?void 0:g.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(k){return{ok:!1,error:k instanceof Error?k.message:"Could not launch IDE"}}},[e,t]),u=l.useCallback(async(w,j,g,v)=>{var N,x,C;const k=Date.now();try{const S={cliType:g};(N=v==null?void 0:v.workspacePath)!=null&&N.trim()?S.dir=v.workspacePath.trim():v!=null&&v.workspaceId&&(S.workspaceId=v.workspaceId),(x=v==null?void 0:v.resumeSessionId)!=null&&x.trim()&&(S.resumeSessionId=v.resumeSessionId.trim()),Array.isArray(v==null?void 0:v.cliArgs)&&v.cliArgs.length>0&&(S.cliArgs=v.cliArgs),(C=v==null?void 0:v.initialModel)!=null&&C.trim()&&(S.initialModel=v.initialModel.trim());const I=await c(w,S),P=(I==null?void 0:I.result)||I,L=(P==null?void 0:P.sessionId)||(P==null?void 0:P.id);return I!=null&&I.success&&L?(t({machineId:w,kind:j,providerType:g,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,launchedSessionId:L,startedAt:k}),{ok:!0}):I!=null&&I.success?(t({machineId:w,kind:j,providerType:g,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:k}),{ok:!0}):{ok:!1,error:(I==null?void 0:I.error)||(P==null?void 0:P.error)||`Could not launch ${j.toUpperCase()} session`}}catch(S){return gc(S)?(t({machineId:w,kind:j,providerType:g,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:k}),{ok:!0}):{ok:!1,error:S instanceof Error?S.message:`Could not launch ${j.toUpperCase()} session`}}},[c,e,t]),h=l.useCallback(async w=>{var j;if(i!=null&&i.listMeshes)return i.listMeshes(w);if(!w)return[];try{const g=await e(w,"list_meshes",{}),v=(g==null?void 0:g.result)??g;if((v==null?void 0:v.success)===!1)throw new Error((v==null?void 0:v.error)||"Could not load meshes");return(Array.isArray(v==null?void 0:v.meshes)?v.meshes:Array.isArray((j=v==null?void 0:v.result)==null?void 0:j.meshes)?v.result.meshes:[]).map(N=>{var x;return{id:String((N==null?void 0:N.id)||""),name:String((N==null?void 0:N.name)||(N==null?void 0:N.id)||"Untitled mesh"),repoIdentity:(N==null?void 0:N.repoIdentity)||(N==null?void 0:N.repo_identity)||null,workspace:Array.isArray(N==null?void 0:N.nodes)&&N.nodes.length>0?String(((x=N.nodes[0])==null?void 0:x.workspace)||""):null,nodesCount:Array.isArray(N==null?void 0:N.nodes)?N.nodes.length:void 0,status:(N==null?void 0:N.status)||null}}).filter(N=>N.id)}catch(g){throw console.error("List meshes failed",g),g}},[i,e]),b=l.useCallback(async(w,j,g)=>{if(!j.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(w,j,g);const v=Date.now();try{const k={meshId:j.trim()};g.trim()&&(k.cliType=g.trim());const N=await e(w,"launch_mesh_coordinator",k),x=(N==null?void 0:N.result)??N;if((x==null?void 0:x.success)===!1||(N==null?void 0:N.success)===!1){const S=String((x==null?void 0:x.code)||(N==null?void 0:N.code)||""),I=Iv((x==null?void 0:x.meshCoordinatorSetup)||(x==null?void 0:x.manualSetup)||(N==null?void 0:N.meshCoordinatorSetup)||(N==null?void 0:N.manualSetup));return{ok:!1,error:(x==null?void 0:x.error)||(N==null?void 0:N.error)||"Could not launch mesh coordinator",code:S||void 0,manualSetup:I}}const C=(x==null?void 0:x.sessionId)||(x==null?void 0:x.id);return C?r(C):t({machineId:w,kind:"cli",providerType:(x==null?void 0:x.cliType)||g.trim()||void 0,workspacePath:(x==null?void 0:x.workspace)||null,startedAt:v}),{ok:!0}}catch(k){return gc(k)?(t({machineId:w,kind:"cli",providerType:g.trim()||void 0,startedAt:v}),{ok:!0}):{ok:!1,error:k instanceof Error?k.message:"Could not launch mesh coordinator"}}},[i,r,e,t]),y=l.useCallback(async(w,j)=>{if(!w||!j)return[];try{const g=await e(w,"list_saved_sessions",{providerType:j,kind:"cli",limit:30}),v=(g==null?void 0:g.result)??g;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(g){return console.error("List saved sessions failed",g),[]}},[e]),f=l.useCallback(async w=>{await Ju({conversation:n,mode:w,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:p,handleLaunchMachineIde:m,handleLaunchMachineProvider:u,handleListMachineMeshes:h,handleLaunchMeshCoordinator:b,handleListMachineSavedSessions:y,setActiveCliViewMode:f}}function Lv(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 Pv(e,t,r=Date.now()){return!e||!Lv(t)?null:{tabKey:e,nonce:r}}function Dv({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:i}){const[c,d]=l.useState(null),[p,m]=l.useState(null),u=l.useMemo(()=>{var w,j;if(!e){if(c){const g=t.find(v=>v.tabKey===c);if(g)return g}return r[0]}const f=n[a];if(f){const g=t.find(v=>v.tabKey===f);if(g)return g}return((w=o[a])==null?void 0:w[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(w=>{const j=new URLSearchParams(w),g=kb(f);return g?j.set("activeTab",g):j.delete("activeTab"),j},{replace:!0})},[i]),y=l.useCallback((f,w)=>{const j=Pv(f,w);j&&m(j)},[]);return{activeConv:u,openDesktopConversation:b,requestScrollToBottom:y,scrollToBottomRequest:p,setDesktopActiveTab:h}}function $v(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 Ev(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 Bv({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),d=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){p(),a.current=null;return}if(!(e!=null&&e.sessionId)){p(),a.current=null;return}const m=qn(e,r),u=Ev({tabKey:e.tabKey,historySessionId:qr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Ms(e),liveState:m}),h=u.autoReadKey,b=$v({autoReadKey:h,shouldMarkSeen:u.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!u.shouldMarkSeen){b.shouldCancelPending&&p(),a.current=h;return}if(!b.shouldSchedule)return;b.shouldCancelPending&&p();const y=()=>{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 w=u.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:w,completionMarker:u.completionMarker}).catch(()=>{})};if(o.current=b.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(y,1500);const w=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=w,document.addEventListener("visibilitychange",w);return}const f=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(y,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 Za(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 Fv({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var _;const{launchCli:p}=ma(),[m,u]=l.useState(!1),[h,b]=l.useState([]),[y,f]=l.useState(()=>_t()),[w,j]=l.useState(!1),[g,v]=l.useState(null),k=l.useRef(null),N=l.useMemo(()=>r||t||e,[e,r,t]),x=!!N&&nt(N)&&!rt(N),C=l.useMemo(()=>{if(!N||!x)return null;const B=N.daemonId||N.routeId||"",E=es(N),F=Za(N);return`${B}:${E}:${N.providerSessionId||""}:${F}`},[N,x]),S=l.useMemo(()=>!N||!x?"":Za(N),[N,x]),{isCreatingChat:I,isRefreshingHistory:P,handleSwitchSession:L,handleNewChat:A,handleRefreshHistory:R}=rp({sendDaemonCommand:a,activeConv:N,chats:(_=n.find(B=>B.id===(N==null?void 0:N.routeId)))==null?void 0:_.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),$=l.useCallback(()=>{u(!0)},[]),X=l.useCallback(()=>{u(!1)},[]),T=l.useCallback(async()=>{if(!(!N||!x||w)){j(!0);try{const B=N.daemonId||N.routeId,E=es(N),F=Za(N),K=await a(B,"list_saved_sessions",{agentType:E,providerType:E,kind:"cli",limit:50,...N.providerSessionId?{providerSessionId:N.providerSessionId}:{},...F?{workspace:F}:{}}),z=(K==null?void 0:K.result)??K;b(Array.isArray(z==null?void 0:z.sessions)?z.sessions:[])}catch(B){console.error("Refresh saved sessions failed",B),b([])}finally{j(!1)}}},[N,w,x,a]);l.useEffect(()=>{if(!m){k.current=null;return}if(!x){k.current=null,b([]),j(!1);return}!C||w||k.current!==C&&(k.current=C,T())},[T,m,w,x,C]);const M=l.useCallback(async B=>{if(!N||!x||!B.providerSessionId||!B.workspace)return;const E=N.daemonId||N.routeId,F=es(N);try{v(B.providerSessionId);const K=await p(E,{cliType:F,dir:B.workspace,resumeSessionId:B.providerSessionId,initialModel:Ud(B.summaryMetadata,"model",{preferShortValue:!0})||void 0}),z=(K==null?void 0:K.result)??K,ne=typeof(z==null?void 0:z.sessionId)=="string"?z.sessionId:typeof(z==null?void 0:z.id)=="string"?z.id:"";ne&&d(q=>{const J=new URLSearchParams(q);return J.set("activeTab",ne),J},{replace:!0}),X()}catch(K){console.error("Resume saved session failed",K)}finally{v(null)}},[X,N,x,a,d]);return{historyModalOpen:m,openHistoryModal:$,closeHistoryModal:X,historyTargetConv:N,isSavedSessionHistoryTarget:x,isHistoryCreatingChat:I,isHistoryRefreshingHistory:P,handleHistorySwitchSession:L,handleHistoryNewChat:A,handleHistoryRefresh:R,savedHistorySessions:h,savedHistoryFilters:y,setSavedHistoryFilters:f,missingWorkspaceResumePath:S,isSavedHistoryLoading:w,resumingSavedHistorySessionId:g,handleRefreshSavedHistory:T,handleResumeSavedHistorySession:M}}function Ov({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}){const[d,p]=l.useState(null),[m,u]=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 g=d!=null&&d.tabKey?o.find(v=>v.tabKey===d.tabKey):a?o.find(v=>v.tabKey===a):null;return(g==null?void 0:g.routeId)===j?g:Gt(o,j)},[o,d,a]),y=l.useMemo(()=>{if(b)return i.find(j=>j.id===b.routeId)},[i,b]);l.useEffect(()=>{h&&(p({routeId:h.routeId,tabKey:Dl(h)}),u(h),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,h]);const f=l.useCallback(j=>{j&&(p({routeId:j.routeId,tabKey:Dl(j)}),u(j))},[]),w=l.useCallback(()=>{p(null),u(null)},[]);return{remoteDialogConv:b,remoteDialogIdeEntry:y,remoteDialogActiveConv:m,setRemoteDialogActiveConv:u,openRemoteDialog:f,closeRemoteDialog:w}}function Hv({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:p}){const{remoteDialogConv:m,remoteDialogIdeEntry:u,remoteDialogActiveConv:h,setRemoteDialogActiveConv:b,openRemoteDialog:y,closeRemoteDialog:f}=Ov({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}),[w,j]=l.useState(!1),[g,v]=l.useState(null),k=l.useCallback(async C=>{const S=C||d;!S||!nt(S)&&!rt(S)||(v(S),j(!0))},[d]),N=l.useCallback(()=>{j(!1),v(null)},[]),x=l.useCallback(async C=>{const S=g||d;if(!S||!nt(S)&&!rt(S)){N();return}j(!1);try{const I=es(S),P=S.routeId||S.daemonId||"";await p(P,"stop_cli",{cliType:I,targetSessionId:S.sessionId,mode:C})}catch(I){console.error("Stop CLI failed:",I)}finally{v(null)}},[d,N,g,p]);return{remoteDialogConv:m,remoteDialogIdeEntry:u,remoteDialogActiveConv:h,setRemoteDialogActiveConv:b,openRemoteDialog:y,closeRemoteDialog:f,cliStopDialogOpen:w,cliStopTargetConv:g,requestCliStop:k,cancelCliStop:N,confirmCliStop:x}}function eo(e,t=!0){return(e??!0)&&t}const Bi=l.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:d,handleForceSendChat:p,isSendingChat:m,sendFeedbackMessage:u=null,handleFocusAgent:h,isFocusingAgent:b,actionLogs:y,userName:f,scrollToBottomRequestNonce:w,isInputActive:j=!0,isVisible:g=!0}){const v=n,k=!n,N=eo(g,v),x=eo(g,k),C=eo(g),S=Ku(t),I=S.status||S.modalMessage||S.modalButtons?{...t,...S.status?{status:S.status}:{},...S.modalMessage!==void 0?{modalMessage:S.modalMessage}:{},...S.modalButtons!==void 0?{modalButtons:S.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Hd,{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(Xs,{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:v?"visible":"hidden",pointerEvents:v?"auto":"none"},children:s.jsx(s0,{activeConv:I,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,isVisible:N,isInputActive:j&&N})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:k?"visible":"hidden",pointerEvents:k?"auto":"none"},children:s.jsx(Wo,{activeConv:I,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:h,isFocusingAgent:b,actionLogs:y,userName:f,scrollToBottomRequestNonce:w,isInputActive:j&&x,isVisible:x})})]}):s.jsx(Wo,{activeConv:I,ideEntry:a,handleSendChat:d,handleForceSendChat:p,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:h,isFocusingAgent:b,actionLogs:y,userName:f,scrollToBottomRequestNonce:w,isInputActive:j&&C,isVisible:C})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.handleForceSendChat===t.handleForceSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function zv({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var v,k,N;const i=Wr(),c=Ds(e),d=o?null:tu(e),p=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),m=!o&&e.streamSource==="agent-stream"&&!!e.agentName,u=!o&&!m&&(e.transport==="pty"||e.transport==="acp"),h=Zs(e),b=jb(e),y=(v=e.settings)==null?void 0:v.meshNodeFor,f=e.meshQueueStats,w=((k=e.coordinator)==null?void 0:k.meshId)||((N=e.settings)==null?void 0:N.meshCoordinatorFor),j=l.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),g=l.useCallback(()=>{if(r){r();return}const x=lp(e);x&&i(Or(x))},[e,i,r]);return!p&&!m&&!u&&!d&&!y&&!f?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[p&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:g,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})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(Qs,{size:12}),s.jsx("span",{children:h})]}),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(Qs,{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(fs,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(fs,{size:12}),s.jsx("span",{children:d})]})),y&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(fs,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),w&&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(zh,{size:12}),s.jsxs("span",{children:[f.pending," Pending"]})]})]})}function Wv({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:p,onOpenNativeConversation:m,onOpenMachine:u,onOpenHistory:h,onOpenRemote:b,onOpenMeshGraph:y,onStopCli:f,cliViewMode:w,onSetCliViewMode:j,handleSendChat:g,handleForceSendChat:v,handleFocusAgent:k,handleModalButton:N,handleRelaunch:x}){var A,R;const C=l.useRef(null),S=nt(e)&&!t,I=S&&w==="terminal",P=!!e.daemonId&&!!((A=e.coordinator)!=null&&A.meshId||(R=e.settings)!=null&&R.meshCoordinatorFor),L=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${L} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(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(zv,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>m(e),onOpenMachine:()=>u(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S&&w&&s.jsx(Su,{mode:w,onChange:j,compact:!0}),S&&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})}),P&&y&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>y(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&&!S&&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(Bi,{activeConv:e,clearToken:0,isCliTerminal:I,ideEntry:n,terminalRef:C,handleModalButton:N,handleRelaunch:x,handleSendChat:g,handleForceSendChat:v,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:k,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const to={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 Kv(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function up(){const[e,t]=l.useState("unix"),[r,n]=l.useState("powershell"),[a,o]=l.useState(!1),i=e==="unix"?"unix":r;l.useEffect(()=>{t(Kv())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(to[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:to[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:to[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 pp({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:qt},{key:"chats",label:"Chats",icon:Ps}];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 Fs({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 gr({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 Uv({conversation:e,onCancel:t,onConfirm:r}){const n=pt(e),a=_s(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 A,R;const p=t==="needs_attention"||t==="task_complete",m=t==="working",u=t==="earlier",h=t==="task_complete",{isReconnecting:b,isConnecting:y}=nr(e.conversation),f=pt(e.conversation),w=_s(e.conversation),j=wu(e.conversation,{requiresAction:t==="needs_attention"}),g=p?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":u?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",v=p?"bg-accent-primary shadow-glow":m?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":u?"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",k=u?"text-text-secondary":"text-text-primary",N=u?"text-text-muted":"text-text-secondary",x=u?"text-text-secondary opacity-80":"text-text-muted",C=u?"text-text-muted opacity-80":"text-text-muted",S=!m&&!h,I=!!e.conversation.daemonId&&!!((A=e.conversation.coordinator)!=null&&A.meshId||(R=e.conversation.settings)!=null&&R.meshCoordinatorFor),P="text-[color:var(--status-warning)]",L=$=>{if(!i)return;$.preventDefault(),$.stopPropagation();const X=i==null?void 0:i(e.conversation);Promise.resolve(X).catch(T=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",T)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${g}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[p||m?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${v}`,style:p?{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(Kr,{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 ${k}`,children:f}),S&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${C}`,children:Od(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${N}`,children:[s.jsx("span",{className:"truncate",children:w}),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:`${P} animate-pulse`,children:"Reconnecting…"})]}):y?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:P,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${x}`,children:e.preview})]}),p&&!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"}),m&&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 yc({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 Gv({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:p,onOpenConversation:m,onShowAllHidden:u,onHideConversation:h,onOpenMeshGraph:b,onOpenNewSession:y,onOpenMachine:f,onOpenSettings:w,onSectionChange:j,wsStatus:g="connected",isStandalone:v=!1,onCollectChatDebugBundle:k,isConversationMuted:N,onToggleMuteConversation:x}){const[C,S]=l.useState(null),I=g==="disconnected"||g==="reconnecting"||g==="offline"||g==="auth_failed",P=i.length>0,L=t.length>0||r.length>0||n.length>0||a.length>0,A=e==="machines"?"Machines":"Chats",R=v?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",$=v?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",X=l.useCallback(async _=>{const B=Ns(_);if(!B)return;const E=Array.isArray(_.messages)?_.messages:[],F=iu({activeConv:_,visibleMessages:E,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:E.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),K=await p(B,"get_chat_debug_bundle",{...ks(_),delivery:"daemon_file",frontendSnapshot:F}),z=Mr(K),ne=du(z),q=await cu(ne);q==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),it.showToast(lu(z,{locatorCopyStatus:q}),q==="failed"?"warning":"success")},[d,p]),T=k||X,M=l.useCallback(()=>{C&&(h==null||h(C),S(null))},[C,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 ${R}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:A}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||r.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(Kr,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:w,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(gr,{icon:s.jsx(yc,{}),title:g==="offline"?"Network offline":g==="auth_failed"?"Session expired":"Reconnecting",subtitle:g==="offline"?"Waiting for network…":g==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):i.length===0?s.jsx(gr,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:v?"Waiting for your daemon":"Connect your machines",subtitle:v?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can launch sessions with any installed provider.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!v&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(up,{})})}):s.jsx(Fs,{children:i.map((_,B)=>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] ${B>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(_.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:c(_.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:_.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:_.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[_.unread," new"]}):_.total>0?`${_.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:_.subtitle}),_.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[_.total," chat",_.total!==1?"s":"",_.unread>0?` · ${_.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},_.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(jn,{title:"Needs attention",className:"mb-0"}),s.jsx(Fs,{children:t.map((_,B)=>s.jsx("div",{className:B>0?"border-t border-border-subtle/70":"",children:s.jsx(kn,{item:_,type:"needs_attention",getAvatarText:c,onOpenConversation:m,onRequestHideConversation:h?()=>S(_.conversation):void 0,onOpenMeshGraph:b,onCollectChatDebugBundle:T,isMuted:N==null?void 0:N(_.conversation),onToggleMute:x?()=>x(_.conversation):void 0})},_.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(jn,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(Fs,{children:r.map((_,B)=>s.jsx("div",{className:B>0?"border-t border-border-subtle/70":"",children:s.jsx(kn,{item:_,type:"task_complete",getAvatarText:c,onOpenConversation:m,onRequestHideConversation:h?()=>S(_.conversation):void 0,onOpenMeshGraph:b,onCollectChatDebugBundle:T,isMuted:N==null?void 0:N(_.conversation),onToggleMute:x?()=>x(_.conversation):void 0})},_.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(jn,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(Fs,{children:n.map((_,B)=>s.jsx("div",{className:B>0?"border-t border-border-subtle/70":"",children:s.jsx(kn,{item:_,type:"working",getAvatarText:c,onOpenConversation:m,onRequestHideConversation:h?()=>S(_.conversation):void 0,onOpenMeshGraph:b,onCollectChatDebugBundle:T,isMuted:N==null?void 0:N(_.conversation),onToggleMute:x?()=>x(_.conversation):void 0})},_.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(jn,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(Fs,{children:a.map((_,B)=>s.jsx("div",{className:B>0?"border-t border-border-subtle/70":"",children:s.jsx(kn,{item:_,type:"earlier",getAvatarText:c,onOpenConversation:m,onRequestHideConversation:h?()=>S(_.conversation):void 0,onOpenMeshGraph:b,onCollectChatDebugBundle:T,isMuted:N==null?void 0:N(_.conversation),onToggleMute:x?()=>x(_.conversation):void 0})},_.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(gr,{icon:s.jsx(yc,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):P?s.jsx(gr,{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(Ps,{size:20})}),title:"No conversations yet",subtitle:Cu,children:y&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:y,"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(gr,{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(Fs,{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:u,children:"Restore all"})]})})})]}),e==="chats"&&y&&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:y,"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"})]})}),C&&s.jsx(Uv,{conversation:C,onCancel:()=>S(null),onConfirm:M}),s.jsx(pp,{section:e,onSectionChange:j})]})}function Vv(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 mp(e){const t=[e.workspace||"Workspace unknown"],r=Ts(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Vv(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Fi({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:d,onConfirm:p}){const[m,u]=l.useState(r);l.useEffect(()=>{u(r)},[r]);const h=Nv(r),b=m.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:m,onChange:y=>u(y.target.value),onKeyDown:y=>{y.key!=="Enter"||!b||a||(y.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(y=>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(y.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(Js,{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:y.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:y.path})]})]},y.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(b||r),disabled:!b&&!r||a,children:i})]})]})})}function hp({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:i="Launch",busyLabel:c="Launching…",busy:d=!1,showArgsInput:p,argsValue:m,onArgsChange:u,showModelInput:h,modelValue:b,onModelChange:y,historyProviderNode:f,onConfirm:w,onCancel:j}){const g=n==null?void 0:n.find(v=>v.key===a);return s.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:j,"aria-label":"Close launch confirmation",children:s.jsx(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:v=>o(v.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:n.map(v=>s.jsx("option",{value:v.key,children:v.label},v.key))}),(g==null?void 0:g.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:g.description})]}),f,r.map(v=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:v.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:v.value})]},`${v.label}:${v.value}`)),h&&y&&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:v=>y(v.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),p&&u&&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:m||"",onChange:v=>u(v.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:j,disabled:d,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:w,disabled:d,children:[s.jsx(Cd,{size:14}),d?c:i]})]})]})})}function vc(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function fp(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?"⭐ ":""}${vc(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:vc(i),description:i,workspaceId:null,workspacePath:i}),n){const d=`saved:${n}`;if(o.some(p=>p.key===d))return{options:o,selectedKey:d}}return c?{options:o,selectedKey:`saved:${c.id}`}:i?{options:o,selectedKey:`custom:${i}`}:{options:o,selectedKey:"__home__"}}function qv(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Yv(e){return[qv(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Jv(e){return e.lastLaunchedAt?xa(e.lastLaunchedAt):""}function xp(e){return{metaText:Yv(e),updatedLabel:Jv(e)}}function so(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Xv({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var $e,tt,Ue,Ve;const i=Vr(),[c,d]=l.useState(!1),p=((($e=e.detectedIdes)==null?void 0:$e.length)||0)>0,m=l.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),u=e.defaultWorkspaceId||null,[h,b]=l.useState(u||((tt=m[0])==null?void 0:tt.id)||""),[y,f]=l.useState(""),[w,j]=l.useState(""),[g,v]=l.useState([]),[k,N]=l.useState(!1),[x,C]=l.useState(""),[S,I]=l.useState(!1),[P,L]=l.useState(so(p,t.length,r.length)),A=l.useRef(null),[R,$]=l.useState(null),X=l.useRef("__home__"),[T,M]=l.useState("__home__"),[_,B]=l.useState(""),[E,F]=l.useState(""),[K,z]=l.useState(""),[ne,q]=l.useState([]),[J,xe]=l.useState(()=>_t().textQuery),[ue,O]=l.useState(()=>_t().workspaceQuery),[H,ve]=l.useState(()=>_t().modelQuery),[we,be]=l.useState(()=>_t().resumableOnly),[Ne,re]=l.useState(()=>_t().sortMode),[je,ce]=l.useState(!1),[U,W]=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 ie=h==="__custom__"?y.trim():((Ue=m.find(Te=>Te.id===h))==null?void 0:Ue.path)||"",ae=h==="__custom__"&&!!ie&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),D=h!=="__custom__"&&((Ve=m.find(Te=>Te.id===h))==null?void 0:Ve.path)||"",oe=l.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),ge=l.useCallback(async Te=>{N(!0),C("");try{const ze=await a(Te);j(ze.path),f(ze.path),v(ze.directories)}catch(ze){C(ze instanceof Error?ze.message:"Could not load folder")}finally{N(!1)}},[a]),pe=l.useCallback(()=>{var ze;b("__custom__"),I(!0);const Te=$i(e.platform,Di(y.trim(),D,oe,e.defaultWorkspacePath,(ze=m.find(ot=>ot.id===u))==null?void 0:ze.path,m.map(ot=>ot.path)));ge(Te)},[y,u,ge,oe,D,e.platform,m]),te=l.useCallback(Te=>{if(Te!=null&&Te.workspaceId){b(Te.workspaceId),f("");return}if(Te!=null&&Te.workspacePath){b("__custom__"),f(Te.workspacePath);return}b(""),f("")},[]),Me=l.useCallback(Te=>{if(b(Te),Te==="__custom__"){pe();return}f("")},[pe]),_e=l.useCallback(Te=>{b("__custom__"),f(Te)},[]),Ce=l.useCallback((Te,ze)=>{A.current=ze,X.current=Te.selectedWorkspaceKey||"__home__",M(Te.selectedWorkspaceKey||"__home__"),B(Te.initialArgs||""),F(Te.initialModel||""),z(""),q([]);const ot=Te.providerType?`${e.id}:${Te.providerType}`:null;if(p0(se.current,ot)){const Je=_t();xe(Je.textQuery),O(Je.workspaceQuery),ve(Je.modelQuery),be(Je.resumableOnly),re(Je.sortMode)}se.current=ot,$(Te),Te.providerType&&o&&(ce(!0),o(Te.providerType).then(Je=>q(Je||[])).catch(Je=>console.warn("Failed to load saved sessions",Je)).finally(()=>ce(!1)))},[o,e.id]),Ke=l.useMemo(()=>Iu(ne,{textQuery:J,workspaceQuery:ue,modelQuery:H,resumableOnly:we,sortMode:Ne}),[H,we,ne,Ne,J,ue]);l.useEffect(()=>{K&&(Ke.some(Te=>Te.providerSessionId===K)||z(""))},[Ke,K]);const Ze=l.useCallback(()=>{A.current&&(W(!0),A.current().finally(()=>{A.current=null,W(!1),$(null)}))},[]),me=l.useCallback(()=>{A.current=null,$(null)},[]),De=l.useCallback(Te=>{X.current=Te,M(Te)},[]);return l.useEffect(()=>{var Te;Y.current!==e.id&&(Y.current=e.id,b(u||((Te=m[0])==null?void 0:Te.id)||"__custom__"),f(""),j(""),v([]),C(""),I(!1),xe(_t().textQuery),O(_t().workspaceQuery),ve(_t().modelQuery),be(_t().resumableOnly),re(_t().sortMode),se.current=null,L(so(p,t.length,r.length)))},[r.length,t.length,u,p,e.id,m]),l.useEffect(()=>{var Te;h!=="__custom__"&&(h&&m.some(ze=>ze.id===h)||b(u||((Te=m[0])==null?void 0:Te.id)||"__custom__"))},[u,h,m]),l.useEffect(()=>{P==="ide"&&p||P==="cli"&&t.length>0||P==="acp"&&r.length>0||L(so(p,t.length,r.length))},[P,r.length,t.length,p]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:p,workspaceRows:m,defaultWorkspaceId:u,workspaceChoice:h,customWorkspacePath:y,browseCurrentPath:w,browseDirectories:g,browseBusy:k,browseError:x,browseDialogOpen:S,activeLauncherKind:P,launchConfirm:R,launchConfirmWorkspaceKeyRef:X,launchConfirmWorkspaceKey:T,launchConfirmArgs:_,launchConfirmModel:E,launchConfirmResumeId:K,launchConfirmSavedSessions:ne,launchConfirmTextFilter:J,launchConfirmWorkspaceFilter:ue,launchConfirmModelFilter:H,launchConfirmResumableOnly:we,launchConfirmSortMode:Ne,filteredLaunchConfirmSavedSessions:Ke,launchConfirmSessionsLoading:je,launchConfirmBusy:U,resolvedWorkspacePath:ie,canCreateMissingWorkspace:ae,openBrowseDialog:pe,loadBrowsePath:ge,handleWorkspaceChoiceChange:Me,chooseCustomWorkspacePath:_e,setCustomWorkspacePath:f,setBrowseDialogOpen:I,setActiveLauncherKind:L,openLaunchConfirm:Ce,handleConfirmLaunch:Ze,closeLaunchConfirm:me,setWorkspaceSelectionFromOption:te,setLaunchConfirmWorkspaceKeyAndSync:De,setLaunchConfirmArgs:B,setLaunchConfirmModel:F,setLaunchConfirmResumeId:z,setLaunchConfirmTextFilter:xe,setLaunchConfirmWorkspaceFilter:O,setLaunchConfirmModelFilter:ve,setLaunchConfirmResumableOnly:be,setLaunchConfirmSortMode:re}}function Qv({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:d,section:p,showBottomNav:m,onBack:u,onSectionChange:h,onOpenConversation:b,onOpenRecent:y,onOpenMachineDetails:f,onMachineUpgrade:w,onLaunchDetectedIde:j,onAddWorkspace:g,onBrowseDirectory:v,onLaunchWorkspaceProvider:k,onListSavedSessions:N}){const x=T=>T==="ide"?"Workspace":T==="cli"?"CLI":"ACP",C=r.slice(0,4),S=t.slice(0,3),I=Xv({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:c,onBrowseDirectory:v,onListSavedSessions:N}),P=l.useMemo(()=>C.map(T=>{const{metaText:M,updatedLabel:_}=xp(T);return{key:`recent-launch:${T.id}`,primary:T.label,secondary:M,updatedLabel:_,onClick:()=>{const{options:B,selectedKey:E}=fp({machine:{workspaces:I.workspaceRows,defaultWorkspaceId:I.defaultWorkspaceId},currentWorkspacePath:T.workspace});I.openLaunchConfirm({title:T.kind==="ide"?sa("restart-ide",T.label):T.providerSessionId?Mu(T.label):sa("start-fresh",T.label),description:T.kind==="ide"?ra("restart-ide"):T.providerSessionId?Au():ra("start-fresh"),confirmLabel:T.kind==="ide"?na("restart-ide"):T.providerSessionId?ta(!0):na("start-fresh"),busyLabel:T.kind==="ide"?aa("restart-ide"):T.providerSessionId?Ci(!0):aa("start-fresh"),workspaceOptions:B,selectedWorkspaceKey:E,details:[{label:"Mode",value:x(T.kind)},...T.providerType?[{label:"Provider",value:T.providerType}]:[]]},async()=>{const F=B.find(K=>K.key===I.launchConfirmWorkspaceKeyRef.current);I.setWorkspaceSelectionFromOption(F),await y({...T,workspace:(F==null?void 0:F.workspacePath)??null})})}}}),[I,y,C]),L=l.useMemo(()=>S.map(T=>({key:`recent-chat:${T.conversation.tabKey}`,primary:pt(T.conversation),secondary:zg(T.conversation,{timestampLabel:T.timestamp?Od(T.timestamp):null}),unread:T.unread,onClick:()=>b(T.conversation)})),[b,S]),A=I.showAllRecent?P:P.slice(0,4),R=P.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:u,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(T=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${T.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:T.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:T.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:T.secondary})]},T.key))})]}),R&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:A.map(T=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:T.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:T.primary}),T.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:T.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:T.secondary})]},T.key))}),P.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(T=>!T),children:I.showAllRecent?"Show fewer":`Show ${P.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:w,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(Fi,{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:T=>{I.loadBrowsePath(T)},onConfirm:T=>{I.chooseCustomWorkspacePath(T),I.setBrowseDialogOpen(!1)}}),I.launchConfirm&&s.jsx(hp,{title:I.launchConfirm.title,description:I.launchConfirm.description,details:I.launchConfirm.details,workspaceOptions:I.launchConfirm.workspaceOptions,selectedWorkspaceKey:I.launchConfirmWorkspaceKey,onWorkspaceChange:I.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:I.launchConfirm.providerType?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:Ii()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:I.launchConfirmTextFilter,onChange:T=>I.setLaunchConfirmTextFilter(T.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:I.launchConfirmWorkspaceFilter,onChange:T=>I.setLaunchConfirmWorkspaceFilter(T.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:I.launchConfirmModelFilter,onChange:T=>I.setLaunchConfirmModelFilter(T.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),s.jsxs("select",{value:I.launchConfirmSortMode,onChange:T=>I.setLaunchConfirmSortMode(T.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled: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:T=>I.setLaunchConfirmResumableOnly(T.target.checked),disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:I.launchConfirmResumeId,onChange:T=>I.setLaunchConfirmResumeId(T.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:f0()}),I.filteredLaunchConfirmSavedSessions.map(T=>s.jsxs("option",{value:T.providerSessionId,disabled:!T.canResume,children:[T.title||T.providerSessionId," ",T.canResume?"":"(workspace missing)"]},T.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 T=I.filteredLaunchConfirmSavedSessions.find(_=>_.providerSessionId===I.launchConfirmResumeId);if(!T)return null;const M=mp(T);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:M.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:M.providerSessionId}),s.jsx("div",{className:"mt-1",children:M.metaLine}),M.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:M.updatedLabel}),M.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:M.preview})]})})()]}),onConfirm:I.handleConfirmLaunch,onCancel:I.closeLaunchConfirm}),m&&s.jsx(pp,{section:p,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 Zv(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 ew(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 tw(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:Ts(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=Er(n)?"cli":Gs(n)?"acp":"ide",o=Ts(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((i=n.activeChat)==null?void 0:i.title)||(Er(n)?n.cliName||n.type:Gs(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Gs(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 sw(e,t){const r=new Map;for(const n of t){const a=Ds(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((u,h)=>h.timestamp-u.timestamp)[0]||null,i=(o==null?void 0:o.conversation)||null,c=Po(n),d=a.filter(u=>u.unread||u.requiresAction).length,p=ew(n),m=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:Ft(n,{fallbackId:n.id}),subtitle:m.join(" · "),unread:d,total:a.length,latestConversation:i,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:c,preview:i?Wg(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 rw(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 nw({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:m,onRequestedMachineConsumed:u,requestedMobileSection:h,onRequestedMobileSectionConsumed:b,setSelectedTabKey:y,setScreen:f,setSelectedMachineId:w,setSection:j,setMachineBackTarget:g,resetMachineAction:v}){const k=l.useRef(null),N=l.useCallback(x=>{if(!(x!=null&&x.sessionId))return;const C=qn(x,i),S=Math.max(Date.now(),Ms(x),C.lastUpdated||0);Nn("mark_read:start",{tabKey:x.tabKey,sessionId:x.sessionId,displayPrimary:pt(x),inboxBucket:C.inboxBucket,unread:C.unread,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,activityAt:Ms(x),readAt:S}),c(Ds(x)||x.routeId,"mark_session_seen",{sessionId:x.sessionId,providerSessionId:x.providerSessionId,seenAt:S,completionMarker:C.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 C;if(!n){rw(o)&&f("inbox"),y(((C=e[0])==null?void 0:C.tabKey)||null),k.current=null;return}if(o!=="chat"){k.current=null;return}const x=`${n.tabKey}:${n.sessionId||""}`;k.current!==x&&(k.current=x,N(n))},[e,N,o,n,f,y]),l.useEffect(()=>{if(!d)return;const x=e.find(C=>C.tabKey===d);x&&(y(x.tabKey),f("chat"),p==null||p())},[e,p,d,f,y]),l.useEffect(()=>{if(!m)return;const x=t.find(C=>C.id===m);x&&(w(x.id),v(),j("machines"),g("inbox"),f("machine"),u==null||u())},[t,u,m,v,g,f,j,w]),l.useEffect(()=>{h&&(j(h),f("inbox"),b==null||b())},[b,h,f,j]),l.useEffect(()=>{const x=r.filter(C=>C.inboxBucket==="task_complete"||C.unread);x.length!==0&&Nn("inbox_state",{screen:o,selectedTabKey:a,items:x.map(C=>{const S=qn(C.conversation,i);return{liveState:S,tabKey:C.conversation.tabKey,sessionId:C.conversation.sessionId,displayPrimary:pt(C.conversation),serverBucket:S.inboxBucket,computedBucket:C.inboxBucket,serverUnread:S.unread,computedUnread:C.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:Ms(C.conversation)}})})},[r,i,o,a]),{markConversationRead:N}}function aw(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function wc(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ow(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function iw({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const{launchCli:a}=ma(),[o,i]=l.useState("idle"),[c,d]=l.useState(""),[p,m]=l.useState(null),u=l.useCallback(()=>{i("idle"),d(""),m(null)},[]),h=l.useCallback(async(v,k,N)=>{var x;try{i("loading"),d(`Launching ${k}…`);const C={ideType:k,enableCdp:!0};(x=N==null?void 0:N.workspacePath)!=null&&x.trim()&&(C.workspace=N.workspacePath.trim()),await e(v,"launch_ide",C),i("done"),d(`${k} launch requested`)}catch(C){i("error"),d(C instanceof Error?C.message:"Launch IDE failed"),console.error("Launch IDE failed",C)}},[e]),b=l.useCallback(async(v,k,N)=>{if(k.trim())try{i("loading"),d(N!=null&&N.createIfMissing?"Creating folder…":"Saving workspace…");const x=await e(v,"workspace_add",{path:k.trim(),createIfMissing:(N==null?void 0:N.createIfMissing)===!0});if(x!=null&&x.success){i("done"),d(N!=null&&N.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]),y=l.useCallback(async v=>{var k,N,x,C,S,I;try{i("loading"),d("Starting daemon upgrade…");const P=await e(v,"daemon_upgrade",{});if((k=P==null?void 0:P.result)!=null&&k.alreadyLatest){i("done"),d(`Already on v${((N=P==null?void 0:P.result)==null?void 0:N.version)||"latest"}.`);return}if((x=P==null?void 0:P.result)!=null&&x.upgraded||(C=P==null?void 0:P.result)!=null&&C.success){i("done"),d(`Upgrade to v${((S=P==null?void 0:P.result)==null?void 0:S.version)||"latest"} started. Daemon is restarting…`);return}i("error"),d(((I=P==null?void 0:P.result)==null?void 0:I.error)||"Upgrade failed")}catch(P){i("error"),d(P instanceof Error?P.message:"Upgrade failed")}},[e]),f=l.useCallback(async(v,k,N,x)=>{var I,P,L;const C=Date.now(),S={machineId:v,kind:k,providerType:N,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:C};try{i("loading"),d(`Launching ${N}…`),m(S);const A={cliType:N};(I=x==null?void 0:x.workspacePath)!=null&&I.trim()?A.dir=x.workspacePath.trim():x!=null&&x.workspaceId&&(A.workspaceId=x.workspaceId),x!=null&&x.resumeSessionId&&(A.resumeSessionId=x.resumeSessionId),(P=x==null?void 0:x.args)!=null&&P.trim()&&(A.cliArgs=x.args.trim().split(/\s+/).filter(Boolean)),(L=x==null?void 0:x.model)!=null&&L.trim()&&(A.initialModel=x.model.trim());const R=await a(v,A),$=(R==null?void 0:R.result)||R,X=($==null?void 0:$.sessionId)||($==null?void 0:$.id);if(R!=null&&R.success&&X){m(null),i("done"),d(`${N} launched`),t(Or(X));return}if(R!=null&&R.success){i("loading"),d(`${N} launch requested — waiting for session…`);return}m(null),i("error"),d((R==null?void 0:R.error)||($==null?void 0:$.error)||`Could not launch ${k.toUpperCase()} workspace`)}catch(A){if(ow(A)){i("loading"),d(`${N} launch requested — waiting for session…`);return}m(null),i("error"),d(A instanceof Error?A.message:`Could not launch ${k.toUpperCase()} workspace`)}},[t,e]),w=l.useCallback(async(v,k)=>{try{const N=await e(v,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),x=(N==null?void 0:N.result)??N;return Array.isArray(x==null?void 0:x.sessions)?x.sessions:[]}catch(N){return console.error("Failed to list saved sessions on mobile:",N),[]}},[e]),j=l.useCallback(async(v,k)=>Ei(e,v,k),[e]);l.useEffect(()=>{if(!p)return;const v=wc(p.workspacePath),k=r.find(x=>{var A,R,$,X;if(!x||x.type==="adhdev-daemon"||aw(x.daemonId||x.id)!==p.machineId||(x.transport==="acp"?"acp":x.transport==="pty"?"cli":null)!==p.kind||String(x.agentType||x.type||"")!==p.providerType)return!1;const P=String(x.providerSessionId||"");if(p.resumeSessionId&&P)return P===p.resumeSessionId;if(v){const T=wc(x.workspace||x.runtimeWorkspaceLabel);return T?T===v:!1}return Number(x.lastUpdated||x._lastUpdate||x.timestamp||((X=($=(R=(A=x.activeChat)==null?void 0:A.messages)==null?void 0:R.at)==null?void 0:$.call(R,-1))==null?void 0:X.timestamp)||0)>=p.startedAt-5e3});if(!k)return;const N=cp({entrySessionId:k.sessionId,entryInstanceId:k.instanceId,entryRouteId:k.id,conversations:n});N&&(m(null),i("done"),d(`${p.providerType} launched`),t(Or(N)))},[n,r,t,p]),l.useEffect(()=>{if(!p)return;const v=window.setTimeout(()=>{m(k=>!k||k.startedAt!==p.startedAt?k:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(v)},[p]);const g=l.useCallback(async(v,k)=>{if(k.kind==="ide"&&k.providerType){await h(v,k.providerType,{workspacePath:k.workspace||null});return}(k.kind==="cli"||k.kind==="acp")&&k.providerType&&await f(v,k.kind,k.providerType,{workspacePath:k.workspace||null,resumeSessionId:k.providerSessionId||null})},[h,f]);return{machineAction:{state:o,message:c},resetMachineAction:u,handleLaunchDetectedIde:h,handleAddWorkspace:b,handleMachineUpgrade:y,handleLaunchWorkspaceProvider:f,handleListSavedSessions:w,handleBrowseDirectory:j,handleOpenRecent:g}}function lw({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:p}){const m=l.useCallback(j=>{o(j.tabKey),i("chat"),n(j)},[n,i,o]),u=l.useCallback(j=>{const g=e.find(v=>v.routeId===j.routeId&&v.streamSource==="native");g&&(o(g.tabKey),i("chat"),n(g))},[e,n,i,o]),h=l.useCallback(()=>{n(t),i("inbox")},[n,t,i]),b=l.useCallback((j,g="inbox")=>{c(j),a(),d("machines"),p(g),i("machine")},[a,p,i,d,c]),y=l.useCallback(j=>{const g=Ds(j);g&&b(g,"chat")},[b]),f=l.useCallback(()=>{a(),i(r)},[r,a,i]),w=l.useCallback(j=>{d(j),i("inbox")},[i,d]);return{openConversation:m,openNativeConversation:u,backFromConversation:h,openMachine:b,openConversationMachine:y,backFromMachine:f,changeMachineSection:w}}function tr(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function cw(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function dw({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:m,onRequestedMachineConsumed:u,requestedMobileSection:h,onRequestedMobileSectionConsumed:b,onOpenHistory:y,onOpenRemote:f,onStopCli:w,wsStatus:j,isConnected:g,onShowAllHiddenConversations:v,onHideConversation:k,onOpenMeshGraph:N,onOpenNewSession:x,liveSessionInboxState:C,setCliViewModeOverrides:S}){const[I,P]=l.useState(()=>{var te;return((te=e[0])==null?void 0:te.tabKey)||null}),[L,A]=l.useState(()=>e[0]?"chat":"inbox"),[R,$]=l.useState("chats"),[X,T]=l.useState(null),[M,_]=l.useState("inbox"),B=l.useRef([]),E=Wr(),F="0.9.82",K=l.useMemo(()=>e.find(te=>te.tabKey===I)||e[0]||null,[e,I]),z=l.useMemo(()=>K?r.find(te=>te.id===K.routeId):void 0,[r,K]),ne=l.useMemo(()=>!K||rt(K)||!nt(K)?null:ar(K),[K]),q=l.useMemo(()=>r.filter(te=>te.type==="adhdev-daemon").sort(pi),[r]),J=l.useMemo(()=>q.find(te=>te.id===X)||null,[q,X]),xe=ya({sendDaemonCommand:a,activeConv:K||void 0,setActionLogs:o,isStandalone:i}),ue=iw({sendDaemonCommand:a,navigate:E,ides:r,conversations:e}),O=l.useMemo(()=>e.map(te=>{const Me=L==="chat"&&(K==null?void 0:K.tabKey)===te.tabKey,_e=ba(te,C,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Me}),Ce=Ms(te),Ke=vu(te);return{conversation:te,timestamp:Ce,preview:Ke,unread:_e.unread,requiresAction:_e.requiresAction,isWorking:_e.isWorking,inboxBucket:_e.inboxBucket}}),[e,C,L,K]),{markConversationRead:H}=nw({conversations:e,machineEntries:q,items:O,selectedConversation:K,selectedTabKey:I,screen:L,liveSessionInboxState:C,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:m,onRequestedMachineConsumed:u,requestedMobileSection:h,onRequestedMobileSectionConsumed:b,setSelectedTabKey:P,setScreen:A,setSelectedMachineId:T,setSection:$,setMachineBackTarget:_,resetMachineAction:ue.resetMachineAction}),ve=lw({conversations:e,selectedConversation:K,machineBackTarget:M,markConversationRead:H,resetMachineAction:ue.resetMachineAction,setSelectedTabKey:P,setScreen:A,setSelectedMachineId:T,setSection:$,setMachineBackTarget:_}),{isMuted:we,autoMuteIfCoordinator:be,toggleTarget:Ne}=Ny();l.useEffect(()=>{if(i)for(const te of O)be(te.conversation)},[O,i,be]);const re=l.useMemo(()=>Fn(O.filter(te=>te.requiresAction&&!we(te.conversation))),[O,we]),je=l.useMemo(()=>Fn(O.filter(te=>te.unread&&!te.requiresAction&&!we(te.conversation))),[O,we]),ce=l.useMemo(()=>Zv(O.filter(te=>!te.unread&&!te.requiresAction&&te.isWorking),B.current),[O]);l.useEffect(()=>{B.current=ce.map(te=>te.conversation.tabKey)},[ce]);const U=l.useMemo(()=>Fn(O.filter(te=>!te.unread&&!te.requiresAction&&!te.isWorking)),[O]),W=l.useMemo(()=>J?O.filter(te=>Ds(te.conversation)===J.id):[],[O,J]),Y=l.useMemo(()=>tw(J,r),[r,J]),se=(J==null?void 0:J.version)||null,ie=!!J&&!!se&&!0&&se!==F,ae=l.useMemo(()=>(J==null?void 0:J.availableProviders)||[],[J]),D=l.useMemo(()=>ae.filter(te=>tr(te,"cli")).map(te=>({type:te.type,displayName:te.displayName||te.type,icon:te.icon})),[ae]),oe=l.useMemo(()=>ae.filter(te=>tr(te,"acp")).map(te=>({type:te.type,displayName:te.displayName||te.type,icon:te.icon})),[ae]),ge=l.useMemo(()=>sw(q,O),[O,q]),pe=l.useCallback(async te=>{J&&await ue.handleOpenRecent(J.id,te)},[ue,J]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:L==="chat"&&K?s.jsx(Wv,{selectedConversation:K,isAcp:rt(K),isStandalone:i,selectedIdeEntry:z,actionLogs:n,userName:c,isSendingChat:xe.isSendingChat,sendFeedbackMessage:xe.sendFeedbackMessage,isFocusingAgent:xe.isFocusingAgent,handleModalButton:xe.handleModalButton,handleRelaunch:xe.handleRelaunch,onBack:ve.backFromConversation,onOpenNativeConversation:ve.openNativeConversation,onOpenMachine:ve.openConversationMachine,onOpenHistory:y,onOpenRemote:f,onOpenMeshGraph:N,onStopCli:w,cliViewMode:ne,onSetCliViewMode:async te=>{await Ju({conversation:K,mode:te,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:S})},handleSendChat:xe.handleSendChat,handleForceSendChat:xe.handleForceSendChat,handleFocusAgent:xe.handleFocusAgent}):L==="machine"&&J?s.jsx(Qv,{selectedMachineEntry:J,selectedMachineConversations:W,selectedMachineRecentLaunches:Y,cliProviders:D,acpProviders:oe,selectedMachineNeedsUpgrade:ie,appVersion:F,machineAction:ue.machineAction,isStandalone:i,section:R,showBottomNav:M==="inbox",onBack:ve.backFromMachine,onSectionChange:ve.changeMachineSection,onOpenConversation:ve.openConversation,onOpenRecent:pe,onOpenMachineDetails:()=>E(`/machines/${J.id}`),onMachineUpgrade:()=>ue.handleMachineUpgrade(J.id),onLaunchDetectedIde:(te,Me)=>ue.handleLaunchDetectedIde(J.id,te,Me),onAddWorkspace:(te,Me)=>ue.handleAddWorkspace(J.id,te,Me),onBrowseDirectory:te=>ue.handleBrowseDirectory(J.id,te),onLaunchWorkspaceProvider:(te,Me,_e)=>ue.handleLaunchWorkspaceProvider(J.id,te,Me,_e),onListSavedSessions:te=>ue.handleListSavedSessions(J.id,te)}):s.jsx(Gv,{section:R,attentionItems:re,unreadItems:je,workingItems:ce,completedItems:U,hiddenConversations:t,machineCards:ge,getAvatarText:cw,actionLogs:n,sendDaemonCommand:a,onOpenConversation:ve.openConversation,onShowAllHidden:v,onHideConversation:k,onOpenMeshGraph:N,onOpenNewSession:x,onOpenMachine:ve.openMachine,onOpenSettings:()=>E("/settings"),onSectionChange:$,wsStatus:j,isConnected:g,isStandalone:i,isConversationMuted:i?we:void 0,onToggleMuteConversation:i?Ne:void 0})})}function ro(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function uw({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const i=l.useRef(0),[c,d]=l.useState(!1),[p,m]=l.useState(null),u=l.useCallback(()=>{i.current=0,d(!1),m(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",u),window.addEventListener("drop",u),()=>{window.removeEventListener("dragend",u),window.removeEventListener("drop",u)}),[u]);const h=l.useCallback(w=>{w.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),b=l.useCallback(w=>{if(!w.dataTransfer.types.includes("text/tab-key"))return;if(w.preventDefault(),!ro(t,r)){m("merge");return}const j=w.currentTarget.getBoundingClientRect(),g=w.clientX-j.left,v=j.width/3;g<v?m("split-left"):g>v*2?m("split-right"):m("merge")},[t,r]),y=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),m(null))},[]),f=l.useCallback(w=>{i.current=0,d(!1);const j=w.dataTransfer.getData("text/tab-key"),g=j?e.some(k=>k.tabKey===j):!1,v=p;if(m(null),o(),!!j){if(w.preventDefault(),v==="split-left"&&ro(t,r)){r==null||r(j,"split-left");return}if(v==="split-right"&&ro(t,r)){r==null||r(j,"split-right");return}if(g){a(j);return}n==null||n(j)}},[e,p,t,r,n,a,o]);return{dragOver:c,dropAction:p,resetDragState:u,handleDragEnter:h,handleDragOver:b,handleDragLeave:y,handleDrop:f}}function pw(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 mw({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,i]=l.useState(t??null),[c,d]=l.useState(r??[]),[p,m]=l.useState(null),u=l.useRef(null),h=l.useRef(null),b=l.useRef(n),y=l.useRef(a);l.useEffect(()=>{b.current=n},[n]),l.useEffect(()=>{y.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(C=>{const S=pw(C,e);return S.length===C.length&&S.every((I,P)=>I===C[P])?C:S})},[e]);const f=l.useMemo(()=>{const C=p??c;if(C.length===0)return e;const S=new Map(C.map((I,P)=>[I,P]));return[...e].sort((I,P)=>{const L=S.get(I.tabKey)??999,A=S.get(P.tabKey)??999;return L-A})},[e,p,c]);l.useEffect(()=>{var S,I;if(f.length===0){o!==null&&(i(null),(S=b.current)==null||S.call(b,null));return}if(o&&f.some(P=>P.tabKey===o))return;const C=f[0].tabKey;C!==o&&(i(C),(I=b.current)==null||I.call(b,C))},[f,o]);const w=l.useMemo(()=>f.find(C=>C.tabKey===o),[f,o]),j=l.useCallback(C=>{var S;i(C),(S=b.current)==null||S.call(b,C)},[]),g=l.useCallback((C,S,I)=>{d(P=>{var $;const L=P.filter(X=>X!==C),A=L.indexOf(S);if(A<0)return P;const R=I==="left"?A:A+1;return L.splice(R,0,C),($=y.current)==null||$.call(y,L),L}),m(null)},[]),v=l.useCallback((C,S,I)=>{const L=(c.length>0?c:e.map($=>$.tabKey)).filter($=>$!==C),A=L.indexOf(S);if(A<0)return;const R=I==="left"?A:A+1;L.splice(R,0,C),u.current=L,m(L)},[c,e]),k=l.useCallback(()=>{var S;const C=u.current;C&&(d(C),(S=y.current)==null||S.call(y,C))},[]),N=l.useCallback(()=>{u.current=null,m(null)},[]),x=l.useCallback(C=>{d(S=>{var P;const I=S.filter(L=>L!==C);return I.push(C),(P=y.current)==null||P.call(y,I),I})},[]);return{activeTabId:o,activeConv:w,sortedConversations:f,previewOrderRef:u,draggingTabRef:h,selectTab:j,handleTabReorder:g,updatePreviewOrder:v,commitPreviewOrder:k,clearPreviewOrder:N,moveTabToEnd:x,setDraggingTabKey:C=>{h.current=C}}}function hw({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 Oi({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:o}){if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const i=!r&&!n,c=n&&!!o,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",p=n?Cu:r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can launch sessions with any installed provider.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:p}),c&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Qt,"aria-label":Qt,children:[s.jsx(Id,{size:14}),s.jsx("span",{children:Qt})]})}),i&&s.jsx(up,{}),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 bp="adhdev-tab-shortcuts";function gp(){try{return JSON.parse(localStorage.getItem(bp)||"{}")}catch{return{}}}function yp({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>gp()),[c,d]=l.useState(null),p=l.useCallback(u=>{const h=[];return u.metaKey&&h.push(a?"⌘":"Meta"),u.ctrlKey&&h.push("Ctrl"),u.altKey&&h.push(a?"⌥":"Alt"),u.shiftKey&&h.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(u.key)?null:(h.push(u.key.length===1?u.key.toUpperCase():u.key),h.join("+"))},[a]),m=l.useCallback(u=>{i(u);try{localStorage.setItem(bp,JSON.stringify(u))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const u=h=>{if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){d(null);return}const b=p(h);if(!b)return;const y={...o};for(const[f,w]of Object.entries(y))w===b&&delete y[f];y[c]=b,m(y),d(null)};return window.addEventListener("keydown",u,!0),()=>window.removeEventListener("keydown",u,!0)},[e,c,o,m,p]),l.useEffect(()=>{if(!e)return;const u=h=>{if(!(!h.ctrlKey&&!h.metaKey&&!h.altKey)){for(const[b,y]of Object.entries(o))if(t.includes(b)&&p(h)===y){h.preventDefault(),r(),n(b);return}}};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e,o,t,r,n,p]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:m}}const no=e=>{e.preventDefault()},fw=l.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:p,onConversationActivated:m,onPreviewReorder:u,onReorderTab:h,onCommitPreviewOrder:b,onClearPreviewOrder:y,onDragStateReset:f,onDragTabKeyChange:w,onReceiveTab:j,onOpenContextMenu:g,longPressTimer:v,isGroupActive:k}){const N=nr(t),x=N.isGenerating?"agent-tab-generating":N.isWaiting?"agent-tab-waiting":"",C=N.isReconnecting,S=Og(t),I=Hg(t),P=l.useCallback(B=>{c.current=t.tabKey,w(t.tabKey),B.dataTransfer.setData("text/tab-key",t.tabKey),B.dataTransfer.effectAllowed="move"},[t.tabKey,c,w]),L=l.useCallback(()=>{c.current=null,w(null),b(),y(),f()},[c,w,b,y,f]),A=l.useCallback(B=>{const E=c.current;if(!(!E||E===t.tabKey)&&B.dataTransfer.types.includes("text/tab-key")){B.preventDefault(),B.stopPropagation();const F=B.currentTarget.getBoundingClientRect(),K=B.clientX<F.left+F.width/2?"left":"right";u(E,t.tabKey,K)}},[t.tabKey,c,u]),R=l.useCallback(B=>{B.preventDefault(),B.stopPropagation();const E=B.dataTransfer.getData("text/tab-key");if(E&&E!==t.tabKey){const F=B.currentTarget.getBoundingClientRect(),K=B.clientX<F.left+F.width/2?"left":"right";i.includes(E)?h(E,t.tabKey,K):j&&j(E)}y()},[t.tabKey,i,h,j,y]),$=l.useCallback(B=>{B.stopPropagation(),d(),p(t.tabKey),m(t)},[t,m,d,p]),X=l.useCallback(B=>{B.preventDefault(),g(B.clientX,B.clientY,t.tabKey)},[t.tabKey,g]),T=l.useCallback(B=>{const E=B.touches[0];v.current=setTimeout(()=>{g(E.clientX,E.clientY,t.tabKey)},600)},[t.tabKey,v,g]),M=l.useCallback(()=>{v.current&&clearTimeout(v.current)},[v]),_=["adhdev-dockview-tab",x,r&&"is-active",k&&"is-group-active",C&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:_,draggable:!0,onDragStart:P,onDragEnd:L,onDragOver:A,onDrop:R,onClick:$,onContextMenu:X,onTouchStart:T,onTouchEnd:M,onTouchMove:M,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:N.isGenerating?s.jsx("div",{className:"tab-spinner"}):N.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):C?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):N.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),S.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:I,"aria-label":I||S.join(" · "),children:S.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:[C?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Ss(t)}):N.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Ss(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:Ss(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 xw({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:u,onDragStateReset:h,onDragTabKeyChange:b,onReceiveTab:y,onHideTab:f,isGroupActive:w,allowTabShortcuts:j=!0}){const[g,v]=l.useState(null),k=l.useRef(null),N=l.useRef(null),x=l.useMemo(()=>e.map(R=>R.tabKey),[e]);Ur("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(g==null?void 0:g.tabKey)||null});const{isMac:C,tabShortcuts:S,shortcutListening:I,setShortcutListening:P,saveShortcuts:L}=yp({enabled:j,sortedTabKeys:e.map(R=>R.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!g)return;const R=$=>{const X=document.querySelector("[data-pane-context-menu]");X&&X.contains($.target)||v(null)};return window.addEventListener("mousedown",R,!0),()=>window.removeEventListener("mousedown",R,!0)},[g]),l.useEffect(()=>{const R=N.current;if(!R)return;const $=X=>{Math.abs(X.deltaY)<=Math.abs(X.deltaX)||(X.preventDefault(),R.scrollLeft+=X.deltaY)};return R.addEventListener("wheel",$,{passive:!1}),()=>R.removeEventListener("wheel",$)},[]);const A=l.useCallback((R,$,X)=>{v({x:R,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:N,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(R=>s.jsx(fw,{conv:R,isActive:t===R.tabKey,isDraggedTab:a.current===R.tabKey,isTaskCompleteUnread:n.has(R.tabKey),shortcut:j?S[R.tabKey]:void 0,conversationKeys:x,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:u,onDragStateReset:h,onDragTabKeyChange:b,onReceiveTab:y,onOpenContextMenu:A,longPressTimer:k,isGroupActive:w},R.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),g&&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:g.x,top:g.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:no,onClick:R=>{R.stopPropagation(),P(g.tabKey),v(null)},children:["⌨ ",S[g.tabKey]?`Change shortcut (${S[g.tabKey]})`:"Set shortcut"]}),S[g.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:no,onClick:()=>{const R={...S};delete R[g.tabKey],L(R),v(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:no,onClick:()=>{f(g.tabKey),v(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:()=>P(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:R=>R.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",C?"⌘+1":"Ctrl+1",", ",C?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function bw({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,userName:d,groupIndex:p,onFocus:m,isSplitMode:u,numGroups:h,onMoveTab:b,onReceiveTab:y,style:f,onActiveTabChange:w,initialActiveTabId:j,initialTabOrder:g,onTabOrderChange:v,onHideTab:k,isFocused:N,allowTabShortcuts:x=!0,onOpenNewSession:C,liveSessionInboxState:S}){const{sendCommand:I}=mt(),P=l.useRef(null),{activeTabId:L,activeConv:A,sortedConversations:R,draggingTabRef:$,selectTab:X,handleTabReorder:T,updatePreviewOrder:M,commitPreviewOrder:_,clearPreviewOrder:B,moveTabToEnd:E,setDraggingTabKey:F}=mw({conversations:e,initialActiveTabId:j,initialTabOrder:g,onActiveTabChange:w,onTabOrderChange:v}),K=ya({sendDaemonCommand:a,activeConv:A,setActionLogs:o,isStandalone:i}),{dragOver:z,dropAction:ne,resetDragState:q,handleDragEnter:J,handleDragOver:xe,handleDragLeave:ue,handleDrop:O}=uw({conversations:e,numGroups:h,onMoveTab:b,onReceiveTab:y,onOwnTabDrop:E,onClearPreviewOrder:B}),H=A&&!rt(A)&&ar(A)==="terminal",ve=l.useMemo(()=>A?t.find(re=>re.id===A.routeId):void 0,[t,A]),we=l.useMemo(()=>A?n.filter(re=>re.routeId===A.tabKey):[],[n,A]),be=l.useMemo(()=>new Set(R.filter(re=>Uf(re,S,{isOpenConversation:re.tabKey===L})).map(re=>re.tabKey)),[L,S,R]);Ur("PaneGroup",{groupIndex:p,conversationCount:e.length,activeTabId:L,dragOver:z});const Ne=l.useCallback(re=>{re.streamSource==="agent-stream"&&re.agentType&&I(re.routeId,ou(),{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:m,style:{...f,outline:z?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(xw,{conversations:R,activeTabId:L,groupIndex:p,numGroups:h,unreadTabKeys:be,draggingTabRef:$,onFocus:m,onSelectTab:X,onConversationActivated:Ne,onPreviewReorder:M,onReorderTab:T,onCommitPreviewOrder:_,onClearPreviewOrder:B,onDragStateReset:q,onDragTabKeyChange:F,onMoveTab:b,onReceiveTab:y,onHideTab:k,isGroupActive:N??!1,allowTabShortcuts:x}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:J,onDragOver:xe,onDragLeave:ue,onDrop:O,children:[z&&s.jsx(hw,{dropAction:ne,canSplit:!!(h<4&&b)}),A?s.jsx(Bi,{activeConv:A,clearToken:r[A.tabKey]||0,isCliTerminal:!!H,ideEntry:ve,terminalRef:P,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:!u||!!N}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Oi,{conversationsCount:e.length,isSplitMode:u,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:C})})]})]})}function gw({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:m,hasRegisteredMachines:u,userName:h,focusedGroup:b,focusGroup:y,moveTabToGroup:f,splitTabRelative:w,closeGroup:j,handleResizeStart:g,groupActiveTabIds:v,setGroupActiveTab:k,groupTabOrders:N,setGroupTabOrder:x,toggleHiddenTab:C,onOpenNewSession:S,allowTabShortcuts:I=!0,liveSessionInboxState:P}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((L,A)=>{const R=t&&n.length===r?`${n[A]}%`:void 0;return s.jsxs(St.Fragment,{children:[t&&A>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:$=>g(A-1,$),onDoubleClick:()=>j(A),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(bw,{style:t?{flexBasis:R??`${100/r}%`,flexGrow:R?0:1,flexShrink:R?0:1}:void 0,conversations:L,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:m,hasRegisteredMachines:u,userName:h,groupIndex:A,isFocused:t&&b===A,onFocus:()=>y(A),isSplitMode:t,numGroups:r,onMoveTab:($,X)=>{X==="left"&&A>0?f($,A-1):X==="right"&&A<r-1?f($,A+1):X==="split-left"&&r<4?w($,A,"left"):X==="split-right"&&r<4&&w($,A,"right")},onReceiveTab:$=>f($,A),onActiveTabChange:$=>k(A,$),initialActiveTabId:v[A],initialTabOrder:N[A],onTabOrderChange:$=>x(A,$),onHideTab:C,onOpenNewSession:S,allowTabShortcuts:I,liveSessionInboxState:P})]},A)})})}function vp({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?xt.onScreenshot("ide-page",(m,u)=>{if(m!==e)return;const h=new FileReader;h.onload=()=>o(h.result),h.readAsDataURL(u)}):void 0,[e]),l.useEffect(()=>{r!=="connected"&&o(null)},[r]),l.useEffect(()=>{var m;return e?((m=xt.onStatus)==null?void 0:m.call(xt,(u,h)=>{u===e&&h!=null&&h.screenshotUsage&&c(h.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?xt.get(e):null;if(!(!p||r!=="connected"))return n!=="chat"&&t?p.startScreenshots(t):p.stopScreenshots(t),()=>{p.stopScreenshots(t)}},[n,r,t,e]);const d=l.useCallback(async(p,m)=>{const u=e?xt.get(e):null;return!u||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):u.sendInput(p,m,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:i,handleRemoteAction:d}}const wp="adhdev-dashboard-action-shortcuts",yw=1200,vw=[["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 ww(){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 jp(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(jp(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(wp)||"{}"),n={...t,...r};for(const[a,o]of vw)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function kp(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function jw({enabled:e=!0,onTrigger:t}){const r=ww(),[n,a]=l.useState(()=>ca(r)),[o,i]=l.useState(null),[c,d]=l.useState([]),p=l.useRef({parts:[],timer:null}),m=l.useCallback(f=>{const w=[];return f.metaKey&&w.push(r?"⌘":"Meta"),f.ctrlKey&&w.push("Ctrl"),f.altKey&&w.push(r?"⌥":"Alt"),f.shiftKey&&f.key.length!==1&&w.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(w.push(kp(f.key)),w.join("+"))},[r]),u=l.useCallback(f=>{a(f);try{localStorage.setItem(wp,JSON.stringify(f))}catch{}},[]);l.useEffect(()=>{const f=ca(r),w=Object.entries(n),j=Object.entries(f);w.length===j.length&&w.every(([g,v])=>f[g]===v)||u(f)},[n,r,u]);const h=l.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),b=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},yw))},[]);l.useEffect(()=>{if(!o)return;const f=w=>{if(w.preventDefault(),w.stopPropagation(),w.key==="Escape"){i(null),d([]);return}const j=m(w);if(!j)return;const v=!(w.metaKey||w.ctrlKey||w.altKey)&&/^[A-Z0-9]$/.test(j);if(c.length===0&&v){d([j]);return}const N=[...c,j].slice(0,2).join(" "),x={...n};for(const[C,S]of Object.entries(x))S===N&&delete x[C];x[o]=N,u(x),i(null),d([])};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[n,m,u,o,c]),l.useEffect(()=>{if(!e||o)return;const f=w=>{if(w.defaultPrevented)return;const j=m(w);if(!j)return;const g=w.metaKey||w.ctrlKey||w.altKey;if(Jo(w.target))return;const v=p.current.parts,k=g?[j]:[...v.slice(-1),j].slice(-2),N=k.join(" "),x=k[k.length-1],C=Object.entries(n).filter(([,A])=>!!A),S=C.find(([,A])=>A===N);if(S){w.preventDefault(),h(),t(S[0]);return}if(C.some(([,A])=>A.startsWith(`${N} `))){w.preventDefault(),p.current.parts=k,b();return}const P=C.find(([,A])=>A===x);if(P){w.preventDefault(),h(),t(P[0]);return}if(C.some(([,A])=>A.startsWith(`${x} `))){w.preventDefault(),p.current.parts=[x],b();return}h()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[n,b,e,m,t,h,o]),l.useEffect(()=>()=>h(),[h]);const y=l.useMemo(()=>jp(r),[r]);return{isMac:r,actionDefinitions:y,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:u}}function kw({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 Np(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function jc({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!Np(n):!0}function Nw({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:Np(r)}const Sp=1e3,Sw=4;function kc(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Nc(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function Cw({detachDelayMs:e=Sp,stillnessThresholdPx:t=Sw,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,d=null,p=null,m=!1;const u=()=>{p!=null&&(a(p),p=null)},h=()=>{u(),c=null},b=()=>{u(),o=null,i=null,c=null,d=null,m=!1},y=()=>{!o||!c||!d||m||p!=null||(p=n(()=>{p=null,!(!o||!c||!d||m)&&kc(d,i)&&(Nc(c,d,t)||(m=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},f=j=>{if(!(!o||m)){if(!kc(j,i)){d={clientX:j.clientX,clientY:j.clientY},h();return}(!c||Nc(c,j,t))&&(u(),c={clientX:j.clientX,clientY:j.clientY}),d={clientX:j.clientX,clientY:j.clientY},y()}},w=j=>{!o||m||(j&&(d={clientX:j.clientX,clientY:j.clientY}),h())};return{startDrag:j=>{u(),o=j.panelId,i=j.selfPanelBounds??null,c=null,d={clientX:j.clientX,clientY:j.clientY},m=!1},markSelfPanel:f,markNonSelfPanel:w,markNoDropTarget:w,markDockTarget:w,endDrag:b,isDragging:()=>o!=null,hasDetached:()=>m,dispose:b}}function Iw(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Sn(e){return e.isActive}function Sc(e){return e.isVisible}const Cp=l.createContext(null);function ka(){const e=l.useContext(Cp);if(!e)throw new Error("DashboardDockviewContext missing");return e}function On(e){return pt(e)||e.tabKey}function Mw(e){return`remote:${e}`}function zt(e){return e.startsWith("remote:")}function Cc(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Aw(e){e.preventDefault()}function ao(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 oo(e,t){e.classList.remove(Co.className,Io.className),e.classList.add(t==="light"?Co.className:Io.className)}function Ic(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 Tw(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 _w(e,t,r){var i;const n=[t];let a;for(const c of n){let d;for(const p of c){const m=e.addPanel({id:p.tabKey,component:"conversation",title:On(p),params:{kind:"conversation",tabKey:p.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=m.id)}a=d??a}return r??((i=t[0])==null?void 0:i.tabKey)??null}function Mc(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 Ac(e,t,r){var d,p;const n=r?Mw(r):null;for(const m of[...e.panels])zt(m.id)&&(!n||m.id!==n)&&e.removePanel(m);if(!r||!n)return;const a=Gt(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),i=ku(a);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((p=e.panels.find(m=>!zt(m.id)))==null?void 0:p.id);e.addPanel({id:n,component:"remote",title:i,params:{kind:"remote",routeId:r},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function Rw({params:e,api:t}){var b;const r=ka(),n=l.useRef(null),[a,o]=l.useState(()=>Sn(t)),[i,c]=l.useState(()=>Sc(t)),d=r.conversationsByTabKey.get(e.tabKey),p=ya({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});l.useEffect(()=>{o(Sn(t)),c(Sc(t));const y=[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 y)f.dispose()}},[t]);const m=l.useMemo(()=>d?r.ides.find(y=>y.id===d.routeId):void 0,[r.ides,d]),u=l.useMemo(()=>d?r.actionLogs.filter(y=>y.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(Oi,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const h=!rt(d)&&ar(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(Bi,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:h,ideEntry:m,terminalRef:n,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:u,userName:r.userName,scrollToBottomRequestNonce:((b=r.scrollToBottomRequest)==null?void 0:b.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:i})})}function Lw({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(p=>p.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((d=r==null?void 0:r.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=vp({doId:a,targetSessionId:r?au(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(Ed,{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 Pw(){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(Oi,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Dw(e){var g,v;Tw(e);const t=ka(),r=l.useCallback(k=>{"button"in k&&k.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(k=>Ng(k),[]),i=l.useCallback(()=>kg(a),[a]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const k=Gt([...t.conversationsByTabKey.values()],e.params.routeId),N=((g=e.api.group.activePanel)==null?void 0:g.id)===e.api.id,x=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${N?" is-active":""}${x?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(k==null?void 0:k.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:k!=null&&k.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:k.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const d=t.conversationsByTabKey.get(e.params.tabKey);if(!d)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const p=((v=e.api.group.activePanel)==null?void 0:v.id)===e.api.id,m=e.api.isGroupActive,u=ba(d,t.liveSessionInboxState,{isOpenConversation:p}),h=u.isReconnecting,b=u.isConnecting,y=u.isGenerating||c,f=u.isWaiting,w=u.unread,j=t.tabShortcuts[d.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${m?" is-group-active":""}${h?" is-reconnecting":""}`,title:pt(d),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:k=>{var N;k.preventDefault(),r(k),t.openTabContextMenu({x:k.clientX,y:k.clientY,tabKey:d.tabKey,sourceDocument:((N=k.target)==null?void 0:N.ownerDocument)??document})},children:[w&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:y?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:Ss(d)}):b?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Ss(d)}):s.jsx("span",{children:Ss(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 $w({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:p,toggleHiddenTab:m,actionShortcuts:u,registerActionHandlers:h,onActiveTabChange:b,onOpenNewSession:y,onRequestScrollToBottom:f,requestedActiveTabKey:w,requestedRemoteIdeId:j,onRequestedActiveTabConsumed:g,scrollToBottomRequest:v,liveSessionInboxState:k,layoutProfile:N}){var ot,Je,Re;const{theme:x}=$s(),{sendCommand:C}=mt(),S=l.useRef(null),I=l.useRef(null),P=l.useRef(null),L=l.useRef(!1),A=l.useRef(!1),R=l.useRef(!1),$=l.useRef(null),X=l.useRef([]),[T,M]=l.useState(null),[_,B]=l.useState(0),E=l.useRef(typeof window>"u"?{}:tv(N)),F=l.useMemo(()=>new Map(e.map(G=>[G.tabKey,G])),[e]),K=l.useMemo(()=>{const G=S.current;return G?G.groups.some(V=>{try{const ee=V.model.location.type;return ee!=="floating"&&ee!=="popout"?!1:V.panels.some(he=>F.has(he.id))}catch{return!1}}):!1},[F,_,e]),z=l.useCallback(()=>{var G;(G=S.current)==null||G.focus()},[]),ne=l.useCallback((G,V)=>{f==null||f(G,V)},[f]),q=l.useCallback(G=>{const V=document,ee=G.document;for(const Z of V.querySelectorAll('link[rel="stylesheet"]')){const fe=ee.createElement("link");fe.rel="stylesheet",fe.href=Z.href,Z.crossOrigin&&(fe.crossOrigin=Z.crossOrigin),ee.head.appendChild(fe)}for(const Z of V.querySelectorAll("style")){const fe=ee.createElement("style");fe.textContent=Z.textContent,ee.head.appendChild(fe)}const he=[];for(const Z of V.styleSheets)try{for(const fe of Z.cssRules)fe instanceof CSSStyleRule&&(fe.selectorText===":root"||fe.selectorText==="html")&&he.push(fe.cssText)}catch{}if(he.length>0){const Z=ee.createElement("style");Z.textContent=he.join(`
|
|
63
|
+
`),ee.head.appendChild(Z)}const ye=V.documentElement.getAttribute("data-theme");ye&&ee.documentElement.setAttribute("data-theme",ye),ee.documentElement.style.colorScheme=ye==="light"?"light":"dark",ee.body.className=V.body.className;const ke=V.documentElement.getAttribute("style");ke&&ee.documentElement.setAttribute("style",ke);const Q=ee.getElementById("dv-popout-window");Q instanceof HTMLElement&&(Q.classList.add("adhdev-dockview"),oo(Q,x))},[x]),J=l.useCallback(()=>{var V;const G=S.current;if(G)for(const ee of G.groups)try{const he=(V=ee.element)==null?void 0:V.ownerDocument;if(!he||he===document)continue;const ye=he.getElementById("dv-popout-window");ye instanceof HTMLElement&&(ye.classList.add("adhdev-dockview"),oo(ye,x));const ke=document.documentElement.getAttribute("data-theme");ke&&he.documentElement.setAttribute("data-theme",ke),he.documentElement.style.colorScheme=ke==="light"?"light":"dark",he.body.className=document.body.className;const Q=document.documentElement.getAttribute("style");Q?he.documentElement.setAttribute("style",Q):he.documentElement.removeAttribute("style")}catch{}},[x]),xe=l.useCallback(G=>{const V=S.current;if(!V)return;const ee=V.getPanel(G);ee&&V.addPopoutGroup(ee,{popoutUrl:"/popout.html",onDidOpen:({window:he})=>{q(he),je();const ye=F.get(G);he.document.title=ye?`${pt(ye)} — ADHDev`:"ADHDev — Popout"}})},[F,q]),ue=l.useCallback(G=>{const V=S.current,ee=V==null?void 0:V.getPanel(G);if(!V||!ee)return;const he=V.groups.filter(ye=>{var ke;try{return((ke=ye.element)==null?void 0:ke.ownerDocument)===document}catch{return!0}});he.length>0?ee.api.moveTo({group:he[0],position:"center"}):ee.api.moveTo({position:"center"}),ee.api.setActive()},[]),O=l.useCallback(G=>{var he;const V=S.current;if(!V)return!1;const ee=V.getPanel(G);if(!ee)return!1;try{return((he=ee.group.element)==null?void 0:he.ownerDocument)!==document}catch{return!1}},[]),H=l.useCallback(G=>{O(G)&&ue(G),m(G)},[O,ue,m]),ve=l.useCallback(G=>{const V=S.current,ee=V==null?void 0:V.getPanel(G);!V||!ee||V.addFloatingGroup(ee,{width:600,height:500})},[]),we=l.useCallback(G=>{var ee;const V=(ee=S.current)==null?void 0:ee.getPanel(G);if(!V)return!1;try{return V.group.model.location.type==="floating"}catch{return!1}},[]),be=l.useCallback(()=>{var V,ee;const G=(ee=(V=S.current)==null?void 0:V.activePanel)==null?void 0:ee.id;return!G||zt(G)?null:F.has(G)?G:null},[F]),Ne=l.useCallback(G=>{const V=S.current,ee=V==null?void 0:V.getPanel(G);if(!V||!ee)return;const he=V.groups.filter(ye=>{try{return ye.model.location.type==="grid"}catch{return!0}});he.length>0?ee.api.moveTo({group:he[0],position:"center"}):ee.api.moveTo({position:"center"}),ee.api.setActive()},[]),re=l.useCallback(()=>{var ke;const G=S.current;if(!G)return;const ee=G.groups.filter(Q=>{var Z;try{return((Z=Q.element)==null?void 0:Z.ownerDocument)===document&&Q.model.location.type==="grid"}catch{return!1}})[0]||null,he=[...G.panels];for(const Q of he){const Z=(ke=Q.group.element)==null?void 0:ke.ownerDocument,fe=Q.group.model.location.type;Z===document&&fe==="grid"||(ee&&ee.id!==Q.group.id?Q.api.moveTo({group:ee,position:"center"}):Q.api.moveTo({position:"center"}))}const ye=G.activePanel;ye&&(ye.group.model.openPanel(ye),ye.api.setActive()),ao(document)},[]),je=l.useCallback(()=>{var V,ee;const G=S.current;if(G)for(const he of G.groups){const ye=(V=he.element)==null?void 0:V.ownerDocument;if(!ye||ye===document)continue;const ke=ye.getElementById("dv-popout-window");if(!(ke instanceof HTMLElement))continue;let Q=null,Z=ye.title||"ADHDev",fe="Popout workspace";const Ie=he.activePanel;if(Ie)if(Q=Ie.id,zt(Ie.id)){const Le=((ee=Ie.params)==null?void 0:ee.routeId)||Ie.id.slice(7),Ye=Gt([...F.values()],Le);Z=ku(Ye),fe=Ye!=null&&Ye.machineName?`Remote view · ${Ye.machineName}`:"Remote view"}else{const Le=F.get(Ie.id);Z=Le?pt(Le):Ie.title||Ie.id,fe=Le?Ss(Le):"Dockview panel"}ye.title=`${Z} — ADHDev`;const Pe=Array.from(ye.querySelectorAll("#adhdev-popout-header"));for(const Le of Pe)Le.remove();const Ae=ye.createElement("div");Ae.id="adhdev-popout-header",ye.body.appendChild(Ae),Ae.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(";")),Ae.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;">${Cc(Z)}</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;">${Cc(fe)}</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=Ae.querySelector("[data-adhdev-popout-focus]");Ee&&(Ee.onclick=()=>{window.focus()});const He=Ae.querySelector("[data-adhdev-popout-dock]");He&&(He.disabled=!Q,He.style.opacity=Q?"1":"0.5",He.style.cursor=Q?"pointer":"default",He.onclick=()=>{var Le;Q&&ue(Q),(Le=ye.defaultView)==null||Le.focus()})}},[F,ue]),ce=l.useCallback(G=>{var he;const V=S.current,ee=V==null?void 0:V.getPanel(G);if(!(!V||!ee)){ee.group.model.openPanel(ee),ee.api.setActive(),ne(G,"dockview-shortcut");try{const ye=ee.group.model.location;ye.type==="popout"?ye.getWindow().focus():ao((he=ee.group.element)==null?void 0:he.ownerDocument)}catch{}}},[ne]),U=l.useCallback(G=>{const V=S.current,ee=V==null?void 0:V.activePanel,he=(V==null?void 0:V.activeGroup)||(ee==null?void 0:ee.group);if(!V||!ee||!he)return;const ye=he.panels||[];if(ye.length<=1)return;const ke=ye.findIndex(fe=>fe.id===ee.id);if(ke<0)return;const Q=(ke+G+ye.length)%ye.length,Z=ye[Q];Z&&(Z.group.model.openPanel(Z),Z.api.setActive(),zt(Z.id)||ne(Z.id,"dockview-shortcut"))},[ne]),W=l.useCallback(G=>{var Ee;const V=S.current,ee=(V==null?void 0:V.activeGroup)||((Ee=V==null?void 0:V.activePanel)==null?void 0:Ee.group);if(!V||!ee)return;const he=V.groups||[],ye=he.find(He=>He.id===ee.id);if(!ye)return;const ke=ye.element.getBoundingClientRect(),Q=ke.left+ke.width/2,Z=ke.top+ke.height/2,fe=(He,Le,Ye,st)=>Math.max(0,Math.min(Le,st)-Math.max(He,Ye)),Ie=He=>{const Le=He.element.getBoundingClientRect(),Ye=Le.left+Le.width/2,st=Le.top+Le.height/2;let ht=0,kt=0,bt=0,ft=!1;if(G==="left"?(ft=Ye<Q,ht=Math.max(0,ke.left-Le.right),kt=Math.abs(st-Z),bt=fe(ke.top,ke.bottom,Le.top,Le.bottom)):G==="right"?(ft=Ye>Q,ht=Math.max(0,Le.left-ke.right),kt=Math.abs(st-Z),bt=fe(ke.top,ke.bottom,Le.top,Le.bottom)):G==="above"?(ft=st<Z,ht=Math.max(0,ke.top-Le.bottom),kt=Math.abs(Ye-Q),bt=fe(ke.left,ke.right,Le.left,Le.right)):(ft=st>Z,ht=Math.max(0,Le.top-ke.bottom),kt=Math.abs(Ye-Q),bt=fe(ke.left,ke.right,Le.left,Le.right)),!ft)return Number.POSITIVE_INFINITY;const Ge=bt>0?0:120;return ht*3+kt+Ge};let Pe=null,Ae=Number.POSITIVE_INFINITY;for(const He of he){if(He.id===ye.id)continue;const Le=Ie(He);Number.isFinite(Le)&&(Le>=Ae||(Ae=Le,Pe=He))}return Pe||void 0},[]),Y=l.useCallback(G=>{var he;const V=W(G);if(!V)return;const ee=V.activePanel||V.panels[0];ee&&(V.model.openPanel(ee),ee.api.setActive(),zt(ee.id)||ne(ee.id,"dockview-focus"),ao((he=V.element)==null?void 0:he.ownerDocument))},[W,ne]),se=l.useCallback((G,V)=>{const ee=S.current,he=ee==null?void 0:ee.activePanel,ye=(ee==null?void 0:ee.activeGroup)||(he==null?void 0:he.group);if(!ee||!he||!ye)return;let ke=W(G);!ke&&(V!=null&&V.createGroupIfMissing)&&(ke=ee.addGroup({referenceGroup:ye,direction:G})),ke&&(he.api.moveTo({group:ke,position:"center"}),he.group.model.openPanel(he),he.api.setActive(),zt(he.id)||ne(he.id,V!=null&&V.createGroupIfMissing?"dockview-split":"dockview-move"))},[W,ne]),{isMac:ie,tabShortcuts:ae,shortcutListening:D,setShortcutListening:oe,saveShortcuts:ge}=yp({sortedTabKeys:e.map(G=>G.tabKey),onFocus:z,onSelectTab:ce}),pe=l.useCallback(()=>{var ee;const G=S.current;if(!G)return;const V=G.activePanel;if(V){if(zt(V.id)){const he=((ee=V.params)==null?void 0:ee.routeId)||V.id.slice(7),ye=Gt(e,he);ye!=null&&ye.tabKey&&oe(ye.tabKey);return}F.has(V.id)&&oe(V.id)}},[F,ce,oe,e]),te=l.useCallback(G=>{const V=[];return G.metaKey&&V.push(ie?"⌘":"Meta"),G.ctrlKey&&V.push("Ctrl"),G.altKey&&V.push(ie?"⌥":"Alt"),G.shiftKey&&G.key.length!==1&&V.push(ie?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(G.key)?null:(V.push(kp(G.key)),V.join("+"))},[ie]),Me=l.useCallback(G=>{var V,ee;switch(G){case"splitActiveTabRight":se("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":se("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const he=be();he&&ve(he);return}case"popoutActiveTab":{const he=be();he&&xe(he);return}case"dockActiveTab":{const he=be();if(!he)return;O(he)?ue(he):we(he)&&Ne(he);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":pe();return;case"hideCurrentTab":{const he=(ee=(V=S.current)==null?void 0:V.activePanel)==null?void 0:ee.id;he&&!zt(he)&&H(he);return}default:return}},[U,Ne,Y,ve,be,H,we,O,ue,se,xe,pe]);l.useEffect(()=>{if(!T)return;const G=T.sourceDocument,V=G.defaultView??window,ee=he=>{const ye=G.querySelector("[data-dockview-tab-context-menu]");ye&&ye.contains(he.target)||M(null)};return V.addEventListener("mousedown",ee,!0),V!==window&&window.addEventListener("mousedown",()=>M(null),!0),()=>{V.removeEventListener("mousedown",ee,!0),V!==window&&window.removeEventListener("mousedown",()=>M(null),!0)}},[T]);const _e=l.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:F,hasDetachedConversationPanels:K,ides:r,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:y,liveSessionInboxState:k,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:H,userName:p,scrollToBottomRequest:v,tabShortcuts:ae,openTabContextMenu:({x:G,y:V,tabKey:ee,sourceDocument:he})=>M({x:G,y:V,tabKey:ee,sourceDocument:he??document}),popoutTab:xe,moveTabBackToMain:ue,isTabInPopout:O,floatTab:ve,isTabFloating:we}),[n,t,F,K,r,i,c,y,k,a,o,H,p,v,ae,xe,ue,O,ve,we]),Ce=T?kw({isTabInPopout:O(T.tabKey),isTabFloating:we(T.tabKey),tabShortcut:ae[T.tabKey],actionShortcuts:u}):[],Ke=l.useCallback(G=>{var he;const V=S.current;if((((he=V==null?void 0:V.activePanel)==null?void 0:he.id)??null)===G.id){G.group.model.openPanel(G);return}G.group.model.openPanel(G),G.api.setActive()},[]),Ze=l.useCallback((G,V="requested-tab")=>{if(!G)return!1;const ee=S.current;if(!ee)return!1;const he=ee.getPanel(G);return he?(Ke(he),ne(G,V),g==null||g(),!0):!1},[Ke,g,ne]),me=l.useCallback(()=>{if(R.current)return!1;const G=Ze($.current,"stored-layout-restore");return G&&(R.current=!0),G},[Ze]),De=l.useCallback(()=>{var V;const G=S.current;G&&ev(N,{activeTabId:((V=G.activePanel)==null?void 0:V.id)??null,layout:G.toJSON()})},[N]),$e=l.useCallback(()=>{sv(N,E.current)},[N]),tt=l.useCallback(G=>{var he,ye,ke,Q;const V=S.current;if(!V)return{kind:"grid"};const ee=V.toJSON();for(const Z of ee.floatingGroups||[])if((ye=(he=Z.data)==null?void 0:he.views)!=null&&ye.includes(G)&&Z.position)return{kind:"floating",position:Z.position};for(const Z of ee.popoutGroups||[])if((Q=(ke=Z.data)==null?void 0:ke.views)!=null&&Q.includes(G))return{kind:"popout",position:Z.position,popoutUrl:Z.url};return{kind:"grid"}},[]),Ue=l.useCallback(G=>{const V=S.current;if(!V)return;const ee=V.getPanel(G),he=E.current[G];if(!ee||!he||he.kind==="grid")return;if(ee.group.model.location.type===he.kind){delete E.current[G],$e();return}if(he.kind==="floating"){V.addFloatingGroup(ee,{x:he.position.left??24,y:he.position.top??24,width:he.position.width,height:he.position.height}),delete E.current[G],$e();return}delete E.current[G],$e()},[$e]);l.useEffect(()=>(h==null||h({setShortcutForActiveTab:pe,restoreHiddenTabToSavedLocation:Ue,activateConversationTab:ce,resetAllPanelsToMain:re,activatePreviousTabInGroup:()=>U(-1),activateNextTabInGroup:()=>U(1),floatActiveTab:()=>{const G=be();G&&ve(G)},popoutActiveTab:()=>{const G=be();G&&xe(G)},dockActiveTab:()=>{const G=be();G&&(O(G)?ue(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,be,we,O,se,ue,xe,h,re,Ue,ce,pe]),l.useEffect(()=>()=>{var G;(G=P.current)==null||G.call(P),P.current=null},[]);const Ve=l.useCallback(G=>{var ee,he;S.current=G.api,(ee=P.current)==null||ee.call(P),P.current=null;const V=Zy(N);if($.current=(V==null?void 0:V.activeTabId)??null,V!=null&&V.layout&&G.api.fromJSON(V.layout,{reuseExistingPanels:!1}),A.current=jc({hasStoredLayout:!!(V!=null&&V.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),A.current||(Mc(G.api,e),Ac(G.api,e,j)),G.api.totalPanels===0&&e.length>0){const ye=_w(G.api,e,w);if(ye){const ke=G.api.getPanel(ye);ke&&Ke(ke)}}else!A.current&&!Ze(w)&&me();if(L.current=!0,G.api.onDidActivePanelChange(ye=>{var Q;if($.current=(ye==null?void 0:ye.id)??null,R.current=!0,je(),ye&&zt(ye.id)){const Z=((Q=ye.params)==null?void 0:Q.routeId)||ye.id.slice(7),fe=Gt(e,Z);b((fe==null?void 0:fe.tabKey)??null),De();return}if(b((ye==null?void 0:ye.id)??null),De(),!ye)return;const ke=F.get(ye.id);(ke==null?void 0:ke.streamSource)==="agent-stream"&&ke.agentType&&C(ke.routeId,ou(),{agentType:ke.agentType,...ke.sessionId&&{targetSessionId:ke.sessionId}}).catch(()=>{})}),G.api.onDidLayoutChange(()=>{De(),je(),B(ye=>ye+1)}),Iw()){const ye=Ae=>({clientX:Ae.clientX,clientY:Ae.clientY}),ke=Ae=>{const Ee=Ae==null?void 0:Ae.getBoundingClientRect();return Ee?{left:Ee.left,right:Ee.right,top:Ee.top,bottom:Ee.bottom}:null},Q=Ae=>{var He;const Ee=(He=I.current)==null?void 0:He.getBoundingClientRect();return Ee?Ae.clientX<Ee.left||Ae.clientX>Ee.right||Ae.clientY<Ee.top||Ae.clientY>Ee.bottom:!1},Z=Cw({detachDelayMs:Sp,onDetach:({panelId:Ae,clientX:Ee,clientY:He})=>{var bt,ft;const Le=G.api.getPanel(Ae);if(!Le)return;try{if(Le.group.model.location.type!=="grid")return}catch{return}const Ye=(bt=I.current)==null?void 0:bt.getBoundingClientRect(),st=(ft=Le.group.element)==null?void 0:ft.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(Le,{x:Ye?Math.max(0,Ee-Ye.left-32):void 0,y:Ye?Math.max(0,He-Ye.top-18):void 0,width:ht,height:kt}),Le.api.setActive(),De(),je(),B(Ge=>Ge+1)}}),fe=[G.api.onWillDragPanel(Ae=>{if(!(Ae.nativeEvent.defaultPrevented||Ae.nativeEvent.shiftKey)){try{if(Ae.panel.group.model.location.type!=="grid")return}catch{return}Z.startDrag({panelId:Ae.panel.id,selfPanelBounds:ke(Ae.panel.group.element),...ye(Ae.nativeEvent)})}}),G.api.onWillShowOverlay(Ae=>{if(Z.hasDetached()){Ae.preventDefault();return}Z.markDockTarget(ye(Ae.nativeEvent))}),G.api.onWillDrop(Ae=>{if(Z.hasDetached()){Ae.preventDefault(),Z.endDrag();return}Z.markDockTarget(ye(Ae.nativeEvent))}),G.api.onDidDrop(()=>Z.endDrag()),G.api.onUnhandledDragOverEvent(Ae=>{Z.isDragging()&&Z.markSelfPanel(ye(Ae.nativeEvent))})],Ie=Ae=>{if(!Z.isDragging())return;const Ee=ye(Ae);Q(Ee)&&Z.markNonSelfPanel(Ee)},Pe=()=>Z.endDrag();window.addEventListener("dragover",Ie,!0),window.addEventListener("drop",Pe,!0),window.addEventListener("dragend",Pe,!0),P.current=()=>{Z.dispose();for(const Ae of fe)Ae.dispose();window.removeEventListener("dragover",Ie,!0),window.removeEventListener("drop",Pe,!0),window.removeEventListener("dragend",Pe,!0)}}G.api.onDidAddGroup(ye=>{requestAnimationFrame(()=>{var ke,Q;try{const Z=(ke=ye.element)==null?void 0:ke.ownerDocument;if(!Z||Z===document)return;(Q=Z.getElementById("dv-popout-window"))==null||Q.classList.add("adhdev-dockview");const fe=document.documentElement.getAttribute("data-theme");fe&&Z.documentElement.setAttribute("data-theme",fe),Z.body.className=document.body.className;const Ie=document.documentElement.getAttribute("style");Ie&&Z.documentElement.setAttribute("style",Ie)}catch{}je(),B(Z=>Z+1)})}),b(((he=G.api.activePanel)==null?void 0:he.id)??null)},[Ke,Ze,F,r,d,N,b,De,w,j,C,je,e]);l.useLayoutEffect(()=>{const G=S.current;if(!G||!L.current||A.current&&jc({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;A.current&&(A.current=!1);const V=X.current,ee=new Set(V),he=e.map(Pe=>Pe.tabKey),ye=new Set(he),ke=Nw({previousVisibleConversationCount:V.length,visibleConversationCount:e.length,ides:r});let Q=!1;for(const Pe of V)ye.has(Pe)||ke||(E.current[Pe]=tt(Pe),Q=!0);Q&&$e(),ke||(Mc(G,e),Ac(G,e,j));const Z=he.filter(Pe=>!ee.has(Pe));let fe=!1;for(const Pe of Z){const Ae=G.getPanel(Pe),Ee=E.current[Pe];if(!Ae||!Ee||Ee.kind==="grid")continue;if(Ae.group.model.location.type===Ee.kind){delete E.current[Pe],fe=!0;continue}if(Ee.kind==="floating"){G.addFloatingGroup(Ae,{x:Ee.position.left??24,y:Ee.position.top??24,width:Ee.position.width,height:Ee.position.height}),delete E.current[Pe],fe=!0;continue}}if(fe&&$e(),X.current=he,w&&Ze(w))return;!G.activePanel&&G.panels[0]&&Ke(G.panels[0]),!!(G.activePanel&&G.getPanel(G.activePanel.id))||me()},[Ke,Ze,me,r,d,$e,tt,w,j,e]),l.useEffect(()=>{L.current&&Ze(w)},[Ze,w]),l.useEffect(()=>{const G=ee=>{const he=ee.target;if(!he)return;const ye=he.querySelector("[data-tab-key]")||he.closest("[data-tab-key]");if(ye){const ke=ye.getAttribute("data-tab-key");if(ke&&ee.dataTransfer){const Q=he.closest(".dv-tab")||ye.closest(".dv-tab")||ye;ee.dataTransfer.effectAllowed="move",ee.dataTransfer.setData("text/tab-key",ke),Q instanceof HTMLElement&&ee.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=Ic(S.current);for(const ee of V)ee.addEventListener("dragstart",G);return()=>{window.removeEventListener("dragstart",G);for(const ee of V)ee.removeEventListener("dragstart",G)}},[_]),l.useEffect(()=>{var V;const G=(V=I.current)==null?void 0:V.querySelector(".adhdev-dockview");G instanceof HTMLElement&&oo(G,x),J(),je()},[je,J,x]),l.useEffect(()=>{je()},[je]),l.useEffect(()=>{const G=V=>{if(V.defaultPrevented||D)return;const ee=te(V);if(!ee)return;const he=V.metaKey||V.ctrlKey||V.altKey;Jo(V.target)&&!he||ca(ie).setActiveTabShortcut!==ee||(V.preventDefault(),V.stopPropagation(),pe())};return window.addEventListener("keydown",G,!0),()=>window.removeEventListener("keydown",G,!0)},[te,ie,D,pe]),l.useEffect(()=>{const G=I.current;if(!G)return;const V=ee=>{var Z,fe;if(!ee.isTrusted)return;const he=(fe=(Z=ee.target)==null?void 0:Z.closest)==null?void 0:fe.call(Z,".dv-scrollable");if(!he)return;ee.preventDefault(),ee.stopPropagation();const ye=Math.abs(ee.deltaX),ke=Math.abs(ee.deltaY),Q=ye>ke?ee.deltaX:ee.deltaY;he.dispatchEvent(new WheelEvent("wheel",{deltaY:Q,deltaMode:ee.deltaMode,bubbles:!1,cancelable:!0}))};return G.addEventListener("wheel",V,{passive:!1,capture:!0}),()=>G.removeEventListener("wheel",V,{capture:!0})},[]),l.useEffect(()=>{const G=Ic(S.current);if(G.length===0)return;const V=G.map(ee=>{let he=[],ye=null;const ke=()=>{ye!=null&&ee.clearTimeout(ye),ye=null,he=[]},Q=()=>{ye!=null&&ee.clearTimeout(ye),ye=ee.setTimeout(()=>{ye=null,he=[]},1200)},Z=Ie=>{if(!Ie.ctrlKey&&!Ie.metaKey&&!Ie.altKey)return;const Pe=te(Ie);if(!Pe)return;const Ae=gp();for(const[Ee,He]of Object.entries(Ae))if(e.some(Le=>Le.tabKey===Ee)&&He===Pe){Ie.preventDefault(),ce(Ee);return}},fe=Ie=>{if(Ie.defaultPrevented||D)return;const Pe=te(Ie);if(!Pe)return;const Ae=Ie.metaKey||Ie.ctrlKey||Ie.altKey;if(Jo(Ie.target))return;const Ee=ca(ie),He=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")),Le=Ae?[Pe]:[...he.slice(-1),Pe].slice(-2),Ye=Le.join(" "),st=Le[Le.length-1],ht=He.find(([,Ge])=>Ge===Ye);if(ht){Ie.preventDefault(),ke(),Me(ht[0]);return}if(He.some(([,Ge])=>Ge.startsWith(`${Ye} `))){Ie.preventDefault(),he=Le,Q();return}const bt=He.find(([,Ge])=>Ge===st);if(bt){Ie.preventDefault(),ke(),Me(bt[0]);return}if(He.some(([,Ge])=>Ge.startsWith(`${st} `))){Ie.preventDefault(),he=[st],Q();return}ke()};return ee.addEventListener("keydown",Z),ee.addEventListener("keydown",fe),()=>{ke(),ee.removeEventListener("keydown",Z),ee.removeEventListener("keydown",fe)}});return()=>{for(const ee of V)ee()}},[te,ie,_,ce,D,Me,e]);const Te=x==="light"?Co:Io,ze=((Re=(Je=(ot=S.current)==null?void 0:ot.activePanel)==null?void 0:Je.group.element)==null?void 0:Re.ownerDocument)??document;return s.jsxs(Cp.Provider,{value:_e,children:[s.jsx("div",{ref:I,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(Gm,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:Rw,remote:Lw},defaultTabComponent:Dw,watermarkComponent:Pw,onReady:Ve,singleTabMode:"default",tabAnimation:"smooth",theme:Te,popoutUrl:"/popout.html"})}),T&&Dr.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:T.x,top:T.y},children: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(rf,{size:13,className:"shrink-0 opacity-70"}),ee=()=>{};switch(G.id){case"dockInWindow":case"dockBackToGrid":V=s.jsx(af,{size:13,className:"shrink-0 opacity-70"}),ee=()=>{Ne(T.tabKey),M(null)};break;case"moveBackToMain":V=s.jsx(sf,{size:13,className:"shrink-0 opacity-70"}),ee=()=>{ue(T.tabKey),M(null)};break;case"floatAsPanel":V=s.jsx(nf,{size:13,className:"shrink-0 opacity-70"}),ee=()=>{ve(T.tabKey),M(null)};break;case"openInNewWindow":V=s.jsx(tf,{size:13,className:"shrink-0 opacity-70"}),ee=()=>{xe(T.tabKey),M(null)};break;case"setShortcut":ee=he=>{he.stopPropagation(),oe(T.tabKey),M(null)};break;case"removeShortcut":V=s.jsx(vt,{size:13,className:"shrink-0 opacity-70"}),ee=()=>{const he={...ae};delete he[T.tabKey],ge(he),M(null)};break;case"hideTab":V=s.jsx(oi,{size:13,className:"shrink-0 opacity-70"}),ee=()=>{H(T.tabKey),M(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${G.tone==="muted"?"text-text-muted":""}`,onMouseDown:Aw,onClick:ee,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)})}),T.sourceDocument.body),D&&Dr.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:()=>oe(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. ",ie?"⌘+1":"Ctrl+1",", ",ie?"⌥+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"})]})}),ze.body)]})}const Ip="adhdev-recent-launch-args-v1",Ew=8;function Bw(e){return String(e||"").trim().replace(/\s+/g," ")}function Mp(e,t){return`${e.trim()}::${t.trim()}`}function Ap(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Ip)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function Fw(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Ip,JSON.stringify(e))}catch{}}function Ow(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=Ap().byKey[Mp(r,n)])==null?void 0:o.items)||[]}function Hw(e,t,r){var m;const n=String(e||"").trim(),a=String(t||"").trim(),o=Bw(r);if(!n||!a||!o)return;const i=Ap(),c=Mp(n,a),d=((m=i.byKey[c])==null?void 0:m.items)||[],p=[o,...d.filter(u=>u!==o)].slice(0,Ew);i.byKey[c]={items:p},Fw(i)}function zw(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 Ww({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 Kw({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:i,onOpenHistory:c,onClearSelection:d}){const p=o?mp(o):null,m=Ww({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Hn,{title:"Saved history",description:Ii(),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:y0()})]}),children:[p?s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),s.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:p.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:p.providerSessionId}),s.jsx("div",{className:"mt-1",children:p.metaLine}),p.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:p.updatedLabel}),p.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:p.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:d,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:m}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function Tp({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 Uw({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 io(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>tr(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>tr(a,"acp"))?"acp":null}function Cn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Gw({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:p}){var Ge,Ot;const m=Vr(),u=l.useMemo(()=>[...e].sort(pi),[e]),[h,b]=l.useState(((Ge=u[0])==null?void 0:Ge.id)||""),y=l.useMemo(()=>u.find(le=>le.id===h)||u[0],[h,u]),f=l.useMemo(()=>((y==null?void 0:y.workspaces)||[]).map(le=>({id:le.id,path:le.path,label:le.label})),[y]),w=(y==null?void 0:y.defaultWorkspaceId)||null,[j,g]=l.useState("workspace"),[v,k]=l.useState(""),[N,x]=l.useState(""),[C,S]=l.useState([]),[I,P]=l.useState(""),[L,A]=l.useState(!1),[R,$]=l.useState(null),[X,T]=l.useState(""),[M,_]=l.useState(io(u[0])),[B,E]=l.useState(""),[F,K]=l.useState(""),[z,ne]=l.useState([]),[q,J]=l.useState(""),[xe,ue]=l.useState([]),[O,H]=l.useState(!1),[ve,we]=l.useState(!1),[be,Ne]=l.useState(""),[re,je]=l.useState(!1),[ce,U]=l.useState(()=>_t()),[W,Y]=l.useState(null),[se,ie]=l.useState(!1),[ae,D]=l.useState(""),[oe,ge]=l.useState(null),[pe,te]=l.useState(!1),[Me,_e]=l.useState(""),[Ce,Ke]=l.useState([]),[Ze,me]=l.useState(!1),[De,$e]=l.useState(""),[tt,Ue]=l.useState(!1),Ve=l.useRef(null),Te=l.useRef(0);l.useEffect(()=>{var le;!h&&((le=u[0])!=null&&le.id)&&b(u[0].id)},[h,u]),l.useEffect(()=>{!y||!(!y.workspaces||!y.availableProviders||!y.detectedIdes||!y.recentLaunches)||m(y.id,{minFreshMs:3e4}).catch(()=>{})},[m,y]);const ze=l.useMemo(()=>((y==null?void 0:y.availableProviders)||[]).filter(le=>tr(le,"cli")),[y]),ot=l.useMemo(()=>((y==null?void 0:y.availableProviders)||[]).filter(le=>tr(le,"acp")),[y]),Je=l.useMemo(()=>((y==null?void 0:y.detectedIdes)||[]).map(le=>({id:le.type,label:le.name||le.type,meta:le.running?"Detected locally":"Available to open"})),[y]),Re=l.useMemo(()=>M==="cli"?ze.map(le=>({id:le.type,label:le.displayName||le.type,meta:"CLI provider"})):M==="acp"?ot.map(le=>({id:le.type,label:le.displayName||le.type,meta:"ACP provider"})):Je,[ot,M,ze,Je]),G=l.useMemo(()=>C.find(le=>le.id===I)||null,[C,I]),V=l.useMemo(()=>ze.find(le=>le.type===B)||null,[ze,B]),ee=l.useMemo(()=>ip(V==null?void 0:V.meshCoordinator,{meshId:(G==null?void 0:G.id)||"",workspace:(G==null?void 0:G.workspace)||""}),[V,G]),he=oe||ee,ye=l.useCallback(async le=>{A(!0),T("");try{const Fe=await c(le);S(Fe),P(de=>{var Be;return Fe.some(Ct=>Ct.id===de)?de:((Be=Fe[0])==null?void 0:Be.id)||""}),$(le)}catch(Fe){S([]),P(""),$(le),T(Fe instanceof Error?Fe.message:"Could not load meshes")}finally{A(!1)}},[c]);l.useEffect(()=>{var Fe;if(!y)return;if(Ve.current!==y.id){Ve.current=y.id,g("workspace"),k(w||((Fe=f[0])==null?void 0:Fe.id)||"__home__"),x(""),S([]),P(""),$(null),T(""),_(io(y)),E(""),K(""),J(""),ue([]),we(!1),Ne(""),U(_t()),D(""),ge(null);return}k(de=>{var Be;return de==="__custom__"||de==="__home__"||f.some(Ct=>Ct.id===de)?de:w||((Be=f[0])==null?void 0:Be.id)||"__home__"}),_(de=>de==="ide"&&Je.length>0||de==="cli"&&ze.length>0||de==="acp"&&ot.length>0?de:io(y))},[ot.length,ze.length,w,Je.length,y,f]),l.useEffect(()=>{!y||j!=="mesh"||R===y.id||L||ye(y.id)},[ye,R,L,y,j]),l.useEffect(()=>{j==="mesh"&&M!=="cli"&&ze.length>0&&_("cli")},[M,ze.length,j]),l.useEffect(()=>{var le;M&&(Re.some(Fe=>Fe.id===B)||E(((le=Re[0])==null?void 0:le.id)||""))},[M,Re,B]),l.useEffect(()=>{ge(null)},[y==null?void 0:y.id,I,B,j]);const ke=l.useCallback(async(le,Fe)=>{const de=Te.current+1;return Te.current=de,H(!0),Ne(""),p(le,Fe).then(Be=>{Te.current===de&&ue(Be)}).catch(Be=>{Te.current===de&&(ue([]),Ne(Be instanceof Error?Be.message:"Could not load saved sessions"))}).finally(()=>{Te.current===de&&(H(!1),we(!0))})},[p]),Q=l.useCallback((le,Fe)=>{ne(Ow(le,Fe))},[]);l.useEffect(()=>{Te.current+=1,J(""),U(_t()),!y||!B||M==="ide"?ne([]):Q(y.id,B),we(!1),ue([]),Ne(""),H(!1)},[M,Q,ke,y,B]),l.useEffect(()=>{if(!q)return;const le=xe.find(Fe=>Fe.providerSessionId===q);le!=null&&le.canResume||J("")},[xe,q]);const Z=v==="__custom__"?N.trim():v==="__home__"?"":((Ot=f.find(le=>le.id===v))==null?void 0:Ot.path)||"",fe=l.useMemo(()=>y?t.filter(le=>le.id!==y.id&&le.daemonId===y.id).map(le=>le.workspace):[],[t,y]),Ie=l.useMemo(()=>((y==null?void 0:y.recentLaunches)||[]).map(le=>le.workspace),[y]),Pe=l.useCallback(le=>{const Fe=String(le.workspace||"").trim();if(!Fe)return;const de=f.find(Be=>Cn(Be.path)===Cn(Fe));if(de){k(de.id),x("");return}k("__custom__"),x(Fe)},[f]),Ae=l.useCallback(le=>{const Fe=String(le.workspace||"").trim();if(!Fe)return{workspaceId:null,workspacePath:null};const de=f.find(Be=>Cn(Be.path)===Cn(Fe));return de?{workspaceId:de.id,workspacePath:null}:{workspaceId:null,workspacePath:Fe}},[f]),Ee=l.useMemo(()=>xe.find(le=>le.providerSessionId===q)||null,[xe,q]),He=l.useMemo(()=>{var Fe;if(M!=="cli"||!y||!B)return null;const le=((Fe=ze.find(de=>de.type===B))==null?void 0:Fe.displayName)||B;return{routeId:y.id,daemonId:y.id,providerSessionId:q||void 0,transport:"pty",mode:"chat",agentName:le,agentType:B,status:"idle",title:le,messages:[],ideType:B,workspaceName:Z,workspacePath:Z,displayPrimary:le,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${y.id}:${B}`,machineName:Ft(y,{fallbackId:y.id})}},[M,ze,Z,y,q,B]),Le=l.useCallback(()=>{var Fe;if(!y)return;k("__custom__"),te(!0),$e("");const le=$i(y.platform,Di(N.trim(),Z,fe,Ie,y.defaultWorkspacePath,(Fe=f.find(de=>de.id===w))==null?void 0:Fe.path,f.map(de=>de.path)));me(!0),n(y.id,le).then(de=>{_e(de.path),x(de.path),Ke(de.directories)}).catch(de=>{$e(de instanceof Error?de.message:"Could not load folder")}).finally(()=>me(!1))},[N,w,Ie,fe,n,Z,y,f]),Ye=l.useCallback(le=>{y&&(me(!0),$e(""),n(y.id,le).then(Fe=>{_e(Fe.path),x(Fe.path),Ke(Fe.directories)}).catch(Fe=>{$e(Fe instanceof Error?Fe.message:"Could not load folder")}).finally(()=>me(!1)))},[n,y]),st=l.useCallback(async()=>{if(!y||!Z)return;Ue(!0),D("");const le=await a(y.id,Z);if(Ue(!1),!le.ok){D(le.error||"Could not save workspace");return}D("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,Z,y]),ht=l.useCallback(async()=>{if(!y)return;if(j==="mesh"){if(!I||!B)return;ie(!0),D(""),ge(null);const de=await d(y.id,I,B);if(ie(!1),!de.ok){if(de.code==="mesh_coordinator_manual_mcp_setup_required"&&de.manualSetup){ge(de.manualSetup),D("Manual MCP setup required before this provider can act as mesh coordinator.");return}D(de.error||"Could not start mesh coordinator");return}r();return}if(!M||!B)return;ie(!0),D("");const le=F.trim()?F.trim().split(/\s+/).filter(Boolean):[],Fe=M==="ide"?await o(y.id,B,{workspacePath:Z||null}):await i(y.id,M,B,{workspaceId:v!=="__home__"&&v!=="__custom__"?v:null,workspacePath:v==="__custom__"&&Z||null,resumeSessionId:M==="cli"&&q?q:null,cliArgs:le});if(ie(!1),!Fe.ok){D(Fe.error||"Could not start session");return}M!=="ide"&&F.trim()&&(Hw(y.id,B,F),Q(y.id,B)),r()},[M,F,Q,r,o,d,i,Z,y,I,q,B,v,j]),kt=j==="mesh"?"Start mesh coordinator":M?x0(M,M==="cli"&&!!q):"Start",bt=j==="mesh"?"Starting coordinator…":M?b0(M,M==="cli"&&!!q):"Starting…",ft=u.length>5;return y?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:[u.length>1&&s.jsx(Hn,{title:"Machine",children:ft?s.jsx("select",{"aria-label":"Machine",value:y.id,onChange:le=>b(le.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:u.map(le=>s.jsx("option",{value:le.id,children:Ft(le,{fallbackId:le.id})},le.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:u.map(le=>{const Fe=Ft(le,{fallbackId:le.id}),de=y.id===le.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${Fe}`,"aria-pressed":de,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${de?"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(le.id),disabled:se,title:Fe,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${le.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:Fe})]},le.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:Le,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(le=>s.jsxs("button",{type:"button",role:"radio","aria-checked":j===le.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${j===le.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:()=>{g(le.id),D(""),le.id==="mesh"&&y&&R!==y.id&&!L&&ye(y.id)},disabled:se,children:[s.jsx("div",{className:"text-sm font-semibold",children:le.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:le.desc})]},le.id))}),j==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:v,onChange:le=>{const Fe=le.target.value;k(Fe),Fe==="__custom__"?Le():D("")},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(le=>s.jsxs("option",{value:le.id,children:[le.id===w?"⭐ ":"",zd(le.path,le.label)||le.path]},le.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v==="__home__"?"Launch without a workspace.":Z||"Select a workspace folder."}),v==="__custom__"&&Z&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Le,disabled:se,children:[s.jsx(Js,{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&&C.length===0&&s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker."}),C.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:C.map(le=>s.jsxs("button",{type:"button",role:"radio","aria-checked":I===le.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${I===le.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>P(le.id),disabled:se,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:le.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[le.repoIdentity||"Repo mesh",typeof le.nodesCount=="number"?` · ${le.nodesCount} node${le.nodesCount===1?"":"s"}`:""]}),le.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",le.workspace]})]},le.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(Uw,{workspaceMode:j,activeKind:M,cliEnabled:ze.length>0,ideEnabled:Je.length>0,acpEnabled:ot.length>0,busy:se,onSelect:_}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:M==="ide"?"Choose IDE":M==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Re.map(le=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${B===le.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>E(le.id),disabled:se,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:le.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:le.meta})]},le.id)),Re.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"&&he&&s.jsx(Tp,{setup:he,providerName:(V==null?void 0:V.displayName)||(V==null?void 0:V.name)||B}),j!=="mesh"&&M!=="ide"&&s.jsxs(Hn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:F,onChange:le=>K(le.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}),z.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:z.map(le=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>K(le),disabled:se,title:le,children:le},le))})]}),j!=="mesh"&&M==="cli"&&s.jsx(Kw,{busy:se,savedSessionsLoading:O,savedSessionsError:be,selectedSession:Ee,onRefresh:()=>{!y||!B||ke(y.id,B)},onOpenHistory:()=>{!y||!B||(je(!0),zw({hasLoadedInitialResults:ve,isLoading:O})&&ke(y.id,B))},onClearSelection:()=>J("")}),ae&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ae.includes("saved")||ae.includes("requested")||ae.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:ae})]}),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||!B||M!=="cli"||L:!M||!B||v==="__custom__"&&!Z),children:[s.jsx(Cd,{size:14}),se?bt:kt]})]})]})}),pe&&s.jsx(Fi,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:Me,directories:Ce,busy:Ze,error:De,onClose:()=>te(!1),onNavigate:Ye,onConfirm:le=>{x(le),_e(le),k("__custom__"),te(!1)}}),re&&He&&s.jsx(Tu,{activeConv:He,ides:[],isCreatingChat:!1,isRefreshingHistory:O,savedSessions:xe,isSavedSessionsLoading:O,isResumingSavedSessionId:W,savedHistoryFilters:ce,missingWorkspaceResumePath:Z||null,onSavedHistoryFiltersChange:U,onClose:()=>je(!1),onNewChat:()=>{J(""),je(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!y||!B||ke(y.id,B)},onResumeSavedSession:le=>{if(!y||!B||W||!le.canResume)return;const Fe=Ae(le);J(le.providerSessionId),Pe(le),Y(le.providerSessionId),je(!1),ie(!0),D(""),i(y.id,"cli",B,{workspaceId:Fe.workspaceId,workspacePath:Fe.workspacePath,resumeSessionId:le.providerSessionId}).then(de=>{if(!de.ok){D(de.error||"Could not resume session");return}r()}).finally(()=>{ie(!1),Y(de=>de===le.providerSessionId?null:de)})}})]}):null}function _p(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 Hi(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=_p(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 zi(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function Rp(e){var t;return!zi(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 Vw(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 Lp(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 qw(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${Lp(e)}::${n}x${a}`}const Yw={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"},Jw={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"},Xw={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"},Qw={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 Es(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=>Jw[t],actionButton:t=>Qw[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=>Yw[t],actionButton:t=>Xw[t]}}const sr={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,layerGap:220,nodeGap:82,edgeLabelBuffer:180,placeholderTopOffset:0},Qr={worktreeCardWidth:188,submoduleCardWidth:188,minWorktreeCardHeight:88,minSubmoduleCardHeight:88,maxEstimatedCardHeight:178,layerGap:160,nodeGap:52,edgeLabelBuffer:120},Zw={maxWidth:180};function ej(e){return e==="TB"?"DOWN":"RIGHT"}function Wi(e,t){return{"elk.algorithm":"layered","elk.direction":ej(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 tj=Wi(sr,"LR");Wi(Qr,"LR");function sj(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 rj=new Vm;function Hr(e,t=!1){const r=t?Qr:sr;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=_p(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 Pp(e,t=!1){const r=t?Qr:sr,n=Hr(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(nj(e)/o),c=Mn(e.label,a,2),d=Mn(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,a,2),p=Mn(zn(e),a+(t?1:4),t?2:3),m=Hi(e),u=Rp(e)?zi(e):null,h=t?0:Mn(u,Math.max(24,Math.floor(n/8)),4),b=t?40+c*16+d*12+(m?22:0)+Math.max(0,i-1)*18+Math.max(18,p*16):52+c*18+d*14+(m?30:0)+i*24+Math.max(22,p*18)+(h>0?22+h*16:0),y=e.type==="submoduleNode"?r.minSubmoduleCardHeight:r.minWorktreeCardHeight;return Math.min(r.maxEstimatedCardHeight,Math.max(y,Math.ceil(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 nj(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 aj(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 oj(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function ij(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 lj(e,t,r){return{id:e.id,x:t,y:r,width:Hr(e),height:Pp(e)}}function cj(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 Dp(e){const t=[...e.nodes].sort(aj),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,cj(r,e)]}function dj(e,t=tj,r=!1,n="LR"){const a=Dp(e),o=new Set(a.map(d=>d.id)),i=a.map(d=>({id:d.id,width:Hr(d,r),height:Pp(d,r)})),c=e.edges.filter(d=>o.has(d.source)&&o.has(d.target)).sort(oj).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 uj(e,t=!1){const r=[...new Set(e.map(a=>Math.round(a.x)))].sort((a,o)=>a-o),n=t?Qr.layerGap:sr.layerGap;return r.length<2?n:Math.min(...r.slice(1).map((a,o)=>a-r[o]))}async function $p(e,t=!1,r="LR",n){var y,f;const o=Wi(t?Qr:sr,r),i=Dp(e),c=new Map(i.map(w=>[w.id,w])),d=dj(e,o,t,r);if(n&&n.size>0)for(const w of d.children??[]){const j=n.get(w.id);j&&j>0&&(w.height=j)}const p=await rj.layout(d),m=(p.children??[]).map(w=>{const j=c.get(w.id);return j?ij(j,Math.round(w.x??0),Math.round(w.y??sr.placeholderTopOffset),!w.id.endsWith("__placeholder")):null}).filter(Boolean),u=new Map(i.map((w,j)=>[w.id,j]));m.sort((w,j)=>(u.get(w.id)??0)-(u.get(j.id)??0));const h=m.map(w=>lj(w.graphNode,w.position.x,w.position.y)),b=new Map;for(const w of p.edges??[]){const j=w.sections;if(!j||j.length===0)continue;const g=j[0],v=(y=w.sources)==null?void 0:y[0],k=(f=w.targets)==null?void 0:f[0];if(!v||!k)continue;const N=[];N.push({x:Math.round(g.startPoint.x),y:Math.round(g.startPoint.y)});for(const x of g.bendPoints??[])N.push({x:Math.round(x.x),y:Math.round(x.y)});N.push({x:Math.round(g.endPoint.x),y:Math.round(g.endPoint.y)}),b.set(w.id,{id:w.id,source:v,target:k,points:N})}return{nodes:m,bounds:h,edgeRoutes:b,columnGap:uj(h,t),layoutOptions:{...o}}}function pj(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 Ep(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function mj(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(pj),...e.edges.map(Ep)].join("::")}function hj(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(Ep)].join("::")}const fj=7,Ki=l.createContext(Es("dark")),Bp=l.createContext(!1),Fp=l.createContext("LR"),Op={overflowWrap:"anywhere",wordBreak:"break-word"},xj={...Op,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},bj={...Op,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function Hp(e){return e.activeSessionCount>0}function gj(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function Tc(e,t,r){const n=Hp(e),a=gj(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=Hi(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 Tt(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 _c(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 Rc(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 yj(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 vj(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":Tt("health",t)}function wj(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function Lc(e){const t=wj(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 yr(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function jj(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 Pc(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function kj(e){return e.locality==="remote"?"meta":"health"}function Nj({data:e,selected:t}){const r=l.useContext(Ki),n=l.useContext(Bp),a=l.useContext(Fp),o=e.graphNode,i=o.type==="defaultBranchNode",c=o.type==="submoduleNode",d=Rp(o),p=i?"default branch anchor":c?o.submodulePath||"submodule checkout":[o.machineLabel,Pc(o.locality)].filter(Boolean).join(" · ")||o.workspace,m=o.submoduleCommit?o.submoduleCommit.slice(0,7):null,u=Hi(o),h=zi(o),b=Hp(o),y=o.sessionDetails,f=o.sessionDetails,w=jj(o),j=o.sessionDetails.map(v=>{const k=Yt(v),N=v.providerType||"provider unknown",x=yr(v),C=v.startedAt||v.createdAt||null,S=v.statusNote?` · ${v.statusNote}`:"";return`Session: ${v.sessionId} · ${N} · ${k} · ${x} · ${Lc(C)}${S}`});if(n)return s.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${Tc(o,t,r.isDark)}`,style:{width:Hr(o,!0)},title:[o.label,o.branch?`Branch: ${o.branch}`:null,o.machineLabel?`Machine: ${o.machineLabel}`:null,o.workspace?`Workspace: ${o.workspace}`:null,u?`Status: ${u.label}`:null,zn(o),...j].filter(Boolean).join(`
|
|
74
|
+
`),children:[s.jsx(cn,{type:"target",position:a==="TB"?cs.Top:cs.Left,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-xs font-semibold leading-4 ${r.textPrimary}`,children:o.label}),!i&&s.jsx("div",{className:`truncate text-[10px] leading-3.5 ${r.textMuted}`,children:p})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[b&&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:Rc(o.health)},"aria-hidden":!0})]})]}),o.health==="unknown"&&!u&&s.jsx("div",{className:`mt-1.5 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[9px] italic ${Tt("health",r.isDark)}`,children:s.jsx("span",{className:"truncate",children:"Connecting..."})}),u&&s.jsx("div",{className:`mt-1.5 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[9px] font-semibold uppercase tracking-[0.14em] ${_c(u.tone,r.isDark)}`,title:u.label,children:s.jsx("span",{className:"truncate",children:u.label})}),!u&&o.branch&&!c&&o.health!=="unknown"&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[10px] ${Tt("meta",r.isDark)} rounded-full border px-2 py-0.5 inline-block`,title:o.branch,children:o.branch}),w&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[9px] ${r.isDark?"text-cyan-100/85":"text-sky-700"}`,title:j.join(`
|
|
75
|
+
`),children:w}),f.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:f.map(v=>s.jsxs("div",{className:`min-w-0 rounded-md border px-1.5 py-1 ${r.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/80"}`,title:[`Session ID: ${v.sessionId}`,v.providerType?`Provider: ${v.providerType}`:null,`Status: ${Yt(v)}`,`Role: ${yr(v)}`].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:v.providerType||"provider unknown"}),s.jsx("span",{className:`shrink-0 rounded-full border px-1 py-0 text-[8px] font-semibold uppercase tracking-[0.1em] ${lo(v,r.isDark)}`,children:Yt(v)})]}),s.jsxs("div",{className:`mt-0.5 flex min-w-0 items-center gap-1.5 text-[8px] ${r.textMuted}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",children:co(v.sessionId)}),s.jsx("span",{className:"shrink-0",children:yr(v)})]})]},v.sessionId))}),s.jsx(cn,{type:"source",position:a==="TB"?cs.Bottom:cs.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]});const g=[o.label,p,u?`Status: ${u.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&&h?`Note: ${h}`:null,...j].filter(Boolean).join(`
|
|
77
|
+
`);return s.jsxs("div",{className:`rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all ${Tc(o,t,r.isDark)}${vj(o)?" mesh-node-generating":""}`,style:{width:Hr(o)},title:g,children:[s.jsx(cn,{type:"target",position:a==="TB"?cs.Top:cs.Left,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${r.textPrimary}`,children:o.label}),s.jsx("div",{className:`truncate text-[11px] ${r.textMuted}`,children:p})]}),s.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 shrink-0",children:[b&&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:Rc(o.health)},"aria-hidden":!0})]})]}),u?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] ${_c(u.tone,r.isDark)}`,title:u.label,children:s.jsx("span",{className:"truncate",children:u.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] ${Tt("meta",r.isDark)}`,title:o.branch,children:s.jsx("span",{className:"truncate",children:o.branch})}):null,w&&s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[10px] font-medium ${r.isDark?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}`,title:j.join(`
|
|
78
|
+
`),children:s.jsx("span",{className:"truncate",children:w})}),f.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:f.map(v=>{const k=yr(v);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/85"}`,title:[`Session ID: ${v.sessionId}`,v.providerType?`Provider: ${v.providerType}`:null,`Status: ${Yt(v)}`,`Role: ${k}`].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:v.providerType||"provider unknown"}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${lo(v,r.isDark)}`,children:Yt(v)})]}),s.jsxs("div",{className:`mt-0.5 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",children:co(v.sessionId)}),s.jsx("span",{children:k})]})]},v.sessionId)})}),s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"flex min-w-0 flex-wrap gap-1.5 text-[10px]",children:[o.health==="unknown"?s.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${Tt("health",r.isDark)}`,children:"connecting..."}):s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${Tt("health",r.isDark)}`,children:yj(o.health)}),c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Tt("submodule",r.isDark)}`,children:"submodule"}),!i&&o.health==="unknown"&&!o.locality&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${Tt("health",r.isDark)}`,children:"..."}),!i&&(o.health!=="unknown"||o.locality)&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Tt(kj(o),r.isDark)}`,children:Pc(o.locality)}),m&&c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Tt("meta",r.isDark)}`,children:m}),o.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Tt("dirty",r.isDark)}`,children:c?"local changes":`${o.dirtyFiles} dirty`}),o.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Tt("conflict",r.isDark)}`,children:"out of sync"}),o.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Tt("conflict",r.isDark)}`,children:"conflicts"}),!c&&o.upstream&&o.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Tt("orphan",r.isDark)}`,children:"upstream unverified"}),o.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Tt("orphan",r.isDark)}`,children:"needs follow-up"}),!c&&o.refineJobStatus==="completed"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Tt("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:xj,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(v=>{const k=v.startedAt||v.createdAt||null,N=yr(v);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-white/8 bg-white/[0.035]":"border-slate-200 bg-white/80"}`,title:[`Session ID: ${v.sessionId}`,v.providerType?`Provider: ${v.providerType}`:null,`Status: ${Yt(v)}`,`Role: ${N}`,k?`Started: ${k}`:"Started: not reported",v.statusNote?`Note: ${v.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(v.sessionId)}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${lo(v,r.isDark)}`,children:Yt(v)})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"truncate",children:v.providerType||"provider unknown"}),s.jsx("span",{children:N}),s.jsx("span",{children:Lc(k)})]}),v.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${r.textMuted}`,children:v.statusNote})]},v.sessionId)})})]}),d&&h&&s.jsx("div",{className:`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${r.isDark?"border-cyan-400/15 bg-cyan-500/8 text-cyan-50/90":"border-sky-300 bg-sky-50 text-sky-700"}`,style:bj,children:h})]}),s.jsx(cn,{type:"source",position:a==="TB"?cs.Bottom:cs.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const Sj={meshNode:Nj},Cj=8;function Ij(e){if(e.length<2)return null;if(e.length===2){const[p,m]=e;return{d:`M ${p.x},${p.y} L ${m.x},${m.y}`,labelX:(p.x+m.x)/2,labelY:(p.y+m.y)/2}}const t=Cj,r=[`M ${e[0].x},${e[0].y}`];for(let p=1;p<e.length-1;p+=1){const m=e[p-1],u=e[p],h=e[p+1],b=Math.sign(u.x-m.x),y=Math.sign(u.y-m.y),f=Math.sign(h.x-u.x),w=Math.sign(h.y-u.y),j=Math.hypot(u.x-m.x,u.y-m.y),g=Math.hypot(h.x-u.x,h.y-u.y),v=Math.min(t,j/2,g/2);if(v<1||b===f&&y===w){r.push(`L ${u.x},${u.y}`);continue}const k=u.x-b*v,N=u.y-y*v,x=u.x+f*v,C=u.y+w*v;r.push(`L ${k},${N}`),r.push(`Q ${u.x},${u.y} ${x},${C}`)}const n=e[e.length-1];r.push(`L ${n.x},${n.y}`);let a=0;const o=[0];for(let p=1;p<e.length;p+=1)a+=Math.hypot(e[p].x-e[p-1].x,e[p].y-e[p-1].y),o.push(a);const i=a/2;let c=e[0].x,d=e[0].y;for(let p=1;p<e.length;p+=1)if(o[p]>=i){const m=o[p]-o[p-1],u=m===0?0:(i-o[p-1])/m;c=e[p-1].x+(e[p].x-e[p-1].x)*u,d=e[p-1].y+(e[p].y-e[p-1].y)*u;break}return{d:r.join(" "),labelX:c,labelY:d}}function Mj(e){const t=e.data.routePoints;if(t&&t.length>=2){const o=Ij(t);if(o)return[o.d,o.labelX,o.labelY]}const r={sourceX:e.sourceX,sourceY:e.sourceY,sourcePosition:e.sourcePosition,targetX:e.targetX,targetY:e.targetY,targetPosition:e.targetPosition},n=e.data.graphEdge;let a;return n.type==="parentBranch"?a=oh(r):n.type==="worktreeLink"||n.type==="submoduleLink"||n.type==="cloneLink"?a=nh(r):a=ah(r),[a[0],a[1],a[2]]}function Aj(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 Tj(e){const t=l.useContext(Ki),r=e.data.graphEdge,[n,a,o]=Mj(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(Zm,{id:e.id,path:n,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(eh,{children:s.jsx("div",{className:Aj(r,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${a}px, ${o}px)`,pointerEvents:"none",maxWidth:Zw.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const _j={meshEdge:Tj};async function Rj(e,t,r,n,a){const o=await $p(e,r,n,a);return zp(e,o,t,r)}async function Lj(e,t=Es("dark"),r=!1,n="LR"){const a=await $p(e,r,n);return zp(e,a,t,r)}function zp(e,t,r,n=!1){const a=new Set(t.nodes.map(p=>p.id)),o=t.nodes.map(p=>({id:p.id,type:p.type,position:p.position,data:{graphNode:p.graphNode,compact:n},selected:p.selected,draggable:p.draggable,selectable:p.selectable})),i=e.edges.filter(p=>a.has(p.source)&&a.has(p.target)),c=$j(i),d=i.map(p=>{var m;return{id:p.id,source:p.source,target:p.target,label:c.has(p.id)?p.label:void 0,type:"meshEdge",data:{graphEdge:p,routePoints:(m=t.edgeRoutes.get(p.id))==null?void 0:m.points},animated:p.type==="orphanLink",markerEnd:p.direction==="directed"?{type:rh.ArrowClosed,width:p.type==="submoduleLink"?16:18,height:p.type==="submoduleLink"?16:18,color:$c(p)}:void 0,style:{stroke:$c(p),strokeWidth:p.type==="orphanLink"?2.25:p.type==="submoduleLink"?1.7:p.type==="worktreeLink"?1.8:p.type==="cloneLink"?1.6:p.type==="coordinatorLink"?2.25:2,strokeDasharray:p.type==="orphanLink"?"5 4":p.type==="submoduleLink"?"4 3":p.type==="cloneLink"?"6 3":void 0},labelStyle:{fill:r.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:r.edgeLabelBackgroundColor,fillOpacity:1,stroke:r.edgeLabelBorderColor},labelBgPadding:[6,4],labelBgBorderRadius:7}});return{nodes:o,edges:d}}const Pj=3,Dj=2;function Dc(e){switch(e.type){case"coordinatorLink":return 6;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 $j(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<Pj){for(const o of n)t.add(o.id);continue}const a=[...n].sort((o,i)=>{const c=Dc(i)-Dc(o);return c!==0?c:o.id.localeCompare(i.id)});for(const o of a.slice(0,Dj))t.add(o.id)}return t}function $c(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";case"coordinatorLink":return"#64748b";default:return"#64748b"}}function Ej(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 Bj(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 Fj({data:e,viewportKey:t}){const r=th(),n=sh(),a=l.useRef(null),o=l.useMemo(()=>Lp(e),[e]),i=l.useMemo(()=>Vw(e),[e]);return l.useEffect(()=>{if(!r||e.nodes.length===0||a.current===t)return;let c=!1;const d=requestAnimationFrame(()=>{if(c)return;const p=i.length>0&&i.length<e.nodes.length;n.fitView({nodes:p?i.map(m=>({id:m})):void 0,padding:p?.24:.2,maxZoom:p?.98:.9,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(d)}},[e.nodes.length,i,o,r,n,t]),null}const Oj=12;function Hj(e){return e>=16?"min-h-[720px]":e>=10?"min-h-[580px]":"min-h-[460px]"}function zj({data:e,selectedNodeId:t=null,directionPref:r,onNodeClick:n,onEdgeClick:a,onNodeHoverChange:o,onEdgeHoverChange:i}){const{theme:c}=$s(),d=l.useMemo(()=>Es(c),[c]),p=l.useMemo(()=>mj(e),[e]),m=l.useMemo(()=>hj(e),[e]),u=e.nodes.length>=fj,[h]=l.useState("LR"),b=r??h,y=l.useMemo(()=>b==="auto"?sj(e):b,[b,p,e]),f=e.nodes.length>=Oj,[w,j]=l.useState({nodes:[],edges:[]}),g=l.useRef(null),[v,k]=l.useState({width:0,height:0}),N=l.useMemo(()=>`${qw(e,v.width,v.height)}::${y}`,[p,e,v.height,v.width,y]);l.useEffect(()=>{let C=!1;return Lj(e,d,u,y).then(S=>{if(C)return;j(S);const I=requestAnimationFrame(()=>{if(C)return;const P=g.current;if(!P)return;const L=new Map;for(const A of S.nodes){const R=P.querySelector(`.react-flow__node[data-id="${CSS.escape(A.id)}"]`);R&&R.offsetHeight>0&&L.set(A.id,R.offsetHeight)}L.size!==0&&Rj(e,d,u,y,L).then(A=>{C||j(A)})});return()=>cancelAnimationFrame(I)}),()=>{C=!0}},[e,m,d,u,y]);const x=l.useMemo(()=>w.nodes.map(C=>({...C,selected:C.id===t})),[w.nodes,t]);return l.useEffect(()=>{const C=g.current;if(!C)return;const S=()=>{const P=Math.max(0,Math.round(C.clientWidth)),L=Math.max(0,Math.round(C.clientHeight));k(A=>A.width===P&&A.height===L?A:{width:P,height:L})};S();const I=typeof ResizeObserver=="function"?new ResizeObserver(()=>S()):null;return I==null||I.observe(C),window.addEventListener("resize",S),()=>{I==null||I.disconnect(),window.removeEventListener("resize",S)}},[]),s.jsx(Ki.Provider,{value:d,children:s.jsx(Bp.Provider,{value:u,children:s.jsx(Fp.Provider,{value:y,children:s.jsxs("div",{ref:g,className:`${d.graphShellClass} ${Hj(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(qm,{nodes:x,edges:w.edges,nodeTypes:Sj,edgeTypes:_j,minZoom:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(C,S)=>n==null?void 0:n(S.data.graphNode),onEdgeClick:(C,S)=>{var P;const I=(P=S.data)==null?void 0:P.graphEdge;I&&(a==null||a(I))},onNodeMouseEnter:(C,S)=>o==null?void 0:o(S.data.graphNode),onNodeMouseLeave:()=>o==null?void 0:o(null),onEdgeMouseEnter:(C,S)=>{var I;return i==null?void 0:i(((I=S.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(Fj,{data:e,viewportKey:N}),s.jsx(Ym,{className:d.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),f&&s.jsx(Jm,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:Ej,nodeClassName:Bj,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(Xm,{variant:Qm.Dots,gap:18,size:1.2,color:d.graphBackgroundDotColor})]})})]})})})})}const Wj=5*60*1e3;function Wp(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function Kp(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function Kj(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"||Wp(e)||Kp(e)?"remote":"unknown"}function Uj(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 Gj(e){return bi(e)}function Up(e){var t;return Gj(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function Gp(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function Vj(e){return e.activeSessionDetails&&e.activeSessionDetails.length>0?e.activeSessionDetails:(e.activeSessions??[]).map(t=>({sessionId:t,workspace:e.workspace,isCached:!0}))}function Vp(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function qp(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 qj(e){return Ui(e)?"degraded":qp(e)?"dirty":"online"}function Yj(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function Ec(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 uo(e){return e.length===0?"unknown":e.reduce((t,r)=>Ec(r)>Ec(t)?r:t)}function Jj(e){var o,i,c,d,p;const t=new Map,r=new Map;for(const m of e){const u=(i=(o=m.git)==null?void 0:o.branch)==null?void 0:i.trim();u&&(r.set(u,(r.get(u)??0)+1),(c=m.git)!=null&&c.upstream&&t.set(u,(t.get(u)??0)+1))}const n=[...t.entries()].sort((m,u)=>{if(u[1]!==m[1])return u[1]-m[1];const h=["main","master","develop","dev"],b=h.indexOf(m[0]),y=h.indexOf(u[0]);return b!==-1||y!==-1?b===-1?1:y===-1?-1:b-y:m[0].localeCompare(u[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((p=[...r.entries()].sort((m,u)=>u[1]-m[1])[0])==null?void 0:p[0])??null}function Xj(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 Bc(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 Qj(e){return e.reduce((t,r)=>Bc(r.status)>Bc(t.status)?r:t)}function Zj(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 ek(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 tk(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 Fc(e){switch(e){case"running":case"accepted":return 0;case"failed":return 1;case"completed":default:return 2}}function Oc(e){const t=e.lastUpdatedAt||e.completedAt||e.startedAt||"";return Gp(t)??0}function sk(e){return e.length===0?null:e.reduce((t,r)=>{const n=Fc(t.status),a=Fc(r.status);return a!==n?a<n?r:t:Oc(r)>Oc(t)?r:t})}function rk(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 nk(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 ak(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 ok(e,t){if(Up(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=Vp(a)||qp(a),i=!!(a!=null&&a.hasConflicts)||Ui(a),c=(a==null?void 0:a.ahead)??0,d=(a==null?void 0:a.behind)??0,p=(a==null?void 0:a.branch)??null,m=(a==null?void 0:a.upstream)??null,u=(a==null?void 0:a.upstreamStatus)??null,h=r.defaultBranch??t??null;return{status:n,needsConvergence:r.needsConvergence??n!=="merged_to_main",reason:r.reason??"provided_by_coordinator",nextStep:r.nextStep??null,branch:r.branch??p,defaultBranch:h,upstream:r.upstream??m,upstreamStatus:r.upstreamStatus??u,ahead:r.ahead??c,behind:r.behind??d,dirty:r.dirty??o,hasConflicts:r.hasConflicts??i}}function ik(e,t){const r=ok(e,t);return r?{...r,defaultBranch:r.defaultBranch??t}:null}function lk(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function ck(e){var d,p,m;const{nodeStatus:t,expectedSubmodulePaths:r,refreshedAtMs:n}=e,a=[],o=t.machineLabel||t.nodeId,i=t.git;if(!i){if(Up(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const u=t.health==="online"||t.machineStatus==="online"||((d=t.connection)==null?void 0:d.state)==="connected"||((p=t.connection)==null?void 0:p.state)==="self";return a.push(u?`${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(u=>u.path));if(r.size>0){const u=[...r].filter(h=>!c.has(h));u.length>0&&a.push(`${o} is missing submodule visibility for ${u.join(", ")} even though another peer reported it.`)}return((m=t.connection)==null?void 0:m.state)!=="self"&&n!==null&&typeof i.lastCheckedAt=="number"&&n-i.lastCheckedAt>Wj&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(u=>u.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(u=>u.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function Yp(e){const t=gi(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??Jj(t.nodes),a=Gp(t.refreshedAt),o=new Set(t.nodes.flatMap(M=>{var _;return(((_=M.git)==null?void 0:_.submodules)??[]).map(B=>B.path)})),i=[],c=[],d=ek(t),p=new Map,m=rk(tk(t));for(const M of t.nodes){const _=M.git,B=(_==null?void 0:_.branch)??null,E=qj(_),F=Vp(_)||E==="dirty",K=Xj(M,n),z=ik(M,n),ne=ck({nodeStatus:M,expectedSubmodulePaths:o,refreshedAtMs:a}),q=typeof M.clonedFromNodeId=="string"?M.clonedFromNodeId:null,J=Vj(M),xe=sk(m.get(M.nodeId)??[]),ue=Uj(M),O={id:M.nodeId,type:K.length>0?"orphanNode":"worktreeNode",label:M.machineLabel||M.nodeId.slice(0,8),workspace:M.workspace,branch:B,upstream:(_==null?void 0:_.upstream)??null,upstreamStatus:(_==null?void 0:_.upstreamStatus)??null,daemonId:Wp(M),machineId:Kp(M),machineLabel:M.machineLabel||null,locality:Kj(M),connectionTransport:ue.connectionTransport,connectionState:ue.connectionState,connectionReason:ue.connectionReason,connectionReported:ue.connectionReported,connectionRttMs:ue.connectionRttMs,health:uo([M.health,E]),ahead:(_==null?void 0:_.ahead)??0,behind:(_==null?void 0:_.behind)??0,dirty:F,dirtyFiles:Yj(_),hasConflicts:(_==null?void 0:_.hasConflicts)??!1,activeSessionCount:J.length,activeSessions:J.map(H=>H.sessionId),sessionDetails:J,providers:M.providers??[],isOrphan:K.length>0,orphanReasons:K,error:M.error,nextStepHint:ne.snapshotWarnings[0]??K[0]??(z==null?void 0:z.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:q,worktreeBranch:M.worktreeBranch??null,submodulePath:null,submoduleCommit:(_==null?void 0:_.headCommit)??null,outOfSync:Ui(_),snapshotCompleteness:ne.snapshotCompleteness,snapshotWarnings:ne.snapshotWarnings,branchConvergence:z,refineJobStatus:(xe==null?void 0:xe.status)??null,refineJobId:(xe==null?void 0:xe.jobId)??null,refineJobBranch:(xe==null?void 0:xe.branch)??null,refineJobInto:(xe==null?void 0:xe.into)??null,source:M};if(i.push(O),B){const H=p.get(B)??[];H.push(O.id),p.set(B,H)}for(const H of(_==null?void 0:_.submodules)??[]){const ve=`${O.id}::submodule::${H.path}`,we=H.path.split("/").filter(Boolean).pop()||H.path;i.push({id:ve,type:"submoduleNode",label:we,workspace:H.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:O.daemonId,machineId:O.machineId,machineLabel:O.machineLabel,locality:O.locality,connectionTransport:O.connectionTransport,connectionState:O.connectionState,connectionReason:O.connectionReason,connectionReported:O.connectionReported,connectionRttMs:O.connectionRttMs,health:lk(H),ahead:0,behind:0,dirty:H.dirty,dirtyFiles:H.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],error:H.error,nextStepHint:H.error||(H.outOfSync?`${H.path} is out of sync with the parent checkout`:H.dirty?`${H.path} has local changes`:`${H.path} is in sync with the parent checkout`),parentNodeId:O.id,submodulePath:H.path,submoduleCommit:H.commit,outOfSync:H.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:O.id,parentWorkspace:M.workspace,submodule:H}}),c.push({id:`${O.id}--${ve}`,source:O.id,target:ve,type:"submoduleLink",label:H.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const u=n?`__branch_${n}`:null;if(u&&n){const _=(p.get(n)??[]).map(q=>i.find(J=>J.id===q)).filter(Boolean),B=_.map(q=>q.branchConvergence).filter(Boolean),E=Zj(t),F=_.length>0&&_.every(q=>nk(q,n)),K=(E==null?void 0:E.length)===0&&F?ak(n,_):B.length>0?Qj(B):null,z=(E==null?void 0:E.length)===0&&F?0:B.filter(q=>q.needsConvergence).length,ne={id:u,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:uo(_.map(q=>q.health)),ahead:0,behind:0,dirty:_.some(q=>q.dirty),dirtyFiles:_.reduce((q,J)=>q+J.dirtyFiles,0),hasConflicts:_.some(q=>q.hasConflicts),activeSessionCount:_.reduce((q,J)=>q+J.activeSessionCount,0),activeSessions:_.flatMap(q=>q.activeSessions),sessionDetails:_.flatMap(q=>q.sessionDetails),providers:[...new Set(_.flatMap(q=>q.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:z>0?`${z} workspace(s) on ${n} still need follow-up`:_.length>0?`${_.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:K,source:{nodeId:u,machineLabel:n,workspace:t.repoIdentity,health:uo(_.map(q=>q.health)),providers:[],activeSessions:[],activeSessionDetails:[]}};i.push(ne);for(const q of i)if(!(q.id===u||q.type==="submoduleNode")){if(q.branch===n){c.push({id:`${u}--${q.id}`,source:u,target:q.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(q.branch){c.push({id:`${u}--${q.id}`,source:u,target:q.id,type:q.isOrphan?"orphanLink":"parentBranch",label:q.branch,direction:"undirected"});continue}q.isOrphan&&c.push({id:`${u}--${q.id}`,source:u,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 _=`clone_${M.clonedFromNodeId}--${M.id}`;if(b.has(_))continue;b.add(_);const B=M.worktreeBranch??M.branch??void 0;c.push({id:_,source:M.clonedFromNodeId,target:M.id,type:"cloneLink",label:B?`cloned · ${B}`:"cloned",direction:"directed"})}const y=i.find(M=>M.type!=="submoduleNode"&&M.connectionState==="self");if(y)for(const M of i)M.id!==y.id&&(M.type==="submoduleNode"||M.type==="defaultBranchNode"||!M.connectionReported&&M.connectionTransport===null||M.connectionState!=="self"&&c.push({id:`coord_${y.id}--${M.id}`,source:y.id,target:M.id,type:"coordinatorLink",direction:"directed"}));const f=i.filter(M=>M.type!=="defaultBranchNode"),w=f.filter(M=>M.isOrphan).length,j=f.filter(M=>M.hasConflicts).length,g=f.filter(M=>M.health==="offline").length,v=f.filter(M=>M.type==="submoduleNode"&&M.outOfSync).length,k=f.filter(M=>{var _;return M.type!=="submoduleNode"&&((_=M.branchConvergence)==null?void 0:_.needsConvergence)}).length,N=f.filter(M=>{var _;return((_=M.branchConvergence)==null?void 0:_.status)==="blocked_review"}).length,x=f.filter(M=>{var _;return((_=M.branchConvergence)==null?void 0:_.status)==="pushed_feature_branch_needs_merge"}).length,C=f.filter(M=>{var _;return((_=M.branchConvergence)==null?void 0:_.status)==="cleanup_candidate"}).length,S=f.filter(M=>{var _;return((_=M.branchConvergence)==null?void 0:_.status)==="not_mergeable"}).length,I=f.filter(M=>M.snapshotWarnings.length>0).length,P=f.filter(M=>M.snapshotCompleteness==="pending_git").length,L=f.filter(M=>M.snapshotCompleteness==="missing_git").length,A=f.filter(M=>M.snapshotCompleteness==="missing_submodule_report").length,R=f.filter(M=>M.snapshotCompleteness==="stale").length,$=f.filter(M=>M.refineJobStatus==="running"||M.refineJobStatus==="accepted").length,X=f.filter(M=>M.refineJobStatus==="failed").length,T=[P>0?`${P} node(s) are still waiting for a live peer git snapshot`:null,L>0?`${L} node(s) have no visible peer git snapshot`:null,A>0?`${A} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,R>0?`${R} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return k>0&&d.push(`${k} workspace(s) still need follow-up before the mesh is converged`),w>0&&d.push(`${w} workspace(s) need attention before safe coordination`),N>0&&d.push(`${N} workspace(s) are blocked on branch convergence or upstream sync`),x>0&&d.push(`${x} clean feature branch workspace(s) still need merge follow-up`),C>0&&d.push(`${C} worktree workspace(s) are ready for refine / cleanup`),S>0&&d.push(`${S} workspace(s) have local changes or conflicts blocking convergence`),j>0&&d.push(`${j} workspace(s) report merge conflicts`),g>0&&d.push(`${g} node(s) are currently offline`),v>0&&d.push(`${v} submodule(s) are out of sync with their parent checkout`),d.push(...T),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:f.length,onlineNodes:f.filter(M=>M.health==="online").length,dirtyNodes:f.filter(M=>M.dirty).length,orphanNodes:w,errorNodes:f.filter(M=>!!M.error||M.outOfSync).length,offlineNodes:g,followUpNodes:k,blockedReviewNodes:N,mergeReadyNodes:x,cleanupCandidateNodes:C,notMergeableNodes:S,incompleteSnapshotNodes:I,pendingGitSnapshotNodes:P,missingGitSnapshotNodes:L,missingSubmoduleSnapshotNodes:A,staleGitSnapshotNodes:R,activeRefineNodes:$,failedRefineNodes:X,totalActiveSessions:f.reduce((M,_)=>M+_.activeSessionCount,0)},warnings:d,snapshotWarnings:T}}function dk(e){return!e.nodes.some(t=>t.snapshotCompleteness==="pending_git"||t.snapshotCompleteness==="missing_git"||t.snapshotCompleteness==="missing_submodule_report")}const uk=5,pk={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 Jp(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 Xp(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 mk(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 Qp(e){switch(e){case"active":return"emerald";case"paused":return"amber";case"completed":return"sky";case"abandoned":return"rose";default:return"muted"}}function hk(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 Zp(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 Hc(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 zc(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 Gi(e){return e.replace(/[_-]+/g," ")}function em(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 tm(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 fk({status:e}){var w,j,g,v;const{theme:t}=$s(),r=l.useMemo(()=>Es(t),[t]),n=l.useMemo(()=>gi(e),[e]),a=((w=n.queue)==null?void 0:w.summary)??null,o=((j=n.queue)==null?void 0:j.tasks)??[],i=((g=n.ledger)==null?void 0:g.summary)??pk,c=((v=n.ledger)==null?void 0:v.entries)??[],d=n.missions??[],p=d.filter(k=>k.status==="active"||k.status==="paused"),m=d.filter(k=>k.status==="completed"||k.status==="abandoned"),u=n.asyncRefineJobs??[],[h,b]=l.useState(null),y=l.useCallback(()=>b(null),[]),f=l.useMemo(()=>{const k=[];for(const N of n.nodes){const x=N.activeSessionDetails&&N.activeSessionDetails.length>0?N.activeSessionDetails:(N.activeSessions??[]).map(C=>({sessionId:C,workspace:N.workspace,isCached:!0}));for(const C of x)k.push({node:N,session:C})}return k},[n.nodes]);return s.jsxs("div",{className:"flex flex-col gap-3 pb-2",children:[s.jsx(jk,{meshTheme:r,liveMissions:p,historyMissions:m,hasMissionField:Array.isArray(n.missions),onSelect:k=>b({kind:"mission",mission:k})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(kk,{meshTheme:r,ledgerSummary:i,entries:c,onSelect:k=>b({kind:"ledger",entry:k})}),s.jsx(Nk,{meshTheme:r,queueSummary:a,tasks:o,onSelect:k=>b({kind:"queue",task:k})})]}),s.jsx(Ck,{meshTheme:r,nodes:n.nodes}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(Ik,{meshTheme:r,entries:f,onSelect:(k,N)=>b({kind:"session",node:k,session:N})}),s.jsx(Mk,{meshTheme:r,jobs:u})]}),h&&s.jsx(bk,{meshTheme:r,detail:h,onClose:y})]})}function Rs({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 Pt({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 Zr({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=uk){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 xk(e){switch(e.kind){case"mission":return{kicker:"Mission",title:e.mission.title};case"ledger":return{kicker:"Ledger entry",title:Gi(e.entry.kind)};case"queue":return{kicker:"Queue task",title:e.task.id};case"session":return{kicker:"Session",title:Na(e.session.sessionId)}}}function bk({meshTheme:e,detail:t,onClose:r}){l.useEffect(()=>{const d=p=>{p.key==="Escape"&&r()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[r]);const n=e.isDark,{kicker:a,title:o}=xk(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(gk,{meshTheme:e,mission:t.mission}),t.kind==="ledger"&&s.jsx(yk,{meshTheme:e,entry:t.entry}),t.kind==="queue"&&s.jsx(vk,{meshTheme:e,task:t.task}),t.kind==="session"&&s.jsx(wk,{meshTheme:e,node:t.node,session:t.session})]})]})})}function gk({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(Pt,{meshTheme:e,label:t.status,tone:Qp(t.status)}),s.jsx(Pt,{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:zc(o.wallClockMs)??"—"}),s.jsx(gt,{meshTheme:e,label:"Total runtime",value:zc(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 yk({meshTheme:e,entry:t}){const r=tm(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(Pt,{meshTheme:e,label:Gi(t.kind),tone:em(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 vk({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(Pt,{meshTheme:e,label:t.status,tone:Zp(t.status)}),(t.requeueCount??0)>0&&s.jsx(Pt,{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 wk({meshTheme:e,node:t,session:r}){var a,o;const n=Jp(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(Pt,{meshTheme:e,label:n,tone:Xp(n)}),s.jsx(Pt,{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 Wc({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(Pt,{meshTheme:e,label:t.status,tone:Qp(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 jk({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(Rs,{meshTheme:e,title:"Missions",count:t.length||void 0,children:[t.length>0?s.jsxs("div",{className:"flex flex-col gap-0.5",children:[d.visible.map(p=>s.jsx(Wc,{meshTheme:e,mission:p,onSelect:()=>a(p)},p.id)),s.jsx(Ca,{meshTheme:e,expanded:d.expanded,hiddenCount:d.hiddenCount,onToggle:d.toggle})]}):s.jsx(Zr,{meshTheme:e,children:n?"No active missions. The coordinator creates a mission for multi-task work.":"Mission data unavailable from this daemon — update the daemon to see missions."}),r.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${c?"border-white/8":"border-slate-200"}`,children:[s.jsxs("button",{type:"button",onClick:()=>i(p=>!p),className:`flex w-full items-center gap-1.5 text-[11px] font-medium ${e.textSecondary}`,children:[s.jsx("span",{className:`inline-block transition-transform ${o?"rotate-90":""}`,children:"▸"}),s.jsx("span",{children:"Completed / abandoned history"}),s.jsx("span",{className:`tabular-nums ${e.textMuted}`,children:r.length})]}),o&&s.jsx("div",{className:"mt-2 flex flex-col gap-0.5",children:r.map(p=>s.jsx(Wc,{meshTheme:e,mission:p,onSelect:()=>a(p)},p.id))})]})]})}function kk({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(Rs,{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=tm(c.payload);return s.jsxs(Sa,{meshTheme:e,onClick:()=>n(c),children:[s.jsx(Pt,{meshTheme:e,label:Gi(c.kind),tone:em(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 Nk({meshTheme:e,queueSummary:t,tasks:r,onSelect:n}){const a=l.useMemo(()=>[...r].sort((i,c)=>{const d=Hc(i.status)-Hc(c.status);return d!==0?d:(c.updatedAt||"").localeCompare(i.updatedAt||"")}),[r]),o=Ia(a);return t?s.jsxs(Rs,{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(Pt,{meshTheme:e,label:i.status,tone:Zp(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(Rs,{meshTheme:e,title:"Queue",children:s.jsx(Zr,{meshTheme:e,children:"No queue activity."})})}function Sk(e){return e.autoFastForwardEligible||e.suggestedAction==="auto_fast_forward"?{label:"fast-forward",tone:"sky"}:e.launchBlockedReason?{label:"blocked",tone:"rose"}:null}function Ck({meshTheme:e,nodes:t}){const r=e.isDark;return s.jsx(Rs,{meshTheme:e,title:"Nodes",count:t.length,children:t.length===0?s.jsx(Zr,{meshTheme:e,children:"No nodes in this mesh yet."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:t.map(n=>{var c,d,p;const a=(((c=n.activeSessionDetails)==null?void 0:c.length)??0)||(((d=n.activeSessions)==null?void 0:d.length)??0),o=Sk(n),i=((p=n.git)==null?void 0:p.branch)??n.worktreeBranch??null;return s.jsxs("div",{className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 overflow-hidden rounded-xl border px-3 py-2 ${r?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx(Pt,{meshTheme:e,label:n.health,tone:hk(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:mk(n)}),a>0&&s.jsxs("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:[a," session",a>1?"s":""]}),o&&s.jsx(Pt,{meshTheme:e,label:o.label,tone:o.tone})]},n.nodeId)})})})}function Ik({meshTheme:e,entries:t,onSelect:r}){const n=Ia(t);return s.jsx(Rs,{meshTheme:e,title:"Active sessions",count:t.length||void 0,children:t.length===0?s.jsx(Zr,{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=Jp(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(Pt,{meshTheme:e,label:i,tone:Xp(i)})]},o.sessionId)}),s.jsx(Ca,{meshTheme:e,expanded:n.expanded,hiddenCount:n.hiddenCount,onToggle:n.toggle})]})})}function Mk({meshTheme:e,jobs:t}){const r=e.isDark,n=t.filter(a=>a.status==="failed").length;return s.jsx(Rs,{meshTheme:e,title:"Refine jobs",count:t.length||void 0,action:n>0?s.jsx(Pt,{meshTheme:e,label:`${n} failed`,tone:"rose"}):void 0,children:t.length===0?s.jsx(Zr,{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 Ak=[{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 (green) — a direct host/STUN path; lowest latency.","relay (amber, dashed link) — TURN-relayed; works through restrictive networks but is slower.","disconnected / failed (red) — no live P2P link from the coordinator right now.","The coordinator→node link edge and the node chip both carry the transport (and RTT when measured)."]},{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 Tk({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(Oh,{size:15})})}function _k({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:Ak.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 sm({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(Tk,{meshTheme:e,open:n,onToggle:()=>a(!n)})]})}const Rk={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0},Vi=l.createContext(Es("dark"));function et({label:e,tone:t="default"}){const r=l.useContext(Vi);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(Vi);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 Lk(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 po(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 Pk(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function Dk(e){return e.startedAt||e.createdAt||null}function $k(e){const t=Dk(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 rm(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function Ek(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 Bk(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 Fk(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 Ok(e){return e.assignedNodeId||e.targetNodeId||null}function Kc(e){return e?e.slice(0,7):null}function Hk(e,t){var o,i,c;const r=Kc((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?[Kc(a.commit),a.message].filter(Boolean).join(" · "):null}function zk(e,t){const r=Hk(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function Wk(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 Kk(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 Uk(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":Bk(e.connection)}function Gk(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 Uc(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 Vk(e){return e.direction==="directed"?"directed":"undirected"}function qk(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function Yk(e){var t,r,n,a;return[e.meshId,e.refreshedAt,e.nodes.length,((r=(t=e.queue)==null?void 0:t.summary)==null?void 0:r.active)??"",((a=(n=e.ledger)==null?void 0:n.summary)==null?void 0:a.recentFailures)??"",...e.nodes.map(o=>{var i,c,d,p,m,u,h,b,y,f,w,j,g,v,k,N,x,C,S,I,P,L;return[o.nodeId,o.daemonId??"",o.machineId??"",o.machineLabel,o.machineStatus??"",((i=o.connection)==null?void 0:i.state)??"",((c=o.connection)==null?void 0:c.transport)??"",((d=o.connection)==null?void 0:d.source)??"",o.health,o.gitProbePending?1:0,((p=o.git)==null?void 0:p.branch)??"",((m=o.git)==null?void 0:m.upstream)??"",((u=o.git)==null?void 0:u.upstreamStatus)??"",((h=o.git)==null?void 0:h.ahead)??"",((b=o.git)==null?void 0:b.behind)??"",((y=o.git)==null?void 0:y.headCommit)??"",((f=o.git)==null?void 0:f.staged)??"",((w=o.git)==null?void 0:w.modified)??"",((j=o.git)==null?void 0:j.untracked)??"",((g=o.git)==null?void 0:g.deleted)??"",((v=o.git)==null?void 0:v.renamed)??"",(k=o.git)!=null&&k.hasConflicts?1:0,((N=o.git)==null?void 0:N.lastCheckedAt)??"",((x=o.activeSessions)==null?void 0:x.join(","))??"",((C=o.activeSessionDetails)==null?void 0:C.length)??"",((S=o.activeSessionDetails)==null?void 0:S.map(A=>[A.sessionId,A.providerType??"",A.state??"",A.chatStatus??"",A.lifecycle??"",A.role??"",A.isSelfCoordinator?1:0,A.statusNote??"",A.startedAt??"",A.createdAt??""].join("/")).join(","))??"",((I=o.providers)==null?void 0:I.join(","))??"",((P=o.providerPriority)==null?void 0:P.join(","))??"",o.error??"",(((L=o.git)==null?void 0:L.submodules)??[]).map(A=>[A.path,A.commit,A.dirty?1:0,A.outOfSync?1:0,A.error??""].join("/")).join(",")].join("|")})].join("::")}function Jk({canonicalStatus:e,queueSummary:t,ledgerSummary:r,isBootstrapMode:n,meshTheme:a,sessionEntries:o,inlineMode:i=!1}){var N;const c=t&&(t.active>0||t.historical>0),d=r.recentFailures>0||r.taskFailed>0,p=(N=e.queue)!=null&&N.tasks?e.queue.tasks.filter(x=>x.status==="failed"||x.status==="cancelled").slice(0,5):[],m=e.asyncRefineJobs,u=(m==null?void 0:m.filter(x=>x.status==="running"||x.status==="accepted"))??[],h=(m==null?void 0:m.filter(x=>x.status==="failed"))??[],b=e.staleDirectWorkSummary,y=b&&b.count>0;if(!c&&!d&&e.nodes.length===0&&!n&&u.length===0&&h.length===0&&!y&&o.length===0)return null;const f=a.isDark,w=`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"}`,g=`flex cursor-pointer list-none items-center gap-1.5 px-2.5 py-1.5 [&::-webkit-details-marker]:hidden ${a.textSecondary}`;function v({label:x,value:C,tone:S}){const I=S==="rose"?f?"text-rose-300":"text-rose-600":S==="sky"?f?"text-sky-300":"text-sky-600":S==="amber"?f?"text-amber-300":"text-amber-600":S==="emerald"?f?"text-emerald-300":"text-emerald-600":S==="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:C}),s.jsx("span",{className:`mt-0.5 text-[9px] uppercase tracking-wide ${a.textMuted}`,children:x})]})}const k=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(v,{label:"Pending",value:t.pending}),s.jsx(v,{label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(v,{label:"Done",value:t.completed,tone:"emerald"}),s.jsx(v,{label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0})]}):s.jsxs(s.Fragment,{children:[s.jsx(v,{label:"Done",value:r.taskCompleted,tone:"emerald"}),s.jsx(v,{label:"Failed",value:r.taskFailed,tone:r.taskFailed>0?"rose":void 0}),s.jsx(v,{label:"Sessions",value:r.sessionLaunched}),s.jsx(v,{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(v,{label:"Ledger done",value:r.taskCompleted,tone:"emerald"}),s.jsx(v,{label:"Sessions",value:r.sessionLaunched}),s.jsx(v,{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 ${w}`,children:s.jsx("div",{className:"flex flex-col gap-1",children:e.nodes.map(x=>{var A;const C=((A=x.connection)==null?void 0:A.state)??"unknown",S=C==="unknown"||C==="connecting",L=S?"bg-amber-400":C==="failed"||C==="closed"||C==="disconnected"?f?"bg-rose-400":"bg-rose-500":C==="connected"||C==="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:S?"…":C})]},x.nodeId)})})}),m&&m.length>0&&s.jsx("div",{className:`pt-2.5 ${w}`,children:s.jsxs("details",{className:j,children:[s.jsxs("summary",{className:g,children:[s.jsx("span",{className:"flex-1",children:"Refine jobs"}),s.jsx("span",{className:`tabular-nums ${f?"text-slate-400":"text-slate-500"}`,children:m.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:m.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))})]})}),p.length>0&&s.jsx("div",{className:m&&m.length>0?"":`pt-2.5 ${w}`,children:s.jsxs("details",{className:j,children:[s.jsxs("summary",{className:g,children:[s.jsx("span",{className:`flex-1 ${f?"text-rose-300":"text-rose-600"}`,children:"Failed tasks"}),s.jsx("span",{className:`tabular-nums ${f?"text-rose-400":"text-rose-500"}`,children:p.length})]}),s.jsx("div",{className:"flex flex-col gap-1 px-2.5 pb-2",children:p.map(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))})]})}),y&&s.jsxs("div",{className:`flex items-center justify-between pt-2.5 ${w}`,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 ${w}`,children:s.jsxs("details",{className:j,children:[s.jsxs("summary",{className:g,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:rm(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?k: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"}),u.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:[u.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"})]}),k]})}function Xk(e){return e.nodes.length===0?!1:e.nodes.every(t=>t.health==="unknown"&&(!t.connection||t.connection.state==="unknown"))}function nm({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null,bootstrapFallback:a,activeTab:o,onActiveTabChange:i,helpOpen:c,onHelpOpenChange:d,hideControls:p=!1}){var _e,Ce,Ke,Ze;const{theme:m}=$s(),u=l.useMemo(()=>Es(m),[m]),h=a??Xk(e),b=l.useMemo(()=>gi(e),[e]),y=l.useMemo(()=>Yk(b),[b]),f=l.useMemo(()=>Yp(b),[y]),[w,j]=l.useState("overview"),[g,v]=l.useState(!1),k=o??w,N=c??g,x=l.useCallback(me=>{i?i(me):j(me)},[i]),C=l.useCallback(me=>{d?d(me):v(me)},[d]),[S,I]=l.useState(!1);l.useEffect(()=>{k==="graph"&&I(!0)},[k]);const[P,L]=l.useState(null),[A,R]=l.useState(null),[$,X]=l.useState(null),[T,M]=l.useState({}),[_,B]=l.useState(null),[E,F]=l.useState(null),K=l.useMemo(()=>new Map(b.nodes.map(me=>[me.nodeId,me])),[b.nodes]),z=l.useMemo(()=>new Map(f.nodes.map(me=>[me.id,me])),[f.nodes]),ne=((_e=b.queue)==null?void 0:_e.summary)??null,q=((Ce=b.ledger)==null?void 0:Ce.summary)??Rk,J=l.useMemo(()=>Fk(b),[b]),xe=l.useMemo(()=>{const me=new Map;for(const De of J){const $e=Wn(De.session);me.set($e,(me.get($e)??0)+1)}return[...me.entries()].sort((De,$e)=>$e[1]-De[1])},[J]);l.useEffect(()=>{P&&(z.has(P)||(L(null),X(me=>!me||"nodeId"in me&&me.nodeId===P?null:me)))},[z,P]);const ue=P?K.get(P)??null:null,O=qk(f,P),H=($==null?void 0:$.kind)==="edge"&&A?f.edges.find(me=>me.id===A)??null:null,ve=H?f.nodes.find(me=>me.id===H.source)??null:null,we=H?f.nodes.find(me=>me.id===H.target)??null:null;l.useEffect(()=>{var me,De,$e;if(P)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:b.meshId,selectedNodeId:P,canonicalNode:ob(ue),graphNode:O?{id:O.id,branch:O.branch,upstream:O.upstream,headCommit:O.submoduleCommit,submoduleCount:((De=(me=ue==null?void 0:ue.git)==null?void 0:me.submodules)==null?void 0:De.length)??0,snapshotCompleteness:O.snapshotCompleteness,snapshotWarnings:O.snapshotWarnings,branchConvergence:(($e=O.branchConvergence)==null?void 0:$e.status)??null}:null})}catch{}},[b.meshId,O,P,ue]);const be=($==null?void 0:$.kind)==="session"?J.find(me=>me.nodeId===$.nodeId&&me.session.sessionId===$.sessionId)??null:null,Ne=l.useMemo(()=>J.filter(me=>me.nodeId===P),[P,J]),re=Kk({coordinatorDaemonId:r,selectedNodeStatus:ue,selectedSessionEntry:be}),je=(re==null?void 0:re.workspace)??null,ce=je?T[je]??null:null,U=zk(ue,(ce==null?void 0:ce.entries)??[]),W=(O==null?void 0:O.daemonId)??(ue==null?void 0:ue.daemonId)??r??null,Y=!!(O&&n&&W&&O.type!=="submoduleNode"&&O.behind>0&&O.ahead===0&&O.dirtyFiles===0&&!O.dirty&&!O.hasConflicts&&O.upstreamStatus==="fresh"),se=l.useCallback(()=>{L(null),R(null),X(null),B(null)},[]);l.useEffect(()=>{B(null)},[P]);const ie=l.useCallback(async()=>{if(!O||!W||!n||!Y)return;F(O.id),B(null);const me=(ue==null?void 0:ue.workspace)??O.workspace??"";try{const De=await n(W,"fast_forward_mesh_node",{meshId:b.meshId,nodeId:O.id,workspace:me,updateSubmodules:!0,dryRun:!0,execute:!1}),$e=(De==null?void 0:De.result)??De;if(B({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 ${O.label}?`))return;const Ue=await n(W,"fast_forward_mesh_node",{meshId:b.meshId,nodeId:O.id,workspace:me,updateSubmodules:!0,dryRun:!1,execute:!0}),Ve=(Ue==null?void 0:Ue.result)??Ue;B({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){B({phase:"dry_run",error:De instanceof Error?De.message:"fast-forward failed"})}finally{F(null)}},[Y,b.meshId,O,W,n]);l.useEffect(()=>{if(!O&&!H)return;const me=De=>{De.key==="Escape"&&se()};return window.addEventListener("keydown",me),()=>window.removeEventListener("keydown",me)},[se,H,O]),l.useEffect(()=>{if(!re||!n)return;const{daemonId:me,workspace:De}=re,$e=T[De];if($e!=null&&$e.loading||$e&&($e.entries.length>0||$e.error))return;let tt=!1;return M(Ue=>{var Ve;return{...Ue,[De]:{loading:!0,error:null,entries:((Ve=Ue[De])==null?void 0:Ve.entries)??[]}}}),n(me,"git_log",{workspace:De,limit:5}).then(Ue=>{tt||M(Ve=>({...Ve,[De]:{loading:!1,error:null,entries:Wk(Ue)}}))}).catch(Ue=>{tt||M(Ve=>({...Ve,[De]:{loading:!1,error:Ue instanceof Error?Ue.message:"git_log failed",entries:[]}}))}),()=>{tt=!0}},[T,re,n]);const ae=[...f.warnings??[],...b.nodes.filter(me=>me.machineStatus&&me.machineStatus!=="online").map(me=>`${me.machineLabel}: ${me.machineStatus}`)],D=f.stats.incompleteSnapshotNodes>0,oe=f.stats.followUpNodes>0?`${f.stats.followUpNodes} need follow-up`:D?"mesh visibility incomplete":"mesh converged",ge=f.stats.followUpNodes>0?"danger":D?"warn":"good",[pe,te]=l.useState("LR"),Me=me=>me?u.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":u.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(Vi.Provider,{value:u,children:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[!p&&s.jsx("div",{className:"shrink-0 flex items-center justify-end",children:s.jsx(sm,{meshTheme:u,activeTab:k,onActiveTabChange:x,helpOpen:N,onHelpOpenChange:C})}),N&&s.jsx(_k,{meshTheme:u,onClose:()=>C(!1)}),s.jsx("div",{className:`${k==="overview"?"flex":"hidden"} min-h-0 flex-1 flex-col overflow-y-auto`,children:k==="overview"&&s.jsx(fk,{status:e})}),s.jsx("div",{className:`${k==="graph"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-4`,children:s.jsxs("div",{className:`${u.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 ${u.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-wrap gap-2 text-xs ${u.textSecondary}`,children:[s.jsx(et,{label:oe,tone:ge}),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"}),((ne==null?void 0:ne.active)??0)>0&&s.jsx(et,{label:`${(ne==null?void 0:ne.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:u.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(pe==="auto"),title:"Auto-detect direction",children:"Auto"}),s.jsx("button",{type:"button",onClick:()=>te("LR"),className:Me(pe==="LR"),title:"Left to right",children:"LR"}),s.jsx("button",{type:"button",onClick:()=>te("TB"),className:Me(pe==="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 ${u.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 ${u.textSecondary} [&::-webkit-details-marker]:hidden`,children:(()=>{var $e;const me=(($e=b.asyncRefineJobs)==null?void 0:$e.filter(tt=>tt.status==="failed").length)??0,De=q.recentFailures;return me>0?s.jsxs("span",{className:u.isDark?"text-rose-300":"text-rose-600",children:[me," refine failed"]}):De>0?s.jsxs("span",{className:u.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 ${u.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsx(Jk,{canonicalStatus:b,queueSummary:ne,ledgerSummary:q,isBootstrapMode:h,meshTheme:u,sessionEntries:J,inlineMode:!0})})]})}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${u.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 ${u.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 ${u.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:`${q.recentFailures} recent failures`,tone:q.recentFailures>0?"danger":"good"}),xe.length===0?s.jsx(et,{label:"no session metadata"}):xe.slice(0,2).map(([me,De])=>s.jsx(et,{label:`${De} ${me}`,tone:po(me)},me))]}),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"})]}),ae.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:ae.map(me=>s.jsx("span",{className:u.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:me},me))}),s.jsx("div",{className:`text-xs ${u.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 ${u.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 ${u.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:S?f.nodes.length>0?s.jsx(zj,{data:f,selectedNodeId:P,directionPref:pe,onNodeClick:me=>{if(($==null?void 0:$.kind)==="node"&&P===me.id){se();return}R(null),L(me.id),X({kind:"node",nodeId:me.id})},onEdgeClick:me=>{if(($==null?void 0:$.kind)==="edge"&&A===me.id){se();return}L(null),R(me.id),X({kind:"edge",edgeId:me.id})}}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:t}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:"Loading graph…"})}),O&&($==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 ${u.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 ${u.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 ${u.textPrimary}`,children:O.label}),s.jsx("div",{className:`mt-0.5 font-mono text-[11px] ${u.textMuted}`,children:O.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[O.behind>0&&s.jsx("button",{type:"button",onClick:()=>{ie()},disabled:!Y||E===O.id,className:u.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:E===O.id?"Checking":"Heal"}),s.jsx("button",{type:"button",onClick:se,"aria-label":"Close detail panel",className:u.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 me=(ue==null?void 0:ue.health)??O.health;return me==="unknown"?s.jsx(et,{label:"connecting...",tone:"default"}):s.jsx(et,{label:me,tone:Lk(me)})})(),O.branch&&s.jsx(et,{label:O.branch,tone:"default"}),O.ahead>0&&s.jsx(et,{label:`ahead ${O.ahead}`,tone:"warn"}),O.behind>0&&s.jsx(et,{label:`behind ${O.behind}`,tone:"warn"}),O.dirtyFiles>0&&s.jsx(et,{label:`${O.dirtyFiles} dirty`,tone:"warn"}),(ue==null?void 0:ue.connection)&&ue.connection.state!=="unknown"&&s.jsx(et,{label:Uk(ue),tone:Ek(ue.connection)}),((Ke=ue==null?void 0:ue.connection)==null?void 0:Ke.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:[O.machineLabel&&s.jsx(Nt,{label:"Machine",value:O.machineLabel}),O.locality&&O.locality!=="unknown"&&s.jsx(Nt,{label:"Locality",value:O.locality}),s.jsx(Nt,{label:"Workspace",value:(ue==null?void 0:ue.workspace)??O.workspace}),U&&s.jsx(Nt,{label:"HEAD",value:U}),(O.dirtyFiles>0||O.ahead>0||O.behind>0)&&s.jsx(Nt,{label:"Dirty/ahead/behind",value:`${O.dirtyFiles}/${O.ahead}/${O.behind}`}),Ne.length>0&&s.jsx(Nt,{label:"Sessions",value:String(Ne.length)}),O.upstream&&s.jsx(Nt,{label:"Upstream",value:O.upstream}),(()=>{var De;const me=((De=ue==null?void 0:ue.connection)==null?void 0:De.source)??Gk(O);return me&&me!=="unknown"?s.jsx(Nt,{label:"Source",value:String(me)}):null})(),(()=>{var De;const me=(De=ue==null?void 0:ue.connection)==null?void 0:De.transport;return me&&me!=="unknown"?s.jsx(Nt,{label:"Transport",value:me}):null})(),(()=>{const me=O.machineId??(ue==null?void 0:ue.machineId);return me?s.jsx(Nt,{label:"Machine id",value:me}):null})(),(()=>{const me=O.daemonId??(ue==null?void 0:ue.daemonId);return me?s.jsx(Nt,{label:"Daemon id",value:me}):null})()]}),Ne.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${u.textMuted}`,children:"Active Sessions"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:Ne.map(me=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${u.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 ${u.textMuted}`,title:me.session.sessionId,children:rm(me.session.sessionId)}),s.jsx(et,{label:Wn(me.session),tone:po(Wn(me.session))})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 ${u.textMuted}`,children:[s.jsx("span",{className:"truncate",children:me.session.providerType||"provider unknown"}),s.jsx("span",{children:Pk(me.session)}),s.jsx("span",{children:$k(me.session)})]}),me.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${u.textMuted}`,children:me.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${u.textMuted}`,title:me.session.workspace||me.workspace,children:[(me.session.workspace||me.workspace).slice(0,38),me.branch?` · ${me.branch}`:""]})]},me.session.sessionId))})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${u.textMuted}`,children:"Ledger (mesh-wide)"}),s.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[s.jsx(Nt,{label:"Completed",value:String(q.taskCompleted)}),s.jsx(Nt,{label:"Failed",value:s.jsx("span",{className:q.taskFailed>0?u.isDark?"text-rose-300":"text-rose-600":"",children:q.taskFailed})}),s.jsx(Nt,{label:"Launched",value:String(q.sessionLaunched)}),s.jsx(Nt,{label:"Recent failures",value:s.jsx("span",{className:q.recentFailures>0?u.isDark?"text-amber-300":"text-amber-600":"",children:q.recentFailures})})]})]}),(()=>{var $e,tt;const me=(($e=b.queue)==null?void 0:$e.tasks)??((tt=b.queue)==null?void 0:tt.items)??null;if(!Array.isArray(me)||me.length===0)return null;const De=me.filter(Ue=>Ok(Ue)===P).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 ${u.textMuted}`,children:"Queue tasks"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:De.map(Ue=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${u.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 ${u.textMuted}`,children:Ue.id.slice(0,12)}),s.jsx(et,{label:Ue.status??"unknown",tone:po(Ue.status)})]}),Ue.message&&s.jsx("div",{className:`mt-0.5 truncate ${u.textMuted}`,children:Ue.message.slice(0,48)})]},Ue.id))})]})})(),O.snapshotWarnings.length>0&&s.jsxs("div",{className:u.isDark?"mt-3 rounded-xl border border-amber-400/20 bg-amber-500/10 p-3 text-xs text-amber-100":"mt-3 rounded-xl border border-amber-300 bg-amber-50 p-3 text-xs text-amber-800",children:[s.jsx("div",{className:"font-medium",children:"Key warning"}),s.jsx("div",{className:"mt-1",children:O.snapshotWarnings[0]})]}),((Ze=O.branchConvergence)==null?void 0:Ze.nextStep)&&s.jsxs("div",{className:u.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:O.branchConvergence.nextStep})]}),_&&s.jsxs("div",{className:u.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:_.phase==="execute"?"Heal result":"Heal preview"}),s.jsx("div",{className:"mt-1",children:_.code??_.error??"No result code returned."})]})]}),H&&($==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 ${u.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 ${u.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 ${u.textPrimary}`,children:H.label||Uc(H)}),s.jsx("div",{className:`mt-0.5 break-all font-mono text-[11px] ${u.textMuted}`,children:H.id})]}),s.jsx("button",{type:"button",onClick:se,"aria-label":"Close detail panel",className:u.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:Uc(H),tone:"default"}),s.jsx(et,{label:Vk(H),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)??H.source}),s.jsx(Nt,{label:"To",value:(we==null?void 0:we.label)??H.target}),s.jsx(Nt,{label:"Label",value:H.label??"none"})]})]})]})]})})]})})}function yt(e){return typeof e=="string"?e.trim():""}function Xo(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function qi(...e){const t=new Set;for(const r of e){const n=yt(r);n&&t.add(n)}return[...t]}function Qk(e,t){var u,h;const r=Xo(e==null?void 0:e.settings),n=yt((u=e==null?void 0:e.coordinator)==null?void 0:u.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=qi(e==null?void 0:e.id,e==null?void 0:e.sessionId,e==null?void 0:e.session_id,e==null?void 0:e.providerSessionId,e==null?void 0:e.provider_session_id,e==null?void 0:e.targetSessionId,e==null?void 0:e.target_session_id,c.sessionId,c.session_id,c.providerSessionId,c.provider_session_id),p=d[0]||"";if(!p)return null;const m=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:p,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,...m?{role:m}:{},...i?{isSelfCoordinator:n===t}:{},workspace:yt(e==null?void 0:e.workspace)||null}}function am(e,t){var n;return t?(Array.isArray((n=e.status)==null?void 0:n.sessions)?e.status.sessions:[]).map(a=>Qk(a,t)).filter(a=>a!==null):[]}function da(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function Zk(e,t){const r=new Set(da(t));return da(e).some(n=>r.has(n))}function e1(e,t){const r=t.filter(a=>!!a);return r.length===0?e:[...e.filter(a=>!r.some(o=>Zk(a,o))),...r]}function t1(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:[],p=new Map;for(const h of d){const b=qi(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),y=b[0]||"";if(!y)continue;const f=b.map(w=>r.get(w)).find(Boolean);f&&(n=!0),p.set(y,f?{...h,sessionId:y,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:y})}for(const h of i.activeSessions??[])p.has(h)||p.set(h,{sessionId:h,workspace:i.workspace,isCached:!0});const m=c===0;for(const h of t){if(da(h).some(w=>p.has(w)))continue;const y=h.nodeId!=null&&h.nodeId===i.nodeId,f=h.isSelfCoordinator&&!h.nodeId&&m;!y&&!f||(n=!0,p.set(h.sessionId,{sessionId:h.sessionId,providerType:h.providerType,state:h.state,chatStatus:h.chatStatus,lifecycle:h.lifecycle,surfaceKind:h.surfaceKind,recoveryState:h.recoveryState,role:h.role,isSelfCoordinator:h.isSelfCoordinator,workspace:h.workspace||i.workspace}))}const u=[...p.values()];return u.length===0?i:{...i,activeSessionDetails:u,activeSessions:u.map(h=>h.sessionId)}});return n?{...e,nodes:o}:e}function s1(e,t){const n=am(e,t).map(a=>{var d;const o=(Array.isArray((d=e.status)==null?void 0:d.sessions)?e.status.sessions:[]).find(p=>yt(p==null?void 0:p.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 om({status:e,daemonId:t,extraDaemonIds:r,meshId:n,sendData:a,extraLiveSessions:o=[]}){const[i,c]=l.useState(new Map),d=l.useRef(new Map),p=l.useMemo(()=>{const b=new Set;if(t&&b.add(t),r)for(const y of r)y&&b.add(y);return[...b].sort()},[t,r]),m=p.join(",");l.useEffect(()=>{d.current=new Map,c(new Map)},[t,n]),l.useEffect(()=>{if(!n||!a||p.length===0)return;const b=p.map(y=>ts.subscribe({sendData:a},y,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${y}`,params:{includeSessions:!0}},f=>{if(f.topic!=="daemon.metadata")return;const w=s1(f,n);if(w===(d.current.get(y)??null))return;d.current.set(y,w);const j=am(f,n);c(g=>{const v=new Map(g);return v.set(y,j),v})}));return()=>{for(const y of b)y()}},[m,n,a]);const u=l.useMemo(()=>{const b=[];for(const y of i.values())b.push(...y);return b},[i]),h=l.useMemo(()=>e1(u,o),[o,u]);return l.useMemo(()=>e?t1(e,h):null,[h,e])}const Gc=[1500,4e3,9e3];function r1(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 n1(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>{var r;return r1(t)?!1:t.gitProbePending||((r=t.connection)==null?void 0:r.state)==="connecting"?!0:t.machineStatus==="online"||t.launchReady===!0})}function a1(e){return!Number.isInteger(e)||e<0?Gc[0]:Gc[e]??null}const mo=new Map;function o1(e,t){return!e||!t?null:`${e}::${t}`}function i1(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:qi(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 l1({activeConv:e,sendDaemonCommand:t,onClose:r}){var z,ne,q,J,xe,ue;const n=((z=e.coordinator)==null?void 0:z.meshId)??(typeof((ne=e.settings)==null?void 0:ne.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),a=e.daemonId??null,o=o1(a,n),i=o?mo.get(o)??null:null,c=fi(),{sendData:d}=mt(),{theme:p}=$s(),m=l.useMemo(()=>Es(p),[p]),[u,h]=l.useState("overview"),[b,y]=l.useState(!1),f=l.useMemo(()=>i1(e,n),[e.agentType,(q=e.coordinator)==null?void 0:q.meshId,e.sessionId,(J=e.settings)==null?void 0:J.meshCoordinatorFor,(xe=e.settings)==null?void 0:xe.meshNodeFor,(ue=e.settings)==null?void 0:ue.meshNodeId,e.status,e.workspacePath,n]),[w,j]=l.useState(i),[g,v]=l.useState(!1),[k,N]=l.useState(!1),[x,C]=l.useState(null),[S,I]=l.useState((i==null?void 0:i.refreshedAt)??null),P=l.useRef(i!==null),L=l.useRef(!1),A=l.useRef(!1),R=l.useRef(!0),$=l.useRef(0),X=l.useRef(null);l.useEffect(()=>{P.current=w!==null},[w]);const T=l.useCallback(()=>{X.current!==null&&(clearTimeout(X.current),X.current=null)},[]);l.useEffect(()=>{T(),$.current=0;const O=o?mo.get(o)??null:null;j(O),I((O==null?void 0:O.refreshedAt)??null),P.current=O!==null,A.current=!1,N(!1),C(null)},[o,T]);const M=l.useCallback(async(O=!1,H=!1)=>{if(!a||!n){C("This coordinator does not expose a live mesh id."),j(null);return}if(L.current){O&&(A.current=!0);return}H||(T(),$.current=0),L.current=!0;const ve=!P.current;v(ve),N(O&&P.current),C(null);try{const we=c!=null&&c.loadMeshStatus?await c.loadMeshStatus(a,n,{refresh:O,retryProfile:H?"interactive":"settled"}):await t(a,"mesh_status",{meshId:n,refresh:O}),be=yi(we);if(!be){C("mesh_status returned an unexpected payload.");return}if(o&&mo.set(o,be),j(be),P.current=!0,I(be.refreshedAt||new Date().toISOString()),n1(be.nodes)){const Ne=a1($.current);Ne!==null&&R.current&&($.current+=1,X.current=setTimeout(()=>{R.current&&M(!0,!0)},Ne))}else $.current=0}catch(we){C(we instanceof Error?we.message:"Failed to load live mesh status")}finally{L.current=!1,v(!1),N(!1),A.current&&R.current&&(A.current=!1,window.setTimeout(()=>{R.current&&M(!0)},0))}},[o,T,a,n,c,t]);l.useEffect(()=>(R.current=!0,$.current=0,(async()=>(await M(!1,!0),R.current&&X.current===null&&!L.current&&M(!0,!0)))(),()=>{R.current=!1,T()}),[M,T]),l.useEffect(()=>{const O=H=>{H.key==="Escape"&&r()};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[r]);const _=(w==null?void 0:w.meshName)||n||"Repo Mesh",B=l.useMemo(()=>f?[f]:[],[f]),E=om({status:w,daemonId:a,meshId:n,sendData:d,extraLiveSessions:B}),F=S?new Date(S).toLocaleTimeString():null,K=l.useMemo(()=>g?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[g]);return s.jsx("div",{className:m.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:m.dialogShellClass,onClick:O=>O.stopPropagation(),children:[s.jsxs("div",{className:m.dialogHeaderClass,children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-400/20 bg-sky-500/12 text-sky-200 shadow-[0_12px_30px_rgba(14,165,233,0.18)]",children:s.jsx(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:m.dialogTitleClass,children:_}),s.jsx("span",{className:m.dialogKickerClass,children:"Mesh observability"})]}),s.jsxs("p",{className:m.dialogSubtitleClass,children:[pt(e),e.workspaceName?` · ${e.workspaceName}`:"",w!=null&&w.repoIdentity?` · ${w.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[s.jsx(sm,{meshTheme:m,activeTab:u,onActiveTabChange:h,helpOpen:b,onHelpOpenChange:y}),F&&s.jsx("span",{className:m.dialogRefreshedChipClass,children:k?"Refreshing mesh...":`Refreshed ${F}`}),!k&&w&&s.jsx("span",{className:m.dialogRefreshedChipClass,children:d&&!x?"Live daemon metadata":"Metadata subscription unavailable"}),s.jsx("button",{type:"button",onClick:()=>{M(!0)},disabled:g||k,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:g||k?"Refreshing…":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:m.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:s.jsx(vt,{size:16})})]})]}),x&&s.jsx("div",{className:m.isDark?"shrink-0 border-b border-rose-400/20 bg-rose-500/12 px-4 py-2 text-sm text-rose-200 md:px-5":"shrink-0 border-b border-rose-300 bg-rose-50 px-4 py-2 text-sm text-rose-700 md:px-5",children:x}),s.jsx("div",{className:m.dialogBodyClass,children:E?s.jsx(nm,{status:E,emptyMessage:K,daemonId:a,sendDaemonCommand:t,activeTab:u,onActiveTabChange:h,helpOpen:b,onHelpOpenChange:y,hideControls:!0}):s.jsx("div",{className:m.dialogEmptyClass,children:K})})]})})}function c1(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 p=(d==null?void 0:d.result)??d;a(typeof(p==null?void 0:p.remoteUrl)=="string"?p.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>i(!1))},[e,t,r]);const c=d1(n);return{remoteUrl:n,githubUrl:c,loading:o}}function d1(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 im=5e3;function u1(e){return`git:${e}`}function p1({workspace:e,includeDiffSummary:t=!1,intervalMs:r=im}){return{type:"subscribe",topic:"workspace.git",key:u1(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function Yi(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Ls(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 m1(e){const t=Yi(e);return(t==null?void 0:t.success)===!1?{status:null,error:Ls(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Ls(t,"Git status response did not include status")}}function h1(e){const t=Yi(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Ls(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Ls(t,"Git diff summary response did not include diffSummary")}}function ho(e){return e===void 0||typeof e=="boolean"}function f1(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&ho(t.binary)&&ho(t.truncated)&&ho(t.staged)}function x1(e){const t=Yi(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Ls(t,"Git file diff request failed")}:f1(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Ls(t,"Git file diff response did not include a valid diff object")}}function b1({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=im}){const{sendCommand:o,sendData:i}=mt(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[p,m]=l.useState(null),[u,h]=l.useState(null),[b,y]=l.useState(!1),[f,w]=l.useState(null),j=l.useCallback(async()=>{if(!(!d||!e||!c)){y(!0),w(null);try{const v=m1(await o(e,"git_status",{workspace:c}));if(v.error){m(null),h(null),w(v.error);return}if(m(v.status),!n){h(null);return}const k=h1(await o(e,"git_diff_summary",{workspace:c}));if(k.error){h(null),w(k.error);return}h(k.diffSummary)}catch(v){w(Ls(v,"Git status request failed"))}finally{y(!1)}}},[d,e,n,o,c]),g=l.useMemo(()=>c?p1({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return l.useEffect(()=>{if(!d||!e||!c||!g){m(null),h(null),y(!1),w(null);return}const v=i?ts.subscribe({sendData:i},e,g,k=>{var N,x;k.workspace===c&&(m(k.status),h(k.diffSummary??null),w(((N=k.status)==null?void 0:N.error)||((x=k.diffSummary)==null?void 0:x.error)||null),y(!1))},{retryIntervalMs:1e3}):null;return j(),()=>{v==null||v()}},[d,e,j,g,i,c]),{status:p,diffSummary:u,loading:b,error:f,refresh:j}}const g1={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},y1={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 Vc(e){return e.split("/").pop()??e}function v1(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function w1({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=g1[o.status]??"?",d=y1[o.status]??"text-zinc-400",p=v1(o.path),m=Vc(o.path),u=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:[p&&s.jsxs("span",{className:"text-text-secondary",children:[p,"/"]}),s.jsx("span",{className:"text-text-primary",children:m}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",Vc(o.oldPath)]}),u]}),!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 j1(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 lm({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,p)=>j1(d,p))}),r&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary border-t border-border/30",children:["Diff truncated — run ",s.jsx("code",{className:"font-mono",children:"git diff"})," locally for full output."]})]})}function k1(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 cm({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=mt(),{status:a,diffSummary:o,loading:i,error:c,refresh:d}=b1({daemonId:e,workspace:t,includeDiffSummary:!0}),[p,m]=l.useState(null),[u,h]=l.useState(null),[b,y]=l.useState(""),[f,w]=l.useState(!1),[j,g]=l.useState(!1),[v,k]=l.useState(null),[N,x]=l.useState(null),{githubUrl:C}=c1(e,t),S=l.useCallback(async $=>{if(!((p==null?void 0:p.path)===$.path&&!p.loading)){m({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}),T=x1(X);if(T.error||!T.diff){m({path:$.path,diff:"",binary:!1,truncated:!1,loading:!1,error:T.error??"Failed to load diff"});return}m({path:$.path,diff:T.diff.diff,binary:T.diff.binary??!1,truncated:T.diff.truncated??!1,loading:!1,error:null})}catch(X){const T=X instanceof Error?X.message:"Failed to load diff";m({path:$.path,diff:"",binary:!1,truncated:!1,loading:!1,error:T})}}},[e,n,p,t]),I=l.useCallback($=>{y(""),w(!1),k(null),x(null),h($)},[]),P=l.useCallback(()=>{h(null),k(null),g(!1)},[]),L=l.useCallback(async()=>{var $,X,T;if(u){g(!0),k(null);try{let M;u==="checkpoint"?M=await n(e,"git_checkpoint",{workspace:t,message:b,includeUntracked:f}):u==="stash"?M=await n(e,"git_stash_push",{workspace:t,message:b,includeUntracked:f}):u==="stash_pop"?M=await n(e,"git_stash_pop",{workspace:t}):u==="checkout_files"&&p&&(M=await n(e,"git_checkout_files",{workspace:t,paths:[p.path]}));const _=(M==null?void 0:M.result)??M;if((_==null?void 0:_.success)===!1||_!=null&&_.error){k((_==null?void 0:_.error)??"Action failed"),g(!1);return}u==="checkpoint"?x(`Checkpoint created: ${((X=($=_==null?void 0:_.checkpoint)==null?void 0:$.commit)==null?void 0:X.slice(0,7))??"done"}`):u==="stash"?x(`Stashed as ${((T=_==null?void 0:_.stash)==null?void 0:T.stashRef)??"stash@{0}"}`):u==="stash_pop"?x("Stash restored"):(x("File reverted"),m(null)),h(null),await d()}catch(M){k(M instanceof Error?M.message:"Action failed")}finally{g(!1)}}},[u,n,e,t,b,f,p,d]),A=!!(a!=null&&a.hasConflicts),R=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}),C&&s.jsx("a",{href:`${C}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-sky-400 underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:d,disabled:i,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),s.jsx("button",{onClick:r,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(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"}),R===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(w1,{files:o.files,truncated:o.truncated,selectedPath:(p==null?void 0:p.path)??null,onFileClick:S}),!i&&!o&&!c&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:p?s.jsx(lm,{diff:p.diff,binary:p.binary,truncated:p.truncated,loading:p.loading,error:p.error,className:"h-full"}):s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),N&&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:N}),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:A,title:A?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),s.jsx("button",{onClick:()=>I("stash"),disabled:A,title:A?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),s.jsx("button",{onClick:()=>I("stash_pop"),disabled:A||!(a!=null&&a.stashCount),title:A?"Resolve conflicts before restoring a stash":a!=null&&a.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),s.jsx("button",{onClick:()=>I("checkout_files"),disabled:!p,title:p?`Revert changes to ${p.path}`:"Select a file to revert",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkout selected"}),o&&o.files.length>0&&s.jsx("button",{onClick:()=>{const $=k1((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"})]}),u&&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:[u==="checkpoint"&&"Create checkpoint commit",u==="stash"&&"Stash changes",u==="stash_pop"&&"Restore latest stash?",u==="checkout_files"&&`Revert changes to ${(p==null?void 0:p.path)??"file"}?`]}),(u==="checkpoint"||u==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:b,onChange:$=>y($.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:$=>w($.target.checked)}),"Include untracked files"]})]}),v&&s.jsx("p",{className:"text-xs text-red-400",children:v}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:P,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||(u==="checkpoint"||u==="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 N1({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=l.useState(!1),[o,i]=l.useState(!1),[c,d]=l.useState(!1),[p,m]=l.useState(!1),[u,h]=l.useState(!1),[b,y]=l.useState("quickstart"),[f,w]=l.useState("workspace"),j=l.useMemo(()=>!t&&!e,[t,e]),g=l.useCallback(S=>{a(S),S&&i(!1)},[]),v=l.useCallback(S=>{i(S),S&&a(!1)},[]),k=l.useCallback(()=>{y(r===0?"quickstart":"shortcuts"),w("workspace"),d(!0),a(!1),i(!1)},[r]),N=l.useCallback(()=>{d(!1)},[]),x=l.useCallback(()=>{m(!0)},[]),C=l.useCallback(()=>{m(!1)},[]);return l.useEffect(()=>{if(!j){h(!1);return}h(!0);const S=window.setTimeout(()=>{h(!1)},1e4);return()=>window.clearTimeout(S)},[j]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:p,guideNudgeVisible:u,guideTab:b,shortcutSection:f,isDesktopDashboard:j,setGuideTab:y,setShortcutSection:w,handleInboxOpenChange:g,handleHiddenOpenChange:v,handleOpenShortcutHelp:k,closeShortcutHelp:N,openNewSession:x,closeNewSession:C}}function S1(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 C1(e){return e instanceof Error?e.message:String(e||"")}function I1(e){const t=C1(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function M1({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:i,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:p,mobileChatConversations:m,hiddenConversations:u,ides:h,actionLogs:b,sendDaemonCommand:y,setActionLogs:f,setCliViewModeOverrides:w,isStandalone:j,initialDataLoaded:g,userName:v,requestedMobileTabKey:k,onRequestedMobileTabConsumed:N,requestedMachineId:x,onRequestedMachineConsumed:C,requestedMobileSection:S,onRequestedMobileSectionConsumed:I,containerRef:P,isSplitMode:L,numGroups:A,groupSizes:R,groupedConvs:$,clearedTabs:X,focusedGroup:T,focusGroup:M,moveTabToGroup:_,splitTabRelative:B,closeGroup:E,handleResizeStart:F,groupActiveTabIds:K,setGroupActiveTab:z,groupTabOrders:ne,setGroupTabOrder:q,toggleHiddenTab:J,visibleConversations:xe,requestedDesktopTabKey:ue,onRequestedDesktopTabConsumed:O,onDesktopActiveTabChange:H,onRequestScrollToBottom:ve,onHideConversation:we,onShowHiddenConversation:be,onShowAllHiddenConversations:Ne,scrollToBottomRequest:re,machineEntries:je,layoutProfile:ce,onBrowseMachineDirectory:U,onSaveMachineWorkspace:W,onLaunchMachineIde:Y,onLaunchMachineProvider:se,onListMachineMeshes:ie,onLaunchMeshCoordinator:ae,onListMachineSavedSessions:D,notifications:oe,notificationUnreadCount:ge,liveSessionInboxState:pe,onMarkNotificationRead:te,onMarkNotificationUnread:Me,onDeleteNotification:_e}){const Ce=St.useRef(null),{inboxOpen:Ke,hiddenOpen:Ze,shortcutHelpOpen:me,newSessionOpen:De,guideNudgeVisible:$e,guideTab:tt,shortcutSection:Ue,isDesktopDashboard:Ve,setGuideTab:Te,setShortcutSection:ze,handleInboxOpenChange:ot,handleHiddenOpenChange:Je,handleOpenShortcutHelp:Re,closeShortcutHelp:G,openNewSession:V,closeNewSession:ee}=N1({isMobile:t,showMobileChatMode:e,visibleConversationCount:xe.length}),[he,ye]=St.useState(null),[ke,Q]=St.useState(null),Z=St.useCallback((de,Be)=>{ye({daemonId:de,workspace:Be})},[]),fe=St.useCallback(de=>{Q(de)},[]),Ie=St.useCallback(de=>{var Be;Dr.flushSync(()=>{be(de)}),(Be=Ce.current)==null||Be.restoreHiddenTabToSavedLocation(de.tabKey)},[be]),Pe=St.useCallback(de=>{var Ct;const Be=m.find(Lt=>Fo(Lt,de))||u.find(Lt=>Fo(Lt,de));Be&&(u.some(Lt=>Lt.tabKey===Be.tabKey)&&Ie(Be),H(Be.tabKey),(Ct=Ce.current)==null||Ct.activateConversationTab(Be.tabKey),ve(Be.tabKey,"notification-open")),te(de.id),ot(!1)},[Ie,u,m,H,te,ve]),Ae=St.useCallback(()=>{var Be;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Be=Ce.current)==null||Be.resetAllPanelsToMain(),Je(!1))},[Je]),Ee=St.useCallback(async de=>{var Oe;if(!r)return;const Be=(Oe=r.modalButtons)==null?void 0:Oe[de];if(!Be)return;const Ct=Ns(r);if(!Ct)return;const Lt=Be.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),is=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Lt);try{await y(Ct,"resolve_action",{button:Be,action:is?"approve":"reject",buttonIndex:de,...ks(r)})}catch(at){I1(at)||console.error("[Shortcut approval] Failed:",at)}},[r,y]),{isMac:He,actionDefinitions:Le,actionShortcuts:Ye,shortcutListening:st,shortcutListeningDraft:ht,setShortcutListening:kt,setShortcutListeningDraft:bt,saveShortcuts:ft}=jw({enabled:Ve&&!me,onTrigger:de=>{var Be,Ct,Lt,is,Oe,at,ls,en,tn,sn,rn,nn,an,on,bs,ln;if(de==="openShortcutHelp"){Re();return}if(de==="openNewSession"){V();return}if(de==="hideCurrentTab"){r&&we(r);return}if(de==="toggleHiddenTabs"){Je(!Ze);return}if(de==="openHistoryForActiveTab"){r&&!rt(r)&&o(r);return}if(de==="openRemoteForActiveTab"){r&&!nt(r)&&!rt(r)&&i(r);return}if(de==="splitActiveTabRight"){(Be=Ce.current)==null||Be.splitActiveTabRight();return}if(de==="splitActiveTabDown"){(Ct=Ce.current)==null||Ct.splitActiveTabDown();return}if(de==="floatActiveTab"){(Lt=Ce.current)==null||Lt.floatActiveTab();return}if(de==="popoutActiveTab"){(is=Ce.current)==null||is.popoutActiveTab();return}if(de==="dockActiveTab"){(Oe=Ce.current)==null||Oe.dockActiveTab();return}if(de==="focusLeftPane"){(at=Ce.current)==null||at.focusLeftPane();return}if(de==="focusRightPane"){(ls=Ce.current)==null||ls.focusRightPane();return}if(de==="focusUpPane"){(en=Ce.current)==null||en.focusUpPane();return}if(de==="focusDownPane"){(tn=Ce.current)==null||tn.focusDownPane();return}if(de==="moveActiveTabToLeftPane"){(sn=Ce.current)==null||sn.moveActiveTabToLeftPane();return}if(de==="moveActiveTabToRightPane"){(rn=Ce.current)==null||rn.moveActiveTabToRightPane();return}if(de==="moveActiveTabToUpPane"){(nn=Ce.current)==null||nn.moveActiveTabToUpPane();return}if(de==="moveActiveTabToDownPane"){(an=Ce.current)==null||an.moveActiveTabToDownPane();return}if(de==="triggerPrimaryApprovalAction"){Ee(0);return}if(de==="triggerSecondaryApprovalAction"){Ee(1);return}if(de==="triggerTertiaryApprovalAction"){Ee(2);return}if(de==="setActiveTabShortcut"){(on=Ce.current)==null||on.setShortcutForActiveTab();return}if(de==="selectPreviousGroupTab"){(bs=Ce.current)==null||bs.activatePreviousTabInGroup();return}if(de==="selectNextGroupTab"){(ln=Ce.current)==null||ln.activateNextTabInGroup();return}!r||!nt(r)||rt(r)||de==="toggleCliView"&&p(d==="chat"?"terminal":"chat")}}),Ge=St.useCallback(()=>{G(),kt(null),bt([])},[G,kt,bt]),Ot=St.useMemo(()=>Ue==="all"?Le:Le.filter(de=>S1(de)===Ue),[Le,Ue]),le=St.useCallback(()=>{const de=Object.fromEntries(Le.map(Be=>[Be.id,""]));ft(de)},[Le,ft]),Fe=St.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const de=Object.fromEntries(Le.map(Be=>[Be.id,Be.defaultShortcut]));ft(de)},[Le,ft]);return St.useEffect(()=>{const de=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",de),()=>window.removeEventListener("keydown",de)},[r,we]),St.useEffect(()=>{if(!me||st)return;const de=Be=>{Be.key==="Escape"&&(Be.preventDefault(),Ge())};return window.addEventListener("keydown",de,!0),()=>window.removeEventListener("keydown",de,!0)},[Ge,me,st]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(u0,{activeConv:r,wsStatus:n,isConnected:a,conversations:xe,hiddenConversations:u,onOpenHistory:o,onHideConversation:we,onShowConversation:Ie,onShowAllHidden:Ne,onResetPanelsToMain:Ae,notifications:oe,notificationUnreadCount:ge,onOpenNotification:Pe,onMarkNotificationRead:te,onMarkNotificationUnread:Me,onDeleteNotification:_e,inboxOpen:Ke,onInboxOpenChange:ot,hiddenOpen:Ze,onHiddenOpenChange:Je,onOpenNewSession:t?void 0:V,onOpenDashboardGuide:Re,guideNudgeVisible:$e,actionShortcuts:Ye,onOpenRemote:()=>{!r||nt(r)||rt(r)||i(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:p,onOpenGitDialog:Z,onOpenMeshGraph:fe}),e?s.jsx(dw,{conversations:m,hiddenConversations:u,ides:h,actionLogs:b,sendDaemonCommand:y,setActionLogs:f,setCliViewModeOverrides:w,isStandalone:j,userName:v,requestedActiveTabKey:k,onRequestedActiveTabConsumed:N,requestedMachineId:x,onRequestedMachineConsumed:C,requestedMobileSection:S,onRequestedMobileSectionConsumed:I,onOpenHistory:o,onOpenRemote:i,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Ne,onHideConversation:we,onOpenMeshGraph:fe,onOpenNewSession:V,liveSessionInboxState:pe}):t?s.jsx(gw,{containerRef:P,isSplitMode:L,numGroups:A,groupSizes:R,groupedConvs:$,clearedTabs:X,ides:h,actionLogs:b,sendDaemonCommand:y,setActionLogs:f,isStandalone:j,hasRegisteredMachines:je.length>0,userName:v,focusedGroup:T,focusGroup:M,moveTabToGroup:_,splitTabRelative:B,closeGroup:E,handleResizeStart:F,groupActiveTabIds:K,setGroupActiveTab:z,groupTabOrders:ne,setGroupTabOrder:q,toggleHiddenTab:J,onOpenNewSession:V,allowTabShortcuts:!1,liveSessionInboxState:pe}):s.jsx($w,{visibleConversations:xe,clearedTabs:X,ides:h,actionLogs:b,sendDaemonCommand:y,setActionLogs:f,isStandalone:j,hasRegisteredMachines:je.length>0,initialDataLoaded:g,userName:v,toggleHiddenTab:J,actionShortcuts:Ye,registerActionHandlers:de=>{Ce.current=de},onActiveTabChange:H,requestedActiveTabKey:ue,onRequestedActiveTabConsumed:O,onRequestScrollToBottom:ve,scrollToBottomRequest:re,onOpenNewSession:V,liveSessionInboxState:pe,layoutProfile:ce}),De&&s.jsx(Gw,{machines:je,ides:h,onClose:ee,onBrowseDirectory:U,onSaveWorkspace:W,onLaunchIde:Y,onLaunchProvider:se,onListMeshes:ie,onLaunchMeshCoordinator:ae,onListSavedSessions:D}),ke&&s.jsx(l1,{activeConv:ke,sendDaemonCommand:y,onClose:()=>Q(null)}),he&&s.jsx(cm,{daemonId:he.daemonId,workspace:he.workspace,onClose:()=>ye(null)}),me&&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:de=>de.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(de=>s.jsx("button",{type:"button",className:`btn btn-sm ${tt===de.id?"btn-primary":"btn-secondary"}`,onClick:()=>Te(de.id),children:de.label},de.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 ",He?"⌥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(de=>s.jsx("button",{type:"button",className:`btn btn-sm ${Ue===de.id?"btn-primary":"btn-secondary"}`,onClick:()=>ze(de.id),children:de.label},de.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:le,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(de=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${st===de.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:de.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:de.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:de.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===de.id?ht.length>0?`${ht.join(" ")} ...`:"Listening...":Ye[de.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{kt(de.id),bt([])},children:st===de.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Be={...Ye};Be[de.id]="",ft(Be)},children:"Disable"})]})]})},de.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",He?"⌘⇧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 fo=[{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 A1({onClose:e}){const[t,r]=l.useState(0),n=fo[t],a=t===fo.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:fo.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 T1({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 _1({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,i]=l.useState(()=>a||"native"),c=l.useMemo(()=>Ru(t),[t]),d=l.useMemo(()=>e?Mi(e,{machineNames:c,connectionStates:r,defaultConnectionState:"new"}):[],[e,c,r]),p=l.useMemo(()=>d.find(f=>f.streamSource==="native"),[d]),m=l.useMemo(()=>d.filter(f=>f.streamSource==="agent-stream"),[d]),u=l.useMemo(()=>e?Gt(d,e.id):null,[d,e]);l.useEffect(()=>{a&&i(a)},[a]),l.useEffect(()=>{if(a||!u)return;const f=u.streamSource==="native"?"native":u.tabKey;!f||o===f||o==="native"&&i(f)},[o,u,a]),l.useEffect(()=>{var f;o!=="native"&&(m.some(w=>w.tabKey===o)||i(((f=m[0])==null?void 0:f.tabKey)||"native"))},[o,m]),l.useEffect(()=>{o==="native"&&(p||m[0]&&i(m[0].tabKey))},[o,p,m]);const h=l.useMemo(()=>o==="native"&&p?p:m.find(f=>f.tabKey===o)||u||p||m[0],[o,p,u,m]),b=l.useMemo(()=>m.map(f=>({tabKey:f.tabKey,title:ju(f)||n,status:f.status})),[m,n]),y=l.useCallback(f=>{if(f)return d.find(w=>Fo(w,{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:y}}function R1({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:i,isStandalone:c,userName:d,onOpenHistory:p,onConversationChange:m,onClose:u}){const[h,b]=l.useState("split"),[y,f]=l.useState(()=>xs(e)?"native":e.tabKey),w=l.useRef(null),j=l.useMemo(()=>t||r.find(M=>M.id===e.routeId),[e.routeId,t,r]),g=l.useMemo(()=>It((j==null?void 0:j.type)||""),[j==null?void 0:j.type]),{conversations:v,extensionTabs:k,hasExtensions:N}=_1({ideData:j,allIdes:r,connectionStates:n,ideName:g||"IDE",preferredTabKey:xs(e)?void 0:e.tabKey}),x=l.useMemo(()=>j?Gt(v,j.id):null,[j,v]);l.useEffect(()=>{const M=w.current,_={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(w.current=_,!(M&&M.routeId===_.routeId&&M.tabKey===_.tabKey&&M.streamSource===_.streamSource)){if(xs(e)){f("native");return}f(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),l.useEffect(()=>{if(y==="native"){if(v.some(M=>M.streamSource==="native"))return;(x==null?void 0:x.streamSource)==="agent-stream"&&f(x.tabKey);return}if(!v.some(M=>M.tabKey===y)){if((x==null?void 0:x.streamSource)==="agent-stream"){f(x.tabKey);return}f("native")}},[v,y,x]);const C=l.useMemo(()=>y==="native"?v.find(M=>M.streamSource==="native")||e:v.find(M=>M.tabKey===y)||e,[e,v,y]),S=Ku(C),I=l.useMemo(()=>S.status||S.modalMessage||S.modalButtons?{...C,...S.status?{status:S.status}:{},...S.modalMessage!==void 0?{modalMessage:S.modalMessage}:{},...S.modalButtons!==void 0?{modalButtons:S.modalButtons}:{}}:C,[C,S]),P=Gr(I),L=ya({sendDaemonCommand:o,activeConv:I,setActionLogs:i,isStandalone:c}),{connScreenshot:A,screenshotUsage:R,handleRemoteAction:$}=vp({doId:P,targetSessionId:au(I),connState:I.connectionState||"new",viewMode:h}),X=l.useMemo(()=>a.filter(M=>M.routeId===I.tabKey),[a,I.tabKey]);l.useEffect(()=>{m==null||m(I)},[I,m]),l.useEffect(()=>{const M=_=>{_.key==="Escape"&&u()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[u]);const T=l.useCallback(M=>{M.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:u,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:T,children:[s.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[s.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(qt,{size:16})}),s.jsx("span",{className:"truncate",children:vi(C)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:u,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(M=>{const _=h===M;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${_?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>b(M),title:M==="split"?"Split view":"Remote only",children:M==="split"?s.jsx(Kh,{size:15}):s.jsx(qt,{size:15})},M)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>p(C),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:u,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(T1,{hasExtensions:N,ideName:g||"IDE",activeChatTab:y,extensionTabs:k,onSelectTab:f}),s.jsx(Hd,{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(Ed,{addLog:()=>{},connState:I.connectionState||"new",connScreenshot:A,screenshotUsage:R,transportType:I.transport,onAction:$})})]})]})})}function L1({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=Ug(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 P1({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o,interactivePrompt:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(o0,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(Tu,{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(R1,{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(L1,{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(_u,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),s.jsx(Fd,{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(A1,{onClose:o.onClose})]})}function D1({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],p=i.version||i.daemonVersion||"unknown",m=i.versionUpdateRequired===!0,h=np(i)==="preview"?"Update to preview":m?"Update now":"Upgrade";return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:m?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${m?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:c}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",p]}),m&&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:m?"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:m?"var(--status-danger)":"var(--status-warning)",background:m?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${m?"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 $1(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function E1(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 B1(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>E1(t)).map(t=>t.id)}}function F1(){var rl,nl,al,ol;const{sendCommand:e}=mt(),t=Vr(),r=Wu(),n=si(),a=Wr(),[o,i]=ih(),c=o.get("activeTab"),d=((rl=n.state)==null?void 0:rl.openRemoteForTabKey)||null,p=((nl=n.state)==null?void 0:nl.openMachineId)||null,m=((al=n.state)==null?void 0:al.mobileSection)||null,u=gu(),h=u.ides||[],b=u.initialLoaded??!0,{updateRouteChats:y,setToasts:f}=u,[w,j]=l.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),g=u.toasts||[],v=u.wsStatus||"connected",k=u.isConnected??!0,N=u.connectionStates||{},x=u.showReconnected||!1,{layoutProfile:C,groupAssignments:S,updateGroupAssignments:I,focusedGroup:P,updateFocusedGroup:L,focusGroup:A,groupActiveTabIds:R,updateGroupActiveTabIds:$,setGroupActiveTab:X,groupTabOrders:T,updateGroupTabOrders:M,setGroupTabOrder:_,groupSizes:B,updateGroupSizes:E,isMobile:F,hasHydratedStoredLayout:K,hydrateStoredLayout:z,focusConversationTab:ne}=av(),[q,J]=l.useState(()=>Ri());l.useEffect(()=>dy(J),[]);const xe=l.useMemo(()=>$1({isMobile:F,mobileViewMode:q}),[F,q]),[ue,O]=l.useState([]),[H,ve]=l.useState({}),[we,be]=l.useState({});Ur("Dashboard",{ideCount:h.length,toastCount:g.length,focusedGroup:P,groupCount:Object.keys(S).length,actionLogCount:ue.length});const Ne=l.useMemo(()=>h.filter(Xe=>Xe.type==="adhdev-daemon").sort(pi),[h]),je=!!Ne[0];l.useEffect(()=>{const{metadataDaemonIds:Xe,runtimeDaemonIds:Ht}=B1(Ne);for(const or of Xe)t(or,{minFreshMs:3e4}).catch(()=>{});for(const or of Ht)r(or,{minFreshMs:3e4}).catch(()=>{})},[t,r,Ne]);const ce=l.useMemo(()=>_y(h,H),[h,H]),{hiddenTabs:U,autoHiddenTabs:W,autoHideTarget:Y,hideTarget:se,toggleTarget:ie,showTarget:ae,showAllTabs:D}=jy(),{conversations:oe,visibleConversations:ge,visibleTabKeys:pe,resolveConversationBySessionId:te,resolveConversationByTarget:Me}=Ky({ides:ce,connectionStates:N,clearedTabs:we,hiddenTabs:U}),_e=l.useMemo(()=>new Map(oe.map(Xe=>[Xe.tabKey,Xe])),[oe]),Ce=l.useMemo(()=>wy(oe,U,W),[oe,U,W]);l.useEffect(()=>{for(const Xe of Ce)Y(Xe)},[Ce,Y]),bg(ge,xe),l.useEffect(()=>{Object.keys(H).length!==0&&ve(Xe=>Ry(Xe,h))},[h,H]);const Ke=l.useMemo(()=>Kf(h),[h]),{notifications:Ze,unreadCount:me}=wv({conversations:oe,liveSessionInboxState:Ke}),{handleMarkDashboardNotificationRead:De,handleMarkDashboardNotificationUnread:$e,handleDeleteDashboardNotification:tt}=jv({notifications:Ze,sendDaemonCommand:e}),{containerRef:Ue,normalizedGroupAssignments:Ve,numGroups:Te,isSplitMode:ze,groupedConvs:ot,moveTabToGroup:Je,closeGroup:Re,handleResizeStart:G,splitTabRelative:V}=pv({groupAssignments:S,updateGroupAssignments:I,updateFocusedGroup:L,updateGroupActiveTabIds:$,updateGroupTabOrders:M,groupSizes:B,updateGroupSizes:E,isMobile:F,visibleConversations:ge,visibleTabKeys:pe}),{activeConv:ee,openDesktopConversation:he,requestScrollToBottom:ye,scrollToBottomRequest:ke,setDesktopActiveTab:Q}=Dv({isMobile:F,conversations:oe,visibleConversations:ge,groupActiveTabIds:R,focusedGroup:P,groupedConvs:ot,setSearchParams:i});Bv({activeConv:ee,isMobile:F,liveSessionInboxState:Ke,sendDaemonCommand:e});const{requestedDesktopTabKey:Z,requestedMobileTabKey:fe,consumeRequestedActiveTab:Ie}=Uy({isMobile:F,urlActiveTab:c,resolveConversationBySessionId:te,setSearchParams:i}),{remoteDialogConv:Pe,remoteDialogIdeEntry:Ae,remoteDialogActiveConv:Ee,setRemoteDialogActiveConv:He,openRemoteDialog:Le,closeRemoteDialog:Ye,cliStopDialogOpen:st,cliStopTargetConv:ht,requestCliStop:kt,cancelCliStop:bt,confirmCliStop:ft}=Hv({isMobile:F,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:Z,conversations:oe,ides:h,resolveConversationByTarget:Me,activeConv:ee,sendDaemonCommand:e}),{historyModalOpen:Ge,openHistoryModal:Ot,closeHistoryModal:le,historyTargetConv:Fe,isSavedSessionHistoryTarget:de,isHistoryCreatingChat:Be,isHistoryRefreshingHistory:Ct,handleHistorySwitchSession:Lt,handleHistoryNewChat:is,handleHistoryRefresh:Oe,savedHistorySessions:at,savedHistoryFilters:ls,setSavedHistoryFilters:en,missingWorkspaceResumePath:tn,isSavedHistoryLoading:sn,resumingSavedHistorySessionId:rn,handleRefreshSavedHistory:nn,handleResumeSavedHistorySession:an}=Fv({activeConv:ee,remoteDialogConv:Pe,remoteDialogActiveConv:Ee,ides:h,sendDaemonCommand:e,updateRouteChats:y,setToasts:f,setClearedTabs:be,setSearchParams:i}),on=l.useMemo(()=>ge,[ge]),bs=F&&q==="chat",ln=l.useMemo(()=>oe.filter(Xe=>ja(U,Xe)),[oe,U]),el=l.useCallback(Xe=>{const Ht=new URLSearchParams(o);Ht.set("activeTab",Xe),i(Ht,{replace:!0})},[o,i]),{trackPendingLaunch:ym}=_v({ides:h,conversations:oe,onOpenSession:el}),{handleBrowseMachineDirectory:vm,handleSaveMachineWorkspace:wm,handleLaunchMachineIde:jm,handleLaunchMachineProvider:km,handleListMachineMeshes:Nm,handleLaunchMeshCoordinator:Sm,handleListMachineSavedSessions:Cm,setActiveCliViewMode:Im}=Rv({sendDaemonCommand:e,trackPendingLaunch:ym,onOpenSession:el,activeConv:ee,ides:h,setCliViewModeOverrides:ve});Ly({visibleConversations:ge,clearedTabs:we,setClearedTabs:be,setActionLogs:O}),Gy({ides:h,sendDaemonCommand:e,setToasts:f,resolveConversationByTarget:Me});const Mm=qu(),{isRefreshingHistory:Am,handleRefreshHistory:Tm}=rp({sendDaemonCommand:e,activeConv:ee,chats:(ol=h.find(Xe=>Xe.id===(ee==null?void 0:ee.routeId)))==null?void 0:ol.chats,updateRouteChats:y,setToasts:f,setClearedTabs:be});iv({urlActiveTab:F&&!bs?c:null,conversations:oe,resolveConversationBySessionId:te,normalizedGroupAssignments:Ve,hasHydratedStoredLayout:F&&!bs?K:!0,hydrateStoredLayout:F&&!bs?z:()=>{},focusConversationTab:ne,setSearchParams:i,historyModalOpen:Ge,activeConv:ee,isRefreshingHistory:Am,ides:h,handleRefreshHistory:Tm});const _m=l.useMemo(()=>!ee||!nt(ee)||rt(ee)?null:ar(ee),[ee]),{versionMismatchDaemons:Rm,hasRequiredVersionDaemons:tl,targetVersion:Lm,versionBannerDismissed:Pm,setVersionBannerDismissed:Dm,upgradingDaemons:$m,handleBannerUpgrade:Em}=hv({ides:h,sendDaemonCommand:e}),sl=l.useCallback(Xe=>{ae(Xe),he(Xe)},[he,ae]),Bm=l.useCallback(Xe=>{se(Xe)},[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:[(!Pm||tl)&&s.jsx(D1,{daemons:Rm,targetVersion:Lm,required:tl,upgradingDaemons:$m,onUpgrade:Em,onDismiss:()=>Dm(!0)}),s.jsx(M1,{showMobileChatMode:bs,isMobile:F,activeConv:ee,wsStatus:v,isConnected:k,onOpenHistory:Xe=>{Xe&&He(Xe),Ot()},onOpenRemote:Le,onStopCli:kt,activeCliViewMode:_m,onSetActiveCliViewMode:Im,mobileChatConversations:on,ides:h,actionLogs:ue,sendDaemonCommand:e,setActionLogs:O,setCliViewModeOverrides:ve,isStandalone:je,initialDataLoaded:b,userName:u.userName,requestedMobileTabKey:fe,onRequestedMobileTabConsumed:Ie,requestedMachineId:p,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:m,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:Ue,isSplitMode:ze,numGroups:Te,groupSizes:B,groupedConvs:ot,clearedTabs:we,focusedGroup:P,focusGroup:A,moveTabToGroup:Je,splitTabRelative:V,closeGroup:Re,handleResizeStart:G,groupActiveTabIds:R,setGroupActiveTab:X,groupTabOrders:T,setGroupTabOrder:_,toggleHiddenTab:Xe=>ie(_e.get(Xe)||{tabKey:Xe}),visibleConversations:ge,hiddenConversations:ln,requestedDesktopTabKey:Z,onRequestedDesktopTabConsumed:Ie,onDesktopActiveTabChange:Q,onRequestScrollToBottom:ye,onHideConversation:Bm,onShowHiddenConversation:sl,onShowAllHiddenConversations:D,scrollToBottomRequest:ke,machineEntries:Ne,layoutProfile:C,onBrowseMachineDirectory:vm,onSaveMachineWorkspace:wm,onLaunchMachineIde:jm,onLaunchMachineProvider:km,onListMachineMeshes:Nm,onLaunchMeshCoordinator:Sm,onListMachineSavedSessions:Cm,notifications:Ze,notificationUnreadCount:me,liveSessionInboxState:Ke,onMarkNotificationRead:De,onMarkNotificationUnread:$e,onDeleteNotification:tt}),s.jsx("style",{children:`
|
|
87
|
+
body { overflow: hidden; overscroll-behavior: none; }
|
|
88
|
+
`}),s.jsx(P1,{historyModal:{open:Ge,targetConv:Fe,ides:h,isCreatingChat:Be,isRefreshingHistory:de?!1:Ct,savedSessions:at,savedHistoryFilters:ls,missingWorkspaceResumePath:tn||null,onSavedHistoryFiltersChange:en,isSavedSessionsLoading:sn,isResumingSavedSessionId:rn,onClose:le,onNewChat:is,onSwitchSession:Lt,onRefreshHistory:de?nn:Oe,onResumeSavedSession:an},remoteDialog:{conversation:Pe,ideEntry:Ae,ides:h,connectionStates:N,actionLogs:ue,sendDaemonCommand:e,setActionLogs:O,isStandalone:je,userName:u.userName,onOpenHistory:Xe=>{Xe&&He(Xe),Ot()},onConversationChange:He,onClose:Ye},cliStopDialog:{open:st,targetConv:ht,onCancel:bt,onStopNow:async()=>{await ft("hard")},onSaveAndStop:async()=>{await ft("save")}},connectionBanner:{wsStatus:v,showReconnected:x,loginUrl:u.connectionLoginUrl,onReconnect:u.retryServerConnection},toastOverlay:{toasts:g,onDismiss:Xe=>f(Ht=>Ht.filter(or=>or.id!==Xe)),onClick:Xe=>{if(Xe.targetKey){const Ht=Me(Xe.targetKey);Ht&&(ne(Ht.tabKey,Ve),sl(Ht),ye(Ht.tabKey,"toast-open"))}}},onboarding:{open:w,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}j(!1)}},interactivePrompt:Mm})]})}function O1({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const{launchCli:o}=ma(),[i,c]=l.useState([]),[d,p]=l.useState(null),[m,u]=l.useState(null),[h,b]=l.useState(!1),[y,f]=l.useState(null),[w,j]=l.useState(!1),[g,v]=l.useState(""),k=l.useRef(null),N=l.useCallback(E=>{k.current=E},[]),x=l.useCallback((E,F,K=!1)=>{c(z=>[...z.slice(-100),{timestamp:Date.now(),level:E,message:F}]),setTimeout(()=>{var z;return(z=a.current)==null?void 0:z.scrollIntoView({behavior:"smooth"})},100),K&&it.showToast(F,E==="error"||E==="warn"?"warning":"success")},[a]),C=l.useCallback(E=>{const F=E instanceof Error?E.message:String(E||"");return F.includes("P2P command timeout")||F.includes("P2P not connected")||F.includes("P2P not available")},[]),S=l.useCallback(async(E,F)=>{var K;if(!e||d)return!1;p(E),x("info",`Launching ${It(E)}${F!=null&&F.workspace?` in ${F.workspace}`:""}...`);try{const z={ideType:E,enableCdp:!0};(K=F==null?void 0:F.workspace)!=null&&K.trim()?z.workspace=F.workspace.trim():F!=null&&F.useDefaultWorkspace&&(z.useDefaultWorkspace=!0);const ne=await r(e,"launch_ide",z);return x(ne!=null&&ne.success?"info":"error",ne!=null&&ne.success?`${It(E)} launched`:`Failed: ${ne==null?void 0:ne.error}`,!0),!!(ne!=null&&ne.success)}catch(z){return x("error",`Launch error: ${z.message}`,!0),!1}finally{p(null)}},[e,d,x,r]),I=l.useCallback(async E=>{if(!e)return{success:!1};const{cliType:F,dir:K,workspaceId:z,useDefaultWorkspace:ne,useHome:q,argsStr:J,model:xe,resumeSessionId:ue}=E;if(!F)return x("warn","Select a CLI or ACP provider first",!0),{success:!1};const O=J?J.split(/\s+/).filter(Boolean):void 0,H=(K==null?void 0:K.trim())||(z?"(saved id)":ne?"(default workspace)":q?"(home)":"");x("info",`Launching ${F}${H?` in ${H}`:""}${xe?` (model: ${xe})`:""}...`),u(F);try{const ve={cliType:F,cliArgs:O,initialModel:xe||void 0};K!=null&&K.trim()?ve.dir=K.trim():z?ve.workspaceId=z:ne?ve.useDefaultWorkspace=!0:q&&(ve.useHome=!0),ue&&(ve.resumeSessionId=ue);const we=await o(e,ve),be=(we==null?void 0:we.result)||we;return we!=null&&we.success?(x("info",`${F} launched`,!0),(be==null?void 0:be.launchSource)==="home"?x("info","📂 Running in home directory (explicit choice)"):(be==null?void 0:be.launchSource)==="defaultWorkspace"&&x("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:be==null?void 0:be.sessionId}):(x("error",`Failed: ${(we==null?void 0:we.error)||(be==null?void 0:be.error)}`,!0),(we==null?void 0:we.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&f({cliType:F,argsStr:J,model:xe}),{success:!1,sessionId:be==null?void 0:be.sessionId})}catch(ve){return C(ve)?(x("warn",`${F} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(x("error",`Launch error: ${ve.message}`,!0),{success:!1})}finally{u(null)}},[e,x,C,r]),P=l.useCallback(async(E,F,K,z)=>e?E?F.trim()?I({cliType:E,dir:F,argsStr:K,model:z}):(f({cliType:E,argsStr:K,model:z}),{success:!1}):(x("warn","Select a provider",!0),{success:!1}):{success:!1},[e,x,I]),L=l.useCallback(async(E,F,K)=>{if(e&&window.confirm(`Stop ${E}?
|
|
89
|
+
This will terminate the process.`))try{const z=await r(e,"stop_cli",{cliType:E,dir:F,targetSessionId:K});z!=null&&z.success?x("info",`${E} stopped`,!0):x("error",`Stop failed: ${(z==null?void 0:z.error)||"Unknown error"}`,!0)}catch(z){x("error",`Stop failed: ${z.message}`,!0)}},[e,x,r]),A=l.useCallback(async E=>{try{await r(E.daemonId,"restart_ide",{ideType:E.type}),x("info",`${It(E.type)} restart initiated`,!0)}catch(F){x("error",`Restart failed: ${F.message}`,!0)}},[x,r]),R=l.useCallback(async E=>{if(window.confirm(`Stop ${It(E.type)}?
|
|
90
|
+
This will disconnect CDP and optionally kill the process.`))try{const F=await r(E.daemonId,"stop_ide",{ideType:E.type,killProcess:!0});F!=null&&F.success?x("info",`${It(E.type)} stopped`,!0):x("error",`Stop failed: ${(F==null?void 0:F.error)||"Unknown error"}`,!0)}catch(F){x("error",`Stop failed: ${F.message}`,!0)}},[x,r]),$=l.useCallback(async()=>{if(e)try{const E=await r(e,"detect_ides",{});x("info",`Found ${((E==null?void 0:E.result)||[]).length} IDE(s)`,!0)}catch(E){x("error",`Detection failed: ${E.message}`,!0)}},[e,x,r]),X=l.useCallback(async E=>{if(!e||!E.trim())return!1;b(!0);try{const F=await r(e,"workspace_add",{path:E.trim()});return F!=null&&F.success?(x("info",`Workspace added: ${E.trim()}`),!0):(x("error",(F==null?void 0:F.error)||"workspace_add failed"),!1)}catch(F){return x("error",F.message),!1}finally{b(!1)}},[e,x,r]),T=l.useCallback(async E=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){b(!0);try{const F=await r(e,"workspace_remove",{id:E});F!=null&&F.success?x("info","Workspace removed",!0):x("error",(F==null?void 0:F.error)||"workspace_remove failed",!0)}catch(F){x("error",F.message,!0)}finally{b(!1)}}},[e,x,r]),M=l.useCallback(async E=>{var F;if(e){b(!0);try{const K=await r(e,"workspace_set_default",E===null?{clear:!0}:{id:E});if(K!=null&&K.success){x("info",E?"Default workspace updated":"Default workspace cleared",!0);const z=typeof K.defaultWorkspacePath=="string"?K.defaultWorkspacePath:"";z&&((F=k.current)==null||F.call(k,z))}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]),_=l.useCallback(async E=>{var K;if(!e||!E.trim())return;const F=E.trim();b(!0);try{const z=await r(e,"workspace_set_default",{path:F});z!=null&&z.success?(x("info","Default workspace set from history"),(K=k.current)==null||K.call(k,F)):x("error",(z==null?void 0:z.error)||"Could not set default (path missing on disk?)")}catch(z){x("error",z.message)}finally{b(!1)}},[e,x,r]),B=l.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:g}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:g})}catch(E){x("warn",`Live nickname updated, but account sync failed: ${E.message}`)}x("info",`Nickname set to "${g||"(cleared)"}"`),j(!1)}catch(E){x("error",`Failed: ${E.message}`)}},[e,g,t,x,n,r]);return{logs:i,launchingIde:d,launchingAgentType:m,workspaceBusy:h,launchPick:y,setLaunchPick:f,editingNickname:w,setEditingNickname:j,nicknameInput:g,setNicknameInput:v,addLog:x,handleLaunchIde:S,runLaunchCliCore:I,handleLaunchCli:P,handleStopCli:L,handleRestartIde:A,handleStopIde:R,handleDetectIdes:$,handleWorkspaceAdd:X,handleWorkspaceRemove:T,handleWorkspaceSetDefault:M,handleWorkspaceResumePath:_,handleSaveNickname:B,setOnDefaultWorkspaceChanged:N}}function H1({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(un,{icon:s.jsx(Sd,{size:16}),label:"Uptime",value:typeof e.uptime=="number"?Jf(e.uptime):"Waiting…"}),s.jsx(un,{icon:s.jsx(qt,{size:16}),label:"IDEs",value:`${t.length}`}),s.jsx(un,{icon:s.jsx(ii,{size:16}),label:"CLIs",value:`${r.length}`}),s.jsx(un,{icon:s.jsx(Gh,{size:16}),label:"ACPs",value:`${n.length}`})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),s.jsxs("div",{className:"flex gap-6",children:[s.jsx(wl,{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(wl,{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 z1(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 W1(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 xo(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 qc(e){if(!e||typeof e!="object")return null;if(xo(e))return e;const t=e,r=t.result;return xo(r)?r:xo(t.sourceConfig)?t.sourceConfig:null}function K1(e){const t=e.trim();return t||null}function U1({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var N;const o=t.filter(x=>x.category==="ide"),[i,c]=l.useState(((N=o[0])==null?void 0:N.type)||""),[d,p]=l.useState(""),[m,u]=l.useState(""),[h,b]=l.useState(!1),[y,f]=l.useState(""),[w,j]=l.useState(!1),g=x=>{const C=x.toLowerCase().replace(/[^a-z0-9-]/g,"");p(C),(!m||m===v(d))&&u(v(C))},v=x=>x.split("-").map(C=>C.charAt(0).toUpperCase()+C.slice(1)).join(" "),k=async()=>{if(!(!d||!m||!i)){b(!0),f("");try{const x=await r(e,"provider_clone",{type:d,name:m,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:w?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=>g(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:m,onChange:x=>u(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"})]}),y&&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:y})]})}),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:w?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:k,disabled:!d||!m||h,className:"machine-btn",style:{background:d&&m?"rgba(34,197,94,0.12)":void 0,borderColor:d&&m?"rgba(34,197,94,0.3)":void 0,color:d&&m?"#86efac":void 0,opacity:!d||!m||h?.4:1},children:h?"⏳ Creating...":"✨ Create Provider"})]})})]})})}const Yc={"user-custom":"Custom",trusted:"Official","trusted-with-scripts":"Official · runs JS","external-safe":"External · spec-only","external-untrusted":"⚠ External · untrusted JS"},G1={"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 V1({trust:e,sourceName:t,description:r}){const n=t&&(e==="external-safe"||e==="external-untrusted")?`${Yc[e]} · ${t}`:Yc[e];return s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded border whitespace-nowrap ${G1[e]}`,title:r,children:n})}function q1(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 Y1={detected:"Detected",not_detected:"Not detected",enabled_unchecked:"Enabled (unchecked)",disabled:"Disabled"},Jc={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"},J1={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 Xc(e){if(!e)return"—";const t=e.ok?"OK":"Failed",r=e.message||e.path||e.command||"";return r?`${t} — ${r}`:t}function X1(e){return e==="cli"||e==="acp"}function Q1({prov:e,providerInfo:t,savingKey:r,onSetSetting:n,onEnableToggle:a,onDetect:o,onResetCommand:i}){const[c,d]=l.useState(!1),p=(t==null?void 0:t.enabled)===!0||e.values.enabled===!0,m=t==null?void 0:t.machineStatus,u=p&&m==="disabled"?"enabled_unchecked":m||(p?"enabled_unchecked":"disabled"),h=X1(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 ${J1[e.category]??"border-border-subtle text-text-muted"}`,children:e.category.toUpperCase()}),(t==null?void 0:t.trust)&&s.jsx(V1,{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 ${Jc[u]??Jc.disabled}`,children:Y1[u]??u}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[h&&s.jsx("button",{onClick:b=>{b.stopPropagation(),a(e.type,!p)},disabled:r===`${e.type}.enabled`,className:`machine-btn text-[10px] px-2 py-0.5 ${p?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:p?"Disable":"Enable"}),s.jsx("span",{className:"text-text-muted text-xs",children:c?"▾":"▸"})]})]}),c&&s.jsxs("div",{className:"border-t border-border-subtle px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{className:"grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Type:"})," ",s.jsx("span",{className:"font-mono",children:e.type})]}),(t==null?void 0:t.providerVersion)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Version:"})," ",t.providerVersion]}),(t==null?void 0:t.binary)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Binary:"})," ",s.jsx("span",{className:"font-mono",children:t.binary})]}),(t==null?void 0:t.status)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Status:"})," ",t.status]}),(t==null?void 0:t.details)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Details:"})," ",t.details]}),(t==null?void 0:t.sourceLayer)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Source:"})," ",t.sourceLayer,t.sourceName?` · ${t.sourceName}`:""]}),(t==null?void 0:t.trust)&&(t==null?void 0:t.trustDescription)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Trust:"})," ",t.trustDescription]}),(()=>{const b=t==null?void 0:t.links;if(!b)return null;const y=Object.entries(b).map(([f,w])=>({k:f,href:q1(w)})).filter(f=>f.href!==null);return y.length===0?null:s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Links:"})," ",y.map(({k:f,href:w})=>s.jsx("a",{href:w,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:"})," ",Xc(t==null?void 0:t.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Verification:"})," ",Xc(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:y=>{const f=parseInt(y.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:y=>void n(e.type,b.key,y.target.value),className:"machine-input text-[11px]",children:b.options.map(y=>s.jsx("option",{value:y,children:y},y))}):s.jsx("input",{type:"text",defaultValue:String(e.values[b.key]??b.default??""),onBlur:y=>void n(e.type,b.key,y.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:!p||r===`${e.type}.detect`,className:`machine-btn text-[10px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${p?"":"opacity-40 cursor-not-allowed"}`,title:p?"Run detection for the configured executable":"Enable provider before detection",children:"Detect"}),s.jsx("button",{onClick:()=>void i(e.type),className:"machine-btn text-[10px] px-2 py-0.5",children:"Reset command"})]})})]})]})}function An(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function Z1({machineId:e,sendDaemonCommand:t,onChange:r}){const[n,a]=l.useState([]),[o,i]=l.useState([]),[c,d]=l.useState(!1),[p,m]=l.useState(null),[u,h]=l.useState(!1),[b,y]=l.useState(""),[f,w]=l.useState("main"),[j,g]=l.useState(""),[v,k]=l.useState(!1),[N,x]=l.useState(null),[C,S]=l.useState(null),I=l.useCallback(async()=>{if(e){d(!0),m(null);try{const R=An(await t(e,"list_provider_sources",{}));if(!(R!=null&&R.success)){m((R==null?void 0:R.error)||"Failed to load sources");return}a(R.sources||[]),i(R.conflicts||[])}catch(R){m((R==null?void 0:R.message)||String(R))}finally{d(!1)}}},[e,t]);l.useEffect(()=>{I()},[I]);const P=async()=>{if(b.trim()){k(!0),m(null);try{const R=An(await t(e,"add_provider_source",{url:b.trim(),ref:f.trim()||"main",...j.trim()?{name:j.trim()}:{}}));R!=null&&R.success?(h(!1),y(""),w("main"),g(""),await I(),r==null||r()):m((R==null?void 0:R.error)||"Failed to add source")}catch(R){m((R==null?void 0:R.message)||String(R))}finally{k(!1)}}},L=async R=>{if(confirm(`Remove provider source ${R}? This deletes the cloned manifests and clears any active-source entries that pointed here.`)){x(R),m(null);try{const $=An(await t(e,"remove_provider_source",{name:R}));$!=null&&$.success?(await I(),r==null||r()):m(($==null?void 0:$.error)||"Failed to remove source")}catch($){m(($==null?void 0:$.message)||String($))}finally{x(null)}}},A=async(R,$)=>{S(`${R}:${$}`),m(null);try{const X=An(await t(e,"set_active_provider_source",{type:R,sourceName:$}));X!=null&&X.success?(await I(),r==null||r()):m((X==null?void 0:X.error)||"Failed to set active source")}catch(X){m((X==null?void 0:X.message)||String(X))}finally{S(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"})]})]}),p&&s.jsx("div",{className:"mb-2 text-[11px] text-red-400 bg-red-500/10 border border-red-500/20 rounded px-2 py-1",children:p}),n.length===0?s.jsx("div",{className:"text-[11px] text-text-muted italic",children:'No external sources registered. Use "+ Add source" to register a 3rd-party provider git URL.'}):s.jsx("ul",{className:"flex flex-col gap-2",children:n.map(R=>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:R.name}),s.jsxs("div",{className:"text-[10px] text-text-muted truncate",children:[R.url," ",s.jsxs("span",{className:"opacity-60",children:["@ ",R.ref]})]})]}),s.jsx("button",{type:"button",onClick:()=>void L(R.name),disabled:N===R.name,className:"machine-btn text-[10px] text-red-400 hover:bg-red-500/[0.10]",children:N===R.name?"…":"Remove"})]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:Object.entries(R.providers).map(([$,X])=>s.jsxs("span",{className:"mr-3",children:[s.jsxs("span",{className:"text-text-secondary",children:[$,":"]})," ",X.length]},$))})]},R.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(R=>s.jsxs("li",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"font-mono text-[11px]",children:[R.type," ",s.jsxs("span",{className:"text-text-muted",children:["(",R.category,")"]})]}),s.jsx("div",{className:"flex gap-1.5 flex-wrap",children:R.candidates.map($=>s.jsxs("button",{type:"button",onClick:()=>void A(R.type,$),disabled:C===`${R.type}:${$}`,className:`text-[10px] px-2 py-0.5 rounded border ${R.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:R.active===$?"Active":`Switch active to ${$}`,children:[R.active===$?"● ":"",$]},$))})]},R.type))})]}),u&&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:R=>y(R.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:R=>w(R.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:R=>g(R.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 P(),disabled:v||!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:v?"Cloning…":"Clone + register"})]})]})]})}function eN({machineId:e,providers:t,sendDaemonCommand:r}){var M;const[n,a]=l.useState([]),[o,i]=l.useState(!1),[c,d]=l.useState(null),[p,m]=l.useState("all"),[u,h]=l.useState(!1),[b,y]=l.useState(!1),[f,w]=l.useState(!1),[j,g]=l.useState(null),[v,k]=l.useState("normal"),[N,x]=l.useState(""),[C,S]=l.useState(!1),I=l.useCallback(async()=>{if(e)try{const _=await r(e,"get_provider_source_config",{}),B=qc(_);B&&(g(B),k(B.sourceMode),x(B.explicitProviderDir||""))}catch{}},[e,r]),P=l.useCallback(async()=>{if(e){i(!0);try{const _=await r(e,"get_provider_settings",{}),B=z1(_);if(B){const E=W1(B,t,{filterSchema:F=>F.filter(K=>K.key!=="enabled")});E.sort((F,K)=>F.category.localeCompare(K.category)||F.displayName.localeCompare(K.displayName)),a(E)}}catch{}i(!1)}},[e,t,r]);l.useEffect(()=>{n.length===0&&P(),j||I()},[]);const L=async(_,B,E)=>{d(`${_}.${B}`),a(F=>F.map(K=>K.type===_?{...K,values:{...K.values,[B]:E}}:K));try{const F=await r(e,"set_provider_setting",{providerType:_,key:B,value:E});F!=null&&F.success||P()}catch{P()}d(null)},A=async(_,B)=>{await L(_,"enabled",B),await P()},R=async _=>{d(`${_}.detect`);try{await r(e,"detect_provider",{providerType:_})}finally{await P(),d(null)}},$=async _=>{await L(_,"executablePath",""),await L(_,"executableArgs",""),await P()},X=async()=>{S(!0);try{const _=await r(e,"set_provider_source_config",{providerSourceMode:v,providerDir:K1(N)}),B=qc(_);B?(g(B),k(B.sourceMode),x(B.explicitProviderDir||"")):await I(),await P()}catch{await I()}S(!1)},T=n.filter(_=>p==="all"||_.category===p);return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[s.jsxs("div",{className:"flex gap-1 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(_=>s.jsx("button",{onClick:()=>m(_),className:`machine-btn text-[10px] px-2 py-0.5 ${p===_?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:_.toUpperCase()},_))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>y(_=>!_),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:P,disabled:o,className:"machine-btn text-[10px]",children:[o?"⏳":"↻"," Refresh"]}),s.jsx("button",{onClick:()=>w(_=>!_),className:"machine-btn text-[10px]",title:"Show source configuration (advanced)",children:"⚙ Advanced"})]})]}),b&&s.jsx(Z1,{machineId:e,sendDaemonCommand:r,onChange:()=>{P()}}),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:v,onChange:_=>k(_.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:N,onChange:_=>x(_.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void X(),disabled:C,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:C?"Applying…":"Apply + Reload"})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"User root:"})," ",(j==null?void 0:j.userDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Upstream root:"})," ",(j==null?void 0:j.upstreamDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:"Provider roots:"})," ",((M=j==null?void 0:j.providerRoots)==null?void 0:M.join(" → "))||"—"]})]})]}),o&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings…"}):T.length===0?s.jsx("div",{className:"px-4.5 py-8 rounded-xl border border-border-subtle bg-bg-secondary text-center",children:s.jsx("div",{className:"text-[12px] text-text-muted",children:p==="all"?'No providers installed yet. Open "Add provider" above to install one.':`No ${p.toUpperCase()} providers installed.`})}):s.jsx("div",{className:"flex flex-col gap-1.5",children:T.map(_=>s.jsx(Q1,{prov:_,providerInfo:t.find(B=>B.type===_.type),savingKey:c,onSetSetting:L,onEnableToggle:A,onDetect:R,onResetCommand:$},_.type))}),u&&s.jsx(U1,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>h(!1),onCreated:()=>{h(!1),P()}})]})}const tN=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function sN({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function rN(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function nN(e){return e.trim().toLowerCase()}function Ma(e,t){const r=nN(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function Ji(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function rr(e,t=220){const r=Ji(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function aN(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 oN(e,t){return e.filter(r=>Ma([r.level,r.message],t))}function Qc(e){return`${e.timestamp}:${e.level}:${e.message}`}function iN(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const i of e.entries)n.set(Qc(i),i);for(const i of t.entries)n.set(Qc(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 lN(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 cN(e,t){return e.split(`
|
|
91
|
+
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>Ma([r],t))}function dN(e,t){return e.filter(r=>Ma([r.level,r.category,r.stage,r.interactionId,Ji(r.payload)],t))}function uN(e,t){return e.filter(r=>Ma([r.kind,r.topic,r.interactionId,Ji(r.payload)],t))}function Zc(e){return e==="warn"||e==="error"}function pN({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=>Zc(a.level)).length+r.filter(a=>Zc(a.level)).length}}function mN({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} ${rr(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}`:""} ${rr(o.payload,500)}`.trim())].join(`
|
|
95
|
+
`)),a.join(`
|
|
96
|
+
|
|
97
|
+
`)}function hN({machineId:e,sendDaemonCommand:t}){const[r,n]=l.useState([]),[a,o]=l.useState("empty"),[i,c]=l.useState(""),[d,p]=l.useState([]),[m,u]=l.useState([]),[h,b]=l.useState(null),[y,f]=l.useState(!0),[w,j]=l.useState("info"),[g,v]=l.useState("all"),[k,N]=l.useState(!0),[x,C]=l.useState(!0),[S,I]=l.useState(""),[P,L]=l.useState(""),[A,R]=l.useState(0),$=l.useRef(0),X=l.useRef(0),T=l.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),M=l.useRef([]),_=l.useCallback(()=>{const q={entries:[],kind:"empty",rawText:"",lastTs:0};T.current=q,$.current=0,n([]),c(""),o("empty"),N(!0)},[]),B=l.useCallback(()=>{M.current=[],X.current=0,p([]),C(!0)},[]),E=l.useCallback(q=>{q!==w&&(_(),j(q))},[w,_]),F=l.useCallback(q=>{v(J=>J===q?J:q)},[]),K=l.useCallback(()=>{_(),B(),u([]),b(null),I(""),L(""),qs.clear()},[_,B]),z=l.useCallback(()=>{R(q=>q+1)},[]),ne=l.useCallback(async()=>{if(!e)return;const q=$.current,J=X.current,[xe,ue]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:w,since:q}),t(e,"get_debug_trace",sN({count:120,since:J,category:g}))]);if(xe.status==="fulfilled"){const O=xe.value,H=(O==null?void 0:O.result)||O,ve=aN(H),we=iN(T.current,ve,300);T.current=we,$.current=we.lastTs,N(!1),I((O==null?void 0:O.success)===!1?String((O==null?void 0:O.error)||"Could not load daemon logs"):""),o(we.kind),c(we.rawText),n(we.entries)}else N(!1),I(xe.reason instanceof Error?xe.reason.message:"Could not load daemon logs");if(ue.status==="fulfilled"){const O=ue.value,H=(O==null?void 0:O.result)||O;if((O==null?void 0:O.success)===!1)L(String((O==null?void 0:O.error)||"Could not load daemon trace"));else if(Array.isArray(H==null?void 0:H.trace)){const ve=H.trace,we=lN(M.current,ve,120),be=ve.reduce((Ne,re)=>Math.max(Ne,Number(re.ts||0)),J);M.current=we,be>J&&(X.current=be),L(""),p(we)}else L("");C(!1)}else C(!1),L(ue.reason instanceof Error?ue.reason.message:"Could not load daemon trace");u(qs.list({limit:120})),b(Date.now())},[w,e,t,g]);return l.useEffect(()=>{B()},[B,g]),l.useEffect(()=>{if(!e||(ne(),!y))return;const q=setInterval(()=>{ne()},3e3);return()=>clearInterval(q)},[y,ne,e,A]),{daemonLogs:r,daemonLogKind:a,daemonRawText:i,debugTrace:d,webEvents:m,lastUpdatedAt:h,autoRefresh:y,logLevel:w,traceCategory:g,daemonLoading:k,traceLoading:x,daemonFetchError:S,traceFetchError:P,setAutoRefresh:f,setLogLevel:E,setTraceCategory:F,refresh:z,clear:K}}function fN({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 ed(e){return e==="warn"||e==="error"}function xN(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 bN(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 td(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function gN(e){const t=rr(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function yN(e){const t=rr(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function vN({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:yN(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:gN(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:bN(o,i),severity:xN(o),message:o,raw:o})}),a.sort((o,i)=>o.ts!==i.ts?o.ts-i.ts:td(o.source)-td(i.source))}function wN(e){return`${e.source}:${e.severity}:${e.message}`}function jN(e){const t=e.filter(n=>ed(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!ed(n.severity))continue;const a=wN(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 kN(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function sd(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${kN(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function NN({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]",sd(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(sd):["No diagnostic events captured."]].join(`
|
|
102
|
+
`)),a.join(`
|
|
103
|
+
|
|
104
|
+
`)}function SN(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function CN(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function IN({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:i,searchQuery:c,daemonLoading:d,traceLoading:p,daemonFetchError:m,traceFetchError:u}){const h=rN(n,o),b=oN(e,c),y=cN(t,c),f=dN(h,c),w=uN(a,c),j=SN(b,i),g=i==="all"?y:[],v=CN(f,i),k=i==="issues"?[]:w,N=pN({daemonLogs:b,daemonRawLines:y,trace:f,webEvents:w}),x=vN({daemonLogs:j,daemonRawLines:g,trace:v,webEvents:k}),C=jN(x),S=fN({daemonLoading:d,traceLoading:p,daemonFetchError:m,traceFetchError:u,daemonLogKind:r,daemonLogsCount:b.length,daemonRawLineCount:y.length,traceCount:f.length,webEventCount:w.length});return{filteredDaemonLogs:b,filteredDaemonRawLines:y,filteredTraceEntries:f,filteredWebEvents:w,visibleDaemonLogs:j,visibleDaemonRawLines:g,visibleTraceEntries:v,visibleWebEvents:k,quickFilterCounts:N,diagnosticEvents:x,diagnosticsSummary:C,sourceStates:S}}function MN(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function dm(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 bo(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 Xi(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function AN({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:dm(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:Xi(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 TN({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:i,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:p,onClear:m}){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(u=>s.jsx("button",{type:"button",onClick:()=>a(u.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===u.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:u.label},u.id))}),s.jsx("input",{value:r,onChange:u=>o(u.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:i,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:d,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:p,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:m,className:"machine-btn",children:"Clear"})]})]})}function _N({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:tN.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 RN({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:i,traceFetchError:c}){var m,u;const d=((m=e.latestIssue)==null?void 0:m.severity)==="error"?"danger":((u=e.latestIssue)==null?void 0:u.severity)==="warn"?"warning":"good",p=i||c?"danger":o?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${bo(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 ${bo(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:[Xi(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:dm(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 ${bo(p)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:i||c?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",MN(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 LN({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()," · ",Xi(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function PN({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:i,visibleWebEvents:c,quickFilter:d,searchQuery:p}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(m=>({...m,timeline:!m.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(m=>s.jsx(AN,{event:m},m.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(m=>({...m,daemon:!m.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((m,u)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:m},`raw-${u}`)),e.daemonLogKind!=="text"&&a.map((m,u)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Qo(m.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(m.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:m.level==="error"?"ERR":m.level==="warn"?"WRN":m.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:m.message})]},`log-${u}`))]})]}),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(m=>({...m,trace:!m.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[i.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&i.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:p.trim()?"No trace entries match the current search.":e.traceCategory==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),i.map(m=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Qo(m.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(m.ts).toLocaleTimeString()}),s.jsx("span",{children:m.level.toUpperCase()}),s.jsxs("span",{children:[m.category,".",m.stage]}),m.interactionId&&s.jsxs("span",{children:["ix=",m.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:rr(m.payload,360)||"No payload"})]},m.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(m=>({...m,web:!m.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[c.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:p.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),c.map(m=>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(m.ts).toLocaleTimeString()}),s.jsx("span",{children:m.kind}),m.topic&&s.jsxs("span",{children:["topic=",m.topic]}),m.interactionId&&s.jsxs("span",{children:["ix=",m.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:rr(m.payload,360)||"No payload"})]},m.id))]})]})]})}function DN({machineId:e,sendDaemonCommand:t}){const r=hN({machineId:e,sendDaemonCommand:t}),[n,a]=l.useState("info"),[o,i]=l.useState(""),[c,d]=l.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),p=l.useRef(null),m=l.useRef(!1),u=l.useMemo(()=>IN({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&&u.diagnosticEvents.length>0){const y=m.current?"smooth":"instant";setTimeout(()=>{var f;(f=p.current)==null||f.scrollIntoView({behavior:y}),m.current=!0},50)}},[u.diagnosticEvents.length,r.autoRefresh]);const h=l.useCallback(async()=>{var f;const y=mN({daemonLogs:u.visibleDaemonLogs,daemonRawLines:u.visibleDaemonRawLines,trace:u.visibleTraceEntries,webEvents:u.visibleWebEvents});if(!y.trim()){it.showToast("No visible logs to copy.","info");return}try{await((f=navigator.clipboard)==null?void 0:f.writeText(y)),it.showToast("Copied visible logs to clipboard.","success")}catch(w){it.showToast(w instanceof Error?w.message:"Could not copy visible logs","warning")}},[u.visibleDaemonLogs,u.visibleDaemonRawLines,u.visibleTraceEntries,u.visibleWebEvents]),b=l.useCallback(async()=>{var f;const y=NN({events:u.diagnosticEvents,summary:u.diagnosticsSummary,sources:u.sourceStates});try{await((f=navigator.clipboard)==null?void 0:f.writeText(y)),it.showToast("Copied diagnostic bundle to clipboard.","success")}catch(w){it.showToast(w instanceof Error?w.message:"Could not copy diagnostic bundle","warning")}},[u.diagnosticEvents,u.diagnosticsSummary,u.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(TN,{quickFilter:n,quickFilterCounts:u.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:()=>{b()},onCopyVisible:()=>{h()},onToggleAutoRefresh:()=>r.setAutoRefresh(y=>!y),onRefresh:r.refresh,onClear:r.clear}),s.jsx(_N,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(RN,{diagnosticsSummary:u.diagnosticsSummary,diagnosticEventsCount:u.diagnosticEvents.length,sourceStates:u.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(LN,{patterns:u.diagnosticsSummary.repeatedPatterns}),s.jsx(PN,{streams:r,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:u.diagnosticEvents,visibleDaemonLogs:u.visibleDaemonLogs,visibleDaemonRawLines:u.visibleDaemonRawLines,visibleTraceEntries:u.visibleTraceEntries,visibleWebEvents:u.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:p})]})}function $N(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 um(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 EN(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=um((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 BN(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function go(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 yo(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function vo(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function rd(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 FN(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function ON(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 HN(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 zN({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=l.useState(""),[o,i]=l.useState(null),[c,d]=l.useState(!1),p=by(e,{enabled:!!e,includeSessions:!0,limit:Hl,intervalMs:Kb}),m=p.diagnostics,u=p.loading,h=p.applyDiagnostics,b=l.useMemo(()=>$N({diagnostics:m,loading:u,refreshing:c,error:n}),[m,u,c,n]),y=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:Hl}),A=yo(L);if(!(A!=null&&A.success))throw new Error((A==null?void 0:A.error)||"Could not load hosted runtime diagnostics");h(A.diagnostics||A.result||null),a("")}catch(L){const A=L instanceof Error?L.message:"Could not load hosted runtime diagnostics";a(A)}finally{d(!1)}}},[h,e,r]);l.useEffect(()=>{!e||m||u||c||f()},[m,u,e,f,c]);const w=l.useCallback(async(L,A)=>{const R=`${L}:${A.sessionId}`;if(!(L==="session_host_stop_session"&&!window.confirm(`Stop ${A.displayName}?
|
|
105
|
+
This will terminate the hosted runtime.`))){i(R);try{const $=await r(e,L,{sessionId:A.sessionId}),X=yo($);if(!(X!=null&&X.success))throw new Error((X==null?void 0:X.error)||"Session host action failed");const T=L==="session_host_resume_session"?"resumed":L==="session_host_restart_session"?"restarted":"stopped";it.showToast(`Session host ${T}: ${A.displayName}`,"success"),await f()}catch($){const X=$ instanceof Error?$.message:"Session host action failed";it.showToast(X,"warning"),a(X)}finally{i($=>$===R?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 A=await r(e,"session_host_prune_duplicate_sessions",{}),R=yo(A);if(!(R!=null&&R.success))throw new Error((R==null?void 0:R.error)||"Duplicate prune failed");const $=R.result||{},X=Array.isArray($.prunedSessionIds)?$.prunedSessionIds.length:0,T=typeof $.duplicateGroupCount=="number"?$.duplicateGroupCount:0;it.showToast(`Pruned ${X} duplicate runtime(s) across ${T} group(s)`,"success"),await f()}catch(A){const R=A instanceof Error?A.message:"Duplicate prune failed";it.showToast(R,"warning"),a(R)}finally{i(A=>A==="session_host_prune_duplicate_sessions"?null:A)}}},[e,f,r]),g=l.useMemo(()=>[...(m==null?void 0:m.sessions)||[]].sort((L,A)=>(A.lastActivityAt||0)-(L.lastActivityAt||0)),[m==null?void 0:m.sessions]),v=l.useMemo(()=>m!=null&&m.liveRuntimes||m!=null&&m.recoverySnapshots||m!=null&&m.inactiveRecords?{liveRuntimes:(m==null?void 0:m.liveRuntimes)||[],recoverySnapshots:(m==null?void 0:m.recoverySnapshots)||[],inactiveRecords:(m==null?void 0:m.inactiveRecords)||[]}:EN(g),[m==null?void 0:m.inactiveRecords,m==null?void 0:m.liveRuntimes,m==null?void 0:m.recoverySnapshots,g]),k=v.liveRuntimes,N=v.recoverySnapshots,x=v.inactiveRecords,C=l.useMemo(()=>HN(k),[k]),S=l.useMemo(()=>[...(m==null?void 0:m.recentTransitions)||[]].slice(-6).reverse(),[m==null?void 0:m.recentTransitions]),I=l.useMemo(()=>[...(m==null?void 0:m.recentLogs)||[]].reverse().find(L=>L.level==="warn"||L.level==="error")||null,[m==null?void 0:m.recentLogs]),P=(L,A)=>{var F;const R=o===`session_host_resume_session:${L.sessionId}`,$=o===`session_host_restart_session:${L.sessionId}`,X=o===`session_host_stop_session:${L.sessionId}`,T=um(L.meta),M=y.get(L.sessionId),_=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,B=A==="recovery"?"Recover":"Resume",E=BN(A);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:L.displayName||(M==null?void 0:M.cliName)||L.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${ON(L.lifecycle)}`,children:L.lifecycle}),T&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:T})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:L.workspaceLabel||(M==null?void 0:M.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:((F=L.writeOwner)==null?void 0:F.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:FN(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(wd,{size:11})," ",_]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",rd(L.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",E]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[A==="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:()=>{w("session_host_resume_session",L)},children:R?`${B}ing…`:B}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{w("session_host_restart_session",L)},children:$?"Restarting…":"Restart"}),A==="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:()=>{w("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(fs,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:g0()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[C>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{j()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${C})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${b.toneClass}`,children:b.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{f()},disabled:u||c,children:[s.jsx(fa,{size:13}),u||c?"Refreshing…":"Refresh"]})]})]}),n&&!m&&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(Xs,{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})]})]})}),m&&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:m.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:N.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:m.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:rd(m.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:vo(m.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(Xs,{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:[vo(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:go("live")}),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 live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:k.map(L=>P(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(fs,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:go("recovery")}),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 recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:N.map(L=>P(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:go("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:x.map(L=>P(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"}),S.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:S.map(L=>{var R;const A=g.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:(A==null?void 0:A.displayName)||((R=y.get(L.sessionId))==null?void 0:R.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:vo(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:m.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function WN({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 KN(e,t){const r=np(e),n=Ks(e,t),a=Ai(e,n),o=_r(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 wo({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 jo({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 UN({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),m=KN(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(wo,{icon:s.jsx(Ps,{size:13}),children:"Current Chats"}),s.jsx(jo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(u=>{const h=qo(u);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(u),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(u)}),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:_s(u)})]},u.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(wo,{icon:s.jsx(Sd,{size:13}),children:"Recent Launches"}),s.jsx(jo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(u=>{const{metaText:h,updatedLabel:b}=xp(u);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(u),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:u.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})]},u.id)})})})]}),m.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(wo,{icon:s.jsx(Xs,{size:13}),children:"Daemon Update"}),s.jsx(jo,{className:m.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":m.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:m.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[m.description,m.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",m.targetVersion,m.channel?` (${m.channel})`:""]})]}),m.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:m.buttonLabel})]}):s.jsx("div",{className:m.tone==="good"?"text-xs font-medium text-emerald-300":"text-xs font-medium text-sky-300",children:"No preview update action is needed."})]})})]})]})}function GN({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:p,handleWorkspaceSetDefault:m}=o,[u,h]=l.useState(!1),[b,y]=l.useState(""),[f,w]=l.useState([]),[j,g]=l.useState(!1),[v,k]=l.useState(""),N=l.useCallback(async C=>{g(!0),k("");try{const S=await Ei(i,e,C);y(S.path),w(S.directories)}catch(S){k(S instanceof Error?S.message:"Could not load folder")}finally{g(!1)}},[e,i]),x=l.useCallback(()=>{h(!0);const C=[...r.map(I=>I.workspace),...n.map(I=>I.workspace),...a.map(I=>I.workspace)],S=$i(t.platform,Di(C,t.defaultWorkspacePath,(t.workspaces||[]).map(I=>I.path)));N(S)},[a,n,r,N,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(Js,{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(C=>{const S=C.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${S?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:S?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void m(S?null:C.id),className:`text-base leading-none shrink-0 transition-colors ${S?"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:zd(C.path,C.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:C.path,children:C.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void p(C.id),children:"Remove"})]},C.id)})})]}),u&&s.jsx(Fi,{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:v,confirmLabel:"Add workspace",onClose:()=>h(!1),onNavigate:C=>{N(C)},onConfirm:C=>{(async()=>{if(!C)return;await d(C)&&h(!1)})()}})]})}function VN({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(GN,{machineId:t,machine:e,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function qN({onNicknameSynced:e}={}){var Ne,re,je,ce,U,W,Y,se,ie,ae;const{id:t}=lh(),r=Wr(),n=si(),{sendCommand:a}=mt(),o=Vr(),i=Wu(),c=gu(),d=c.ides||[],p=c.initialLoaded??!0,m=d.find(D=>D.id===t&&D.type==="adhdev-daemon"),u=d.some(D=>D.type==="adhdev-daemon"),h=t?(Ne=c.connectionRetryStatuses)==null?void 0:Ne[t]:void 0,b=!!(h!=null&&h.blocked),[y,f]=l.useState("workspace"),[w,j]=l.useState(null);l.useCallback((D,oe)=>{j({daemonId:D,workspace:oe})},[]);const[,g]=l.useState("ide"),v=l.useRef(null),[k,N]=l.useState(null),x=l.useRef("__home__"),[C,S]=l.useState("__home__"),[I,P]=l.useState(!1),L=l.useRef(null);l.useEffect(()=>{!t||!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||o(t,{minFreshMs:3e4}).catch(()=>{})},[o,m,t]),l.useEffect(()=>{if(!t||!m||y!=="overview")return;const D=m.machine;(typeof(D==null?void 0:D.cpus)!="number"||typeof(D==null?void 0:D.totalMem)!="number"||typeof(D==null?void 0:D.arch)!="string"||typeof(D==null?void 0:D.release)!="string")&&i(t,{minFreshMs:3e4}).catch(()=>{})},[y,i,m,t]),xy(t&&y==="overview"?[t]:[],{enabled:y==="overview",intervalMs:Ob});const A=()=>{if(u){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},R=O1({machineId:t,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:L});l.useEffect(()=>it.onToast(oe=>{c.setToasts(pe=>{if(pe.some(_e=>_e.message===oe.message&&oe.timestamp-_e.timestamp<3e3))return pe;const Me={id:oe.id,message:oe.message,type:oe.type,timestamp:oe.timestamp,targetKey:oe.targetKey,actions:oe.actions};return[...pe.slice(-4),Me]});const ge=oe.duration||5e3;setTimeout(()=>c.setToasts(pe=>pe.filter(te=>te.id!==oe.id)),ge)}),[c]);const $=(m==null?void 0:m.availableProviders)||[],X={};for(const D of $)X[D.type]=D.icon;const T=m?{id:m.id,hostname:Wd(m,{fallbackId:m.id}),platform:((re=m.machine)==null?void 0:re.platform)||"unknown",arch:((je=m.machine)==null?void 0:je.arch)||"",cpus:((ce=m.machine)==null?void 0:ce.cpus)||0,totalMem:((U=m.machine)==null?void 0:U.totalMem)||0,freeMem:(W=m.machine)==null?void 0:W.freeMem,availableMem:(Y=m.machine)==null?void 0:Y.availableMem,loadavg:(se=m.machine)==null?void 0:se.loadavg,uptime:(ie=m.machine)==null?void 0:ie.uptime,release:((ae=m.machine)==null?void 0:ae.release)||"",cdpConnected:!!m.cdpConnected,machineNickname:m.machineNickname||null,p2p:m.p2p?{screenshotActive:!1,...m.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:m.detectedIdes||[],workspaces:m.workspaces||[],defaultWorkspaceId:m.defaultWorkspaceId??m.activeWorkspaceId??null,defaultWorkspacePath:m.defaultWorkspacePath??m.activeWorkspacePath??null}:null,M=d.filter(D=>D.daemonId===t&&D.type!=="adhdev-daemon").filter(D=>!Er(D)&&!Gs(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,version:D.version||"",instanceId:D.instanceId||"",status:D.status,workspace:D.workspace||null,terminals:D.terminals||0,aiAgents:nx(D.aiAgents||(D.agents||[]).map(oe=>({id:oe.name,name:oe.name,status:oe.status,version:oe.version}))),activeChat:D.activeChat||null,chats:D.chats||[],childSessions:D.childSessions||[],cdpConnected:D.cdpConnected||!1,daemonId:t,lastMessageAt:D.lastMessageAt})),_=d.filter(D=>D.daemonId===t&&Er(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,cliName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,mode:D.mode,runtimeKey:D.runtimeKey,runtimeDisplayName:D.runtimeDisplayName,runtimeWorkspaceLabel:D.runtimeWorkspaceLabel,runtimeWriteOwner:D.runtimeWriteOwner||null,runtimeAttachedClients:D.runtimeAttachedClients||[],daemonId:t,lastMessageAt:D.lastMessageAt})),B=d.filter(D=>D.daemonId===t&&Gs(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,acpName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,daemonId:t,lastMessageAt:D.lastMessageAt})),E=m?Ft(m,{fallbackId:t}):"",F="workspace",K=n.state,z=K==null?void 0:K.initialMachineTab,ne=K==null?void 0:K.initialWorkspaceCategory;K==null||K.initialWorkspaceId,K==null||K.initialWorkspacePath;const q=z==="ides"||z==="clis"||z==="acps"?"workspace":z||F,J=z==="ides"?"ide":z==="clis"?"cli":z==="acps"?"acp":ne,xe=[...M.map(D=>{var oe;return{id:`ide:${D.type}:${D.workspace||""}`,label:((oe=D.activeChat)==null?void 0:oe.title)||D.type,kind:"ide",providerType:D.type,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:D.lastMessageAt||0}}),..._.map(D=>{var oe;return{id:`cli:${D.type}:${D.workspace||""}`,label:((oe=D.activeChat)==null?void 0:oe.title)||D.cliName,kind:"cli",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:D.lastMessageAt||0}}),...B.map(D=>{var oe;return{id:`acp:${D.type}:${D.workspace||""}`,label:((oe=D.activeChat)==null?void 0:oe.title)||D.acpName,kind:"acp",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:Ts(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:D.lastMessageAt||0}})].sort((D,oe)=>(oe.lastLaunchedAt||0)-(D.lastLaunchedAt||0)),ue=((m==null?void 0:m.recentLaunches)||[]).length>0?((m==null?void 0:m.recentLaunches)||[]).map(D=>({id:D.id,label:D.title||D.providerName||D.providerType,kind:D.kind,providerType:D.providerType,providerSessionId:D.providerSessionId,subtitle:Ts(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace,summaryMetadata:D.summaryMetadata,lastLaunchedAt:D.lastLaunchedAt})):xe,O=l.useMemo(()=>{var oe;const D=((oe=c.connectionStates)==null?void 0:oe[t||""])||void 0;return d.filter(ge=>ge.daemonId===t&&ge.type!=="adhdev-daemon").flatMap(ge=>Mi(ge,{connectionStates:t&&D?{[t]:D}:void 0,defaultConnectionState:D})).filter(ge=>!(ge.transport==="pty"&&ge.mode==="terminal")).sort((ge,pe)=>qo(pe)-qo(ge))},[d,c.connectionStates,t]),H=l.useCallback(D=>{const oe=lp(D);oe&&r(Or(oe))},[r]),ve=l.useCallback(()=>{v.current&&(P(!0),v.current().finally(()=>{v.current=null,P(!1),N(null)}))},[]),we=l.useCallback(D=>{if(!T)return;const{options:oe,selectedKey:ge}=fp({machine:T,currentWorkspacePath:D.workspace}),pe=async()=>{g(D.kind),f("workspace")};v.current=async()=>{const te=oe.find(Ce=>Ce.key===x.current),Me=(te==null?void 0:te.workspacePath)??null,_e=(te==null?void 0:te.workspaceId)??null;if(D.kind==="ide"&&D.providerType){await R.handleLaunchIde(D.providerType,Me?{workspace:Me}:void 0);return}if((D.kind==="cli"||D.kind==="acp")&&D.providerType){await R.runLaunchCliCore({cliType:D.providerType,dir:_e?void 0:Me||"",workspaceId:_e||void 0,model:D.kind==="acp"&&Ud(D.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:D.providerSessionId});return}await pe()},x.current=ge,S(ge),N({title:D.kind==="ide"?sa("restart-ide",D.label):D.providerSessionId?Mu(D.label):sa("start-fresh",D.label),description:D.kind==="ide"?ra("restart-ide"):D.providerSessionId?Au():ra("start-fresh"),confirmLabel:D.kind==="ide"?na("restart-ide"):D.providerSessionId?ta(!0):na("start-fresh"),busyLabel:D.kind==="ide"?aa("restart-ide"):D.providerSessionId?Ci(!0):aa("start-fresh"),workspaceOptions:oe,details:[{label:"Mode",value:D.kind.toUpperCase()},...D.providerType?[{label:"Provider",value:D.providerType}]:[]]})},[R,T]);if(l.useEffect(()=>{f(q)},[F,q,t]),l.useEffect(()=>{J&&g(J)},[J,t]),!T)return p?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:A,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const be=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(qt,{size:14})," Workspace"]}),count:M.length+_.length+B.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(fs,{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(Wh,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Fh,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:A,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[R.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:R.nicknameInput,onChange:D=>R.setNicknameInput(D.target.value),onKeyDown:D=>{D.key==="Enter"&&R.handleSaveNickname(),D.key==="Escape"&&R.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:R.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:()=>R.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:()=>{R.setEditingNickname(!0),R.setNicknameInput(T.machineNickname||"")},title:"Click to set nickname",children:E}),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:[T.platform," · ",T.arch]}),s.jsxs("span",{children:[T.cpus," cores"]}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),T.p2p.available&&s.jsxs("span",{children:["P2P ",T.p2p.state==="connected"?"connected":T.p2p.state]}),T.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:T.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:be.map(D=>s.jsxs("button",{onClick:()=>f(D.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${y===D.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[D.label,D.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${y===D.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:D.count})]},D.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[y==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(UN,{machineEntry:m,providers:$,recentLaunches:ue,currentConversations:O,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",ap(m))}catch{}},onOpenRecent:we,onOpenConversation:H}),s.jsx(VN,{machine:T,machineId:t,ideSessions:M,cliSessions:_,acpSessions:B,actions:R,sendDaemonCommand:a})]}),y==="providers"&&s.jsx(eN,{machineId:t,providers:$,sendDaemonCommand:a}),y==="overview"&&s.jsx(H1,{machine:T,ideSessions:M,cliSessions:_,acpSessions:B}),y==="session-host"&&s.jsx(zN,{machineId:t,cliSessions:_,sendDaemonCommand:a}),y==="logs"&&s.jsx(DN,{machineId:t,sendDaemonCommand:a})]})})}),R.launchPick&&T&&s.jsx(WN,{machine:T,launchPick:R.launchPick,actions:R}),k&&s.jsx(hp,{title:k.title,description:k.description,details:k.details,workspaceOptions:k.workspaceOptions,selectedWorkspaceKey:C,onWorkspaceChange:D=>{x.current=D,S(D)},confirmLabel:k.confirmLabel,busyLabel:k.busyLabel,busy:I,onConfirm:ve,onCancel:()=>{v.current=null,N(null)}}),w&&s.jsx(cm,{daemonId:w.daemonId,workspace:w.workspace,onClose:()=>j(null)}),s.jsx(_u,{toasts:c.toasts||[],onDismiss:D=>c.setToasts(oe=>oe.filter(ge=>ge.id!==D)),onClickToast:D=>{D.targetKey&&r(Or(D.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 YN={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},pm=l.createContext(null);function JN(){const e=l.useContext(pm);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function Qi({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 XN({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 QN({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 mm({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 hm({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 ZN(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function eS({meshes:e,loading:t,error:r,onDismissError:n,daemons:a,features:o,showCreate:i,onToggleCreate:c,createName:d,onCreateNameChange:p,createRepoIdentity:m,onCreateRepoIdentityChange:u,createRepoRemoteUrl:h,onCreateRepoRemoteUrlChange:b,newMeshDaemonId:y,onNewMeshDaemonIdChange:f,newMeshWorkspace:w,onNewMeshWorkspaceChange:j,createPickerWorkspaces:g,onSelectMesh:v,onCreate:k,onCancelCreate:N}){return s.jsxs(Xr,{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(hs,{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:y,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:ZN(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:w,onChange:x=>j(x.target.value),disabled:!y||!g.length,children:y?g.length===0?s.jsx("option",{value:"",children:"No registered workspaces"}):g.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(Tr,{value:d,onChange:x=>p(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(Tr,{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(Tr,{value:m,onChange:x=>u(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:k,disabled:!d.trim()||!h.trim()&&!m.trim()||o.createDaemonPicker&&(!y||!w),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:N,children:"Cancel"})]})]}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):e.length===0?s.jsx(wa,{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 C;return s.jsx("button",{type:"button",onClick:()=>v(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(XN,{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:[((C=x.nodes)==null?void 0:C.length)??x.nodeCount??0," node(s)"]})]})]})},x.id)})})]})}function nd(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 tS({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(Qi,{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(hm,{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"}),nd(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:[nd(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 sS(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 rS(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 nS({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 aS({item:e,activeDaemonId:t,sendCommand:r,onDismiss:n,onRefineNode:a,onRequeueLast:o}){var k,N,x;const[i,c]=l.useState(null),[d,p]=l.useState(null),[m,u]=l.useState(!1),[h,b]=l.useState(null),{label:y,color:f}=sS(e.reviewReason),w=rS(e.evidence.bootstrap),j=((k=e.diffSummary)==null?void 0:k.files)??[],g=((N=e.diffSummary)==null?void 0:N.baseRef)??null,v=l.useCallback(async C=>{if(!(!e.workspace||!t)){if(i===C){c(null),p(null);return}c(C),p(null),u(!0),b(null);try{const S=await r(t,"git_diff_file",{workspace:e.workspace,path:C,...g?{base:g}:{}});(S==null?void 0:S.success)!==!1&&typeof(S==null?void 0:S.diff)=="string"?p(S.diff):(S==null?void 0:S.diff)!=null?p(String(S.diff)):b((S==null?void 0:S.error)||"No diff available")}catch(S){b((S==null?void 0:S.message)||"Failed to load diff")}finally{u(!1)}}},[e.workspace,t,r,i,g]);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:y}),w&&s.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${w.color}`,children:w.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"}),g&&s.jsxs("span",{className:"font-mono",children:["vs ",g]})]}),s.jsxs("div",{className:"border border-border-subtle rounded px-2 py-1 bg-bg-primary space-y-0.5",children:[j.slice(0,20).map(C=>s.jsxs("div",{children:[s.jsx("button",{className:"w-full text-left hover:bg-bg-secondary rounded px-1 transition-colors",onClick:()=>v(C.path),children:s.jsx(nS,{file:C})}),i===C.path&&s.jsx("div",{className:"mt-1 mb-1",children:s.jsx(lm,{diff:d??"",loading:m,error:h??void 0,truncated:!1,className:"text-[10px]"})})]},C.path)),j.length>20&&s.jsxs("div",{className:"text-[10px] text-text-muted px-1 pt-0.5",children:["+",j.length-20," more files"]})]})]}),((x=e.diffSummary)==null?void 0:x.error)&&s.jsxs("div",{className:"text-[11px] text-amber-400",children:["Diff probe: ",e.diffSummary.error]})]})}function oS({items:e,loading:t,error:r,remoteNodesExcluded:n,meshId:a,activeDaemonId:o,onRefresh:i,onDismiss:c,onRefineNode:d,onRequeueLast:p,sendCommand:m}){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(Qi,{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(u=>s.jsx(aS,{item:u,activeDaemonId:o,sendCommand:m,onDismiss:c,onRefineNode:d,onRequeueLast:p},u.nodeId))})]})}function iS(e){const t=new Map;for(const r of e)r!=null&&r.id&&t.set(r.id,er(r.availableProviders||[]));return t}function lS(e,t){const r=String(e.daemon_id||e.daemonId||"");return r&&t.has(r)?t.get(r):[]}function cS(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function dS(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 fm(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 uS(e){const t=fm(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 pS(e){return e.isLocalWorktree===!0}function mS(e){var r;const t=Number((r=e.policy)==null?void 0:r.schedulingPriority);return Number.isFinite(t)?t:0}function hS(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 fS(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 ad(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function xS(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 bS({nodes:e,meshQueue:t,activeDaemon:r,daemons:n,selectedMeshId:a,userName:o,features:i,coordinatorDaemonId:c,schedulingStrategy:d,nodeProviderPriorityDrafts:p,onNodeProviderPriorityDraftChange:m,availableCliProviders:u,savingNodePolicyId:h,onUpdateNodeProviderPriority:b,savingNodeSchedulingId:y,onUpdateNodeScheduling:f,nodeSystemPromptDrafts:w,onNodeSystemPromptDraftChange:j,savingNodeSystemPromptId:g,onSaveNodeSystemPrompt:v,selectedNodeId:k,onSelectNode:N,showAddNode:x,onShowAddNode:C,onCancelAddNode:S,nodeWorkspace:I,onNodeWorkspaceChange:P,nodeProviderPriority:L,onNodeProviderPriorityChange:A,nodeDaemonId:R,onNodeDaemonIdChange:$,nodeCustomPath:X,onNodeCustomPathChange:T,nodePickerWorkspaces:M,nodePickerProviders:_,attachableDaemons:B,onAddNode:E,onRemoveNode:F}){const K=l.useMemo(()=>iS(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:[B.length," available"]})]}),n.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:"No connected machine daemons are currently available."}):B.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:B.map(z=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${z.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{$(z.id),P(""),T(!1),A(Fr(er(z.availableProviders||[]))),C()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate",children:ad(z)}),z.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:z.id}),s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted",children:[(z.workspaces||[]).length," workspace(s) detected"]})]},z.id))})]}),!x&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:C,children:[s.jsx(mm,{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:()=>{S(),$(""),T(!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:R,onChange:z=>{var ne;$(z.target.value),P(""),T(!1),A(Fr(er(((ne=n.find(q=>q.id===z.target.value))==null?void 0:ne.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:"Select a machine..."}),n.map(z=>s.jsx("option",{value:z.id,children:ad(z)},z.id))]})}),(i.addNodeDaemonPicker?R:!0)&&s.jsx(jt,{label:"Workspace Path",children:i.addNodeDaemonPicker&&!X&&M.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:M.map(z=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${I===z.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:()=>P(z.path),children:[s.jsx("span",{className:"font-medium block truncate",children:z.label||z.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:z.path})]},z.id||z.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{T(!0),P("")},children:"Or enter a custom path →"})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(Tr,{value:I,onChange:z=>P(z.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:z=>{z.key==="Enter"&&E()}}),M.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{T(!1),P("")},children:"← Pick from saved workspaces"})]}):(()=>{var q;const z=Array.isArray(r==null?void 0:r.workspaces)?r.workspaces:[],ne=`mesh-add-node-workspaces-${a||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(Tr,{value:I,onChange:J=>P(J.target.value),placeholder:((q=z[0])==null?void 0:q.path)||"/Users/dev/projects/myapp",list:z.length>0?ne:void 0,autoFocus:!0}),z.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:ne,children:z.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:z.slice(0,6).map(J=>s.jsx("button",{type:"button",onClick:()=>P(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(rc,{value:L,availableProviders:i.addNodeDaemonPicker?_:u,onChange:A})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:E,disabled:!I.trim()||i.addNodeDaemonPicker&&!R,className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>{S(),$(""),T(!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(wa,{icon:s.jsx(Js,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:e.map(z=>{const ne=uS(z),q=cS(z,t),J=fS(z,r),xe=k===z.id,ue=pS(z),O=z.status||z.machine_status||(q.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 ${xe?"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:()=>N(xe?null:z.id),onKeyDown:i.addNodeDaemonPicker?void 0:H=>{(H.key==="Enter"||H.key===" ")&&(H.preventDefault(),N(xe?null:z.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:z.machine_label||z.machine_nickname||z.hostname||z.workspace}):s.jsx("span",{className:"text-sm font-medium",children:z.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx(hm,{status:O}),q.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:[q.length," active task",q.length===1?"":"s"]}),ue&&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: ",xS(n.find(H=>H.id===String(z.daemon_id||"")),o)," · Machine: ",z.machine_label||z.daemon_id||z.workspace]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:z.workspace}),ue&&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",z.worktreeBranch?` · ${z.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:H=>H.stopPropagation(),children:[s.jsxs(jt,{label:"Preferred AI tools (in order)",hint:ue?"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(rc,{value:p[z.id]??fm(z),availableProviders:lS(z,K),onChange:H=>m(z.id,H),disabled:h===z.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:H=>{H.stopPropagation(),b(z)},disabled:h===z.id,children:h===z.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:ne.configured?"text-text-primary font-mono":"text-amber-400",children:ne.label}),!ne.configured&&ne.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",ne.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:w[z.id]??"",onChange:H=>{const ve=H.target.value;j(z.id,ve)},onClick:H=>H.stopPropagation(),disabled:g===z.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:H=>{H.stopPropagation(),v(z)},disabled:g===z.id,children:g===z.id?"Saving…":"Save instruction"})})]}),s.jsx(gS,{node:z,schedulingStrategy:d,saving:y===z.id,onSave:H=>f(z,H)})]})]}),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:H=>{H.stopPropagation(),F(z.id)},title:"Remove node",children:i.addNodeDaemonPicker?s.jsx(QN,{size:14}):s.jsx(vt,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:H=>H.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:z.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:ne.configured?"text-green-400":"text-amber-400",children:ne.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:z.repoRoot||z.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(z.created_at||z.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),q.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:q.map(H=>s.jsx("li",{className:"font-mono",children:dS(H)},H.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(H=>s.jsxs("li",{className:"font-mono",children:[H.provider," / ",H.status," / ",H.id]},H.id))})]})]})]})]},z.id)})})]})}function gS({node:e,schedulingStrategy:t,saving:r,onSave:n}){const a=mS(e),o=l.useMemo(()=>hS(e),[e]),[i,c]=l.useState(String(a)),[d,p]=l.useState(o),m=t!=="first_eligible";function u(){p(f=>[...f,{providerType:""}])}function h(f,w){p(j=>j.map((g,v)=>v===f?{...g,...w}:g))}function b(f){p(w=>w.filter((j,g)=>g!==f))}function y(){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),w=Number(i);n({schedulingPriority:Number.isFinite(w)?w: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:m?"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,w)=>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(w,{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(w,{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(w)},title:"Remove cap",disabled:r,children:s.jsx(vt,{size:13})})]},w)),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(),u()},disabled:r,children:[s.jsx(mm,{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(),y()},disabled:r,children:r?"Saving…":"Save advanced"})})]})]})}function yS(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function vS({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:r,coordinatorCliType:n,onCoordinatorCliTypeChange:a,launchingCoordinator:o,launchResult:i,attachedDaemonIds:c,isHostNodeAttached:d,selectedHostNode:p,onLaunchCoordinator:m,onAttachSelectedHost:u}){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(hs,{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:[yS(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:m,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:p==null?void 0:p.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:u,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 wS({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=ip(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(Tp,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}const ko=[{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."}],jS=[{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."}],kS={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function ua(e){return{...kS,...(e==null?void 0:e.policy)||{}}}function NS({selectedMesh:e,error:t,onDismissError:r,onBack:n,onDelete:a,displayedMeshStatus:o,graphLoading:i,graphError:c,graphProvenance:d,graphBootstrapFallback:p=!1,onRefreshGraph:m,queueSummary:u,queueLoading:h,queueError:b,onLoadQueue:y,savingPolicy:f,onUpdatePolicy:w,coordinatorPromptDraft:j,onCoordinatorPromptDraftChange:g,savingCoordinatorPrompt:v,onSaveCoordinatorPrompt:k,daemons:N,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:C,coordinatorCliType:S,onCoordinatorCliTypeChange:I,launchingCoordinator:P,launchResult:L,attachedDaemonIds:A,isHostNodeAttached:R,selectedHostNode:$,onLaunchCoordinator:X,activeDaemon:T,activeDaemonId:M,meshQueue:_,userName:B,nodeProviderPriorityDrafts:E,onNodeProviderPriorityDraftChange:F,availableCliProviders:K,savingNodePolicyId:z,onUpdateNodeProviderPriority:ne,savingNodeSchedulingId:q,onUpdateNodeScheduling:J,schedulingStrategy:xe,nodeSystemPromptDrafts:ue,onNodeSystemPromptDraftChange:O,savingNodeSystemPromptId:H,onSaveNodeSystemPrompt:ve,selectedNodeId:we,onSelectNode:be,showAddNode:Ne,onShowAddNode:re,onCancelAddNode:je,nodeWorkspace:ce,onNodeWorkspaceChange:U,nodeProviderPriority:W,onNodeProviderPriorityChange:Y,nodeDaemonId:se,onNodeDaemonIdChange:ie,nodeCustomPath:ae,onNodeCustomPathChange:D,nodePickerWorkspaces:oe,nodePickerProviders:ge,attachableDaemons:pe,onAddNode:te,onRemoveNode:Me,availableCliAgents:_e,features:Ce,reviewInboxItems:Ke,reviewInboxLoading:Ze,reviewInboxError:me,reviewInboxRemoteNodesExcluded:De,onLoadReviewInbox:$e,onDismissReviewInboxItem:tt,onRefineNode:Ue,onRequeueLast:Ve,sendCommand:Te}){var Je;const ze=ua(e),ot=e.nodes||[];return s.jsxs(Xr,{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:()=>m(!0),disabled:i,children:[s.jsx(Qi,{size:13}),i?"Probing…":"Refresh"]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>a(e.id),children:"Delete"})]}),children:[t&&s.jsx(hs,{variant:"error",onDismiss:r,className:"mb-4",children:t}),Ce.meshHostDaemonSection&&s.jsx(vS,{daemons:N,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:Re=>{C(Re),m()},coordinatorCliType:S,onCoordinatorCliTypeChange:I,launchingCoordinator:P,launchResult:L,attachedDaemonIds:A,isHostNodeAttached:R,selectedHostNode:$,onLaunchCoordinator:X,onAttachSelectedHost:()=>{ie(x),re()}}),Ce.queueSection&&s.jsx(tS,{queueSummary:u,queueLoading:h,queueError:b,activeDaemonId:M,onRefresh:y}),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."})}),p&&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(nm,{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:M,sendDaemonCommand:Te,bootstrapFallback:p}):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(oS,{items:Ke,loading:Ze,error:me,remoteNodesExcluded:De,meshId:e.id,activeDaemonId:M,onRefresh:$e,onDismiss:tt,onRefineNode:Ue,onRequeueLast:Ve,sendCommand:Te}),s.jsx(bS,{nodes:ot,meshQueue:_,activeDaemon:T,daemons:N,selectedMeshId:e.id,userName:B,features:{addNodeDaemonPicker:Ce.addNodeDaemonPicker,nodeInstruction:Ce.nodeInstruction},coordinatorDaemonId:x,schedulingStrategy:xe,nodeProviderPriorityDrafts:E,onNodeProviderPriorityDraftChange:F,availableCliProviders:K,savingNodePolicyId:z,onUpdateNodeProviderPriority:ne,savingNodeSchedulingId:q,onUpdateNodeScheduling:J,nodeSystemPromptDrafts:ue,onNodeSystemPromptDraftChange:O,savingNodeSystemPromptId:H,onSaveNodeSystemPrompt:ve,selectedNodeId:we,onSelectNode:be,showAddNode:Ne,onShowAddNode:re,onCancelAddNode:je,nodeWorkspace:ce,onNodeWorkspaceChange:U,nodeProviderPriority:W,onNodeProviderPriorityChange:Y,nodeDaemonId:se,onNodeDaemonIdChange:ie,nodeCustomPath:ae,onNodeCustomPathChange:D,nodePickerWorkspaces:oe,nodePickerProviders:ge,attachableDaemons:pe,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(ze.maxParallelTasks??2),onChange:Re=>w({maxParallelTasks:Number(Re.target.value)}),disabled:f,children:[1,2,3,4,5,6,7,8].map(Re=>s.jsx("option",{value:Re,children:Re},Re))})})}),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:jS.map(Re=>{const G=(ze.schedulingStrategy||"first_eligible")===Re.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:Re.value,checked:G,disabled:f,onChange:()=>w({schedulingStrategy:Re.value})}),s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block text-sm text-text-primary",children:Re.label}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:Re.description})]})]},Re.value)})}),(ze.schedulingStrategy==="priority_only"||ze.schedulingStrategy==="least_loaded"||ze.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:Re=>g({...j,override:Re.target.value}),disabled:v,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:Re=>g({...j,append:Re.target.value}),disabled:v,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:k,disabled:v,children:v?"Saving…":"Save coordinator prompt"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>g({override:"",append:""}),disabled:v,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:Re=>Re?"yes":"no",parse:Re=>Re==="yes"},{label:"Auto-commit a checkpoint after each task",key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:Re=>Re?"yes":"no",parse:Re=>Re==="yes"},{label:"Push approval",key:"requireApprovalForPush",opts:[["required","Require approval before push"],["not_required","Do not require approval"]],val:Re=>Re?"required":"not_required",parse:Re=>Re==="required"},{label:"Destructive git approval",key:"requireApprovalForDestructiveGit",opts:[["required","Require approval"],["not_required","Do not require approval"]],val:Re=>Re?"required":"not_required",parse:Re=>Re==="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:Re=>Re||"warn",parse:Re=>Re},{label:"Auto-publish submodule commits (advanced)",key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled","Require explicit approval"],["enabled","Allow Refinery non-force publish"]],val:Re=>Re?"enabled":"disabled",parse:Re=>Re==="enabled"}].map(({label:Re,key:G,opts:V,val:ee,parse:he})=>s.jsx(jt,{label:Re,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:ee(ze[G]),onChange:ye=>w({[G]:he(ye.target.value)}),disabled:f,children:V.map(([ye,ke])=>s.jsx("option",{value:ye,children:ke},ye))})},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:ze.sessionCleanupOnNodeRemove||"preserve",onChange:Re=>w({sessionCleanupOnNodeRemove:Re.target.value}),disabled:f,children:ko.map(Re=>s.jsx("option",{value:Re.value,children:Re.label},Re.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((Je=ko.find(Re=>Re.value===ze.sessionCleanupOnNodeRemove))==null?void 0:Je.description)||ko[0].description})]}),f&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving…"})]}),Ce.hermesMcpConfig&&s.jsx(wS,{meshId:e.id,availableCliAgents:_e}),Ce.meshHostDaemonSection&&s.jsxs(hs,{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 SS({daemons:e,primaryDaemonId:t,sendCommand:r,unwrapResult:n,normalizeMesh:a,features:o}){const[i,c]=l.useState([]),[d,p]=l.useState(null),[m,u]=l.useState(!0),[h,b]=l.useState(null),[y,f]=l.useState(!1),[w,j]=l.useState(""),[g,v]=l.useState(""),[k,N]=l.useState(""),[x,C]=l.useState(""),[S,I]=l.useState(""),P=l.useMemo(()=>e.find(M=>M.id===x),[e,x]),L=(P==null?void 0:P.workspaces)||[],A=l.useMemo(()=>er((P==null?void 0:P.availableProviders)||[]),[P]),R=l.useCallback(async()=>{u(!0);try{if(o.createDaemonPicker){const M=await Promise.allSettled(e.map(async B=>{if(!B.id)return[];const E=await r(B.id,"list_meshes",{}),F=n(E);if((F==null?void 0:F.success)===!1)throw new Error(F.error||"Failed to load meshes");return(Array.isArray(F==null?void 0:F.meshes)?F.meshes:[]).map(K=>a(K,B.id)).filter(K=>K.id)})),_=new Map;for(const B of M)if(B.status==="fulfilled")for(const E of B.value)_.has(E.id)||_.set(E.id,E);c(Array.from(_.values()))}else{if(!t)return;const M=await r(t,"list_meshes");M!=null&&M.success?(c((M.meshes||[]).map(_=>a(_,t))),b(null)):b((M==null?void 0:M.error)||"Failed to load meshes")}}catch(M){b((M==null?void 0:M.message)||"Failed to load meshes")}finally{u(!1)}},[e,t,r,n,a,o.createDaemonPicker]);async function $(){var E,F;const M=o.createDaemonPicker?x:t;if(!M||!w.trim())return;const _=k.trim(),B=g.trim();if(!(!_&&!B))try{const K={name:w.trim()};_&&(K.repoRemoteUrl=_),B&&(K.repoIdentity=B);const z=await r(M,"create_mesh",K),ne=n(z);if((ne==null?void 0:ne.success)===!1)throw new Error(ne.error||"Create failed");const q=typeof((E=ne==null?void 0:ne.mesh)==null?void 0:E.id)=="string"?ne.mesh.id:"";if(q&&o.createDaemonPicker&&S){const J=await r(M,"add_mesh_node",{meshId:q,daemonId:M,machineId:P==null?void 0:P.machineId,workspace:S,role:"host",providerPriority:Fr(A)}),xe=n(J);if((xe==null?void 0:xe.success)===!1)throw new Error(xe.error||"Mesh created but failed to attach workspace")}f(!1),j(""),v(""),N(""),I(""),await R(),(F=ne==null?void 0:ne.mesh)!=null&&F.id&&p(ne.mesh.id)}catch(K){b((K==null?void 0:K.message)||"Create failed")}}async function X(M){var B;if(!confirm("Delete this mesh? This cannot be undone."))return;const _=((B=i.find(E=>E.id===M))==null?void 0:B.__sourceDaemonId)||t;try{const E=await r(_,"delete_mesh",{meshId:M}),F=n(E);if((F==null?void 0:F.success)===!1)throw new Error(F.error||"Failed to delete");d===M&&p(null),await R()}catch(E){b((E==null?void 0:E.message)||"Delete failed")}}function T(){f(!1),j(""),v(""),N("")}return{meshes:i,setMeshes:c,selectedMeshId:d,setSelectedMeshId:p,loading:m,error:h,setError:b,showCreate:y,setShowCreate:f,createName:w,setCreateName:j,createRepoIdentity:g,setCreateRepoIdentity:v,createRepoRemoteUrl:k,setCreateRepoRemoteUrl:N,newMeshDaemonId:x,setNewMeshDaemonId:C,newMeshWorkspace:S,setNewMeshWorkspace:I,createPickerWorkspaces:L,createPickerProviders:A,loadMeshes:R,handleCreate:$,handleDelete:X,cancelCreate:T}}function CS({selectedMesh:e,selectedMeshId:t,primaryDaemonId:r,activeDaemonId:n,daemons:a,availableCliProviders:o,sendCommand:i,unwrapResult:c,loadLiveMesh:d,resolveCommandTarget:p,launchCoordinator:m,features:u,loadMeshes:h,loadQueue:b,queueSection:y,setError:f}){const[w,j]=l.useState({}),[g,v]=l.useState(null),[k,N]=l.useState(null),[x,C]=l.useState(!1),[S,I]=l.useState(""),[P,L]=l.useState([]),[A,R]=l.useState(""),[$,X]=l.useState(!1),[T,M]=l.useState(""),[_,B]=l.useState(!1),[E,F]=l.useState(null),[K,z]=l.useState(!1),[ne,q]=l.useState({override:"",append:""}),[J,xe]=l.useState(!1),[ue,O]=l.useState({}),[H,ve]=l.useState(null),we=l.useMemo(()=>a.find(oe=>oe.id===A),[a,A]),be=(we==null?void 0:we.workspaces)||[],Ne=l.useMemo(()=>er((we==null?void 0:we.availableProviders)||[]),[we]);async function re(){const oe=(e==null?void 0:e.__sourceDaemonId)||r;if(!t||!oe)return;const ge=S.trim();if(ge)try{const pe={meshId:t,workspace:ge};u.addNodeDaemonPicker&&A?(pe.daemonId=A,pe.machineId=we==null?void 0:we.machineId,pe.providerPriority=Dn(P,Ne)):pe.providerPriority=Dn(P,o);const te=await i(oe,"add_mesh_node",pe),Me=c(te);if((Me==null?void 0:Me.success)===!1)throw new Error(Me.error||"Add node failed");C(!1),I(""),L([]),R(""),X(!1),await h(),y||await b(t)}catch(pe){f((pe==null?void 0:pe.message)||"Add node failed")}}async function je(oe){var Me;if(!e)return;const ge=ua(e),pe=((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(_e=>_e.value===ge.sessionCleanupOnNodeRemove))==null?void 0:Me.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
|
|
112
|
+
|
|
113
|
+
Node removal cleanup policy: ${pe}`))return;const te=e.__sourceDaemonId||r;try{const _e=await i(te,"remove_mesh_node",{meshId:e.id,nodeId:oe}),Ce=c(_e);if((Ce==null?void 0:Ce.success)===!1)throw new Error(Ce.error||"Remove failed");k===oe&&N(null),await h(),y||await b(t)}catch(_e){f((_e==null?void 0:_e.message)||"Remove node failed")}}async function ce(oe){if(!e)return;const ge={...ua(e),...oe},pe=e.__sourceDaemonId||r;try{z(!0),f(null);const te=await i(pe,"update_mesh",{meshId:e.id,policy:ge}),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{z(!1)}}async function U(oe){if(!t)return;const ge=(e==null?void 0:e.__sourceDaemonId)||r,pe=u.addNodeDaemonPicker?Ne:o,te=w[oe.id]||IS(oe),Me=pe.length>0?Dn(te,pe):Jr(te),_e={...oe.policy||{}};delete _e.provider_priority,Me.length?_e.providerPriority=Me:delete _e.providerPriority;try{v(oe.id),f(null);const Ce=await i(ge,"update_mesh_node",{meshId:t,nodeId:oe.id,policy:_e,providerPriority:Me}),Ke=c(Ce);if((Ke==null?void 0:Ke.success)===!1){f(Ke.error||"Node policy update failed");return}await h()}catch(Ce){f((Ce==null?void 0:Ce.message)||"Node policy update failed")}finally{v(null)}}const[W,Y]=l.useState(null);async function se(oe,ge){if(!t)return;const pe=(e==null?void 0:e.__sourceDaemonId)||r,te={};Object.prototype.hasOwnProperty.call(ge,"schedulingPriority")&&(te.schedulingPriority=Number.isFinite(ge.schedulingPriority)?ge.schedulingPriority:0);const Me={meshId:t,nodeId:oe.id,policy:te};Object.prototype.hasOwnProperty.call(ge,"providerRoles")&&(Me.providerRoles=ge.providerRoles);try{Y(oe.id),f(null);const _e=await i(pe,"update_mesh_node",Me),Ce=c(_e);if((Ce==null?void 0:Ce.success)===!1){f(Ce.error||"Node scheduling update failed");return}await h()}catch(_e){f((_e==null?void 0:_e.message)||"Node scheduling update failed")}finally{Y(null)}}async function ie(){if(!r||!t)return;const ge={...(e==null?void 0:e.coordinator)||{}};ne.override.trim()?ge.systemPromptOverride=ne.override:delete ge.systemPromptOverride,ne.append.trim()?ge.systemPromptAppend=ne.append:delete ge.systemPromptAppend,delete ge.systemPromptSuffix;try{xe(!0),f(null);const pe=await i(r,"update_mesh",{meshId:t,coordinator:ge}),te=c(pe);if((te==null?void 0:te.success)===!1){f(te.error||"Coordinator prompt save failed");return}await h()}catch(pe){f((pe==null?void 0:pe.message)||"Coordinator prompt save failed")}finally{xe(!1)}}async function ae(oe){if(!r||!t)return;const ge=(ue[oe.id]||"").trim();try{ve(oe.id),f(null);const pe=await i(r,"update_mesh_node",{meshId:t,nodeId:oe.id,systemPrompt:ge}),te=c(pe);if((te==null?void 0:te.success)===!1){f(te.error||"Node instruction save failed");return}await h()}catch(pe){f((pe==null?void 0:pe.message)||"Node instruction save failed")}finally{ve(null)}}async function D(){if(e){f(null),F(null);try{B(!0);const oe=d?await d(n,e.id,e):null,ge=p(n,e.id,e,e.nodes||[],oe);if("error"in ge)throw new Error(ge.error);const pe=await m(ge.targetDaemonId,{meshId:e.id,inlineMesh:ge.inlineMesh,coordinatorNodeId:ge.coordinatorNodeId,cliType:T.trim()||void 0});F(pe.message)}catch(oe){f((oe==null?void 0:oe.message)||"Coordinator launch failed")}finally{B(!1)}}}return{nodeProviderPriorityDrafts:w,setNodeProviderPriorityDrafts:j,savingNodePolicyId:g,selectedNodeId:k,setSelectedNodeId:N,showAddNode:x,setShowAddNode:C,nodeWorkspace:S,setNodeWorkspace:I,nodeProviderPriority:P,setNodeProviderPriority:L,nodeDaemonId:A,setNodeDaemonId:R,nodeCustomPath:$,setNodeCustomPath:X,nodePickerWorkspaces:be,nodePickerProviders:Ne,coordinatorCliType:T,setCoordinatorCliType:M,launchingCoordinator:_,launchResult:E,savingPolicy:K,coordinatorPromptDraft:ne,setCoordinatorPromptDraft:q,savingCoordinatorPrompt:J,nodeSystemPromptDrafts:ue,setNodeSystemPromptDrafts:O,savingNodeSystemPromptId:H,savingNodeSchedulingId:W,handleAddNode:re,handleRemoveNode:je,handleUpdatePolicy:ce,handleUpdateNodeProviderPriority:U,handleUpdateNodeScheduling:se,handleSaveCoordinatorPrompt:ie,handleSaveNodeSystemPrompt:ae,handleLaunchCoordinator:D}}function IS(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 MS(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 AS({primaryDaemonId:e,activeDaemonId:t,sendCommand:r,unwrapResult:n,loadLiveMesh:a,resolveCommandTarget:o}){const[i,c]=l.useState([]),[d,p]=l.useState(null),[m,u]=l.useState(!1),[h,b]=l.useState(null),y=l.useCallback(async w=>{if(!e||!w){c([]);return}try{const j=await r(e,"get_mesh_queue",{meshId:w});c(j!=null&&j.success?Array.isArray(j.queue)?j.queue:[]:[])}catch{c([])}},[e,r]);async function f(w){var j,g;if(w){u(!0),b(null);try{const v=a?await a(t,w.id,w):null,k=o(t,w.id,w,w.nodes||[],v);if("error"in k)throw new Error(k.error);const N=await r(k.targetDaemonId,"get_mesh_queue",{meshId:w.id}),x=n(N);if((x==null?void 0:x.success)===!1)throw new Error(x.error||"Queue load failed");const C=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))?((g=x==null?void 0:x.result)==null?void 0:g.rows)??(x==null?void 0:x.rows)??(x==null?void 0:x.queue):[];p(MS(C))}catch(v){b((v==null?void 0:v.message)||"Queue load failed")}finally{u(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:d,queueLoading:m,queueError:h,loadQueue:y,handleLoadQueue:f}}function TS(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}function _S({selectedMeshId:e,loadMeshStatus:t,extractStatus:r,normalizeNode:n,gateIncompleteGraph:a}){const[o,i]=l.useState(null),[c,d]=l.useState(!1),[p,m]=l.useState(null),[u,h]=l.useState("idle"),[b,y]=l.useState(!1),f=l.useRef(!1);async function w(j,g=e,v=!1){if(!(!j||!g))try{d(!v&&o===null),h(v?"settling":"first_paint"),m(null);const k=await t(j,g,{refresh:v,retryProfile:v?"settled":"interactive"});y(TS(k));const N=r(k),x=n&&N?{...N,nodes:(N.nodes??[]).map(C=>n(C,N.meshId??g,""))}:N;if(x){if(a&&!v&&o!==null&&!dk(Yp(x))){h("settling"),f.current||(f.current=!0,Promise.resolve().then(()=>w(j,g,!0)).finally(()=>{f.current=!1}));return}i(x),h("settled")}else i(null),m("mesh_status returned an unexpected payload."),h("idle")}catch(k){o||i(null),m((k==null?void 0:k.message)||"Failed to load mesh graph"),h("idle")}finally{d(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:p,setGraphError:m,graphProvenance:u,graphBootstrapFallback:b,loadGraph:w}}function RS({primaryDaemonId:e,sendCommand:t}){const[r,n]=l.useState([]),[a,o]=l.useState(!1),[i,c]=l.useState(null),[d,p]=l.useState(!1),[m,u]=l.useState(new Set),h=l.useCallback(async f=>{if(!e||!f){n([]);return}o(!0),c(null);try{const w=await t(e,"get_mesh_review_inbox",{meshId:f});w!=null&&w.success?(n(Array.isArray(w.inbox)?w.inbox:[]),p(w.remoteNodesExcluded===!0)):(c((w==null?void 0:w.error)||"Failed to load review inbox"),n([]))}catch(w){c((w==null?void 0:w.message)||"Failed to load review inbox"),n([])}finally{o(!1)}},[e,t]),b=l.useCallback(f=>{u(w=>new Set([...w,f]))},[]);return{items:r.filter(f=>!m.has(f.nodeId)),allItems:r,loading:a,error:i,remoteNodesExcluded:d,dismissedNodeIds:m,loadInbox:h,dismissItem:b}}function LS(){const e=JN(),{sendCommand:t,sendData:r,daemons:n,userName:a,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:d,unwrapResult:p,normalizeMesh:m,normalizeNode:u,resolveCommandTarget:h,features:b,gateIncompleteGraph:y}=e,f=n[0],w=(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]),g=l.useMemo(()=>er((f==null?void 0:f.availableProviders)||[]),[f]),{meshes:v,selectedMeshId:k,setSelectedMeshId:N,loading:x,error:C,setError:S,showCreate:I,setShowCreate:P,createName:L,setCreateName:A,createRepoIdentity:R,setCreateRepoIdentity:$,createRepoRemoteUrl:X,setCreateRepoRemoteUrl:T,newMeshDaemonId:M,setNewMeshDaemonId:_,newMeshWorkspace:B,setNewMeshWorkspace:E,createPickerWorkspaces:F,loadMeshes:K,handleCreate:z,handleDelete:ne,cancelCreate:q}=SS({daemons:n,primaryDaemonId:w,sendCommand:t,unwrapResult:p,normalizeMesh:m,features:b}),J=v.find(Oe=>Oe.id===k)||null,{meshGraphStatus:xe,setMeshGraphStatus:ue,graphLoading:O,graphError:H,setGraphError:ve,graphProvenance:we,graphBootstrapFallback:be,loadGraph:Ne}=_S({selectedMeshId:k,loadMeshStatus:o,extractStatus:d,normalizeNode:u,gateIncompleteGraph:y}),[re,je]=l.useState(""),ce=b.meshHostDaemonSection&&re||w,{meshQueue:U,queueSummary:W,queueLoading:Y,queueError:se,loadQueue:ie,handleLoadQueue:ae}=AS({primaryDaemonId:w,activeDaemonId:ce,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:h}),{items:D,loading:oe,error:ge,remoteNodesExcluded:pe,loadInbox:te,dismissItem:Me}=RS({primaryDaemonId:w,sendCommand:t}),{nodeProviderPriorityDrafts:_e,setNodeProviderPriorityDrafts:Ce,savingNodePolicyId:Ke,selectedNodeId:Ze,setSelectedNodeId:me,showAddNode:De,setShowAddNode:$e,nodeWorkspace:tt,setNodeWorkspace:Ue,nodeProviderPriority:Ve,setNodeProviderPriority:Te,nodeDaemonId:ze,setNodeDaemonId:ot,nodeCustomPath:Je,setNodeCustomPath:Re,nodePickerWorkspaces:G,nodePickerProviders:V,coordinatorCliType:ee,setCoordinatorCliType:he,launchingCoordinator:ye,launchResult:ke,savingPolicy:Q,coordinatorPromptDraft:Z,setCoordinatorPromptDraft:fe,savingCoordinatorPrompt:Ie,nodeSystemPromptDrafts:Pe,setNodeSystemPromptDrafts:Ae,savingNodeSystemPromptId:Ee,savingNodeSchedulingId:He,handleAddNode:Le,handleRemoveNode:Ye,handleUpdatePolicy:st,handleUpdateNodeProviderPriority:ht,handleUpdateNodeScheduling:kt,handleSaveCoordinatorPrompt:bt,handleSaveNodeSystemPrompt:ft,handleLaunchCoordinator:Ge}=CS({selectedMesh:J,selectedMeshId:k,primaryDaemonId:w,activeDaemonId:ce,daemons:n,availableCliProviders:g,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:h,launchCoordinator:i,features:{addNodeDaemonPicker:b.addNodeDaemonPicker},loadMeshes:K,loadQueue:ie,queueSection:b.queueSection,setError:S}),Ot=l.useMemo(()=>n.find(Oe=>Oe.id===ce)||f,[n,ce,f]),le=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&&!le.has(Oe.id)),[n,le]),de=(J==null?void 0:J.nodes)||[],Be=l.useMemo(()=>de.find(Oe=>String(Oe.daemon_id||Oe.daemonId||"")===re),[de,re]),Ct=b.meshHostDaemonSection?!!Be:!0,Lt=l.useMemo(()=>xe?[...new Set((xe.nodes??[]).map(Oe=>String(Oe.daemonId||Oe.daemon_id||"")).filter(Boolean))]:[],[xe]),is=om({status:xe,daemonId:ce||null,extraDaemonIds:Lt,meshId:k,sendData:r});return l.useEffect(()=>{Ce(Object.fromEntries(((J==null?void 0:J.nodes)||[]).map(Oe=>[Oe.id,PS(Oe)])))},[J]),l.useEffect(()=>{const Oe=(J==null?void 0:J.coordinator)||{};fe({override:typeof Oe.systemPromptOverride=="string"?Oe.systemPromptOverride:"",append:typeof Oe.systemPromptAppend=="string"?Oe.systemPromptAppend:typeof Oe.systemPromptSuffix=="string"?Oe.systemPromptSuffix:""}),Ae(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?Fr(V):Fr(g);De&&Ve.length===0&&Oe.length>0&&Te(Oe)},[De,g,V,Ve.length,b.addNodeDaemonPicker]),l.useEffect(()=>{const Oe=new Set(((J==null?void 0:J.nodes)||[]).map(at=>at.id));Ze&&!Oe.has(Ze)&&me(null)},[J,Ze]),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){_("");return}(!M||!n.some(Oe=>Oe.id===M))&&_(n[0].id)}},[n,M,b.createDaemonPicker]),l.useEffect(()=>{var Oe;if(!b.createDaemonPicker||!M){E("");return}if(!F.length){E("");return}F.some(at=>at.path===B)||E(((Oe=F[0])==null?void 0:Oe.path)||"")},[M,B,F,b.createDaemonPicker]),l.useEffect(()=>{k&&(ue(null),ve(null),Ne(ce,k))},[k,ce]),l.useEffect(()=>{b.queueSection||ie(k)},[k,b.queueSection]),l.useEffect(()=>{!b.reviewInbox||!k||te(k)},[k,b.reviewInbox]),l.useEffect(()=>{K()},[K]),w?J?s.jsx(NS,{selectedMesh:J,error:C,onDismissError:()=>S(null),onBack:()=>{N(null),ue(null)},onDelete:ne,displayedMeshStatus:is,graphLoading:O,graphError:H,graphProvenance:we,graphBootstrapFallback:be,onRefreshGraph:()=>Ne(ce,k,!0),queueSummary:W,queueLoading:Y,queueError:se,onLoadQueue:()=>ae(J),savingPolicy:Q,onUpdatePolicy:st,coordinatorPromptDraft:Z,onCoordinatorPromptDraftChange:fe,savingCoordinatorPrompt:Ie,onSaveCoordinatorPrompt:bt,daemons:n,coordinatorDaemonId:re,onCoordinatorDaemonIdChange:Oe=>{je(Oe),ue(null)},coordinatorCliType:ee,onCoordinatorCliTypeChange:he,launchingCoordinator:ye,launchResult:ke,attachedDaemonIds:le,isHostNodeAttached:Ct,selectedHostNode:Be,onLaunchCoordinator:Ge,activeDaemon:Ot,activeDaemonId:ce,meshQueue:U,userName:a,nodeProviderPriorityDrafts:_e,onNodeProviderPriorityDraftChange:(Oe,at)=>Ce(ls=>({...ls,[Oe]:at})),availableCliProviders:g,savingNodePolicyId:Ke,onUpdateNodeProviderPriority:ht,savingNodeSchedulingId:He,onUpdateNodeScheduling:kt,schedulingStrategy:ua(J).schedulingStrategy,nodeSystemPromptDrafts:Pe,onNodeSystemPromptDraftChange:(Oe,at)=>Ae(ls=>({...ls,[Oe]:at})),savingNodeSystemPromptId:Ee,onSaveNodeSystemPrompt:ft,selectedNodeId:Ze,onSelectNode:me,showAddNode:De,onShowAddNode:()=>$e(!0),onCancelAddNode:()=>$e(!1),nodeWorkspace:tt,onNodeWorkspaceChange:Ue,nodeProviderPriority:Ve,onNodeProviderPriorityChange:Te,nodeDaemonId:ze,onNodeDaemonIdChange:ot,nodeCustomPath:Je,onNodeCustomPathChange:Re,nodePickerWorkspaces:G,nodePickerProviders:V,attachableDaemons:Fe,onAddNode:Le,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:D,reviewInboxLoading:oe,reviewInboxError:ge,reviewInboxRemoteNodesExcluded:pe,onLoadReviewInbox:()=>k&&void te(k),onDismissReviewInboxItem:Me,onRefineNode:async Oe=>{k&&(await t(ce,"refine_mesh_node",{meshId:k,nodeId:Oe,inlineMesh:J}),te(k))},onRequeueLast:async Oe=>{k&&(await t(ce,"requeue_mesh_queue_task",{meshId:k,nodeId:Oe}),te(k))},sendCommand:t}):s.jsx(eS,{meshes:v,loading:x,error:C,onDismissError:()=>S(null),daemons:n,features:{createDaemonPicker:b.createDaemonPicker},showCreate:I,onToggleCreate:()=>P(!I),createName:L,onCreateNameChange:A,createRepoIdentity:R,onCreateRepoIdentityChange:$,createRepoRemoteUrl:X,onCreateRepoRemoteUrlChange:T,newMeshDaemonId:M,onNewMeshDaemonIdChange:_,newMeshWorkspace:B,onNewMeshWorkspaceChange:E,createPickerWorkspaces:F,onSelectMesh:N,onCreate:z,onCancelCreate:q}):s.jsx(Xr,{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 PS(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 DS({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 p=await t(i,"launch_mesh_coordinator",d),m=(p==null?void 0:p.result)??p;if((m==null?void 0:m.success)===!1)throw new Error(m.error||"Coordinator launch failed");const u=(m==null?void 0:m.sessionId)||((h=m==null?void 0:m.session)==null?void 0:h.id)||(m==null?void 0:m.targetSessionId);return{sessionId:u,message:u?`Coordinator launched (${u})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:yi,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:YN}),[t,r,a]);return s.jsx(pm.Provider,{value:o,children:e})}function Zi(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function $S(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=Zi();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($S(e),{credentials:"same-origin",...t})}function xm(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class ES{constructor(){Qe(this,"adapters",new Map);Qe(this,"states",new Map);Qe(this,"runtimeListeners",new Map);Qe(this,"screenshotCallbacks",new Map);Qe(this,"statusCallbacks",new Set);Qe(this,"stateChangeCallbacks",new Set);Qe(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 ES;function BS(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=Zi();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Tn=BS(),od=3e3,FS=3e4;let Wt=null,OS=0;const pa=new Map;let vs=null,Lr=null;function id(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function vr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function HS(e){return e==="connected"?"connected":e}async function Pr(e,t,r){const n=Du(e,r||{}),a=Wt;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++OS}_${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:p=>{clearTimeout(d),i(p)},reject:p=>{clearTimeout(d),c(p)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function 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 bm(e,t,r){const n=Wt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Du(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(bm);class zS{constructor(t){Qe(this,"daemonId");Qe(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 Pr(this.daemonId,t,r)}async sendInput(t,r){return Pr(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,vs&&(clearInterval(vs),vs=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Pr(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(),vs=setInterval(r,2e3)}stopScreenshots(t){vs&&(clearInterval(vs),vs=null)}}let Et=null;function WS(e){return(!Et||Et.daemonId!==e)&&(Et=new zS(e)),Et}function KS({children:e}){const t=l.useRef($r()),r=$r();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,w)=>{c(f),Lr==null||Lr(f,w)},[]),p=l.useRef(null),m=l.useRef(),u=l.useRef(od),h=l.useRef(!0),b=l.useRef(!1),y=l.useRef("initial_connect");return l.useEffect(()=>{h.current=!0,b.current=!1;function f(){var g,v;if(!h.current||((g=p.current)==null?void 0:g.readyState)===WebSocket.OPEN||((v=p.current)==null?void 0:v.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Tn}...`),vr("connect_attempt",{url:Tn,reason:y.current,delayMs:u.current});let j;try{j=new WebSocket(Tn)}catch(k){console.error("[Standalone WS] Failed to create WebSocket:",k),w();return}p.current=j,j.onopen=()=>{if(!h.current){j.close();return}d("connected"),u.current=od,vr("open",{url:Tn,reason:y.current}),ts.resubscribeAll({sendData:Zo}),console.log("[Standalone WS] Connected")},Wt=j,j.onmessage=k=>{var N,x;try{const C=JSON.parse(k.data);if((C.type==="command_result"||C.type==="error")&&C.requestId){const S=pa.get(C.requestId);S&&(pa.delete(C.requestId),C.type==="error"?S.reject(new Error(((N=C.data)==null?void 0:N.message)||"Command failed")):S.resolve(C.data));return}if(C.type==="session_output"){const S=C.sessionId||C.cliId||C.cliType;S&&Jt.emitSessionOutput(S,typeof C.data=="string"?C.data:"",typeof C.seq=="number"?C.seq:void 0);return}if(C.type==="runtime_snapshot"){Jt.emitRuntimeSnapshot(C.sessionId,typeof C.text=="string"?C.text:"",typeof C.seq=="number"?C.seq:0,!!C.truncated,typeof C.cols=="number"?C.cols:void 0,typeof C.rows=="number"?C.rows:void 0);return}if(C.type==="topic_update"){const S=C.update;S&&ts.publish(S);return}if(C.type==="status"||C.type==="initial_state"){const S=C.data;if(!S)return;const{injectEntries:I,markLoaded:P,getIdes:L}=t.current,A=S.instanceId||"standalone",R=L().find(T=>T.id===A),$=WS(A);Jt.register(A,$),Jt.setState(A,"connected"),d("connected",A),Jt.emitStatus(A,S);const X=Qn(S,{daemonId:A,existingDaemon:R,existingEntries:L()});id("ws_status",{type:C.type,daemonId:A,sessions:(S.sessions||[]).map(T=>({id:T.id,parentId:T.parentId,providerType:T.providerType,kind:T.kind,transport:T.transport,unread:T.unread,inboxBucket:T.inboxBucket,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,title:T.title})),recentLaunches:(S.recentLaunches||[]).map(T=>({id:T.id,providerType:T.providerType,kind:T.kind,workspace:T.workspace,lastLaunchedAt:T.lastLaunchedAt}))}),id("entries",{daemonId:A,entries:X.filter(T=>T.type!=="adhdev-daemon").map(T=>({id:T.id,type:T.type,unread:T.unread,inboxBucket:T.inboxBucket,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,sessionId:T.sessionId}))}),X.length>0&&I(X,{authoritativeDaemonIds:[A]}),P(),i.current!==A&&((x=o.current)==null||x.call(o),i.current=A,o.current=ts.subscribe({sendData:Zo},A,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${A}`,params:{includeSessions:!0}},T=>{if(T.topic!=="daemon.metadata")return;const M=t.current.getIdes(),_=M.find(E=>E.id===A),B=Qn(T.status,{daemonId:A,existingDaemon:_,existingEntries:M,timestamp:T.timestamp});B.length>0&&t.current.injectEntries(B,{authoritativeDaemonIds:[A]}),T.userName&&a.current&&a.current(T.userName)}))}}catch(C){console.error("[Standalone WS] Parse error:",C)}},j.onclose=k=>{h.current&&(Et==null||Et.stopScreenshots(),Et&&Jt.setState(Et.daemonId,"disconnected"),d("disconnected"),p.current=null,y.current=`close:${k.code}${k.wasClean?":clean":":unclean"}`,vr("close",{code:k.code,reason:k.reason||"",wasClean:k.wasClean}),w())},j.onerror=k=>{b.current||!h.current||(y.current="error",vr("error",{message:k instanceof Event?"event":String(k),readyState:j.readyState}),console.warn("[Standalone WS] Error, will reconnect:",k))}}function w(){if(!h.current)return;clearTimeout(m.current);const j=u.current;console.log(`[Standalone WS] Reconnecting in ${j}ms...`),vr("schedule_reconnect",{reason:y.current,delayMs:j}),m.current=setTimeout(()=>{u.current=Math.min(u.current*1.5,FS),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(m.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,Wt=null),Et&&(Et.stopScreenshots(),Jt.unregister(Et.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function US({children:e}){const[t,r]=l.useState("disconnected"),[n,a]=l.useState(null);l.useEffect(()=>(Lr=(i,c)=>{r(i),c&&a(c)},()=>{Lr=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=HS(t),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d}},[t,n]);return s.jsx(Sh,{connectionOverrides:o,children:s.jsx(KS,{children:e})})}const gm="adhdev_standalone_font_preferences",As={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"}],zr=[{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"}],GS=new Set(Aa.map(e=>e.id)),VS=new Set(zr.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=As[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"?GS:VS).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:zr;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function qS(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 js(e,t=document.documentElement){const r=Zt(e),n=qS(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(gm,JSON.stringify(t))}catch{}return t}function YS(){try{const e=localStorage.getItem(gm);if(e)return Zt(JSON.parse(e))}catch{}return As}function JS(){return js(YS())}function wr(e,t){var n;const r=e==="chat"?Aa:zr;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const XS=[{id:"dashboard",path:"/dashboard",icon:s.jsx(vd,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(fs,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(Qs,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(ha,{}),label:"Settings"}];function QS({children:e}){const t=Wr(),r=si(),n=l.useMemo(()=>XS.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(jd,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(kd,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(O0,{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 ZS=[{icon:s.jsx(fs,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ps,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Nd,{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(Qs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(jd,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],eC=[{icon:s.jsx(Uh,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(vd,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Kr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Bh,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(wd,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Hh,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],tC=[{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 sC(){return s.jsxs(Xr,{icon:s.jsx(kd,{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:ZS.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:$u.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Bu.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Eu.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:eC.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:tC.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(wa,{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(ef,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function No(e,t,r){return{...e,[t]:r}}function So({surface:e,title:t,description:r,value:n,options:a,onChange:o}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:i=>{const c=i.target.value;o(c==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:c})},children:a.map(i=>s.jsx("option",{value:i.id,children:i.label},i.id))}),n.preset==="custom"&&s.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:i=>o({preset:"custom",customFamily:i.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:Un(e,n)})]})]})]})}function rC({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:d}){const p=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&s.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&s.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(So,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Aa,onChange:m=>o(No(e,"chat",m))}),s.jsx(So,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:zr,onChange:m=>o(No(e,"code",m))}),s.jsx(So,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:zr,onChange:m=>o(No(e,"terminal",m))})]}),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: ",wr("chat",e.chat.preset)," · Code: ",wr("code",e.code.preset)," · Terminal: ",wr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",wr("chat",As.chat.preset)," / ",wr("code",As.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||!p,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||!p,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 nC(){const{ides:e}=ss(),t=e.find(O=>O.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),[p,m]=l.useState(null),[u,h]=l.useState(As),[b,y]=l.useState(!1),[f,w]=l.useState(""),[j,g]=l.useState(""),[v,k]=l.useState("127.0.0.1"),[N,x]=l.useState(""),[C,S]=l.useState(""),[I,P]=l.useState(""),[L,A]=l.useState(""),[R,$]=l.useState(""),[X,T]=l.useState(!1),M=async()=>{const H=await(await Xt("/auth/session")).json();d(H)},_=async()=>{const H=await(await Xt("/api/v1/standalone/preferences")).json();m(H),k(H.standaloneBindHost);const ve=Zt(H.standaloneFontPreferences);h(ve),js(ve),ei(ve)};l.useEffect(()=>{a!==void 0&&i(a)},[a]),l.useEffect(()=>{Promise.all([M(),_()]).catch(O=>{A(O instanceof Error?O.message:String(O))})},[]),l.useEffect(()=>{js(u)},[u]);const B=O=>{const H=O.target.value.trim();t!=null&&t.id&&H!==a&&n(t.id,"set_user_name",{userName:H}).catch(console.error)},[E,F]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),K=O=>{F(O);try{localStorage.setItem("adhdev_sound",O?"1":"0")}catch{}},z=async()=>{w(""),g(""),y(!0);try{const O=Zt(u),H=await Xt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:O})}),ve=await H.json();if(!H.ok)throw new Error((ve==null?void 0:ve.error)||"Failed to save standalone font preferences");const we=Zt(ve.standaloneFontPreferences);m(ve),h(we),js(we),ei(we),g("Standalone chat fonts saved for this self-hosted dashboard.")}catch(O){w(O instanceof Error?O.message:String(O))}finally{y(!1)}},ne=()=>{const O=Zt(p==null?void 0:p.standaloneFontPreferences);w(""),g(""),h(O),js(O)},q=()=>{w(""),g(""),h(As),js(As)},J=async()=>{A(""),$(""),T(!0);try{const O=await Xt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:v})}),H=await O.json();if(!O.ok)throw new Error((H==null?void 0:H.error)||"Failed to save standalone network preference");m(H),k(H.standaloneBindHost),$(H.standaloneBindHost==="0.0.0.0"?"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.":"Default standalone network mode set to localhost only. Restart standalone to apply it.")}catch(O){A(O instanceof Error?O.message:String(O))}finally{T(!1)}},xe=async()=>{if(A(""),$(""),C.trim().length<4){A("Password must be at least 4 characters.");return}if(C!==I){A("New password and confirmation do not match.");return}T(!0);try{const O=await Xt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:N,newPassword:C})}),H=await O.json();if(!O.ok)throw new Error((H==null?void 0:H.error)||"Failed to save password");d(H),await _(),x(""),S(""),P(""),$(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),xm()}catch(O){A(O instanceof Error?O.message:String(O))}finally{T(!1)}},ue=async()=>{A(""),$(""),T(!0);try{const O=await Xt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:N,clear:!0})}),H=await O.json();if(!O.ok)throw new Error((H==null?void 0:H.error)||"Failed to clear password");d(H),await _(),x(""),S(""),P(""),$("Standalone password disabled.")}catch(O){A(O instanceof Error?O.message:String(O))}finally{T(!1)}};return s.jsxs(Xr,{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(hs,{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(hs,{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:(p==null?void 0:p.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(p==null?void 0:p.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:c!=null&&c.hasPasswordAuth?"Password enabled":c!=null&&c.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(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:v==="127.0.0.1",onChange:()=>k("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:v==="0.0.0.0",onChange:()=>k("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 ",(p==null?void 0:p.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(hs,{variant:"error",children:L}),R&&s.jsx(hs,{variant:"success",children:R}),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:N,onChange:O=>x(O.target.value)}),s.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:c!=null&&c.hasPasswordAuth?"New password":"New standalone password",value:C,onChange:O=>S(O.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:O=>P(O.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{xe()},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:()=>{ue()},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(O=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${O.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:O.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:O.type})]},O.type))})}),s.jsx(dt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Y0,{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(Z0,{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(ty,{})]}),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(cy,{})]}),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(rC,{value:u,savedValue:Zt(p==null?void 0:p.standaloneFontPreferences),saving:b,error:f,notice:j,onChange:h,onSave:()=>{z()},onResetToSaved:ne,onResetToDefaults:q})]}),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(py,{})]})]})}),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(G0,{}),s.jsx(ws,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zh,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,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(Eh,{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:O=>i(O.target.value),onBlur:B,onKeyDown:O=>{O.key==="Enter"&&O.currentTarget.blur()}})]})})})]})}const aC=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],Sr="adhdev_onboarding_done",oC=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],iC={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function lC({onDone:e}){const[t,r]=l.useState([]),[n,a]=l.useState(new Set(aC)),[o,i]=l.useState(!0),[c,d]=l.useState(null),[p,m]=l.useState(!1),[u,h]=l.useState(null),[b,y]=l.useState("all");l.useEffect(()=>{let N=!1;const x=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${x}/providers?sort=popular&limit=100`).then(C=>{if(!C.ok)throw new Error(`HTTP ${C.status}`);return C.json()}).then(C=>{N||r(C.providers??[])}).catch(C=>{N||d(C instanceof Error?C.message:String(C))}).finally(()=>{N||i(!1)}),()=>{N=!0}},[]);const f=t.filter(N=>b==="all"||N.category===b),w=["cli","ide","extension","acp"].map(N=>({category:N,items:f.filter(x=>x.category===N)})).filter(N=>N.items.length>0),j=l.useCallback(N=>{a(x=>{const C=new Set(x);return C.has(N)?C.delete(N):C.add(N),C})},[]),g=l.useCallback(async()=>{if(n.size===0){localStorage.setItem(Sr,"1"),e();return}m(!0);const N=[];for(const x of n)try{const S=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:x})})).json().catch(()=>({}));N.push({type:x,ok:!!S.success,error:S.error})}catch(C){N.push({type:x,ok:!1,error:C instanceof Error?C.message:String(C)})}h(N),m(!1),N.every(x=>x.ok)&&localStorage.setItem(Sr,"1")},[n,e]),v=l.useCallback(()=>{localStorage.setItem(Sr,"1"),e()},[e]),k=l.useCallback(()=>{u&&u.every(N=>N.ok)?e():p||v()},[u,p,e,v]);return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60",onClick:k,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:N=>N.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:oC.map(N=>{const x=N.key==="all"?t.length:t.filter(C=>C.category===N.key).length;return x===0&&N.key!=="all"?null:s.jsxs("button",{onClick:()=>y(N.key),className:`machine-btn text-[10px] px-2 py-0.5 ${b===N.key?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:[N.label," ",s.jsxs("span",{className:"opacity-60",children:["(",x,")"]})]},N.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:w.map(N=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:iC[N.category]??N.category}),s.jsx("div",{className:"grid gap-1.5",children:N.items.map(x=>{var L,A;const C=n.has(x.type),S=u==null?void 0:u.find(R=>R.type===x.type),I=((L=x.manifest)==null?void 0:L.icon)??"📦",P=((A=x.manifest)==null?void 0:A.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${C?"bg-violet-500/[0.06] border-violet-500/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:C,onChange:()=>j(x.type),disabled:p,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:I}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:x.displayName}),P&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:P})]}),S&&s.jsx("span",{className:`text-[10px] font-semibold ${S.ok?"text-green-400":"text-red-400"}`,children:S.ok?"✓ installed":`✗ ${S.error??"failed"}`})]},x.type)})})]},N.category))}),s.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-border-subtle",children:[s.jsxs("div",{className:"text-[11px] text-text-muted",children:[n.size," provider",n.size!==1?"s":""," selected"]}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx("button",{onClick:v,disabled:p,className:"machine-btn text-[11px] px-3 py-1",children:"Skip"}),s.jsx("button",{onClick:()=>{u?(localStorage.setItem(Sr,"1"),e()):g()},disabled:p||!u&&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:p?"Installing…":u?"Done":`Install ${n.size}`})]})]})]})})}function cC(){try{return localStorage.getItem(Sr)==="1"}catch{return!1}}B0();iy();JS();const dC=fd({baseUrl:"",getToken:Zi});function uC({children:e}){const[t,r]=l.useState(null),[n,a]=l.useState(!0),[o,i]=l.useState(""),[c,d]=l.useState(""),[p,m]=l.useState(!1),u=async()=>{a(!0),d("");try{const y=await(await Xt("/auth/session")).json();r(y)}catch(b){d(b instanceof Error?b.message:String(b))}finally{a(!1)}};l.useEffect(()=>{u()},[]),l.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let b=!1;return(async()=>{try{const y=await Xt("/api/v1/standalone/preferences");if(!y.ok)return;const f=await y.json();if(b)return;const w=Zt(f.standaloneFontPreferences);js(w),ei(w)}catch{}})(),()=>{b=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const h=async b=>{b.preventDefault(),m(!0),d("");try{const y=await Xt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),f=await y.json();if(!y.ok)throw new Error((f==null?void 0:f.error)||"Login failed");r(f),i(""),xm()}catch(y){d(y instanceof Error?y.message:String(y))}finally{m(!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:p||!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:p?"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 ld(){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(Mo,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Mo,{to:"/dashboard",replace:!0})}function pC(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let r=!1;if(!cC())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(lC,{onDone:()=>t(!1)}):null}function mC(){const{ides:e}=ss(),t=l.useMemo(()=>{for(const p of e)if(p.activeInteractivePrompt)return p.instanceId??p.id;return null},[e]),{promptSession:r,hasActivePrompt:n,responseError:a,isSubmitting:o,submit:i,cancel:c,reopen:d}=qu(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(Fd,{promptSession:r,isSubmitting:o,error:a,onSubmit:i,onCancel:c})]}):null}function hC(){const e=l.useMemo(()=>({sendCommand:Pr,sendData:Zo,sendPtyInput:bm}),[]);return s.jsx(ch,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Mh,{client:dC,children:s.jsx(uC,{children:s.jsx(US,{children:s.jsx(Th,{value:e,children:s.jsxs(Ph,{sendDaemonCommand:Pr,children:[s.jsx(mC,{}),s.jsxs(QS,{children:[s.jsx(pC,{}),s.jsxs(dh,{children:[s.jsx(ds,{path:"/dashboard",element:s.jsx(F1,{})}),s.jsx(ds,{path:"/machine",element:s.jsx(ld,{})}),s.jsx(ds,{path:"/machines/:id",element:s.jsx(qN,{})}),s.jsx(ds,{path:"/machines",element:s.jsx(ld,{})}),s.jsx(ds,{path:"/about",element:s.jsx(sC,{})}),s.jsx(ds,{path:"/settings",element:s.jsx(nC,{})}),s.jsx(ds,{path:"/mesh",element:s.jsx(DS,{children:s.jsx(LS,{})})}),s.jsx(ds,{path:"*",element:s.jsx(Mo,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}Eg({connectionManager:Jt});uh(document.getElementById("root")).render(s.jsx(hC,{}));
|